45 Commits
Author SHA1 Message Date
Mateusz Pstrucha 1fb6a7608e feat: working docker 2022-04-19 17:28:28 +02:00
Mateusz Pstrucha 6e55829908 refactor: move to yarn 2022-04-19 17:28:17 +02:00
Mateusz Pstrucha 24773df6bf feat: env defaults 2022-04-19 17:27:34 +02:00
Mateusz Pstrucha 6273dd4b3b feat: codes handling 2021-11-09 07:49:01 +01:00
Mateusz Pstrucha 8c6d5d23d0 refactor: separate mongo functions 2021-11-09 07:48:37 +01:00
Mateusz Pstrucha 1bc3fb8008 fix: stale value 2021-11-03 23:48:06 +01:00
Mateusz Pstrucha 4680aaeba6 feat: persistent track history 2021-11-03 23:00:31 +01:00
Mateusz Pstrucha 4ce16a20ad fix: use the morning date 2021-10-28 09:27:48 +02:00
Mateusz Pstrucha 54dec17ef1 Merge branch 'finishing' of github.com:Maathias/radio-rolnik-api into finishing 2021-10-28 09:05:51 +02:00
Mateusz Pstrucha b3bc6942ed feat: static top list for player 2021-10-28 09:04:57 +02:00
Mateusz Pstrucha 6b64955eac feat: static top list for player 2021-10-28 09:03:17 +02:00
Mateusz Pstrucha 260007ca5b refactor: remove dotenv.config from imported files 2021-10-23 16:22:12 +02:00
Mateusz Pstrucha 4dba724336 refactor: move track resolving to player 2021-10-21 01:29:54 +02:00
Mateusz Pstrucha 8c2034ce5b feat: better readme 2021-10-21 01:29:24 +02:00
Mateusz Pstrucha 21ed1e3c20 feat: add admin routes,
fixed: top updates
2021-10-20 02:22:34 +02:00
Mateusz Pstrucha 2caf7d2e9b fix: login not closing 2021-10-19 22:15:55 +02:00
Mateusz Pstrucha 744c6af92c fix: env names, something else 2021-10-05 11:54:13 +02:00
Mateusz Pstrucha 304757862a Merge pull request #11 from Maathias/player-endpoints
Player endpoints
2021-09-29 00:43:46 +02:00
Mateusz Pstrucha ff1215127b feat: dynamic states updates on /player 2021-09-29 00:42:45 +02:00
Mateusz Pstrucha ebef81eda3 feat: better states broadcast 2021-09-29 00:42:26 +02:00
Mateusz Pstrucha 899aa3abc2 feat: more album art urls 2021-09-29 00:40:39 +02:00
Mateusz Pstrucha bc5c9aa29a fix: remove hardcoded api keys (ups) 2021-09-29 00:38:57 +02:00
Mateusz Pstrucha 353a88bc9c fix: change res.end to .json 2021-09-29 00:37:57 +02:00
Sebastian Fudalej 390dac6dc1 Merge pull request #10 from Maathias/redis
feat: add redis for cache
2021-09-26 22:16:05 +02:00
sebafudi b08ef20da2 feat: add redis for cache 2021-09-26 22:15:29 +02:00
Sebastian Fudalej 8faf99de37 Merge pull request #9 from Maathias/docker
Docker
2021-09-25 13:04:30 +02:00
sebafudi 79501a700a fix: recreated package-lock 2021-09-25 13:04:14 +02:00
Sebastian Fudalej 31bac16737 Merge branch 'master' into docker 2021-09-25 13:02:12 +02:00
sebafudi 757a65884d build: dev container now starts up db 2021-09-25 12:57:28 +02:00
sebafudi 138d10de16 feat: add devcontainer 2021-09-24 22:48:12 +02:00
Sebastian Fudalej bbd950fc46 Merge pull request #8 from Maathias/docker
fix: docker networking
2021-09-23 21:57:59 +02:00
sebafudi 830a7175f5 fix: docker networking 2021-09-23 21:49:59 +02:00
Mateusz Pstrucha 490d097e01 Merge pull request #7 from Maathias/db-refactor
feat: some.. changes...
2021-09-23 00:17:24 +02:00
Mateusz Pstrucha 17ab445bb0 feat: some.. changes... 2021-09-23 00:17:06 +02:00
Mateusz Pstrucha 0650c278ae Merge pull request #6 from Maathias/db
Db
2021-09-13 21:47:15 +02:00
Mateusz Pstrucha 51694245ae Merge pull request #5 from Maathias/sockets
feat: dynamically send updates with ws
2021-09-13 21:46:57 +02:00
Mateusz Pstrucha 3f25547362 feat: voting 2021-09-13 21:44:56 +02:00
Mateusz Pstrucha af9934d476 refactor: Track class 2021-09-13 21:44:45 +02:00
Mateusz Pstrucha 27e76f7270 misc: add vscode settings 2021-09-13 21:43:02 +02:00
Mateusz Pstrucha 102ce46727 feat: add db 2021-09-13 21:42:00 +02:00
Mateusz Pstrucha e2bb5fc87a feat: dynamically send updates with ws 2021-09-10 20:40:55 +02:00
Mateusz Pstrucha 1535747758 Create CNAME 2021-09-08 23:12:43 +02:00
Sebastian Fudalej e5c275eefd Merge pull request #4 from Maathias/api-documentation
fix: change /track/:id from integer to string
2021-09-08 23:02:07 +02:00
Sebastian Fudalej 11c6a50104 Merge pull request #3 from Maathias/api-documentation
docs: full api documentation and Swagger UI
2021-09-08 22:54:56 +02:00
Sebastian Fudalej d078efa23b Merge pull request #2 from Maathias/api-documentation
docs: basic /track endpoint
2021-09-08 19:11:08 +02:00
42 changed files with 3746 additions and 1076 deletions

No files matched your search

