From 17ab445bb041aeb4c08da88ebeabd669f5cb3cdd Mon Sep 17 00:00:00 2001 From: Mateusz Pstrucha Date: Thu, 23 Sep 2021 00:17:06 +0200 Subject: [PATCH] feat: some.. changes... --- README.md | 228 +++++++++++++++++++++++--- Track.js | 2 + db.js | 274 ++++++++++++++++---------------- errors.js | 8 + index.js | 34 ++-- models/Search.js | 19 +++ models/User.js | 21 +++ mongo.js | 289 +++++++++++++++++++++++++++++++++ package-lock.json | 395 ++++++++++++++++++++++++++++++++++++++++++++++ package.json | 3 + routes/history.js | 17 -- routes/login.js | 69 ++++++++ routes/search.js | 24 +-- routes/track.js | 34 ++-- routes/vote.js | 137 +++++++++++++--- socket.js | 24 ++- spotify.js | 69 ++++---- 17 files changed, 1370 insertions(+), 277 deletions(-) create mode 100644 errors.js create mode 100644 models/Search.js create mode 100644 models/User.js create mode 100644 mongo.js delete mode 100644 routes/history.js create mode 100644 routes/login.js diff --git a/README.md b/README.md index 75c69b1..9b43a3e 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,13 @@ Backend server for radio-rolnik Get track metadata -`GET` `/track/:id` get track by track id +--- + +#### `GET` `/track/:id` get track + +Get track by track id + +`RESPONSE` ```javascript { @@ -31,50 +37,220 @@ Get track metadata } ``` -### `/status` +--- -Get currently playing track +#### `POST` `/batch` get tracks -`GET` `/status` get track, with additional metadata +Get multiple tracks by track id + +`BODY` ```javascript { - track: TrackID, - progress: Number + tids: [TrackID...] } ``` -### `/history` - -Get previous and next tracks - -`GET` `/history/next` next track +`RESPONSE` ```javascript -{ - track: TrackID, - timestamp: Date -} -``` - -`GET` `/history/previous` next track - -```javascript -{ - tracks: [TrackID...], - timestamps: [Date...] -} +[ + TrackID... +] ``` ### `/search` Search for tracks -`GET` `/search` general search +--- + +#### `GET` `/search/track` track search + +Get a list of Track ids + +`QUERY` ```javascript { - tracks: [TrackID...], + query: String +} +``` + +`RESPONSE` + +```javascript +{ + tids: [TrackID...], total: Number } ``` + +### `/vote` + +Get and update vote values for tracks + +--- + +#### `GET` `/vote/:id` get stats + +Get stats of a track. +When access token is present, also get user's vote value + +`HEADERS` + +```javascript +{ + authorization: String +} +``` + +`RESPONSE` + +```javascript +{ + up: Number, + down: Number, + rank: Number, + cast: String // user's vote value for track. Only if authorized +} +``` + +--- + +#### `POST` `/vote/batch` get multiple stats + +Get stats of multiple tracks. +When access token is present, also get user's vote value per TrackID + +`HEADERS` + +```javascript +{ + authorization: String +} +``` + +`BODY` + +```javascript +{ + tids: [TrackID...] +} +``` + +`RESPONSE` + +```javascript +[ + { + up: Number, + down: Number, + rank: Number, + cast: String // user's vote value for track. Only if authorized + }... +] +``` + +--- + +#### `PATCH` `/vote/:tid` change vote value + +Changes user's vote for a track + +`HEADERS` + +```javascript +{ + authorization: String +} +``` + +`BODY` + +```javascript +{ + value: String // 'up', 'down', '', 'report' +} +``` + +`RESPONSE` + +```javascript +true || false +``` + +### `/login` + +Login and fetch access token + +--- + +#### `GET` `/login/token` get stats + +Exchange Facebook login code for an access token + +`QUERY` + +```javascript +{ + code: String +} +``` + +`RESPONSE` + +```html + + Logowanie... + + +``` + +--- + +## .env + +Enviroment variables required + +### Ports + +```ini +portHttp=3010 +portWs=3020 +``` + +### Spotify API + +```ini +spotifyClientId=ID +spotifyClientSecret=SECRET +``` + +### Facebok API + +```ini +fbAppId=ID +fbSecret=SECRET +``` + +### Mongo DB + +```ini +dbHost=IP +dbPort=PORT +dbName=DB +dbAuth=COLL +dbUser=USER +dbPass=PASSWORD +``` + +### Other + +```ini +timeValid=monday +``` diff --git a/Track.js b/Track.js index abe9026..79f4294 100644 --- a/Track.js +++ b/Track.js @@ -11,6 +11,8 @@ class Track { this.explicit = data.explicit this.banned = data.banned ?? false } + + static idMinLength = 22 } export default Track diff --git a/db.js b/db.js index a61ce79..ad2dd6e 100644 --- a/db.js +++ b/db.js @@ -1,143 +1,48 @@ -import dotenv from 'dotenv' -import mongoose from 'mongoose' +import Jwt from 'jsonwebtoken' -dotenv.config() +import { + getTrack, + putTrack, + countTrackVotes, + getUserVote, + updateUserVote, + countAllVotes, + getUser, + putUser, + getQuery, + setQuery, +} from './mongo.js' -import { byId } from './spotify.js' +import { byId, byQuery } from './spotify.js' import Track from './Track.js' -import { Track as TrackModel } from './models/Track.js' -import Vote from './models/Vote.js' +import { DbError } from './errors.js' -const { dbHost, dbPort, dbName, dbAuth, dbUser, dbPass } = process.env - -mongoose.connect(`mongodb://${dbHost}:${dbPort}/${dbName}`, { - user: dbUser, - pass: dbPass, - authSource: 'admin', - useNewUrlParser: true, - useUnifiedTopology: true, - useFindAndModify: false, -}) - -const database = mongoose.connection - -database.on('error', (err) => { - throw err -}) - -database.once('open', () => { - console.info(`db: connected`) -}) - -// #### #### #### #### -// #### Tracks - -function getTrack(id) { - return new Promise((resolve, reject) => { - TrackModel.findOne({ id }) - .then((track) => { - if (track === null) return reject(new Error(`Tracks: ${id} not found`)) - resolve(track) - }) - .catch((err) => { - reject(err) - }) - }) +/** + * Get Track placement in Top + * @param {String} tid Track id + * @returns {Number} Track's # (>0) + */ +function getTrackRank(tid) { + const rank = topList.indexOf(tid) + if (rank === -1) return rank + else return rank + 1 } -function putTrack(track) { - return new Promise((resolve, reject) => { - TrackModel.create(track).then((tdata) => { - resolve(tdata) - }) - }) -} - -// #### #### #### #### -// #### Votes - -const timeValid = (() => { - switch (process.env.timeValid) { - default: - case 'monday': - var monday = new Date() - monday.setHours(0, 0, 0) - monday.setDate(monday.getDate() - ((monday.getDay() + 6) % 7)) - - return monday - case 'date': - let date = new Date(...JSON.parse(process.env.valid_date)) - return date - } -})() - -function getVotes(tid) { - return new Promise((resolve, reject) => { - Vote.find({ tid, createdAt: { $gt: timeValid } }) - .then((votes) => { - resolve(votes) - }) - .catch((err) => reject(err)) - }) -} - -function countVotes(tid) { - return new Promise((resolve, reject) => { - getVotes(tid).then((votes) => { - let up = 0, - down = 0 - - for (let vote of votes) { - vote.value == 'up' && up++ - vote.value == 'down' && down++ - } - - resolve({ - up, - down, - }) - }) - }) -} - -function getUserVote(tid, uid) { - return new Promise((resolve, reject) => { - Vote.findOne({ tid, uid, createdAt: { $gt: timeValid } }) - .then((vote) => resolve(vote)) - .catch((err) => reject(err)) - }) -} - -function updateUserVote(tid, uid, value) { - return new Promise((resolve, reject) => { - // check if vote already exists - getUserVote(tid, uid).then((vote) => { - if (vote) { - // vote exists - if (vote.value != value) { - // new value is different - Vote.updateOne({ _id: vote._id }, { value }).then((newVote) => { - // updated vote - resolve(!!newVote.ok) - }) - } else { - // unchanged value - resolve(true) - } - } else { - // create new vote - Vote.create({ uid, tid, value }).then((newVote) => { - // created vote - resolve(!!newVote) - }) - } - }) - }) -} +var topList = [], + lastTop = -1 const db = { + /** + * Methods for Track data + */ tracks: { + /** + * Get track by id. + * DB first, then online + * @param {String} id Track id + * @returns {Promise} Track object + */ get: (id) => { return new Promise((resolve, reject) => { // query db first @@ -151,21 +56,118 @@ const db = { resolve(track) }) .catch((spotifyErr) => { - console.error(spotifyErr) - reject(new Error(`Could not retrieve track`)) + reject( + new DbError('DbErrorNotFound', `Could not retrieve track`) + ) }) }) }) }, - put: putTrack, }, votes: { - getTrack: (tid) => {}, - getTrackStats: countVotes, - getUser: (uid) => {}, + /** + * Get Track's stats. + * @param {String} tid Track id + * @returns {Promise<{}>} Votes up and down, rank + */ + getTrackStats: (tid) => { + return new Promise((resolve, reject) => { + countTrackVotes(tid) + .then((stats) => { + resolve({ ...stats, rank: getTrackRank(tid) }) + }) + .catch((err) => reject(err)) + }) + }, getUserTrack: getUserVote, putUserTrack: updateUserVote, }, + users: { + getUser: getUser, + newUser: putUser, + /** + * Verify token content + * @param {String} jwt + * @returns {Promise<{}>} Decoded token content (User data) + */ + verifyJwt: (jwt) => { + return new Promise((resolve, reject) => { + Jwt.verify(jwt ?? '', process.env.fbSecret, (err, decoded) => { + if (err) return reject(err) + resolve(decoded) + }) + }) + }, + }, + top: { + /** + * Current Top tracks + * @type {Array} Array of Track ids + */ + get list() { + return topList + }, + /** + * Last date topList was updated + * @type {Number} Date().now + */ + get lastCount() { + return lastTop + }, + /** + * Get current Top tracks + * @returns {Promise<[]>} Array of Track ids + */ + get: () => { + return new Promise((resolve, reject) => { + let now = new Date().getTime() + + if (now - lastTop > 1e3) { + countAllVotes() + .then((top) => { + topList = top + lastTop = now + resolve(top) + }) + .catch((err) => reject(err)) + } else resolve(topList) + }) + }, + getTrackRank: getTrackRank, + }, + search: { + query: (query) => { + return new Promise((resolve, reject) => { + const market = 'PL' + getQuery(query, market) + .then((search) => { + if (search === null) { + byQuery(query) + .then(({ tids, total }) => { + const out = { + query, + tids, + total, + market, + } + + resolve(out) + setQuery(out) + }) + .catch((err) => reject(err)) + } else { + resolve({ + query: search.query, + tids: search.tids, + total: search.total, + market: search.market, + }) + } + }) + .catch((err) => reject(err)) + }) + }, + }, } export default db diff --git a/errors.js b/errors.js new file mode 100644 index 0000000..e34ce38 --- /dev/null +++ b/errors.js @@ -0,0 +1,8 @@ +class DbError extends Error { + constructor(name, message, ...args) { + super(message, ...args) + this.name = name ?? 'DbError' + } +} + +export { DbError } diff --git a/index.js b/index.js index 4a0b16b..fce9331 100644 --- a/index.js +++ b/index.js @@ -4,11 +4,12 @@ import cookieParser from 'cookie-parser' import { createServer } from 'http' import { broadcast } from './socket.js' +import db from './db.js' import track from './routes/track.js' -import history from './routes/history.js' import search from './routes/search.js' import vote from './routes/vote.js' +import login from './routes/login.js' dotenv.config() @@ -21,9 +22,9 @@ app.use(cookieParser()) app.set('port', process.env.portHttp) app.use('/track', track) -app.use('/history', history) app.use('/search', search) app.use('/vote', vote) +app.use('/login', login) www.listen(process.env.portHttp) @@ -32,18 +33,29 @@ www.on('error', function (error) { throw error } - console.log(`Error: port ${process.env.portHttp}: ${error.code}`) + console.info(`Error: port ${process.env.portHttp}: ${error.code}`) }) www.on('listening', function () { - console.log(`www: listening on ${process.env.portHttp}`) + console.info(`www: listening on ${process.env.portHttp}`) }) -setInterval(() => { - broadcast({ - cat: 'status', - trackid: '2FBP8xsTWbJv3zjc1Dix0c', - progress: 20e3 + new Date().getMilliseconds(), - paused: false, - }) +var i = 0 + +setInterval(async () => { + broadcast([ + { + cat: 'status', + trackid: db.top.list[i], + progress: 20e3 + new Date().getMilliseconds(), + paused: false, + }, + { + cat: 'top', + trackids: await db.top.get(), + timestamp: db.top.lastCount, + }, + ]) + i++ + if (i >= db.top.list.length) i = 0 }, 10e3) diff --git a/models/Search.js b/models/Search.js new file mode 100644 index 0000000..f839f55 --- /dev/null +++ b/models/Search.js @@ -0,0 +1,19 @@ +import mongoose from 'mongoose' + +const search = new mongoose.Schema( + { + query: String, + market: String, + tids: Array, + total: Number, + }, + { + collection: 'search', + timestamps: { createdAt: 'createdAt', updatedAt: 'updatedAt' }, + } +) + +const Search = mongoose.model('Search', search) + +export default Search +export { Search as Vote, search as vote } diff --git a/models/User.js b/models/User.js new file mode 100644 index 0000000..66dadbc --- /dev/null +++ b/models/User.js @@ -0,0 +1,21 @@ +import mongoose from 'mongoose' + +const user = new mongoose.Schema( + { + id: String, + name: String, + accessToken: String, + tokenExpires: Date, + banned: Boolean, + perms: Number, + }, + { + collection: 'users', + timestamps: { createdAt: 'createdAt', updatedAt: 'updatedAt' }, + } +) + +const User = mongoose.model('User', user) + +export default User +export { User, user } diff --git a/mongo.js b/mongo.js new file mode 100644 index 0000000..edfe431 --- /dev/null +++ b/mongo.js @@ -0,0 +1,289 @@ +import dotenv from 'dotenv' +import mongoose from 'mongoose' + +dotenv.config() + +import TrackModel from './models/Track.js' +import Vote from './models/Vote.js' +import User from './models/User.js' +import Search from './models/Search.js' + +const { dbHost, dbPort, dbName, dbAuth, dbUser, dbPass } = process.env + +mongoose.connect(`mongodb://${dbHost}:${dbPort}/${dbName}`, { + user: dbUser, + pass: dbPass, + authSource: dbAuth, + useNewUrlParser: true, + useUnifiedTopology: true, + useFindAndModify: false, +}) + +const database = mongoose.connection + +database.on('error', (err) => { + throw err +}) + +database.once('open', () => { + console.info(`db: connected`) +}) + +// #### Tracks #### #### #### #### #### #### #### #### + +/** + * Fetch track data from database + * @param {String} id track id + * @returns {Promise<{}>} track data + */ +function getTrack(id) { + return new Promise((resolve, reject) => { + TrackModel.findOne({ id }) + .then((track) => { + if (track === null) return reject(new Error(`Tracks: ${id} not found`)) + resolve(track) + }) + .catch((err) => reject(err)) + }) +} + +/** + * Add track to database + * @param {Track} track new track + * @returns {Object} tdata + */ +function putTrack(track) { + return new Promise((resolve, reject) => { + TrackModel.create(track) + .then((tdata) => { + resolve(tdata) + }) + .catch((err) => reject(err)) + }) +} + +export { getTrack, putTrack } + +// #### Votes #### #### #### ######## #### #### #### + +/** + * Date range for valid tracks. + * Oldest a vote can be + * @type Date + */ +const timeValid = (() => { + switch (process.env.timeValid) { + default: + case 'monday': + var monday = new Date() + monday.setHours(0, 0, 0) + monday.setDate(monday.getDate() - ((monday.getDay() + 6) % 7)) + + return monday + case 'date': + let date = new Date(...JSON.parse(process.env.valid_date)) + return date + } +})() + +/** + * Fetch all valid votes for a track + * @param {String} tid track id + * @returns {Promise<[]>} array of votes + */ +function getVotes(tid) { + return new Promise((resolve, reject) => { + Vote.find({ tid, createdAt: { $gt: timeValid } }) + .then((votes) => { + resolve(votes) + }) + .catch((err) => reject(err)) + }) +} + +/** + * Get and count all votes for a track + * @param {String} tid + * @returns + */ +function countTrackVotes(tid) { + return new Promise((resolve, reject) => { + getVotes(tid) + .then((votes) => { + let up = 0, + down = 0 + + for (let vote of votes) { + vote.value == 'up' && up++ + vote.value == 'down' && down++ + } + + resolve({ + up, + down, + }) + }) + .catch((err) => reject(err)) + }) +} + +/** + * Get User's vote value for a track + * @param {String} tid Track id + * @param {String} uid User id + * @returns {Promise<{}>} user's Vote object + */ +function getUserVote(tid, uid) { + return new Promise((resolve, reject) => { + Vote.findOne({ + tid, + uid, + $or: [{ value: 'up' }, { value: 'down' }], + createdAt: { $gt: timeValid }, + }) + .then((vote) => resolve(vote)) + .catch((err) => reject(err)) + }) +} + +/** + * Update User's vote value for a track + * @param {String} tid Track id + * @param {String} uid User id + * @param {('up'|'down'|'report'|'')} value new vote value + * @returns {Promise} vote updated? + */ +function updateUserVote(tid, uid, value) { + return new Promise((resolve, reject) => { + // check if vote already exists + getUserVote(tid, uid) + .then((vote) => { + if (vote && (vote ?? {}).value != 'report') { + // vote exists + if (vote.value != value) { + // new value is different + Vote.updateOne({ _id: vote._id }, { value }) + .then((newVote) => { + // updated vote + resolve(!!newVote.ok) + }) + .catch((err) => reject(err)) + } else { + // unchanged value + resolve(true) + } + } else { + // create new vote + Vote.create({ uid, tid, value }) + .then((newVote) => { + // created vote + resolve(!!newVote) + }) + .catch((err) => reject(err)) + } + }) + .catch((err) => reject(err)) + }) +} + +/** + * Count votes per track and sort + * @returns {Promise<[]>} sorted array of Track ids + */ +function countAllVotes() { + return new Promise((resolve, reject) => { + Vote.find({ + createdAt: { $gt: timeValid }, + $or: [{ value: 'up' }, { value: 'down' }], + }) + .then((votes) => { + let results = {} + for (let { tid, value } of votes) { + value = { up: 1, down: -1 }[value] + + results[tid] ?? (results[tid] = 0) + + results[tid] += value + } + + const keysSorted = Object.keys(results).sort(function (a, b) { + return results[b] - results[a] + }) + + resolve(keysSorted) + }) + .catch((err) => reject(err)) + }) +} + +export { + timeValid, + getVotes, + countTrackVotes, + getUserVote, + updateUserVote, + countAllVotes, +} + +// #### Users #### #### #### #### #### #### #### #### + +/** + * Get User's data + * @param {String} id + * @returns {Promise<{}>} User data + */ +function getUser(id) { + return new Promise((resolve, reject) => { + User.findOne({ id }) + .then((user) => resolve(user)) + .catch((err) => reject(err)) + }) +} + +/** + * Create a new User + * @param {Object} user User data + * @param {String} user.id User's id + * @param {String} user.name User's display name + * @returns + */ +function putUser({ id, name, accessToken, tokenExpires }) { + return new Promise((resolve, reject) => { + User.create({ + id, + name, + accessToken, + tokenExpires, + banned: false, + perms: 0, + }) + .then((user) => resolve(user)) + .catch((err) => reject(err)) + }) +} + +export { getUser, putUser } + +// #### Search #### #### #### #### #### #### #### #### + +function getQuery(query, market) { + return new Promise((resolve, reject) => { + Search.findOne({ + query, + market, + createdAt: { $gt: new Date(new Date() - 36e5 * 24 * 2) }, + }) + .then((search) => resolve(search)) + .catch((err) => reject(err)) + }) +} + +function setQuery(data) { + return new Promise((resolve, reject) => { + Search.create(data) + .then((search) => resolve(search)) + .catch((err) => reject(err)) + }) +} + +export { getQuery, setQuery } diff --git a/package-lock.json b/package-lock.json index 125e60a..4b2d59b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4,6 +4,28 @@ "lockfileVersion": 1, "requires": true, "dependencies": { + "@ksolo/spotify-search": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@ksolo/spotify-search/-/spotify-search-1.0.0.tgz", + "integrity": "sha512-8Ud6chwN3FRqDgup7Fo2iHFcYzedp63cxvIrrqnt8PU74TzvKe4gKFwBv5O3H/skWONtrk3sz3X2HPO1Tg0s3Q==", + "requires": { + "axios": "^0.21.1", + "buffer": "^6.0.3" + } + }, + "@sindresorhus/is": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.2.0.tgz", + "integrity": "sha512-VkE3KLBmJwcCaVARtQpfuKcKv8gcBmUubrfHGF84dXuuW6jgsRYxPtzcIhPyK9WAPpRt2/xY6zkD9MnRaJzSyw==" + }, + "@szmarczak/http-timer": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/@szmarczak/http-timer/-/http-timer-4.0.6.tgz", + "integrity": "sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w==", + "requires": { + "defer-to-connect": "^2.0.0" + } + }, "@types/bson": { "version": "4.0.5", "resolved": "https://registry.npmjs.org/@types/bson/-/bson-4.0.5.tgz", @@ -12,6 +34,30 @@ "@types/node": "*" } }, + "@types/cacheable-request": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/@types/cacheable-request/-/cacheable-request-6.0.2.tgz", + "integrity": "sha512-B3xVo+dlKM6nnKTcmm5ZtY/OL8bOAOd2Olee9M1zft65ox50OzjEHW91sDiU9j6cvW8Ejg1/Qkf4xd2kugApUA==", + "requires": { + "@types/http-cache-semantics": "*", + "@types/keyv": "*", + "@types/node": "*", + "@types/responselike": "*" + } + }, + "@types/http-cache-semantics": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@types/http-cache-semantics/-/http-cache-semantics-4.0.1.tgz", + "integrity": "sha512-SZs7ekbP8CN0txVG2xVRH6EgKmEm31BOxA07vkFaETzZz1xh+cbt8BcI0slpymvwhx5dlFnQG2rTlPVQn+iRPQ==" + }, + "@types/keyv": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@types/keyv/-/keyv-3.1.3.tgz", + "integrity": "sha512-FXCJgyyN3ivVgRoml4h94G/p3kY+u/B86La+QptcqJaWtBWtmc6TtkNfS40n9bIvyLteHh7zXOtgbobORKPbDg==", + "requires": { + "@types/node": "*" + } + }, "@types/mongodb": { "version": "3.6.20", "resolved": "https://registry.npmjs.org/@types/mongodb/-/mongodb-3.6.20.tgz", @@ -26,6 +72,14 @@ "resolved": "https://registry.npmjs.org/@types/node/-/node-16.9.1.tgz", "integrity": "sha512-QpLcX9ZSsq3YYUUnD3nFDY8H7wctAhQj/TFKL8Ya8v5fMm3CFXxo8zStsLAl780ltoYoo1WvKUVGBQK+1ifr7g==" }, + "@types/responselike": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@types/responselike/-/responselike-1.0.0.tgz", + "integrity": "sha512-85Y2BjiufFzaMIlvJDvTTB8Fxl2xfLo4HgmHzVBz08w4wDePCTjYw66PdrolO0kzli3yam/YCgRufyo1DdQVTA==", + "requires": { + "@types/node": "*" + } + }, "accepts": { "version": "1.3.7", "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.7.tgz", @@ -45,6 +99,19 @@ "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=" }, + "axios": { + "version": "0.21.4", + "resolved": "https://registry.npmjs.org/axios/-/axios-0.21.4.tgz", + "integrity": "sha512-ut5vewkiu8jjGBdqpM44XxjuCjq9LAKeHVmoVfHVzy8eHgxxq8SbAVQNovDA8mVi05kP0Ea/n/UzcSHcTJQfNg==", + "requires": { + "follow-redirects": "^1.14.0" + } + }, + "base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==" + }, "bl": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/bl/-/bl-2.2.1.tgz", @@ -101,11 +168,44 @@ "resolved": "https://registry.npmjs.org/bson/-/bson-1.1.6.tgz", "integrity": "sha512-EvVNVeGo4tHxwi8L6bPj3y3itEvStdwvvlojVxxbyYfoaxJ6keLgrTuKdyfEAszFK+H3olzBuafE0yoh0D1gdg==" }, + "buffer": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", + "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", + "requires": { + "base64-js": "^1.3.1", + "ieee754": "^1.2.1" + } + }, + "buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk=" + }, "bytes": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz", "integrity": "sha512-zauLjrfCG+xvoyaqLoV8bLVXXNGC4JqlxFCutSDWA6fJrTo2ZuvLYTqZ7aHBLZSMOopbzwv8f+wZcVzfVTI2Dg==" }, + "cacheable-lookup": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/cacheable-lookup/-/cacheable-lookup-5.0.4.tgz", + "integrity": "sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA==" + }, + "cacheable-request": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/cacheable-request/-/cacheable-request-7.0.2.tgz", + "integrity": "sha512-pouW8/FmiPQbuGpkXQ9BAPv/Mo5xDGANgSNXzTzJ8DrKGuXOssM4wIQRjfanNRh3Yu5cfYPvcorqbhg2KIJtew==", + "requires": { + "clone-response": "^1.0.2", + "get-stream": "^5.1.0", + "http-cache-semantics": "^4.0.0", + "keyv": "^4.0.0", + "lowercase-keys": "^2.0.0", + "normalize-url": "^6.0.1", + "responselike": "^2.0.0" + } + }, "call-bind": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", @@ -115,6 +215,14 @@ "get-intrinsic": "^1.0.2" } }, + "clone-response": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/clone-response/-/clone-response-1.0.2.tgz", + "integrity": "sha1-0dyXOSAxTfZ/vrlCI7TuNQI56Ws=", + "requires": { + "mimic-response": "^1.0.0" + } + }, "combined-stream": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", @@ -170,6 +278,14 @@ "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==" }, + "cross-fetch": { + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-3.1.4.tgz", + "integrity": "sha512-1eAtFWdIubi6T4XPy6ei9iUFoKpUkIF971QLN8lIvvvwueI65+Nw5haMNKUwfJxabqlIIDODJKGrQ66gxC0PbQ==", + "requires": { + "node-fetch": "2.6.1" + } + }, "debug": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", @@ -178,6 +294,26 @@ "ms": "2.1.2" } }, + "decompress-response": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", + "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", + "requires": { + "mimic-response": "^3.1.0" + }, + "dependencies": { + "mimic-response": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", + "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==" + } + } + }, + "defer-to-connect": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/defer-to-connect/-/defer-to-connect-2.0.1.tgz", + "integrity": "sha512-4tvttepXG1VaYGrRibk5EwJd1t4udunSOVMdLSAL6mId1ix438oPwPZMALY41FCijukO1L0twNcGsdzS7dHgDg==" + }, "delayed-stream": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", @@ -203,6 +339,14 @@ "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-8.2.0.tgz", "integrity": "sha512-8sJ78ElpbDJBHNeBzUbUVLsqKdccaa/BXF1uPTw3GrvQTBgrQrtObr2mUrE38vzYd8cEv+m/JBfDLioYcfXoaw==" }, + "ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "requires": { + "safe-buffer": "^5.0.1" + } + }, "ee-first": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", @@ -213,6 +357,14 @@ "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", "integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=" }, + "end-of-stream": { + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz", + "integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==", + "requires": { + "once": "^1.4.0" + } + }, "escape-html": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", @@ -314,6 +466,11 @@ } } }, + "follow-redirects": { + "version": "1.14.4", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.4.tgz", + "integrity": "sha512-zwGkiSXC1MUJG/qmeIFH2HBJx9u0V46QGUe3YR1fXG8bXQxq7fLj0RjLZQ5nubr9qNJUZrH+xUcwXEoXNpfS+g==" + }, "form-data": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.1.tgz", @@ -354,6 +511,32 @@ "has-symbols": "^1.0.1" } }, + "get-stream": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz", + "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==", + "requires": { + "pump": "^3.0.0" + } + }, + "got": { + "version": "11.8.2", + "resolved": "https://registry.npmjs.org/got/-/got-11.8.2.tgz", + "integrity": "sha512-D0QywKgIe30ODs+fm8wMZiAcZjypcCodPNuMz5H9Mny7RJ+IjJ10BdmGW7OM7fHXP+O7r6ZwapQ/YQmMSvB0UQ==", + "requires": { + "@sindresorhus/is": "^4.0.0", + "@szmarczak/http-timer": "^4.0.5", + "@types/cacheable-request": "^6.0.1", + "@types/responselike": "^1.0.0", + "cacheable-lookup": "^5.0.3", + "cacheable-request": "^7.0.1", + "decompress-response": "^6.0.0", + "http2-wrapper": "^1.0.0-beta.5.2", + "lowercase-keys": "^2.0.0", + "p-cancelable": "^2.0.0", + "responselike": "^2.0.0" + } + }, "has": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", @@ -367,6 +550,16 @@ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==" }, + "himalaya": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/himalaya/-/himalaya-1.1.0.tgz", + "integrity": "sha512-LLase1dHCRMel68/HZTFft0N0wti0epHr3nNY7ynpLbyZpmrKMQ8YIpiOV77TM97cNpC8Wb2n6f66IRggwdWPw==" + }, + "http-cache-semantics": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.1.0.tgz", + "integrity": "sha512-carPklcUh7ROWRK7Cv27RPtdhYhUsela/ue5/jKzjegVvXDqM2ILE9Q2BGn9JZJh1g87cp56su/FgQSzcWS8cQ==" + }, "http-errors": { "version": "1.7.2", "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.7.2.tgz", @@ -386,6 +579,15 @@ } } }, + "http2-wrapper": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/http2-wrapper/-/http2-wrapper-1.0.3.tgz", + "integrity": "sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg==", + "requires": { + "quick-lru": "^5.1.1", + "resolve-alpn": "^1.0.0" + } + }, "iconv-lite": { "version": "0.4.24", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", @@ -394,6 +596,11 @@ "safer-buffer": ">= 2.1.2 < 3" } }, + "ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==" + }, "inherits": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", @@ -409,11 +616,100 @@ "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=" }, + "json-buffer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", + "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==" + }, + "jsonwebtoken": { + "version": "8.5.1", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-8.5.1.tgz", + "integrity": "sha512-XjwVfRS6jTMsqYs0EsuJ4LGxXV14zQybNd4L2r0UvbVnSF9Af8x7p5MzbJ90Ioz/9TI41/hTCvznF/loiSzn8w==", + "requires": { + "jws": "^3.2.2", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^5.6.0" + } + }, + "jwa": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.1.tgz", + "integrity": "sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==", + "requires": { + "buffer-equal-constant-time": "1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "jws": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz", + "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==", + "requires": { + "jwa": "^1.4.1", + "safe-buffer": "^5.0.1" + } + }, "kareem": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/kareem/-/kareem-2.3.2.tgz", "integrity": "sha512-STHz9P7X2L4Kwn72fA4rGyqyXdmrMSdxqHx9IXon/FXluXieaFA6KJ2upcHAHxQPQ0LeM/OjLrhFxifHewOALQ==" }, + "keyv": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.0.3.tgz", + "integrity": "sha512-zdGa2TOpSZPq5mU6iowDARnMBZgtCqJ11dJROFi6tg6kTn4nuUdU09lFyLFSaHrWqpIJ+EBq4E8/Dc0Vx5vLdA==", + "requires": { + "json-buffer": "3.0.1" + } + }, + "lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha1-YLuYqHy5I8aMoeUTJUgzFISfVT8=" + }, + "lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha1-bC4XHbKiV82WgC/UOwGyDV9YcPY=" + }, + "lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha1-YZwK89A/iwTDH1iChAt3sRzWg0M=" + }, + "lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha1-POdoEMWSjQM1IwGsKHMX8RwLH/w=" + }, + "lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha1-fFJqUtibRcRcxpC4gWO+BJf1UMs=" + }, + "lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha1-1SfftUVuynzJu5XV2ur4i6VKVFE=" + }, + "lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha1-DdOXEhPHxW34gJd9UEyI+0cal6w=" + }, + "lowercase-keys": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-2.0.0.tgz", + "integrity": "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA==" + }, "lru-cache": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", @@ -461,6 +757,11 @@ "mime-db": "1.44.0" } }, + "mimic-response": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-1.0.1.tgz", + "integrity": "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==" + }, "mongodb": { "version": "3.6.11", "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-3.6.11.tgz", @@ -549,6 +850,16 @@ "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.2.tgz", "integrity": "sha512-hZXc7K2e+PgeI1eDBe/10Ard4ekbfrrqG8Ep+8Jmf4JID2bNg7NvCPOZN+kfF574pFQI7mum2AUqDidoKqcTOw==" }, + "node-fetch": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.1.tgz", + "integrity": "sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw==" + }, + "normalize-url": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-6.1.0.tgz", + "integrity": "sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A==" + }, "object-inspect": { "version": "1.11.0", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.11.0.tgz", @@ -562,11 +873,24 @@ "ee-first": "1.1.1" } }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "requires": { + "wrappy": "1" + } + }, "optional-require": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/optional-require/-/optional-require-1.0.3.tgz", "integrity": "sha512-RV2Zp2MY2aeYK5G+B/Sps8lW5NHAzE5QClbFP15j+PWmP+T9PxlJXBOOLoSAdgwFvS4t0aMR4vpedMkbHfh0nA==" }, + "p-cancelable": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-2.1.1.tgz", + "integrity": "sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg==" + }, "parseurl": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", @@ -591,6 +915,15 @@ "ipaddr.js": "1.9.1" } }, + "pump": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", + "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", + "requires": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, "qs": { "version": "6.10.1", "resolved": "https://registry.npmjs.org/qs/-/qs-6.10.1.tgz", @@ -599,6 +932,11 @@ "side-channel": "^1.0.4" } }, + "quick-lru": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-5.1.1.tgz", + "integrity": "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==" + }, "range-parser": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", @@ -634,6 +972,19 @@ "resolved": "https://registry.npmjs.org/regexp-clone/-/regexp-clone-1.0.0.tgz", "integrity": "sha512-TuAasHQNamyyJ2hb97IuBEif4qBHGjPHBS64sZwytpLEqtBQ1gPJTnOaQ6qmpET16cK14kkjbazl6+p0RRv0yw==" }, + "resolve-alpn": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/resolve-alpn/-/resolve-alpn-1.2.1.tgz", + "integrity": "sha512-0a1F4l73/ZFZOakJnQ3FvkJ2+gSTQWz/r2KE5OdDY0TxPm5h4GkqkWWfM47T7HsbnOtcJVEF4epCVy6u7Q3K+g==" + }, + "responselike": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/responselike/-/responselike-2.0.0.tgz", + "integrity": "sha512-xH48u3FTB9VsZw7R+vvgaKeLKzT6jOogbQhEe/jewwnZgzPcnyWui2Av6JpoYZF/91uueC+lqhWqeURw5/qhCw==", + "requires": { + "lowercase-keys": "^2.0.0" + } + }, "safe-buffer": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", @@ -653,6 +1004,11 @@ "sparse-bitfield": "^3.0.3" } }, + "semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==" + }, "send": { "version": "0.17.1", "resolved": "https://registry.npmjs.org/send/-/send-0.17.1.tgz", @@ -740,6 +1096,32 @@ "memory-pager": "^1.0.2" } }, + "spotify-to-yt": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/spotify-to-yt/-/spotify-to-yt-1.0.5.tgz", + "integrity": "sha512-tjudSnTkTDR8eAqylVbo35BFp+ogYpFEkZxsjh59NXw7UvAJ87sZG5b0WroFjJ0XeAriMTj1A7ZDO2VABjRrwg==", + "requires": { + "@ksolo/spotify-search": "^1.0.0", + "spotify-uri": "^2.2.0", + "spotify-url-info": "^2.2.3", + "youtube-sr": "^4.1.5" + } + }, + "spotify-uri": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/spotify-uri/-/spotify-uri-2.2.0.tgz", + "integrity": "sha512-uUybj02bfyfCoZ0MJ80MkqbKxtIVRJfbRGk05KJFq1li3zb7yNfN1f+TAw4wcXgp7jLWExeiw2wyPQXZ8PHtfg==" + }, + "spotify-url-info": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/spotify-url-info/-/spotify-url-info-2.2.3.tgz", + "integrity": "sha512-cZTE5nOnaAjIiaHG9psVYqKXWOlNUIgSU2e+bNInRaYZNgmVgOcKH0D7V1nSER3gv3h5BXvOo0EJTtrMQQo1bA==", + "requires": { + "cross-fetch": "~3.1.4", + "himalaya": "~1.1.0", + "spotify-uri": "~2.2.0" + } + }, "spotify-web-api-node": { "version": "5.0.2", "resolved": "https://registry.npmjs.org/spotify-web-api-node/-/spotify-web-api-node-5.0.2.tgz", @@ -838,6 +1220,11 @@ "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", "integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw=" }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" + }, "ws": { "version": "8.2.2", "resolved": "https://registry.npmjs.org/ws/-/ws-8.2.2.tgz", @@ -847,6 +1234,14 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" + }, + "youtube-sr": { + "version": "4.1.7", + "resolved": "https://registry.npmjs.org/youtube-sr/-/youtube-sr-4.1.7.tgz", + "integrity": "sha512-OKbm+561Fq5RlnUtJBmPhnyfS6Zon44zdPhY1v/Y9vpAHzqdfxomD43yc0ZQv6zNsVzSlAkGeWhoweNd6DUUjQ==", + "requires": { + "node-fetch": "^2.6.1" + } } } } diff --git a/package.json b/package.json index d78308c..de49291 100644 --- a/package.json +++ b/package.json @@ -29,7 +29,10 @@ "cookie-parser": "^1.4.5", "dotenv": "^8.2.0", "express": "^4.17.1", + "got": "^11.8.2", + "jsonwebtoken": "^8.5.1", "mongoose": "^5.13.9", + "spotify-to-yt": "^1.0.5", "spotify-web-api-node": "^5.0.2", "ws": "^8.2.2" } diff --git a/routes/history.js b/routes/history.js deleted file mode 100644 index 8ab0976..0000000 --- a/routes/history.js +++ /dev/null @@ -1,17 +0,0 @@ -import express from 'express' - -const router = express.Router() - -router.get('/', (req, res) => { - res.send('Get tracks history information (IDs only)') -}) - -router.get('/next', (req, res) => { - res.send('next in queue') -}) - -router.get('/previous', (req, res) => { - res.send('x previous tracks') -}) - -export default router diff --git a/routes/login.js b/routes/login.js new file mode 100644 index 0000000..e258115 --- /dev/null +++ b/routes/login.js @@ -0,0 +1,69 @@ +import dotenv from 'dotenv' +import express from 'express' +import got from 'got' +import Jwt from 'jsonwebtoken' +import db from '../db.js' + +dotenv.config() + +const router = express.Router() + +const appId = process.env.fbAppId, + secret = process.env.fbSecret + +router.get('/token', ({ query: { code } }, res) => { + if (code === undefined) return res.status(400).end('Facebook code required') + if (code.length < 1) + return res.status(400).end('Facebook code needs to be of non zero length') + + got( + `https://graph.facebook.com/v12.0/oauth/access_token?client_id=${appId}&redirect_uri=${'https://radio.rolniknysa.pl/api/login/token'}&client_secret=${secret}&code=${code}` + ) + .json() + .then(({ access_token, expires_in }) => { + got(`https://graph.facebook.com/me?access_token=${access_token}`) + .json() + .then(({ name, id }) => { + const jwt = Jwt.sign( + { + name, + id, + }, + secret + ) + + res.end( + `Logowanie...` + ) + + db.users + .getUser(id) + .then((user) => { + if (user === null) + db.users.newUser({ + name, + id, + accessToken: access_token, + tokenExpires: new Date( + new Date().getTime() + expires_in * 1e3 + ), + }) + }) + .catch((err) => console.error(err)) + }) + .catch((err) => { + res + .status(400) + .end('There was an error processing your profile information') + console.error(err) + }) + }) + .catch((err) => { + res.status(400).end('There was an error requesting an access token') + console.error(err) + }) +}) + +export default router diff --git a/routes/search.js b/routes/search.js index 65dc806..16aad46 100644 --- a/routes/search.js +++ b/routes/search.js @@ -1,20 +1,22 @@ import express from 'express' - -import { byQuery } from '../spotify.js' +import db from '../db.js' const router = express.Router() -router.get('/', (req, res) => { - res.send('Query search') -}) +router.get('/track/:query?', ({ params: { query } }, res) => { + if (query === undefined) return res.status(400).end('Track ID required') + if (query.length < 1) return res.status(400).end('Track ID invalid') -router.get('/track/:query', (req, res) => { - byQuery(req.params.query).then(({ tracks, total }) => { - res.send({ - tracks, - total, + let time = process.hrtime() + db.search + .query(query) + .then(({ tids, total }) => + res.send({ tids, total, elapsed: process.hrtime(time) }) + ) + .catch((err) => { + res.status(500).end('There was an error retrieving track data') + console.error(err) }) - }) }) export default router diff --git a/routes/track.js b/routes/track.js index 1bf70d9..81a66ed 100644 --- a/routes/track.js +++ b/routes/track.js @@ -1,28 +1,36 @@ import express from 'express' -import { byId } from '../spotify.js' import db from '../db.js' +import Track from '../Track.js' const router = express.Router() -router.get('/', (req, res) => { - res.send('Get track metadata.') +router.post('/batch/', ({ body: { tids } }, res) => { + if (tids === undefined) return res.status(400).end('Track ids array required') + if (tids.length < 1) return res.end([]) + + Promise.all(tids.map((tid) => db.tracks.get(tid))) + .then((tracks) => res.send(tracks)) + .catch((err) => { + res.status(500).end('There was an error fetching tracks ') + console.error(err) + }) }) -router.get('/:id', (req, res) => { - if (req.query.votes) { - return res.send({ - set: 'down', - up: 20, - down: 10, - }) - } +router.get('/:id?', ({ params: { id } }, res) => { + if (id === undefined) return res.status(400).end('Track ID required') + if (id.length < Track.idMinLength) + return res.status(400).end('Track ID too short') db.tracks - .get(req.params.id) + .get(id) .then((track) => res.send(track)) .catch((err) => { - res.status(400).end() + if ((err.name = 'DbErrorNotFound')) + return res.status(404).end(err.message) + else res.status(500).end('There was an error fetching track data') + + console.error(err) }) }) diff --git a/routes/vote.js b/routes/vote.js index 0806a8a..edebe21 100644 --- a/routes/vote.js +++ b/routes/vote.js @@ -1,29 +1,130 @@ import express from 'express' import db from '../db.js' +import Track from '../Track.js' const router = express.Router() -router.get('/', (req, res) => { - res.send('Vote for track.') -}) +// get multiple track stats +router.post( + '/batch/', + async ({ body: { tids }, headers: { authorization } }, res) => { + var udata = false -router.get('/:id/', ({ params }, res) => { - db.votes.getTrackStats(params.id).then((stats) => { - res.send(stats) - }) -}) + if (authorization) { + if (authorization.length < 1) + return res.status(400).end('Access token empty') -router.get('/:id/cast', ({ params, query }, res) => { - db.votes.getUserTrack(params.id, query.uid).then((vote) => { - res.send(vote ? vote.value : '') - }) -}) + try { + udata = await db.users.verifyJwt(authorization) + } catch (err) { + return res.status(400).end('Access token invalid') + } + } -router.patch('/:id/', ({ params, body }, res) => { - db.votes.putUserTrack(params.id, body.uid, body.value).then((vote) => { - res.end(JSON.stringify(vote)) - }) -}) + if (tids === undefined) + return res.status(400).end('List of Track ids required') + if (tids.length < 1) return res.end([]) + + Promise.all([ + Promise.all(tids.map((tid) => db.votes.getTrackStats(tid))), + udata && + Promise.all(tids.map((tid) => db.votes.getUserTrack(tid, udata.id))), + ]) + .then(([stats, votes]) => { + if (udata && votes) + stats = stats.map((stat, i) => ({ + ...stat, + cast: votes[i]?.value ?? '', + })) + + res.send(stats) + }) + .catch((err) => { + res.status(500).end('There was an error while fetching some stats') + console.error(err) + }) + } +) + +// get tracks stats +router.get( + '/:tid/', + async ({ params: { tid }, headers: { authorization } }, res) => { + var udata = false + + if (authorization) { + if (authorization.length < 1) + return res.status(400).end('Access token empty') + + try { + udata = await db.users.verifyJwt(authorization) + } catch (err) { + return res.status(400).end('Access token invalid') + } + } + + if (tid === undefined) return res.status(400).end('Track ID required') + + if (tid.length < Track.idMinLength) + return res.status(400).end('Track ID too short') + + Promise.all([ + db.votes.getTrackStats(tid), + udata && db.votes.getUserTrack(tid, udata.id), + ]) + .then(([stats, vote]) => { + // attatch user's vote if authorized + if (udata) stats.cast = vote ? vote.value : '' // null vote counts as empty + + res.send(stats) + }) + .catch((err) => { + res.status(500).end('There was an error getting stats') + console.error(err) + }) + } +) + +// update users vote +router.patch( + '/:tid/', + ({ params: { tid }, body: { value }, headers: { authorization } }, res) => { + if (authorization === undefined) + return res.status(401).end('Access token required') + + if (authorization.length < 1) + return res.status(400).end('Access token invalid') + + if (tid === undefined) return res.status(400).end('Track ID required') + + if (tid.length < Track.idMinLength) + return res.status(400).end('Track ID too short') + + if (value === undefined) return res.status(400).end('Vote value required') + + if (!['up', 'down', '', 'report'].includes(value)) + return res.status(400).end('Invalid vote value') + + db.users + .verifyJwt(authorization) + .then(({ id }) => { + db.votes + .putUserTrack(tid, id, value) + .then((ok) => { + res.end(ok.toString()) + console.info(`vote# ${id} ${value} ${tid}`) + }) + .catch((err) => { + res.status(500).end('There was an error updating your vote') + console.error(err) + }) + }) + .catch((err) => { + res.end('false') + console.error(err) + }) + } +) export default router diff --git a/socket.js b/socket.js index 572631a..4484d1b 100644 --- a/socket.js +++ b/socket.js @@ -1,12 +1,13 @@ import dotenv from 'dotenv' import WebSocket, { WebSocketServer } from 'ws' +import db from './db.js' dotenv.config() const port = process.env.portWs, wss = new WebSocketServer({ port: port }) -console.log('ws: listening on ' + port) +console.info('ws: listening on ' + port) function broadcast(data) { wss.clients.forEach((client) => { @@ -16,8 +17,8 @@ function broadcast(data) { }) } -wss.on('connection', function connection(ws) { - console.log('connected') +wss.on('connection', async function connection(ws, req) { + console.info(`socket # ${req.headers['x-real-ip']} + `) function send(data) { ws.send(JSON.stringify(data)) @@ -35,11 +36,8 @@ wss.on('connection', function connection(ws) { }, { cat: 'top', - trackids: [ - '0VdSlJ7owUK1MuS8Kp7LdE', - '5svu5mLA4U2kdxPj1tLJ2I', - '6BfbSHE9ytCTF910g3wNdj', - ], + trackids: await db.top.get(), + timestamp: db.top.lastCount, }, { cat: 'status', @@ -49,13 +47,11 @@ wss.on('connection', function connection(ws) { }, ]) - ws.on('message', (message) => { - console.log('received: %s', message) - }) + ws.on('message', (message) => console.info('received: %s', message)) - ws.on('close', (message) => { - console.log('disconnected') - }) + ws.on('close', (message) => + console.info(`socket # ${req.headers['x-real-ip']} - `) + ) }) export { wss, broadcast } diff --git a/spotify.js b/spotify.js index c746a59..c989346 100644 --- a/spotify.js +++ b/spotify.js @@ -7,59 +7,66 @@ const spotify = new SpotifyWebApi({ clientSecret: '13858e98eb264cf78251072f2ea5e96d', }) -spotify.clientCredentialsGrant().then( - function (data) { - console.log('Spotify: access token granted') +function grantToken() { + spotify + .clientCredentialsGrant() + .then( + function ({ body: { access_token, expires_in } }) { + console.info('spotify: access token granted ' + expires_in) - // Save the access token so that it's used in future calls - spotify.setAccessToken(data.body['access_token']) - }, - function (err) { - throw err - } -) + spotify.setAccessToken(access_token) + + setTimeout(grantToken, expires_in * 1e3) + }, + function (err) { + throw err + } + ) + .catch((err) => { + console.error(err) + }) +} + +grantToken() function byId(id) { return new Promise((resolve, reject) => { if (typeof id != 'string') return reject(new Error('Incorrect id, must by type String')) - if (id.length < 22) return reject(new Error('Id too short')) + if (id.length < Track.idMinLength) return reject(new Error('Id too short')) spotify .getTrack(id) .then(({ body }) => { - let tdata = { - ...body, - title: body.name, - artists: body.artists.map((a) => a.name), - album: { - name: body.album.name, - art: body.album.images[0].url, - year: body.album.release_date.slice(0, 4), - }, - duration: body.duration_ms, - } - resolve(new Track(tdata)) - }) - .catch((err) => { - reject(err) + resolve( + new Track({ + ...body, + title: body.name, + artists: body.artists.map((a) => a.name), + album: { + name: body.album.name, + art: body.album.images[0].url, + year: body.album.release_date.slice(0, 4), + }, + duration: body.duration_ms, + }) + ) }) + .catch((err) => reject(err)) }) } function byQuery(query) { return new Promise((resolve, reject) => { spotify - .searchTracks(query) + .searchTracks(query, { market: 'PL' }) .then((response) => { resolve({ - tracks: response.body.tracks.items.map((tdata) => tdata.id), + tids: response.body.tracks.items.map((tdata) => tdata.id), total: response.body.tracks.total, }) }) - .catch((err) => { - reject(err) - }) + .catch((err) => reject(err)) }) }