Skip to content

Commit

Permalink
feat(dev): script to import a user's posts from production, for #220 (#…
Browse files Browse the repository at this point in the history
…235)

Closes #220.

What does this PR do / solve?
-----------------------------

When developing and/or testing features (e.g. the "load more" button, see #221) in a local environment, it can be handy to have some posts in the local database.

Overview of changes
-------------------

Introduce `./scripts/import-from-prod.js` which loads [adrien's profile and posts](https://openwhyd.org/adrien) to the local/testing database.

How to test this PR?
--------------------

Run this after starting a local database server (e.g. with `$ docker-compose up`):

```sh
$ node scripts/import-from-prod.js
```

=> http://localhost:8080/all should display several pages of tracks imported from https://openwhyd.org/adrien.
  • Loading branch information
adrienjoly committed Oct 26, 2019
1 parent 711ee25 commit 9c6164f
Show file tree
Hide file tree
Showing 3 changed files with 129 additions and 41 deletions.
3 changes: 2 additions & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
"extends": ["plugin:prettier/recommended"],
"plugins": [],
"parserOptions": {
"ecmaVersion": 2017
"experimentalObjectRestSpread": true,
"ecmaVersion": 2018
},
"env": {
"es6": true
Expand Down
89 changes: 49 additions & 40 deletions docs/INSTALL.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@

### Setup (simple)

Docker makes it easy and safe to install and start the two servers required for Openwhyd: the MongoDB database server, and the web/application server (formerly called *whydJS*). All you need is access to the shell (a.k.a. *terminal*), and to have Docker and Git installed on your machine.
Docker makes it easy and safe to install and start the two servers required for Openwhyd: the MongoDB database server, and the web/application server (formerly called _whydJS_). All you need is access to the shell (a.k.a. _terminal_), and to have Docker and Git installed on your machine.

1. Install [Docker Client](https://www.docker.com/community-edition) and start it
2. [Install Git](https://www.atlassian.com/git/tutorials/install-git) if you don't have it already
3. Clone openwhyd's repository: `git clone https://github.com/openwhyd/openwhyd.git`, then `cd openwhyd`
4. Build and launch Docker processes: `docker-compose up`
6. Open [http://localhost:8080](http://localhost:8080) in your web browser => you should see Openwhyd's home page! 🎉
7. When you're done, shutdown the Docker processes by pressing the `Ctrl-C` key combination in the shell instance where you had run `docker-compose up` (step 4).
5. Open [http://localhost:8080](http://localhost:8080) in your web browser => you should see Openwhyd's home page! 🎉
6. When you're done, shutdown the Docker processes by pressing the `Ctrl-C` key combination in the shell instance where you had run `docker-compose up` (step 4).

Whenever you want to update your local clone of Openwhyd's repository to the latest version, run `git pull` from the `openwhyd` folder where you had cloned the repository (step 3).

Expand All @@ -23,19 +23,19 @@ If you want to rebuild the Docker image and run it in the background, use `docke

### Setup (manual)

* Install Node.js, MongoDB, GraphicsMagick or ImageMagick
* Make sure that `make` and `g++` are installed (required for building npm binaries, *I had to do [this](https://github.com/fedwiki/wiki/issues/46) and [this](https://www.digitalocean.com/community/questions/node-gyp-rebuild-fails-on-install)*)
* Make sure that a MongoDB server is running
* Make sure that the necessary environment variables are defined (see below)
* Make sure that the database is initialized (by running `mongo openwhyd_data config/initdb.js` and `mongo openwhyd_data config/initdb_team.js`)
* Make sure that dependencies are installed (`npm install`)
* If you want notifications to be pushed to your iPhone app, make sure that Apple Push Notification Service (APNS) certificates are copied to `/config/apns` with the following filenames: `aps_dev.cert.pem`, `aps_dev.key.pem`, `aps_prod.cert.pem`, `aps_prod.key.pem`, and `Dev_Whyd.mobileprovision`. (you can test them using `test_apns.sh`)
- Install Node.js, MongoDB, GraphicsMagick or ImageMagick
- Make sure that `make` and `g++` are installed (required for building npm binaries, _I had to do [this](https://github.com/fedwiki/wiki/issues/46) and [this](https://www.digitalocean.com/community/questions/node-gyp-rebuild-fails-on-install)_)
- Make sure that a MongoDB server is running
- Make sure that the necessary environment variables are defined (see below)
- Make sure that the database is initialized (by running `mongo openwhyd_data config/initdb.js` and `mongo openwhyd_data config/initdb_team.js`)
- Make sure that dependencies are installed (`npm install`)
- If you want notifications to be pushed to your iPhone app, make sure that Apple Push Notification Service (APNS) certificates are copied to `/config/apns` with the following filenames: `aps_dev.cert.pem`, `aps_dev.key.pem`, `aps_prod.cert.pem`, `aps_prod.key.pem`, and `Dev_Whyd.mobileprovision`. (you can test them using `test_apns.sh`)

### Usage

* `docker-compose up`, or `npm run run`, or `npm forever:start` (auto-restart daemon)
* Open [http://localhost:8080](http://localhost:8080) (or `WHYD_URL_PREFIX`)
* During development, you may have to restart the server to have your changes taken into account. To restart the Docker container, use `docker-compose restart web`.
- `docker-compose up`, or `npm run run`, or `npm forever:start` (auto-restart daemon)
- Open [http://localhost:8080](http://localhost:8080) (or `WHYD_URL_PREFIX`)
- During development, you may have to restart the server to have your changes taken into account. To restart the Docker container, use `docker-compose restart web`.

### Testing

Expand All @@ -60,37 +60,46 @@ Run all tests against the Docker container:
npm run test-docker
```

### Sample data

If you want to import some user data from openwhyd.org into your local/test database, you can use the following script:

```sh
$ npm run docker-seed # will clear the database
$ node scripts/import-from-prod.js # will import 21 posts from https://openwhyd.org/adrien
```

### Environment variables

* `WHYD_GENUINE_SIGNUP_SECRET` (mandatory. a secret key that is used to make sure that sign-ups are legit)
* `WHYD_SESSION_SECRET` (mandatory. a secret key used to sign session cookies)
* `WHYD_DEV_APNS_PASSPHRASE` (mandatory. the passphrase used to de-cypher APNS certificate and key, for iOS push notifications in DEV mode)
* `WHYD_APNS_PASSPHRASE` (mandatory. the passphrase used to de-cypher APNS certificate and key, for iOS push notifications in PRODUCTION mode)
* `WHYD_ADMIN_OBJECTID` (ObjectId of the user that can access to admin endpoints)
* `WHYD_ADMIN_NAME` (Full-text name of the user that can access to admin endpoints)
* `WHYD_ADMIN_EMAIL` (mandatory. Email address of the user that can access to admin endpoints)
* `WHYD_CONTACT_EMAIL` (mandatory. email for users to contact the site's team)
* `WHYD_URL_PREFIX` (default: `http://localhost:8080`)
* `WHYD_PORT` (default: `8080`)
* `MONGODB_DATABASE` (example: `openwhyd_data`, or `openwhyd_test`)
* `MONGODB_HOST` (default: `localhost`)
* `MONGODB_PORT` (default: `27017`)
* `MONGODB_USER` (default: none)
* `MONGODB_PASS` (default: none)
* `SENDGRID_API_USER` (mandatory. email address of sendgrid account to be used for sending emails)
* `SENDGRID_API_KEY` (mandatory. key / password of sendgrid account)
* `SENDGRID_API_FROM_EMAIL` (mandatory. email address of email sender)
* `SENDGRID_API_FROM_NAME` (mandatory. name of email sender)
* `LAST_FM_API_KEY` (mandatory. for lastfm scrobbling)
* `LAST_FM_API_SECRET` (mandatory. for lastfm scrobbling)
* `ALGOLIA_APP_ID` (mandatory. for search index)
* `ALGOLIA_API_KEY` (mandatory. for search index)
- `WHYD_GENUINE_SIGNUP_SECRET` (mandatory. a secret key that is used to make sure that sign-ups are legit)
- `WHYD_SESSION_SECRET` (mandatory. a secret key used to sign session cookies)
- `WHYD_DEV_APNS_PASSPHRASE` (mandatory. the passphrase used to de-cypher APNS certificate and key, for iOS push notifications in DEV mode)
- `WHYD_APNS_PASSPHRASE` (mandatory. the passphrase used to de-cypher APNS certificate and key, for iOS push notifications in PRODUCTION mode)
- `WHYD_ADMIN_OBJECTID` (ObjectId of the user that can access to admin endpoints)
- `WHYD_ADMIN_NAME` (Full-text name of the user that can access to admin endpoints)
- `WHYD_ADMIN_EMAIL` (mandatory. Email address of the user that can access to admin endpoints)
- `WHYD_CONTACT_EMAIL` (mandatory. email for users to contact the site's team)
- `WHYD_URL_PREFIX` (default: `http://localhost:8080`)
- `WHYD_PORT` (default: `8080`)
- `MONGODB_DATABASE` (example: `openwhyd_data`, or `openwhyd_test`)
- `MONGODB_HOST` (default: `localhost`)
- `MONGODB_PORT` (default: `27017`)
- `MONGODB_USER` (default: none)
- `MONGODB_PASS` (default: none)
- `SENDGRID_API_USER` (mandatory. email address of sendgrid account to be used for sending emails)
- `SENDGRID_API_KEY` (mandatory. key / password of sendgrid account)
- `SENDGRID_API_FROM_EMAIL` (mandatory. email address of email sender)
- `SENDGRID_API_FROM_NAME` (mandatory. name of email sender)
- `LAST_FM_API_KEY` (mandatory. for lastfm scrobbling)
- `LAST_FM_API_SECRET` (mandatory. for lastfm scrobbling)
- `ALGOLIA_APP_ID` (mandatory. for search index)
- `ALGOLIA_API_KEY` (mandatory. for search index)

### Other variables to update

The value of following constants is required to connect to the corresponding APIs:

* `YOUTUBE_API_KEY`
* `SOUNDCLOUD_CLIENT_ID`
* `JAMENDO_CLIENT_ID`
* `DEEZER_APP_ID`
- `YOUTUBE_API_KEY`
- `SOUNDCLOUD_CLIENT_ID`
- `JAMENDO_CLIENT_ID`
- `DEEZER_APP_ID`
78 changes: 78 additions & 0 deletions scripts/import-from-prod.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// You may want to clear the test database with `$ npm run docker-seed`
// before running this script.

const request = require('request');
const mongodb = require('mongodb');

const ObjectID = id => mongodb.ObjectID.createFromHexString(id);

// Parameters // TODO: get from command line arguments and/or env vars
const url = 'mongodb://localhost:27117';
const dbName = 'openwhyd_test';
const username = 'adrien';

const connectToDb = ({ url, dbName }) =>
new Promise((resolve, reject) =>
mongodb.MongoClient.connect(url, (err, client) => {
if (err) reject(err);
else resolve({ db: client.db(dbName), client });
})
);

const fetchUserData = ({ username }) =>
new Promise((resolve, reject) => {
const url = `https://openwhyd.org/${username}?format=json`;
console.log(`fetching tracks from ${url} ...`);
request(url, function(error, response, body) {
if (error) {
reject(error);
} else {
resolve({
posts: JSON.parse(body).map(post => ({
...post,
_id: ObjectID(post._id)
}))
});
}
});
});

function genUserFromPost({ post }) {
return {
_id: ObjectID(post.uId),
id: post.uId,
name: post.uNm
};
}

const insertUser = ({ db, user }) =>
new Promise((resolve, reject) => {
db.collection('user').insertOne(user, function(err, r) {
if (err) reject(err);
else resolve();
});
});

const insertPosts = ({ db, posts }) =>
new Promise((resolve, reject) => {
db.collection('post').insertMany(posts, function(err, r) {
if (err) reject(err);
else resolve();
});
});

(async () => {
console.log(`connecting to ${url}/${dbName} ...`);
const { db, client } = await connectToDb({ url, dbName });
const { posts } = await fetchUserData({ username }); // or require(`./../${username}.json`);
console.log(`imported ${posts.length} posts`);
const user = genUserFromPost({ post: posts[0] });
// console.log('genUserFromPost =>', user);
// await insertUser({ db, user }); // may cause E11000 duplicate key error collection: openwhyd_test.user, after seeding the db
console.log('inserted user');
await insertPosts({ db, posts });
client.close();
})().catch(err => {
console.error(err);
process.exit(1);
});

0 comments on commit 9c6164f

Please sign in to comment.