+41
View File
@@ -0,0 +1,41 @@
// For format details, see https://aka.ms/devcontainer.json. For config options, see the README at:
// https://github.com/microsoft/vscode-dev-containers/tree/v0.194.0/containers/docker-existing-docker-compose
// If you want to run as a non-root user in the container, see .devcontainer/docker-compose.yml.
{
"name": "Existing Docker Compose (Extend)",
// Update the 'dockerComposeFile' list if you have more compose files or use different names.
// The .devcontainer/docker-compose.yml file contains any overrides you need/want to make.
"dockerComposeFile": ["../docker-compose.yml", "docker-compose.yml"],
// The 'service' property is the name of the service for the container that VS Code should
// use. Update this value and .devcontainer/docker-compose.yml to the real service name.
"service": "api",
// The optional 'workspaceFolder' property is the path VS Code should open by default when
// connected. This is typically a file mount in .devcontainer/docker-compose.yml
"workspaceFolder": "/workspace",
// Set *default* container specific settings.json values on container create.
"settings": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
// Add the IDs of extensions you want installed when the container is created.
"extensions": ["dbaeumer.vscode-eslint", "esbenp.prettier-vscode"]
// Use 'forwardPorts' to make a list of ports inside the container available locally.
// "forwardPorts": [],
// Uncomment the next line if you want start specific services in your Docker Compose config.
// "runServices": [],
// Uncomment the next line if you want to keep your containers running after VS Code shuts down.
// "shutdownAction": "none",
// Uncomment the next line to run commands after the container is created - for example installing curl.
// "postCreateCommand": "apt-get update && apt-get install -y curl",
// Uncomment to connect as a non-root user if you've added one. See https://aka.ms/vscode-remote/containers/non-root.
// "remoteUser": "vscode"
}
+38
View File
@@ -0,0 +1,38 @@
version: '3.1'
services:
# Update this to the name of the service you want to work with in your docker-compose.yml file
api:
# If you want add a non-root user to your Dockerfile, you can use the "remoteUser"
# property in devcontainer.json to cause VS Code its sub-processes (terminals, tasks,
# debugging) to execute as the user. Uncomment the next line if you want the entire
# container to run as this user instead. Note that, on Linux, you may need to
# ensure the UID and GID of the container user you create matches your local user.
# See https://aka.ms/vscode-remote/containers/non-root for details.
#
# user: vscode
# Uncomment if you want to override the service's Dockerfile to one in the .devcontainer
# folder. Note that the path of the Dockerfile and context is relative to the *primary*
# docker-compose.yml file (the first in the devcontainer.json "dockerComposeFile"
# array). The sample below assumes your primary file is in the root of your project.
#
# build:
# context: .
# dockerfile: .devcontainer/Dockerfile
volumes:
# Update this to wherever you want VS Code to mount the folder of your project
- .:/workspace:cached
# Uncomment the next line to use Docker from inside the container. See https://aka.ms/vscode-remote/samples/docker-from-docker-compose for details.
# - /var/run/docker.sock:/var/run/docker.sock
# Uncomment the next four lines if you will use a ptrace-based debugger like C++, Go, and Rust.
# cap_add:
# - SYS_PTRACE
# security_opt:
# - seccomp:unconfined
# Overrides default command so things don't shut down after the process ends.
command: /bin/sh -c "while sleep 1000; do :; done"
+12
View File
@@ -0,0 +1,12 @@
.git
node_modules
data
build
.vscode
.github
DockerFile
.dockerignore
.prettierrc
.gitignore
+4 -2
View File
@@ -1,5 +1,7 @@
node_modules/
*cred.json
.vscode/
.env
old/
.env.*
*.env
old/
data/
+7
View File
@@ -0,0 +1,7 @@
{
"search.exclude": {
"**/.git": true,
"**/node_modules": true,
"**/docs": true,
}
}
+7
View File
@@ -0,0 +1,7 @@
FROM node:16
WORKDIR /app
COPY package.json yarn.lock ./
RUN yarn install
COPY . .
ENV NODE_ENV production
CMD ["yarn", "start"]
+218 -26
View File
@@ -2,13 +2,77 @@
Backend server for radio-rolnik
## Resources
Website - https://github.com/Maathias/radio-rolnik/
Player - https://github.com/Maathias/radio-rolnik-player/
## .env
Enviroment variables required
### Ports and domains
```ini
HTTP_PORT=3010
HTTP_DOMAIN=radio.rolniknysa.pl
WS_PORT=3020
```
### Spotify API
```ini
SPOTIFY_CLIENT_ID=<ID>
SPOTIFY_CLIENT_SECRET=<SECRET>
```
### Facebok API
```ini
FB_APPID=<ID>
FB_SECRET=<SECRET>
```
### Mongo DB
```ini
DB_HOST=<IP>
DB_PORT=<PORT>
DB_NAME=<DB>
DB_AUTH=<COLL>
DB_USER=<USER>
DB_PASS=<PASSWORD>
```
### Redis Cache
```ini
CACHE_HOST=<IP>
CACHE_PORT=6379
```
### Other
```ini
PLAYER_SECRET=<SECRET>
TOP_TIME_VALID=<monday,date,period>
TOP_TIME_VALUE=<VALUE?>
```
## Routes
### `/track`
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 +95,178 @@ 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
<body>
Logowanie...
</body>
<script>
window.onload = function () {
opener.exit('<ACCESS TOKEN>')
}
</script>
```
---
+7 -16
View File
@@ -1,27 +1,18 @@
class Track {
constructor(data) {
console.log(data)
this.id = data.id
this.title = data.name
this.title = data.title
this.artists = data.artists.map((a) => a.name)
this.artists = data.artists
this.album = {
name: data.album.name,
art: data.album.images[0].url,
year: data.album.release_date.slice(0, 4),
}
this.album = data.album
this.duration = data.duration_ms
this.duration = data.duration
this.explicit = data.explicit
this.banned = false
this.votes = {
up: 100,
down: 50,
rank: 1,
}
this.banned = data.banned ?? false
}
static idMinLength = 22
}
export default Track
+336 -1
View File
@@ -1,3 +1,338 @@
var db = {}
import Jwt from 'jsonwebtoken'
import {
timeValid,
countTrackVotes,
getUserVote,
updateUserVote,
countAllVotes,
} from './mongo/votes.js'
import {
getPrevious,
allPrevious,
countPrevious,
putPrevious,
} from './mongo/previous.js'
import { getQuery, setQuery } from './mongo/search.js'
import { getTrack, putTrack, updateTrack } from './mongo/tracks.js'
import { getUser, putUser } from './mongo/users.js'
import { getCode } from './mongo/codes.js'
import redis from './redis.js'
import { byId, byQuery } from './spotify.js'
import Track from './Track.js'
import { broadcast as wsBroadcast } from './socket.js'
import { DbError } from './errors.js'
import env from './env.js'
const { FB_SECRET } = env
/**
* 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 parseTop(results) {
return new Promise(async (resolve, reject) => {
for (let tid in results) {
let track = await getTrack(tid)
if (results[tid] < 0) delete results[tid] // remove negative for negative points
if (track.banned) delete results[tid] // remove banned
let count = await countPrevious(tid, timeValid()) // count previous plays
if (count > 0) results[tid] = parseInt(results[tid] / (count + 1)) // halve points for every previous playback
}
const tids = Object.keys(results).sort(function (a, b) {
return results[b] - results[a]
})
resolve(tids)
})
}
function broadcast(cats) {
wsBroadcast(cats.map((cat) => ({ cat, ...current[cat] })))
}
export { getTrackRank, parseTop }
const maxPrevious = 20,
staleTop = 60e3,
staleAfterVotes = 2
var topList = await countAllVotes().then((results) => parseTop(results)),
lastTop = -1,
votesSince = 0
const current = {
next: { tid: null },
status: {
tid: null,
progress: 0,
duration: 0,
paused: true,
timestamp: new Date(),
},
previous: {
combo: (await allPrevious())
.slice(0, maxPrevious)
.map(({ tid, timestamp }) => [tid, timestamp]),
},
}
const db = {
/**
* Methods for Track data
*/
tracks: {
/**
* Get track by id.
* DB first, then online
* @param {String} id Track id
* @returns {Promise<Track>} Track object
*/
get: (id) => {
return new Promise((resolve, reject) => {
// try to find in redis
redis.get(id).then((data) => {
if (data) {
resolve(JSON.parse(data))
} else {
// if not found, query db
getTrack(id)
.then((tdata) => {
redis.set(id, JSON.stringify(tdata))
resolve(new Track(tdata))
})
.catch((dbErr) => {
// track not found in DB, fetch online
byId(id)
.then((track) => {
putTrack(track).then((tdata) => redis.set(id, tdata))
resolve(track)
})
.catch((spotifyErr) => {
reject(
new DbError('DbErrorNotFound', `Could not retrieve track`)
)
})
})
}
})
})
},
},
votes: {
/**
* 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: (...params) => {
return updateUserVote(...params).then((ok) => {
if (ok) votesSince++
return ok
})
},
},
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 ?? '', FB_SECRET, (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 and Fresh flag
*/
get: () => {
return new Promise((resolve, reject) => {
let now = new Date().getTime()
// update if stale
if (now - lastTop > staleTop || votesSince >= staleAfterVotes) {
countAllVotes()
.then((results) => parseTop(results))
.then((top) => {
topList = top // update the list
lastTop = now // update list timestamp
votesSince = 0 // reset number of votes since recount
resolve({ top, fresh: true })
})
.catch((err) => reject(err))
} else resolve({ top: topList, fresh: false })
})
},
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))
})
},
},
current: {
currentTimer: null,
get status() {
return current.status
},
set status(chunk) {
if (current.status.tid != chunk?.tid && current.status.tid) {
// skip duplicates
let last = current.previous.combo[0] ?? [null]
if (last[0] !== current.status.tid) {
const { tid, timestamp } = current.status
current.previous.combo.unshift([tid, timestamp])
putPrevious(tid, timestamp)
// pop on overfill
if (current.previous.combo.length > maxPrevious)
current.previous.combo.pop()
// broadcast change
broadcast(['previous'])
}
}
current.status = { ...current.status, ...chunk, timestamp: new Date() }
clearInterval(this.currentTimer)
let timer = (this.currentTimer = setInterval(() => {
if (current.status.progress + 1e3 > current.status.duration) {
current.status.progress = current.status.duration
return clearInterval(timer)
}
if (!current.status.paused) current.status.progress += 1e3
}, 1e3))
},
get next() {
return current.next
},
set next(chunk) {
current.next = chunk
},
get previous() {
return current.previous
},
set top(chunk) {
current.top = chunk
},
update(data) {
if (!Array.isArray(data)) data = [data]
for (let { cat, content } of data) {
this[cat] = content
}
broadcast(data.map((chunk) => chunk.cat))
},
},
admin: {
ban: (tid) => {
return new Promise((resolve, reject) => {
updateTrack(tid, { banned: true })
.then((status) => {
getTrack(tid).then((tdata) => redis.set(tid, tdata))
resolve(status.nModified === 1)
})
.catch((err) => resolve(false))
})
},
},
previous: {
put: putPrevious,
get: getPrevious,
count: countPrevious,
},
}
export default db
+50
View File
@@ -0,0 +1,50 @@
version: '3.1'
services:
api:
build: .
container_name: radio-rolnik_api
image: radio-rolnik/api
restart: always
depends_on:
- mongo
- redis
links:
- mongo
- redis
environment:
HTTP_PORT: 3010
WS_PORT: 3020
DB_HOST: mongo
DB_NAME: api
DB_USER: radio-rolnikcred
DB_PASS: radio-rolnikcred
CACHE_HOST: redis
ports:
- 3010:3010
- 3020:3020
mongo:
image: mongo:5.0
container_name: radio-rolnik_mongo
restart: always
volumes:
- ./data/mongo:/data/db
command:
- '--logpath'
- '/var/log/mongodb/mongod.log'
environment:
MONGO_INITDB_ROOT_USERNAME: radio-rolnikcred
MONGO_INITDB_ROOT_PASSWORD: radio-rolnikcred
redis:
image: redis:6.2-alpine
container_name: radio-rolnik_redis
restart: always
environment:
ALLOW_EMPTY_PASSWORD: 'yes'
+1
View File
@@ -0,0 +1 @@
docs.radio-rolnik.mtps.pl
+45
View File
@@ -0,0 +1,45 @@
import dotenv from 'dotenv'
const NODE_ENV = process.env.NODE_ENV,
dotfile = {
production: '.env',
development: '.dev.env',
}[NODE_ENV ?? 'production']
console.info(`env: ${NODE_ENV}`)
const config = dotenv.config({ path: `./${dotfile}` })
if (config.error) throw `enviroment file ${dotfile} not found`
const env = {
HTTP_PORT: -1,
HTTP_DOMAIN: '',
WS_PORT: -1,
SPOTIFY_CLIENT_ID: '',
SPOTIFY_CLIENT_SECRET: '',
DB_HOST: '',
DB_PORT: 27017,
DB_AUTH: 'admin',
DB_NAME: '',
DB_USER: '',
DB_PASS: '',
PLAYER_SECRET: '',
TOP_TIME_VALID: 'period',
TOP_TIME_VALUE: 604800,
FB_APPID: '',
FB_SECRET: '',
CACHE_HOST: '',
CACHE_PORT: 6379,
}
for (let key in env) {
process.env[key] && (env[key] = env[key].constructor(process.env[key]))
}
export default env
+8
View File
@@ -0,0 +1,8 @@
class DbError extends Error {
constructor(name, message, ...args) {
super(message, ...args)
this.name = name ?? 'DbError'
}
}
export { DbError }
+44 -16
View File
@@ -1,43 +1,71 @@
import dotenv from 'dotenv'
import env from './env.js'
import express, { json, urlencoded } from 'express'
import { join } from 'path'
import cookieParser from 'cookie-parser'
import { createServer } from 'http'
import fs from 'fs'
import db from './db.js'
import { byId } from './spotify.js'
import track from './routes/track.js'
import status from './routes/status.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'
import player from './routes/player.js'
import admin from './routes/admin.js'
import code from './routes/code.js'
dotenv.config()
import database from './mongo.js'
const { HTTP_PORT } = env
database.on('error', (err) => {
throw err
})
database.once('open', () => {
console.info(`mongo: connected`)
})
var app = express(),
www = createServer(app)
http = createServer(app)
app.use(json())
app.use(urlencoded({ extended: false }))
app.use(cookieParser())
app.set('port', process.env.port)
app.set('port', HTTP_PORT)
app.use('/track', track)
app.use('/status', status)
app.use('/history', history)
app.use('/search', search)
app.use('/vote', vote)
app.use('/login', login)
app.use('/player', player)
app.use('/admin', admin)
app.use('/code', code)
www.listen(process.env.port)
http.listen(HTTP_PORT)
www.on('error', function (error) {
http.on('error', function (error) {
if (error.syscall !== 'listen') {
throw error
}
console.log(`Error: port ${process.env.port}: ${error.code}`)
console.info(`Error: port ${HTTP_PORT}: ${error.code}`)
})
www.on('listening', function () {
console.log(`www: listening on ${process.env.port}`)
http.on('listening', function () {
console.info(`http: listening on ${HTTP_PORT}`)
})
setInterval(() => {
db.top.get().then(({ top, fresh }) => {
if (fresh) {
db.current.update({
cat: 'top',
content: {
tids: top,
timestamp: db.top.lastCount,
},
})
}
})
}, 2e3)
+23
View File
@@ -0,0 +1,23 @@
import mongoose from 'mongoose'
const code = new mongoose.Schema(
{
value: String,
type: String,
claimed: Boolean,
claimedAt: Date,
used: Boolean,
usedAt: Date,
checked: Number,
uid: String,
},
{
collection: 'codes',
timestamps: { createdAt: 'createdAt', updatedAt: 'updatedAt' },
}
)
const Code = mongoose.model('Code', code)
export default Code
export { Code, code }
+17
View File
@@ -0,0 +1,17 @@
import mongoose from 'mongoose'
const prev = new mongoose.Schema(
{
tid: String,
timestamp: Date,
},
{
collection: 'previous',
timestamps: { createdAt: 'createdAt', updatedAt: 'updatedAt' },
}
)
const Prev = mongoose.model('Prev', prev)
export default Prev
export { Prev, prev }
+19
View File
@@ -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 }
+26
View File
@@ -0,0 +1,26 @@
import mongoose from 'mongoose'
const track = new mongoose.Schema(
{
id: String,
title: String,
artists: [String],
album: {
name: String,
art: Array,
year: Number,
},
duration: Number, // milliseconds
explicit: Boolean,
banned: Boolean,
},
{
collection: 'tracks',
timestamps: { createdAt: 'createdAt', updatedAt: 'updatedAt' },
}
)
const Track = mongoose.model('Track', track)
export default Track
export { Track, track }
+21
View File
@@ -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 }
+18
View File
@@ -0,0 +1,18 @@
import mongoose from 'mongoose'
const vote = new mongoose.Schema(
{
uid: String,
tid: String,
value: String,
},
{
collection: 'votes',
timestamps: { createdAt: 'createdAt', updatedAt: 'updatedAt' },
}
)
const Vote = mongoose.model('Vote', vote)
export default Vote
export { Vote, vote }
+17
View File
@@ -0,0 +1,17 @@
import env from './env.js'
import mongoose from 'mongoose'
const { DB_HOST, DB_PORT, DB_NAME, DB_AUTH, DB_USER, DB_PASS } = env
mongoose.connect(`mongodb://${DB_HOST}:${DB_PORT}/${DB_NAME}`, {
user: DB_USER,
pass: DB_PASS,
authSource: DB_AUTH,
// useNewUrlParser: true,
// useUnifiedTopology: true,
// useFindAndModify: false,
})
const database = mongoose.connection
export default database
+41
View File
@@ -0,0 +1,41 @@
import Code from '../models/Code.js'
function getCode(value) {
return new Promise((resolve, reject) => {
Code.findOne({ value }).then((code) => {
resolve(code)
if (code) {
code.checked += 1
code.save()
}
})
})
}
function putCode(meta) {
return Code.create(meta)
.then((ok) => {
resolve()
})
.catch((err) => console.error(err))
}
function claimCode(value, uid) {
return new Promise((resolve, reject) => {
Code.findOne({ value, claimed: false }).then((code) => {
code.claimed = true
code.claimedAt = new Date()
code.uid = uid
code.save().then((code) => resolve(code))
})
})
}
function getClaimed(uid) {
return Code.find({ claimed: true, uid })
}
function useCode() {}
export { getCode, getClaimed, putCode, claimCode, useCode }
+26
View File
@@ -0,0 +1,26 @@
import Prev from '../models/Previous.js'
import { timeValid } from './votes.js'
function getPrevious(tid, from = timeValid(), to = new Date()) {
return Prev.findOne({ tid, createdAt: { $gt: from, $lt: to } })
}
function allPrevious(from = timeValid(), to = new Date()) {
return Prev.find({ createdAt: { $gt: from, $lt: to } }).sort({
createdAt: -1,
})
}
function countPrevious(tid, from = timeValid(), to = new Date()) {
return Prev.countDocuments({
tid,
createdAt: { $gt: from, $lt: to ?? new Date() },
})
}
function putPrevious(tid, timestamp) {
return Prev.create({ tid, timestamp })
}
export { getPrevious, allPrevious, countPrevious, putPrevious }
+23
View File
@@ -0,0 +1,23 @@
import Search from '../models/Search.js'
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 }
+44
View File
@@ -0,0 +1,44 @@
import TrackModel from '../models/Track.js'
/**
* 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 {Promise<{}>} track data
*/
function putTrack(track) {
return new Promise((resolve, reject) => {
TrackModel.create(track)
.then((tdata) => {
resolve(tdata)
})
.catch((err) => reject(err))
})
}
/**
* Update track metadata
* @param {String} tid track id
* @param {*} newTdata values to update
* @returns {Promise<{}>} updated track
*/
function updateTrack(id, newTdata) {
return TrackModel.updateOne({ id }, newTdata)
}
export { getTrack, putTrack, updateTrack }
+38
View File
@@ -0,0 +1,38 @@
import User from '../models/User.js'
/**
* 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 }
+175
View File
@@ -0,0 +1,175 @@
import env from '../env.js'
import Vote from '../models/Vote.js'
const { TOP_TIME_VALID, TOP_TIME_VALUE } = env
/**
* Date range for valid tracks.
* Oldest a vote can be
* @type Date
*/
const timeValid = (set) => {
switch (TOP_TIME_VALID) {
default:
case 'period': // constant period
let now = set ?? new Date(),
period = TOP_TIME_VALUE
if (now.getDay() == 1) {
let saturday = new Date(new Date().setDate(now.getDate() - 2))
saturday.setHours(0, 0, 0, 0)
return saturday
}
return new Date(now.getTime() - period * 1e3)
case 'monday': // beginning of the week
var monday = new Date()
monday.setHours(0, 0, 0)
monday.setDate(monday.getDate() - ((monday.getDay() + 6) % 7))
return monday
case 'date': // fixed date
let date = new Date(...JSON.parse(TOP_TIME_VALUE))
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,
total: 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<boolean>} 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(from) {
return new Promise((resolve, reject) => {
Vote.find({
createdAt: { $gt: timeValid(from), $lt: from ?? new Date() },
$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
}
resolve(results)
})
.catch((err) => reject(err))
})
}
export {
timeValid,
getVotes,
countTrackVotes,
getUserVote,
updateUserVote,
countAllVotes,
}
-917
View File
@@ -1,917 +0,0 @@
{
"name": "radio-rolnik-api",
"version": "1.3.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"accepts": {
"version": "1.3.7",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.7.tgz",
"integrity": "sha512-Il80Qs2WjYlJIBNzNkK6KYqlVMTbZLXgHx2oT0pU/fjRHyEp+PEfEPY0R3WCwAGVOtauxh1hOxNgIf5bv7dQpA==",
"requires": {
"mime-types": "~2.1.24",
"negotiator": "0.6.2"
}
},
"after": {
"version": "0.8.2",
"resolved": "https://registry.npmjs.org/after/-/after-0.8.2.tgz",
"integrity": "sha1-/ts5T58OAqqXaOcCvaI7UF+ufh8="
},
"array-flatten": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
"integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI="
},
"arraybuffer.slice": {
"version": "0.0.7",
"resolved": "https://registry.npmjs.org/arraybuffer.slice/-/arraybuffer.slice-0.0.7.tgz",
"integrity": "sha512-wGUIVQXuehL5TCqQun8OW81jGzAWycqzFF8lFp+GOM5BXLYj3bKNsYC4daB7n6XjCqxQA/qgTJ+8ANR3acjrog=="
},
"backo2": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/backo2/-/backo2-1.0.2.tgz",
"integrity": "sha1-MasayLEpNjRj41s+u2n038+6eUc="
},
"base64-arraybuffer": {
"version": "0.1.4",
"resolved": "https://registry.npmjs.org/base64-arraybuffer/-/base64-arraybuffer-0.1.4.tgz",
"integrity": "sha1-mBjHngWbE1X5fgQooBfIOOkLqBI="
},
"base64id": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/base64id/-/base64id-2.0.0.tgz",
"integrity": "sha512-lGe34o6EHj9y3Kts9R4ZYs/Gr+6N7MCaMlIFA3F1R2O5/m7K06AxfSeO5530PEERE6/WyEg3lsuyw4GHlPZHog=="
},
"bl": {
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/bl/-/bl-2.2.1.tgz",
"integrity": "sha512-6Pesp1w0DEX1N550i/uGV/TqucVL4AM/pgThFSN/Qq9si1/DF9aIHs1BxD8V/QU0HoeHO6cQRTAuYnLPKq1e4g==",
"requires": {
"readable-stream": "^2.3.5",
"safe-buffer": "^5.1.1"
}
},
"blob": {
"version": "0.0.5",
"resolved": "https://registry.npmjs.org/blob/-/blob-0.0.5.tgz",
"integrity": "sha512-gaqbzQPqOoamawKg0LGVd7SzLgXS+JH61oWprSLH+P+abTczqJbhTR8CmJ2u9/bUYNmHTGJx/UEmn6doAvvuig=="
},
"bluebird": {
"version": "3.5.1",
"resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.1.tgz",
"integrity": "sha512-MKiLiV+I1AA596t9w1sQJ8jkiSr5+ZKi0WKrYGUn6d1Fx+Ij4tIj+m2WMQSGczs5jZVxV339chE8iwk6F64wjA=="
},
"body-parser": {
"version": "1.19.0",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.19.0.tgz",
"integrity": "sha512-dhEPs72UPbDnAQJ9ZKMNTP6ptJaionhP5cBb541nXPlW60Jepo9RV/a4fX4XWW9CuFNK22krhrj1+rgzifNCsw==",
"requires": {
"bytes": "3.1.0",
"content-type": "~1.0.4",
"debug": "2.6.9",
"depd": "~1.1.2",
"http-errors": "1.7.2",
"iconv-lite": "0.4.24",
"on-finished": "~2.3.0",
"qs": "6.7.0",
"raw-body": "2.4.0",
"type-is": "~1.6.17"
},
"dependencies": {
"debug": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
"requires": {
"ms": "2.0.0"
}
},
"ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g="
},
"qs": {
"version": "6.7.0",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.7.0.tgz",
"integrity": "sha512-VCdBRNFTX1fyE7Nb6FYoURo/SPe62QCaAyzJvUjwRaIsc+NePBEniHlvxFmmX56+HZphIGtV0XeCirBtpDrTyQ=="
}
}
},
"bson": {
"version": "1.1.5",
"resolved": "https://registry.npmjs.org/bson/-/bson-1.1.5.tgz",
"integrity": "sha512-kDuEzldR21lHciPQAIulLs1LZlCXdLziXI6Mb/TDkwXhb//UORJNPXgcRs2CuO4H0DcMkpfT3/ySsP3unoZjBg=="
},
"bytes": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz",
"integrity": "sha512-zauLjrfCG+xvoyaqLoV8bLVXXNGC4JqlxFCutSDWA6fJrTo2ZuvLYTqZ7aHBLZSMOopbzwv8f+wZcVzfVTI2Dg=="
},
"component-bind": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/component-bind/-/component-bind-1.0.0.tgz",
"integrity": "sha1-AMYIq33Nk4l8AAllGx06jh5zu9E="
},
"component-emitter": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.3.0.tgz",
"integrity": "sha512-Rd3se6QB+sO1TwqZjscQrurpEPIfO0/yYnSin6Q/rD3mOutHvUrCAhJub3r90uNb+SESBuE0QYoB90YdfatsRg=="
},
"component-inherit": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/component-inherit/-/component-inherit-0.0.3.tgz",
"integrity": "sha1-ZF/ErfWLcrZJ1crmUTVhnbJv8UM="
},
"content-disposition": {
"version": "0.5.3",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.3.tgz",
"integrity": "sha512-ExO0774ikEObIAEV9kDo50o+79VCUdEB6n6lzKgGwupcVeRlhrj3qGAfwq8G6uBJjkqLrhT0qEYFcWng8z1z0g==",
"requires": {
"safe-buffer": "5.1.2"
}
},
"content-type": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz",
"integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA=="
},
"cookie": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.0.tgz",
"integrity": "sha512-+Hp8fLp57wnUSt0tY0tHEXh4voZRDnoIrZPqlo3DPiI4y9lwg/jqx+1Om94/W6ZaPDOUbnjOt/99w66zk+l1Xg=="
},
"cookie-parser": {
"version": "1.4.5",
"resolved": "https://registry.npmjs.org/cookie-parser/-/cookie-parser-1.4.5.tgz",
"integrity": "sha512-f13bPUj/gG/5mDr+xLmSxxDsB9DQiTIfhJS/sqjrmfAWiAN+x2O4i/XguTL9yDZ+/IFDanJ+5x7hC4CXT9Tdzw==",
"requires": {
"cookie": "0.4.0",
"cookie-signature": "1.0.6"
}
},
"cookie-signature": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
"integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw="
},
"core-util-is": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz",
"integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac="
},
"debug": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz",
"integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==",
"requires": {
"ms": "^2.1.1"
}
},
"denque": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/denque/-/denque-1.4.1.tgz",
"integrity": "sha512-OfzPuSZKGcgr96rf1oODnfjqBFmr1DVoc/TrItj3Ohe0Ah1C5WX5Baquw/9U9KovnQ88EqmJbD66rKYUQYN1tQ=="
},
"depd": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz",
"integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak="
},
"destroy": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz",
"integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA="
},
"dotenv": {
"version": "8.2.0",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-8.2.0.tgz",
"integrity": "sha512-8sJ78ElpbDJBHNeBzUbUVLsqKdccaa/BXF1uPTw3GrvQTBgrQrtObr2mUrE38vzYd8cEv+m/JBfDLioYcfXoaw=="
},
"ee-first": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
"integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0="
},
"encodeurl": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz",
"integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k="
},
"engine.io": {
"version": "3.5.0",
"resolved": "https://registry.npmjs.org/engine.io/-/engine.io-3.5.0.tgz",
"integrity": "sha512-21HlvPUKaitDGE4GXNtQ7PLP0Sz4aWLddMPw2VTyFz1FVZqu/kZsJUO8WNpKuE/OCL7nkfRaOui2ZCJloGznGA==",
"requires": {
"accepts": "~1.3.4",
"base64id": "2.0.0",
"cookie": "~0.4.1",
"debug": "~4.1.0",
"engine.io-parser": "~2.2.0",
"ws": "~7.4.2"
},
"dependencies": {
"cookie": {
"version": "0.4.1",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.1.tgz",
"integrity": "sha512-ZwrFkGJxUR3EIoXtO+yVE69Eb7KlixbaeAWfBQB9vVsNn/o+Yw69gBWSSDK825hQNdN+wF8zELf3dFNl/kxkUA=="
}
}
},
"engine.io-client": {
"version": "3.5.2",
"resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-3.5.2.tgz",
"integrity": "sha512-QEqIp+gJ/kMHeUun7f5Vv3bteRHppHH/FMBQX/esFj/fuYfjyUKWGMo3VCvIP/V8bE9KcjHmRZrhIz2Z9oNsDA==",
"requires": {
"component-emitter": "~1.3.0",
"component-inherit": "0.0.3",
"debug": "~3.1.0",
"engine.io-parser": "~2.2.0",
"has-cors": "1.1.0",
"indexof": "0.0.1",
"parseqs": "0.0.6",
"parseuri": "0.0.6",
"ws": "~7.4.2",
"xmlhttprequest-ssl": "~1.6.2",
"yeast": "0.1.2"
},
"dependencies": {
"debug": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz",
"integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==",
"requires": {
"ms": "2.0.0"
}
},
"ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g="
}
}
},
"engine.io-parser": {
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-2.2.1.tgz",
"integrity": "sha512-x+dN/fBH8Ro8TFwJ+rkB2AmuVw9Yu2mockR/p3W8f8YtExwFgDvBDi0GWyb4ZLkpahtDGZgtr3zLovanJghPqg==",
"requires": {
"after": "0.8.2",
"arraybuffer.slice": "~0.0.7",
"base64-arraybuffer": "0.1.4",
"blob": "0.0.5",
"has-binary2": "~1.0.2"
}
},
"escape-html": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
"integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg="
},
"etag": {
"version": "1.8.1",
"resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
"integrity": "sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc="
},
"express": {
"version": "4.17.1",
"resolved": "https://registry.npmjs.org/express/-/express-4.17.1.tgz",
"integrity": "sha512-mHJ9O79RqluphRrcw2X/GTh3k9tVv8YcoyY4Kkh4WDMUYKRZUq0h1o0w2rrrxBqM7VoeUVqgb27xlEMXTnYt4g==",
"requires": {
"accepts": "~1.3.7",
"array-flatten": "1.1.1",
"body-parser": "1.19.0",
"content-disposition": "0.5.3",
"content-type": "~1.0.4",
"cookie": "0.4.0",
"cookie-signature": "1.0.6",
"debug": "2.6.9",
"depd": "~1.1.2",
"encodeurl": "~1.0.2",
"escape-html": "~1.0.3",
"etag": "~1.8.1",
"finalhandler": "~1.1.2",
"fresh": "0.5.2",
"merge-descriptors": "1.0.1",
"methods": "~1.1.2",
"on-finished": "~2.3.0",
"parseurl": "~1.3.3",
"path-to-regexp": "0.1.7",
"proxy-addr": "~2.0.5",
"qs": "6.7.0",
"range-parser": "~1.2.1",
"safe-buffer": "5.1.2",
"send": "0.17.1",
"serve-static": "1.14.1",
"setprototypeof": "1.1.1",
"statuses": "~1.5.0",
"type-is": "~1.6.18",
"utils-merge": "1.0.1",
"vary": "~1.1.2"
},
"dependencies": {
"debug": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
"requires": {
"ms": "2.0.0"
}
},
"ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g="
},
"qs": {
"version": "6.7.0",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.7.0.tgz",
"integrity": "sha512-VCdBRNFTX1fyE7Nb6FYoURo/SPe62QCaAyzJvUjwRaIsc+NePBEniHlvxFmmX56+HZphIGtV0XeCirBtpDrTyQ=="
}
}
},
"finalhandler": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.2.tgz",
"integrity": "sha512-aAWcW57uxVNrQZqFXjITpW3sIUQmHGG3qSb9mUah9MgMC4NeWhNOlNjXEYq3HjRAvL6arUviZGGJsBg6z0zsWA==",
"requires": {
"debug": "2.6.9",
"encodeurl": "~1.0.2",
"escape-html": "~1.0.3",
"on-finished": "~2.3.0",
"parseurl": "~1.3.3",
"statuses": "~1.5.0",
"unpipe": "~1.0.0"
},
"dependencies": {
"debug": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
"requires": {
"ms": "2.0.0"
}
},
"ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g="
}
}
},
"forwarded": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.1.2.tgz",
"integrity": "sha1-mMI9qxF1ZXuMBXPozszZGw/xjIQ="
},
"fresh": {
"version": "0.5.2",
"resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
"integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac="
},
"has-binary2": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/has-binary2/-/has-binary2-1.0.3.tgz",
"integrity": "sha512-G1LWKhDSvhGeAQ8mPVQlqNcOB2sJdwATtZKl2pDKKHfpf/rYj24lkinxf69blJbnsvtqqNU+L3SL50vzZhXOnw==",
"requires": {
"isarray": "2.0.1"
},
"dependencies": {
"isarray": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.1.tgz",
"integrity": "sha1-o32U7ZzaLVmGXJ92/llu4fM4dB4="
}
}
},
"has-cors": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/has-cors/-/has-cors-1.1.0.tgz",
"integrity": "sha1-XkdHk/fqmEPRu5nCPu9J/xJv/zk="
},
"http-errors": {
"version": "1.7.2",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.7.2.tgz",
"integrity": "sha512-uUQBt3H/cSIVfch6i1EuPNy/YsRSOUBXTVfZ+yR7Zjez3qjBz6i9+i4zjNaoqcoFVI4lQJ5plg63TvGfRSDCRg==",
"requires": {
"depd": "~1.1.2",
"inherits": "2.0.3",
"setprototypeof": "1.1.1",
"statuses": ">= 1.5.0 < 2",
"toidentifier": "1.0.0"
},
"dependencies": {
"inherits": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz",
"integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4="
}
}
},
"iconv-lite": {
"version": "0.4.24",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",
"integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",
"requires": {
"safer-buffer": ">= 2.1.2 < 3"
}
},
"indexof": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/indexof/-/indexof-0.0.1.tgz",
"integrity": "sha1-gtwzbSMrkGIXnQWrMpOmYFn9Q10="
},
"inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="
},
"ipaddr.js": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
"integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="
},
"isarray": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
"integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE="
},
"kareem": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/kareem/-/kareem-2.3.1.tgz",
"integrity": "sha512-l3hLhffs9zqoDe8zjmb/mAN4B8VT3L56EUvKNqLFVs9YlFA+zx7ke1DO8STAdDyYNkeSo1nKmjuvQeI12So8Xw=="
},
"media-typer": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
"integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g="
},
"memory-pager": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz",
"integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==",
"optional": true
},
"merge-descriptors": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz",
"integrity": "sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E="
},
"methods": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz",
"integrity": "sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4="
},
"mime": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz",
"integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg=="
},
"mime-db": {
"version": "1.44.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.44.0.tgz",
"integrity": "sha512-/NOTfLrsPBVeH7YtFPgsVWveuL+4SjjYxaQ1xtM1KMFj7HdxlBlxeyNLzhyJVx7r4rZGJAZ/6lkKCitSc/Nmpg=="
},
"mime-types": {
"version": "2.1.27",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.27.tgz",
"integrity": "sha512-JIhqnCasI9yD+SsmkquHBxTSEuZdQX5BuQnS2Vc7puQQQ+8yiP5AY5uWhpdv4YL4VM5c6iliiYWPgJ/nJQLp7w==",
"requires": {
"mime-db": "1.44.0"
}
},
"mongodb": {
"version": "3.6.2",
"resolved": "https://registry.npmjs.org/mongodb/-/mongodb-3.6.2.tgz",
"integrity": "sha512-sSZOb04w3HcnrrXC82NEh/YGCmBuRgR+C1hZgmmv4L6dBz4BkRse6Y8/q/neXer9i95fKUBbFi4KgeceXmbsOA==",
"requires": {
"bl": "^2.2.1",
"bson": "^1.1.4",
"denque": "^1.4.1",
"require_optional": "^1.0.1",
"safe-buffer": "^5.1.2",
"saslprep": "^1.0.0"
}
},
"mongoose": {
"version": "5.10.7",
"resolved": "https://registry.npmjs.org/mongoose/-/mongoose-5.10.7.tgz",
"integrity": "sha512-oiofFrD4I5p3PhJXn49QyrU1nX5CY01qhPkfMMrXYPhkfGLEJVwFVO+0PsCxD91A2kQP+d/iFyk5U8e86KI8eQ==",
"requires": {
"bson": "^1.1.4",
"kareem": "2.3.1",
"mongodb": "3.6.2",
"mongoose-legacy-pluralize": "1.0.2",
"mpath": "0.7.0",
"mquery": "3.2.2",
"ms": "2.1.2",
"regexp-clone": "1.0.0",
"safe-buffer": "5.2.1",
"sift": "7.0.1",
"sliced": "1.0.1"
},
"dependencies": {
"safe-buffer": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="
}
}
},
"mongoose-legacy-pluralize": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/mongoose-legacy-pluralize/-/mongoose-legacy-pluralize-1.0.2.tgz",
"integrity": "sha512-Yo/7qQU4/EyIS8YDFSeenIvXxZN+ld7YdV9LqFVQJzTLye8unujAWPZ4NWKfFA+RNjh+wvTWKY9Z3E5XM6ZZiQ=="
},
"mpath": {
"version": "0.7.0",
"resolved": "https://registry.npmjs.org/mpath/-/mpath-0.7.0.tgz",
"integrity": "sha512-Aiq04hILxhz1L+f7sjGyn7IxYzWm1zLNNXcfhDtx04kZ2Gk7uvFdgZ8ts1cWa/6d0TQmag2yR8zSGZUmp0tFNg=="
},
"mquery": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/mquery/-/mquery-3.2.2.tgz",
"integrity": "sha512-XB52992COp0KP230I3qloVUbkLUxJIu328HBP2t2EsxSFtf4W1HPSOBWOXf1bqxK4Xbb66lfMJ+Bpfd9/yZE1Q==",
"requires": {
"bluebird": "3.5.1",
"debug": "3.1.0",
"regexp-clone": "^1.0.0",
"safe-buffer": "5.1.2",
"sliced": "1.0.1"
},
"dependencies": {
"debug": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz",
"integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==",
"requires": {
"ms": "2.0.0"
}
},
"ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g="
}
}
},
"ms": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
},
"negotiator": {
"version": "0.6.2",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.2.tgz",
"integrity": "sha512-hZXc7K2e+PgeI1eDBe/10Ard4ekbfrrqG8Ep+8Jmf4JID2bNg7NvCPOZN+kfF574pFQI7mum2AUqDidoKqcTOw=="
},
"on-finished": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz",
"integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=",
"requires": {
"ee-first": "1.1.1"
}
},
"parseqs": {
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/parseqs/-/parseqs-0.0.6.tgz",
"integrity": "sha512-jeAGzMDbfSHHA091hr0r31eYfTig+29g3GKKE/PPbEQ65X0lmMwlEoqmhzu0iztID5uJpZsFlUPDP8ThPL7M8w=="
},
"parseuri": {
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/parseuri/-/parseuri-0.0.6.tgz",
"integrity": "sha512-AUjen8sAkGgao7UyCX6Ahv0gIK2fABKmYjvP4xmy5JaKvcbTRueIqIPHLAfq30xJddqSE033IOMUSOMCcK3Sow=="
},
"parseurl": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
"integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="
},
"path-to-regexp": {
"version": "0.1.7",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz",
"integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w="
},
"process-nextick-args": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
"integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag=="
},
"proxy-addr": {
"version": "2.0.6",
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.6.tgz",
"integrity": "sha512-dh/frvCBVmSsDYzw6n926jv974gddhkFPfiN8hPOi30Wax25QZyZEGveluCgliBnqmuM+UJmBErbAUFIoDbjOw==",
"requires": {
"forwarded": "~0.1.2",
"ipaddr.js": "1.9.1"
}
},
"range-parser": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
"integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg=="
},
"raw-body": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.4.0.tgz",
"integrity": "sha512-4Oz8DUIwdvoa5qMJelxipzi/iJIi40O5cGV1wNYp5hvZP8ZN0T+jiNkL0QepXs+EsQ9XJ8ipEDoiH70ySUJP3Q==",
"requires": {
"bytes": "3.1.0",
"http-errors": "1.7.2",
"iconv-lite": "0.4.24",
"unpipe": "1.0.0"
}
},
"readable-stream": {
"version": "2.3.7",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz",
"integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==",
"requires": {
"core-util-is": "~1.0.0",
"inherits": "~2.0.3",
"isarray": "~1.0.0",
"process-nextick-args": "~2.0.0",
"safe-buffer": "~5.1.1",
"string_decoder": "~1.1.1",
"util-deprecate": "~1.0.1"
}
},
"regexp-clone": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/regexp-clone/-/regexp-clone-1.0.0.tgz",
"integrity": "sha512-TuAasHQNamyyJ2hb97IuBEif4qBHGjPHBS64sZwytpLEqtBQ1gPJTnOaQ6qmpET16cK14kkjbazl6+p0RRv0yw=="
},
"require_optional": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/require_optional/-/require_optional-1.0.1.tgz",
"integrity": "sha512-qhM/y57enGWHAe3v/NcwML6a3/vfESLe/sGM2dII+gEO0BpKRUkWZow/tyloNqJyN6kXSl3RyyM8Ll5D/sJP8g==",
"requires": {
"resolve-from": "^2.0.0",
"semver": "^5.1.0"
}
},
"resolve-from": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-2.0.0.tgz",
"integrity": "sha1-lICrIOlP+h2egKgEx+oUdhGWa1c="
},
"safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
},
"safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="
},
"saslprep": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/saslprep/-/saslprep-1.0.3.tgz",
"integrity": "sha512-/MY/PEMbk2SuY5sScONwhUDsV2p77Znkb/q3nSVstq/yQzYJOH/Azh29p9oJLsl3LnQwSvZDKagDGBsBwSooag==",
"optional": true,
"requires": {
"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",
"integrity": "sha512-BsVKsiGcQMFwT8UxypobUKyv7irCNRHk1T0G680vk88yf6LBByGcZJOTJCrTP2xVN6yI+XjPJcNuE3V4fT9sAg==",
"requires": {
"debug": "2.6.9",
"depd": "~1.1.2",
"destroy": "~1.0.4",
"encodeurl": "~1.0.2",
"escape-html": "~1.0.3",
"etag": "~1.8.1",
"fresh": "0.5.2",
"http-errors": "~1.7.2",
"mime": "1.6.0",
"ms": "2.1.1",
"on-finished": "~2.3.0",
"range-parser": "~1.2.1",
"statuses": "~1.5.0"
},
"dependencies": {
"debug": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
"requires": {
"ms": "2.0.0"
},
"dependencies": {
"ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g="
}
}
},
"ms": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz",
"integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg=="
}
}
},
"serve-static": {
"version": "1.14.1",
"resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.14.1.tgz",
"integrity": "sha512-JMrvUwE54emCYWlTI+hGrGv5I8dEwmco/00EvkzIIsR7MqrHonbD9pO2MOfFnpFntl7ecpZs+3mW+XbQZu9QCg==",
"requires": {
"encodeurl": "~1.0.2",
"escape-html": "~1.0.3",
"parseurl": "~1.3.3",
"send": "0.17.1"
}
},
"setprototypeof": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.1.tgz",
"integrity": "sha512-JvdAWfbXeIGaZ9cILp38HntZSFSo3mWg6xGcJJsd+d4aRMOqauag1C63dJfDw7OaMYwEbHMOxEZ1lqVRYP2OAw=="
},
"sift": {
"version": "7.0.1",
"resolved": "https://registry.npmjs.org/sift/-/sift-7.0.1.tgz",
"integrity": "sha512-oqD7PMJ+uO6jV9EQCl0LrRw1OwsiPsiFQR5AR30heR+4Dl7jBBbDLnNvWiak20tzZlSE1H7RB30SX/1j/YYT7g=="
},
"sliced": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/sliced/-/sliced-1.0.1.tgz",
"integrity": "sha1-CzpmK10Ewxd7GSa+qCsD+Dei70E="
},
"socket.io": {
"version": "2.4.1",
"resolved": "https://registry.npmjs.org/socket.io/-/socket.io-2.4.1.tgz",
"integrity": "sha512-Si18v0mMXGAqLqCVpTxBa8MGqriHGQh8ccEOhmsmNS3thNCGBwO8WGrwMibANsWtQQ5NStdZwHqZR3naJVFc3w==",
"requires": {
"debug": "~4.1.0",
"engine.io": "~3.5.0",
"has-binary2": "~1.0.2",
"socket.io-adapter": "~1.1.0",
"socket.io-client": "2.4.0",
"socket.io-parser": "~3.4.0"
}
},
"socket.io-adapter": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-1.1.2.tgz",
"integrity": "sha512-WzZRUj1kUjrTIrUKpZLEzFZ1OLj5FwLlAFQs9kuZJzJi5DKdU7FsWc36SNmA8iDOtwBQyT8FkrriRM8vXLYz8g=="
},
"socket.io-client": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-2.4.0.tgz",
"integrity": "sha512-M6xhnKQHuuZd4Ba9vltCLT9oa+YvTsP8j9NcEiLElfIg8KeYPyhWOes6x4t+LTAC8enQbE/995AdTem2uNyKKQ==",
"requires": {
"backo2": "1.0.2",
"component-bind": "1.0.0",
"component-emitter": "~1.3.0",
"debug": "~3.1.0",
"engine.io-client": "~3.5.0",
"has-binary2": "~1.0.2",
"indexof": "0.0.1",
"parseqs": "0.0.6",
"parseuri": "0.0.6",
"socket.io-parser": "~3.3.0",
"to-array": "0.1.4"
},
"dependencies": {
"debug": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz",
"integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==",
"requires": {
"ms": "2.0.0"
}
},
"isarray": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.1.tgz",
"integrity": "sha1-o32U7ZzaLVmGXJ92/llu4fM4dB4="
},
"ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g="
},
"socket.io-parser": {
"version": "3.3.2",
"resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-3.3.2.tgz",
"integrity": "sha512-FJvDBuOALxdCI9qwRrO/Rfp9yfndRtc1jSgVgV8FDraihmSP/MLGD5PEuJrNfjALvcQ+vMDM/33AWOYP/JSjDg==",
"requires": {
"component-emitter": "~1.3.0",
"debug": "~3.1.0",
"isarray": "2.0.1"
}
}
}
},
"socket.io-parser": {
"version": "3.4.1",
"resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-3.4.1.tgz",
"integrity": "sha512-11hMgzL+WCLWf1uFtHSNvliI++tcRUWdoeYuwIl+Axvwy9z2gQM+7nJyN3STj1tLj5JyIUH8/gpDGxzAlDdi0A==",
"requires": {
"component-emitter": "1.2.1",
"debug": "~4.1.0",
"isarray": "2.0.1"
},
"dependencies": {
"component-emitter": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.2.1.tgz",
"integrity": "sha1-E3kY1teCg/ffemt8WmPhQOaUJeY="
},
"isarray": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.1.tgz",
"integrity": "sha1-o32U7ZzaLVmGXJ92/llu4fM4dB4="
}
}
},
"sparse-bitfield": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz",
"integrity": "sha1-/0rm5oZWBWuks+eSqzM004JzyhE=",
"optional": true,
"requires": {
"memory-pager": "^1.0.2"
}
},
"statuses": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz",
"integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow="
},
"string_decoder": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
"integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
"requires": {
"safe-buffer": "~5.1.0"
}
},
"to-array": {
"version": "0.1.4",
"resolved": "https://registry.npmjs.org/to-array/-/to-array-0.1.4.tgz",
"integrity": "sha1-F+bBH3PdTz10zaek/zI46a2b+JA="
},
"toidentifier": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.0.tgz",
"integrity": "sha512-yaOH/Pk/VEhBWWTlhI+qXxDFXlejDGcQipMlyxda9nthulaxLZUNcUqFxokp0vcYnvteJln5FNQDRrxj3YcbVw=="
},
"type-is": {
"version": "1.6.18",
"resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
"integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
"requires": {
"media-typer": "0.3.0",
"mime-types": "~2.1.24"
}
},
"unpipe": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
"integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw="
},
"util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8="
},
"utils-merge": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
"integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM="
},
"vary": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
"integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw="
},
"ws": {
"version": "7.4.6",
"resolved": "https://registry.npmjs.org/ws/-/ws-7.4.6.tgz",
"integrity": "sha512-YmhHDO4MzaDLB+M9ym/mDA5z0naX8j7SIlT8f8z+I0VtzsRbekxEutHSme7NPS2qE8StCYQNUnfWdXta/Yu85A=="
},
"xmlhttprequest-ssl": {
"version": "1.6.3",
"resolved": "https://registry.npmjs.org/xmlhttprequest-ssl/-/xmlhttprequest-ssl-1.6.3.tgz",
"integrity": "sha512-3XfeQE/wNkvrIktn2Kf0869fC0BN6UpydVasGIeSm2B1Llihf7/0UfZM+eCkOw3P7bP4+qPgqhm7ZoxuJtFU0Q=="
},
"yeast": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/yeast/-/yeast-0.1.2.tgz",
"integrity": "sha1-AI4G2AlDIMNy28L47XagymyKxBk="
}
}
}
+39 -32
View File
@@ -1,34 +1,41 @@
{
"name": "radio-rolnik-api",
"version": "1.3.0",
"description": "rolniknysa radio",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "nodemon index"
},
"nodemonConfig": {
"ignore": [
"public/",
"*.json"
]
},
"repository": {
"type": "git",
"url": "git+https://github.com/Maathias/radio-rolnik-api.git"
},
"author": "Mateusz Pstrucha",
"license": "ISC",
"bugs": {
"url": "https://github.com/Maathias/radio-rolnik-api/issues"
},
"homepage": "https://github.com/Maathias/radio-rolnik-api#readme",
"dependencies": {
"cookie-parser": "^1.4.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"mongoose": "^5.10.7",
"spotify-web-api-node": "^5.0.2"
}
"name": "radio-rolnik-api",
"version": "1.3.0",
"description": "rolniknysa radio",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "NODE_ENV=development nodemon index",
"start": "node index.js"
},
"nodemonConfig": {
"ignore": [
"public/",
"*.json"
]
},
"repository": {
"type": "git",
"url": "git+https://github.com/Maathias/radio-rolnik-api.git"
},
"author": "Mateusz Pstrucha",
"license": "ISC",
"bugs": {
"url": "https://github.com/Maathias/radio-rolnik-api/issues"
},
"homepage": "https://github.com/Maathias/radio-rolnik-api#readme",
"dependencies": {
"body-parser": "^1.19.2",
"cookie-parser": "^1.4.5",
"dotenv": "^16.0.0",
"express": "^4.17.3",
"got": "^12.0.1",
"jsonwebtoken": "^8.5.1",
"mongoose": "^6.2.10",
"nodemon": "^2.0.13",
"redis": "^3.1.2",
"spotify-web-api-node": "^5.0.2",
"ws": "^8.5.0"
}
}
+31
View File
@@ -0,0 +1,31 @@
import redis from 'redis'
import env from './env.js'
const { CACHE_PORT: port, CACHE_HOST: host } = env
const client = redis.createClient({ host, port })
client.on('ready', function (error) {
console.info(`cache: connected`)
})
const cache = {
get: (key) => {
return new Promise((resolve, reject) => {
client.get(key, (err, data) => {
if (err) {
reject(err)
}
resolve(data)
})
})
},
set: (key, value) => {
if (typeof value !== 'string') {
value = JSON.stringify(value)
}
client.set(key, value)
},
}
export default cache
+28
View File
@@ -0,0 +1,28 @@
import express from 'express'
import db from '../db.js'
const router = express.Router()
router.get('/ban', ({ query: { tid }, 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')
db.users
.verifyJwt(authorization)
.then(({ perms }) => {
if (perms > 0) {
db.admin.ban(tid).then((ok) => {
res.json(ok.toString())
})
}
})
.catch((err) => {
res.json('false')
console.error(err)
})
})
export default router
+79
View File
@@ -0,0 +1,79 @@
import express from 'express'
import db from '../db.js'
import { getCode, claimCode, getClaimed } from '../mongo/codes.js'
const router = express.Router()
const descriptions = {
top16: `Pozwala na gwarantowane miejsce w Topce dla wybranego przez ciebie utworu.
Działa tylko po Zajęciu a następnie Aktywacji.
Aktywny kod, działa na ostatni utwór na który zagłosujesz przed 8:00 następnego dnia`,
}
router.get('/info/:c', ({ params: { c } }, res) => {
getCode(c).then((code) => {
if (code) {
res.json({
value: code.value,
type: code.type,
claimed: code.claimed,
used: code.used,
checked: code.checked,
desc: descriptions[code.type],
})
} else {
res.status(404).end()
}
})
})
router.get('/list/', ({ 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')
db.users
.verifyJwt(authorization)
.then(({ id }) => {
getClaimed(id).then((list) => res.json(list))
})
.catch((err) => {
console.error(err)
res.status(403).end('Could not validate token')
})
})
router.post(
'/claim/:c',
({ params: { c }, 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 (c === undefined) return res.status(400).end('Code required')
if (c.length < 1) return res.status(400).end('Code invalid')
db.users
.verifyJwt(authorization)
.then(({ id }) => {
claimCode(c, id).then((code) => {
if (code.claimed && code.uid == id) {
res.json('true')
} else res.json('false')
})
})
.catch((err) => {
console.error(err)
res.status(403).end('Could not validate token')
})
}
)
export default router
-17
View File
@@ -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
+78
View File
@@ -0,0 +1,78 @@
import express from 'express'
import got from 'got'
import Jwt from 'jsonwebtoken'
import db from '../db.js'
import env from '../env.js'
const router = express.Router()
const { FB_APPID, FB_SECRET, HTTP_DOMAIN } = env
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=${FB_APPID}&redirect_uri=https://${HTTP_DOMAIN}/api/login/token&client_secret=${FB_SECRET}&code=${code}`
)
.json()
.then(({ access_token, expires_in }) => {
got(`https://graph.facebook.com/me?access_token=${access_token}`)
.json()
.then(({ name, id }) => {
db.users
.getUser(id)
.then((user) => {
if (user === null)
return db.users.newUser({
name,
id,
accessToken: access_token,
tokenExpires: new Date(
new Date().getTime() + expires_in * 1e3
),
})
else return user
})
.then(({ name, id, perms }) => {
const payload = {
name,
id,
perms,
},
jwt = Jwt.sign(payload, FB_SECRET)
res.end(
[
'<body>',
'Logowanie...',
'<br>',
'Jeżeli to okno nie zamknie się automatycznie, spróbuj ponownie.',
JSON.stringify({ name, id, perms }),
'</body>',
'<script>window.onload=function(){',
`localStorage.setItem('token', "${jwt}");`,
`localStorage.setItem('udata', '${JSON.stringify(
payload
)}');`,
'window.close();',
'}</script>',
].join(' ')
)
})
.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
+111
View File
@@ -0,0 +1,111 @@
import express from 'express'
import db, { parseTop } from '../db.js'
import env from '../env.js'
import { countAllVotes } from '../mongo/votes.js'
const { PLAYER_SECRET } = env
const router = express.Router()
function update(data) {
if (!Array.isArray(data)) data = [data]
db.current.update(data)
}
const playerSecret = 'Bearer ' + PLAYER_SECRET
// set current track
router.put(
'/set/status',
(
{
body: { tid = null, progress = null, duration = null, paused = null },
headers: { authorization },
},
res
) => {
if (authorization === undefined)
return res.status(401).end('Authorization required')
if (authorization != playerSecret)
return res.status(403).end('Token invalid')
if (tid !== null)
if (typeof tid !== 'string')
return res.status(400).end('tid value invalid')
if (progress !== null)
if (typeof progress !== 'number')
return res.status(400).end('progress value invalid')
if (duration !== null)
if (typeof duration !== 'number')
return res.status(400).end('duration value invalid')
if (paused !== null)
if (typeof paused !== 'boolean')
return res.status(400).end('paused value invalid')
update({
cat: 'status',
content: {
...(tid !== null && { tid }),
...(progress !== null && { progress }),
...(duration !== null && { duration }),
...(paused !== null && { paused }),
},
})
res.json('true')
}
)
// set next track
router.put(
'/set/next',
({ body: { tid }, headers: { authorization } }, res) => {
if (authorization === undefined)
return res.status(401).end('Authorization required')
if (authorization != playerSecret)
return res.status(403).end('Token invalid')
if (tid === undefined) return res.status(400).end('"tid" field required')
update({
cat: 'next',
content: { tid },
})
res.json('true')
}
)
router.get(
'/get/top/',
({ query: { mode = 'once' }, headers: { authorization } }, res) => {
if (authorization === undefined)
return res.status(401).end('Authorization required')
if (authorization != playerSecret)
return res.status(403).end('Token invalid')
if (mode === 'once') {
let morning = new Date()
morning.setHours(8, 0, 0, 0)
countAllVotes(morning).then((tids) => {
parseTop(tids).then((tids) => res.json(tids))
})
} else if ((mode = 'rolling')) {
db.top.get().then(({ top }) => {
res.json(top)
})
}
}
)
export default router
+13 -11
View File
@@ -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
-9
View File
@@ -1,9 +0,0 @@
import express from 'express'
const router = express.Router()
router.get('/', (req, res) => {
res.send('Get currently playing track metadata.')
})
export default router
+27 -5
View File
@@ -1,15 +1,37 @@
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.send([])
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) => {
byId(req.params.id).then((track) => res.send(track))
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(id)
.then((track) => res.send(track))
.catch((err) => {
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)
})
})
export default router
+130
View File
@@ -0,0 +1,130 @@
import express from 'express'
import db from '../db.js'
import Track from '../Track.js'
const router = express.Router()
// get multiple track stats
router.post(
'/batch/',
async ({ body: { tids }, 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 (tids === undefined)
return res.status(400).end('List of Track ids required')
if (tids.length < 1) return res.json([])
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.json(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.json('false')
console.error(err)
})
}
)
export default router
+52
View File
@@ -0,0 +1,52 @@
import WebSocket, { WebSocketServer } from 'ws'
import db from './db.js'
import env from './env.js'
const { WS_PORT: port } = env,
wss = new WebSocketServer({ port })
console.info('ws: listening on ' + port)
function broadcast(data) {
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(data))
}
})
}
wss.on('connection', async function connection(ws, req) {
console.info(`socket # ${req.headers['x-real-ip']} + `)
function send(data) {
ws.send(JSON.stringify(data))
}
send([
{
cat: 'previous',
...db.current.previous,
},
{
cat: 'next',
...db.current.next,
},
{
cat: 'top',
tids: db.top.list,
timestamp: db.top.lastCount,
},
{
cat: 'status',
...db.current.status,
},
])
ws.on('message', (message) => console.info('received: %s', message))
ws.on('close', (message) =>
console.info(`socket # ${req.headers['x-real-ip']} - `)
)
})
export { wss, broadcast }
+43 -24
View File
@@ -1,53 +1,72 @@
import SpotifyWebApi from 'spotify-web-api-node'
import env from './env.js'
import Track from './Track.js'
const spotify = new SpotifyWebApi({
clientId: 'c9cd1ede71914999a75fbea35313c1a4',
clientSecret: '13858e98eb264cf78251072f2ea5e96d',
})
const { SPOTIFY_CLIENT_ID: clientId, SPOTIFY_CLIENT_SECRET: clientSecret } = env
spotify.clientCredentialsGrant().then(
function (data) {
console.log('Spotify: access token granted')
const spotify = new SpotifyWebApi({ clientId, clientSecret })
// Save the access token so that it's used in future calls
spotify.setAccessToken(data.body['access_token'])
},
function (err) {
throw err
}
)
function grantToken() {
spotify
.clientCredentialsGrant()
.then(
function ({ body: { access_token, expires_in } }) {
console.info('spotify: access token granted')
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 < Track.idMinLength) return reject(new Error('Id too short'))
spotify
.getTrack(id)
.then((data) => {
resolve(new Track(data.body))
})
.catch((err) => {
reject(err)
.then(({ body }) => {
resolve(
new Track({
...body,
title: body.name,
artists: body.artists.map((a) => a.name),
album: {
name: body.album.name,
art: body.album.images,
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))
})
}
+1809
View File
File diff suppressed because it is too large. Load diff