5 Commits
Author SHA1 Message Date
Mateusz Pstrucha 9d53c932fc feat: better readme 2022-04-19 20:24:31 +02:00
Mateusz Pstrucha c5bf2e13c5 fix: lower mongo version for compatability 2022-04-19 19:01:42 +02:00
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
20 changed files with 2225 additions and 2434 deletions

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
.git
node_modules
data
build
.vscode
.github
DockerFile
.dockerignore
.prettierrc
.gitignore
+2 -1
View File
@@ -2,5 +2,6 @@ node_modules/
*cred.json
.env
.env.*
*.env
old/
database
data/
+6 -11
View File
@@ -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"]
+40 -241
View File
@@ -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)
+4 -3
View File
@@ -1,7 +1,5 @@
import Jwt from 'jsonwebtoken'
import database from './mongo.js'
import {
timeValid,
countTrackVotes,
@@ -27,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
@@ -165,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
View File
@@ -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
+35 -5
View File
@@ -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
+16 -5
View File
@@ -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'
@@ -15,13 +14,25 @@ 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)
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)
@@ -31,18 +42,18 @@ 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(() => {
+6 -20
View File
@@ -1,31 +1,17 @@
import env from './env.js'
import mongoose from 'mongoose'
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`)
})
export default database
+6 -3
View File
@@ -1,16 +1,19 @@
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 (process.env.TOP_TIME_VALID) {
switch (TOP_TIME_VALID) {
default:
case 'period': // constant period
let now = set ?? new Date(),
period = process.env.TOP_TIME_VALUE
period = TOP_TIME_VALUE
if (now.getDay() == 1) {
let saturday = new Date(new Date().setDate(now.getDate() - 2))
@@ -30,7 +33,7 @@ const timeValid = (set) => {
return monday
case 'date': // fixed date
let date = new Date(...JSON.parse(process.env.TOP_TIME_VALUE))
let date = new Date(...JSON.parse(TOP_TIME_VALUE))
return date
}
}
-28
View File
@@ -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";
}
}
-2033
View File
File diff suppressed because it is too large. Load diff
+39 -38
View File
@@ -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"
}
}
+3 -3
View File
@@ -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`)
+4 -5
View File
@@ -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(
[
+4 -1
View File
@@ -1,8 +1,11 @@
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) {
@@ -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(
+203
View File
@@ -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>
```
+3 -2
View File
@@ -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
View File
@@ -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
+1809
View File
File diff suppressed because it is too large. Load diff