Merge pull request #15 from Maathias/readme
Readme
This commit was merged in pull request #15.
This commit is contained in:
27 files changed
+2683
-2752
No files matched your search
@@ -0,0 +1,12 @@
|
||||
.git
|
||||
node_modules
|
||||
data
|
||||
build
|
||||
|
||||
.vscode
|
||||
.github
|
||||
|
||||
DockerFile
|
||||
.dockerignore
|
||||
.prettierrc
|
||||
.gitignore
|
||||
+2
-1
@@ -2,5 +2,6 @@ node_modules/
|
||||
*cred.json
|
||||
.env
|
||||
.env.*
|
||||
*.env
|
||||
old/
|
||||
database
|
||||
data/
|
||||
+6
-11
@@ -1,12 +1,7 @@
|
||||
FROM node:14-stretch AS build
|
||||
WORKDIR /build
|
||||
COPY package-lock.json package.json ./
|
||||
RUN npm ci
|
||||
FROM node:16
|
||||
WORKDIR /app
|
||||
COPY package.json yarn.lock ./
|
||||
RUN yarn install
|
||||
COPY . .
|
||||
|
||||
|
||||
FROM node:14-alpine AS deploy
|
||||
USER node
|
||||
WORKDIR /home/node/src
|
||||
COPY --from=build --chown=node:node /build .
|
||||
CMD ["node", "index.js"]
|
||||
ENV NODE_ENV production
|
||||
CMD ["yarn", "start"]
|
||||
@@ -4,269 +4,68 @@ Backend server for radio-rolnik
|
||||
|
||||
## Resources
|
||||
|
||||
Website - https://github.com/Maathias/radio-rolnik/
|
||||
Frontend - [Maathias/radio-rolnik](https://github.com/Maathias/radio-rolnik/)
|
||||
|
||||
Player - https://github.com/Maathias/radio-rolnik-player/
|
||||
Player - [Maathias/radio-rolnik-player](https://github.com/Maathias/radio-rolnik-player/)
|
||||
|
||||
## .env
|
||||
|
||||
Enviroment variables required
|
||||
`.dev.env` will be loaded with `NODE_ENV=development`, otherwise 'production' is used by default.
|
||||
|
||||
### Ports and domains
|
||||
`.env` file is required for production build. It should contain variables defined below.
|
||||
|
||||
```ini
|
||||
HTTP_DOMAIN= <frontend domain>
|
||||
|
||||
SPOTIFY_CLIENT_ID= <spotify api id>
|
||||
SPOTIFY_CLIENT_SECRET= <spotify api secret>
|
||||
|
||||
PLAYER_SECRET= <remote player secret>
|
||||
|
||||
FB_APPID= <facebook api id>
|
||||
FB_SECRET= <facebook api secret>
|
||||
```
|
||||
|
||||
Some of the required variables is provided in `docker-compose.yml`
|
||||
|
||||
```ini
|
||||
HTTP_PORT=3010
|
||||
HTTP_DOMAIN=radio.rolniknysa.pl
|
||||
WS_PORT=3020
|
||||
|
||||
<mongo and redis variables>
|
||||
...
|
||||
```
|
||||
|
||||
### Spotify API
|
||||
The rest can be probably left with default values
|
||||
|
||||
```ini
|
||||
SPOTIFY_CLIENT_ID=<ID>
|
||||
SPOTIFY_CLIENT_SECRET=<SECRET>
|
||||
DB_PORT= 27017,
|
||||
DB_AUTH= 'admin',
|
||||
|
||||
TOP_TIME_VALID= 'period',
|
||||
TOP_TIME_VALUE= 604800,
|
||||
|
||||
CACHE_PORT= 6379,
|
||||
```
|
||||
|
||||
### Facebok API
|
||||
## Usage
|
||||
|
||||
```ini
|
||||
FB_APPID=<ID>
|
||||
FB_SECRET=<SECRET>
|
||||
```
|
||||
`yarn dev` for development, or
|
||||
`yarn start` for running standalone.
|
||||
(Made on Node v16)
|
||||
|
||||
### Mongo DB
|
||||
`docker-compose up` for running in a docker container. Make sure a `.env` file isn't missing before building.
|
||||
|
||||
```ini
|
||||
DB_HOST=<IP>
|
||||
DB_PORT=<PORT>
|
||||
DB_NAME=<DB>
|
||||
DB_AUTH=<COLL>
|
||||
DB_USER=<USER>
|
||||
DB_PASS=<PASSWORD>
|
||||
```
|
||||
With default ports, the app assumes a nginx config:
|
||||
|
||||
### Redis Cache
|
||||
- frontend hosted on `/`
|
||||
|
||||
```ini
|
||||
CACHE_HOST=<IP>
|
||||
CACHE_PORT=6379
|
||||
```
|
||||
- `/api/` passed to `HTTP_PORT`
|
||||
|
||||
### Other
|
||||
- `/ws/` passed to `WS_PORT`
|
||||
|
||||
```ini
|
||||
PLAYER_SECRET=<SECRET>
|
||||
TOP_TIME_VALID=<monday,date,period>
|
||||
TOP_TIME_VALUE=<VALUE?>
|
||||
```
|
||||
MongoDB data volume is mapped to `.data/mongo`
|
||||
|
||||
## Routes
|
||||
|
||||
### `/track`
|
||||
|
||||
Get track metadata
|
||||
|
||||
---
|
||||
|
||||
#### `GET` `/track/:id` get track
|
||||
|
||||
Get track by track id
|
||||
|
||||
`RESPONSE`
|
||||
|
||||
```javascript
|
||||
{
|
||||
id: String,
|
||||
title: String,
|
||||
artists: [String...],
|
||||
album: {
|
||||
name: String,
|
||||
art: String,
|
||||
year: Number,
|
||||
},
|
||||
duration: Number, // milliseconds
|
||||
explicit: Boolean,
|
||||
banned: Boolean,
|
||||
votes: {
|
||||
up: Number,
|
||||
down: Number,
|
||||
rank: Number,
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### `POST` `/batch` get tracks
|
||||
|
||||
Get multiple tracks by track id
|
||||
|
||||
`BODY`
|
||||
|
||||
```javascript
|
||||
{
|
||||
tids: [TrackID...]
|
||||
}
|
||||
```
|
||||
|
||||
`RESPONSE`
|
||||
|
||||
```javascript
|
||||
[
|
||||
TrackID...
|
||||
]
|
||||
```
|
||||
|
||||
### `/search`
|
||||
|
||||
Search for tracks
|
||||
|
||||
---
|
||||
|
||||
#### `GET` `/search/track` track search
|
||||
|
||||
Get a list of Track ids
|
||||
|
||||
`QUERY`
|
||||
|
||||
```javascript
|
||||
{
|
||||
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>
|
||||
```
|
||||
|
||||
---
|
||||
API paths and responses are described in [routes.md](routes/routes.md)
|
||||
@@ -1,23 +1,23 @@
|
||||
import Jwt from 'jsonwebtoken'
|
||||
|
||||
import {
|
||||
getTrack,
|
||||
putTrack,
|
||||
updateTrack,
|
||||
timeValid,
|
||||
countTrackVotes,
|
||||
getUserVote,
|
||||
updateUserVote,
|
||||
countAllVotes,
|
||||
getUser,
|
||||
putUser,
|
||||
getQuery,
|
||||
setQuery,
|
||||
putPrevious,
|
||||
} from './mongo/votes.js'
|
||||
import {
|
||||
getPrevious,
|
||||
countPrevious,
|
||||
timeValid,
|
||||
allPrevious,
|
||||
} from './mongo.js'
|
||||
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'
|
||||
@@ -25,6 +25,9 @@ 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
|
||||
@@ -163,7 +166,7 @@ const db = {
|
||||
*/
|
||||
verifyJwt: (jwt) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
Jwt.verify(jwt ?? '', process.env.FB_SECRET, (err, decoded) => {
|
||||
Jwt.verify(jwt ?? '', FB_SECRET, (err, decoded) => {
|
||||
if (err) return reject(err)
|
||||
resolve(decoded)
|
||||
})
|
||||
|
||||
+29
-31
@@ -3,50 +3,48 @@ version: '3.1'
|
||||
services:
|
||||
api:
|
||||
build: .
|
||||
container_name: radio-rolnik_api
|
||||
image: radio-rolnik/api
|
||||
restart: always
|
||||
container_name: api
|
||||
depends_on:
|
||||
- mongo
|
||||
- redis
|
||||
links:
|
||||
- mongo
|
||||
- redis
|
||||
|
||||
environment:
|
||||
HTTP_PORT: 3010
|
||||
# WS_PORT: 3020
|
||||
WS_PORT: 3020
|
||||
|
||||
DB_HOST: mongo
|
||||
DB_PORT: 27017
|
||||
DB_NAME: radio-rolnik
|
||||
DB_USER: root
|
||||
DB_PASS: supersecurepassword123
|
||||
DB_NAME: api
|
||||
DB_USER: radio-rolnikcred
|
||||
DB_PASS: radio-rolnikcred
|
||||
|
||||
CACHE_HOST: redis
|
||||
CACHE_PORT: 6379
|
||||
ports:
|
||||
- 3010:3010
|
||||
- 3020:3020
|
||||
depends_on:
|
||||
- mongo
|
||||
links:
|
||||
- mongo
|
||||
|
||||
mongo:
|
||||
image: mongo:5.0
|
||||
container_name: mongo
|
||||
image: mongo:4.4
|
||||
container_name: radio-rolnik_mongo
|
||||
restart: always
|
||||
environment:
|
||||
MONGO_INITDB_ROOT_USERNAME: root
|
||||
MONGO_INITDB_ROOT_PASSWORD: supersecurepassword123
|
||||
volumes:
|
||||
- ./database:/data/db
|
||||
ports:
|
||||
- 27017:27017
|
||||
command: --quiet
|
||||
- ./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: redis
|
||||
container_name: radio-rolnik_redis
|
||||
restart: always
|
||||
|
||||
environment:
|
||||
ALLOW_EMPTY_PASSWORD: 'yes'
|
||||
ports:
|
||||
- 6379:6379
|
||||
nginx:
|
||||
image: nginx:1.21-alpine
|
||||
container_name: nginx
|
||||
restart: always
|
||||
volumes:
|
||||
- ./nginx.conf:/etc/nginx/conf.d/default.conf
|
||||
ports:
|
||||
- 80:80
|
||||
@@ -1,15 +1,45 @@
|
||||
import dotenv from 'dotenv'
|
||||
|
||||
const env = process.env.NODE_ENV,
|
||||
const NODE_ENV = process.env.NODE_ENV,
|
||||
dotfile = {
|
||||
production: '.env',
|
||||
development: '.env.dev',
|
||||
}[env ?? 'production']
|
||||
development: '.dev.env',
|
||||
}[NODE_ENV ?? 'production']
|
||||
|
||||
console.info(`env: ${env}`)
|
||||
console.info(`env: ${NODE_ENV}`)
|
||||
|
||||
const config = dotenv.config({ path: `./${dotfile}` })
|
||||
|
||||
if (config.error) throw `enviroment file ${dotfile} not found`
|
||||
|
||||
export default config
|
||||
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
|
||||
@@ -4,7 +4,6 @@ import express, { json, urlencoded } from 'express'
|
||||
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'
|
||||
@@ -13,6 +12,19 @@ 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'
|
||||
|
||||
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(),
|
||||
http = createServer(app)
|
||||
@@ -20,7 +32,7 @@ var app = express(),
|
||||
app.use(json())
|
||||
app.use(urlencoded({ extended: false }))
|
||||
app.use(cookieParser())
|
||||
app.set('port', process.env.HTTP_PORT)
|
||||
app.set('port', HTTP_PORT)
|
||||
|
||||
app.use('/track', track)
|
||||
app.use('/search', search)
|
||||
@@ -28,19 +40,20 @@ app.use('/vote', vote)
|
||||
app.use('/login', login)
|
||||
app.use('/player', player)
|
||||
app.use('/admin', admin)
|
||||
app.use('/code', code)
|
||||
|
||||
http.listen(process.env.HTTP_PORT)
|
||||
http.listen(HTTP_PORT)
|
||||
|
||||
http.on('error', function (error) {
|
||||
if (error.syscall !== 'listen') {
|
||||
throw error
|
||||
}
|
||||
|
||||
console.info(`Error: port ${process.env.HTTP_PORT}: ${error.code}`)
|
||||
console.info(`Error: port ${HTTP_PORT}: ${error.code}`)
|
||||
})
|
||||
|
||||
http.on('listening', function () {
|
||||
console.info(`http: listening on ${process.env.HTTP_PORT}`)
|
||||
console.info(`http: listening on ${HTTP_PORT}`)
|
||||
})
|
||||
|
||||
setInterval(() => {
|
||||
|
||||
@@ -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 }
|
||||
@@ -1,341 +1,17 @@
|
||||
import env from './env.js'
|
||||
import mongoose from 'mongoose'
|
||||
|
||||
import TrackModel from './models/Track.js'
|
||||
import Vote from './models/Vote.js'
|
||||
import User from './models/User.js'
|
||||
import Search from './models/Search.js'
|
||||
import Prev from './models/Previous.js'
|
||||
|
||||
const {
|
||||
DB_HOST,
|
||||
DB_PORT,
|
||||
DB_NAME,
|
||||
dbAuth = 'admin',
|
||||
DB_USER,
|
||||
DB_PASS,
|
||||
} = process.env
|
||||
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: dbAuth,
|
||||
useNewUrlParser: true,
|
||||
useUnifiedTopology: true,
|
||||
useFindAndModify: false,
|
||||
authSource: DB_AUTH,
|
||||
// useNewUrlParser: true,
|
||||
// useUnifiedTopology: true,
|
||||
// useFindAndModify: false,
|
||||
})
|
||||
|
||||
const database = mongoose.connection
|
||||
|
||||
database.on('error', (err) => {
|
||||
throw err
|
||||
})
|
||||
|
||||
database.once('open', () => {
|
||||
console.info(`mongo: 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 {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 }
|
||||
|
||||
// #### Votes #### #### #### ######## #### #### ####
|
||||
|
||||
/**
|
||||
* Date range for valid tracks.
|
||||
* Oldest a vote can be
|
||||
* @type Date
|
||||
*/
|
||||
const timeValid = (set) => {
|
||||
switch (process.env.TOP_TIME_VALID) {
|
||||
default:
|
||||
case 'period': // constant period
|
||||
let now = set ?? new Date(),
|
||||
period = process.env.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(process.env.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,
|
||||
}
|
||||
|
||||
// #### 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 }
|
||||
|
||||
// #### Search #### #### #### #### #### #### #### ####
|
||||
|
||||
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 }
|
||||
export default database
|
||||
@@ -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 }
|
||||
@@ -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 }
|
||||
@@ -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 }
|
||||
@@ -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 }
|
||||
@@ -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
@@ -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,
|
||||
}
|
||||
-28
@@ -1,28 +0,0 @@
|
||||
server {
|
||||
listen 80;
|
||||
|
||||
location / {
|
||||
proxy_pass http://host.docker.internal:3000/;
|
||||
}
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://api:3010/;
|
||||
}
|
||||
|
||||
location /ws/ {
|
||||
proxy_pass http://api:3020/;
|
||||
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header Host $http_host;
|
||||
proxy_set_header X-NginX-Proxy false;
|
||||
|
||||
proxy_read_timeout 86400s;
|
||||
proxy_redirect off;
|
||||
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
}
|
||||
|
||||
}
|
||||
Generated
-2033
File diff suppressed because it is too large.
Load diff
+39
-38
@@ -1,40 +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": {
|
||||
"body-parser": "^1.19.0",
|
||||
"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",
|
||||
"nodemon": "^2.0.13",
|
||||
"redis": "^3.1.2",
|
||||
"spotify-web-api-node": "^5.0.2",
|
||||
"ws": "^8.2.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"
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import redis from 'redis'
|
||||
import env from './env.js'
|
||||
|
||||
const port = process.env.CACHE_PORT
|
||||
const hostName = process.env.CACHE_HOST
|
||||
const { CACHE_PORT: port, CACHE_HOST: host } = env
|
||||
|
||||
const client = redis.createClient({ host: hostName, port })
|
||||
const client = redis.createClient({ host, port })
|
||||
|
||||
client.on('ready', function (error) {
|
||||
console.info(`cache: connected`)
|
||||
|
||||
@@ -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
|
||||
+4
-5
@@ -2,12 +2,11 @@ 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 appId = process.env.FB_APPID,
|
||||
secret = process.env.FB_SECRET,
|
||||
domain = process.env.HTTP_DOMAIN
|
||||
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')
|
||||
@@ -15,7 +14,7 @@ router.get('/token', ({ query: { code } }, res) => {
|
||||
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://${domain}/api/login/token&client_secret=${secret}&code=${code}`
|
||||
`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 }) => {
|
||||
@@ -42,7 +41,7 @@ router.get('/token', ({ query: { code } }, res) => {
|
||||
id,
|
||||
perms,
|
||||
},
|
||||
jwt = Jwt.sign(payload, secret)
|
||||
jwt = Jwt.sign(payload, FB_SECRET)
|
||||
|
||||
res.end(
|
||||
[
|
||||
|
||||
+5
-2
@@ -1,7 +1,10 @@
|
||||
import express from 'express'
|
||||
|
||||
import db, { parseTop } from '../db.js'
|
||||
import { countAllVotes } from '../mongo.js'
|
||||
import env from '../env.js'
|
||||
import { countAllVotes } from '../mongo/votes.js'
|
||||
|
||||
const { PLAYER_SECRET } = env
|
||||
|
||||
const router = express.Router()
|
||||
|
||||
@@ -11,7 +14,7 @@ function update(data) {
|
||||
db.current.update(data)
|
||||
}
|
||||
|
||||
const playerSecret = 'Bearer ' + process.env.PLAYER_SECRET
|
||||
const playerSecret = 'Bearer ' + PLAYER_SECRET
|
||||
|
||||
// set current track
|
||||
router.put(
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
|
||||
---
|
||||
|
||||
### `/track`
|
||||
|
||||
Get track metadata
|
||||
|
||||
#### `GET` `/track/:id` get track
|
||||
|
||||
Get track by track id
|
||||
|
||||
`RESPONSE`
|
||||
|
||||
```javascript
|
||||
{
|
||||
id: String,
|
||||
title: String,
|
||||
artists: [String...],
|
||||
album: {
|
||||
name: String,
|
||||
art: String,
|
||||
year: Number,
|
||||
},
|
||||
duration: Number, // milliseconds
|
||||
explicit: Boolean,
|
||||
banned: Boolean,
|
||||
votes: {
|
||||
up: Number,
|
||||
down: Number,
|
||||
rank: Number,
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
#### `POST` `/batch` get tracks
|
||||
|
||||
Get multiple tracks by track id
|
||||
|
||||
`BODY`
|
||||
|
||||
```javascript
|
||||
{
|
||||
tids: [TrackID...]
|
||||
}
|
||||
```
|
||||
|
||||
`RESPONSE`
|
||||
|
||||
```javascript
|
||||
[
|
||||
TrackID...
|
||||
]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `/search`
|
||||
|
||||
Search for tracks
|
||||
|
||||
#### `GET` `/search/track` track search
|
||||
|
||||
Get a list of Track ids
|
||||
|
||||
`QUERY`
|
||||
|
||||
```javascript
|
||||
{
|
||||
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>
|
||||
```
|
||||
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import WebSocket, { WebSocketServer } from 'ws'
|
||||
import db from './db.js'
|
||||
import env from './env.js'
|
||||
|
||||
const port = process.env.WS_PORT,
|
||||
wss = new WebSocketServer({ port: port })
|
||||
const { WS_PORT: port } = env,
|
||||
wss = new WebSocketServer({ port })
|
||||
|
||||
console.info('ws: listening on ' + port)
|
||||
|
||||
|
||||
+4
-4
@@ -1,11 +1,11 @@
|
||||
import SpotifyWebApi from 'spotify-web-api-node'
|
||||
import env from './env.js'
|
||||
|
||||
import Track from './Track.js'
|
||||
|
||||
const spotify = new SpotifyWebApi({
|
||||
clientId: process.env.SPOTIFY_CLIENT_ID,
|
||||
clientSecret: process.env.SPOTIFY_CLIENT_SECRET,
|
||||
})
|
||||
const { SPOTIFY_CLIENT_ID: clientId, SPOTIFY_CLIENT_SECRET: clientSecret } = env
|
||||
|
||||
const spotify = new SpotifyWebApi({ clientId, clientSecret })
|
||||
|
||||
function grantToken() {
|
||||
spotify
|
||||
|
||||
Reference in new issue
Block a user