Merge pull request #12 from Maathias/finishing

Finishing
This commit was merged in pull request #12.
This commit is contained in:
Mateusz Pstrucha authored and GitHub committed 2021-10-21 01:41:57 +02:00
commit a54208166f
14 files changed
+318 -268

No files matched your search

+58 -42
View File
@@ -2,6 +2,64 @@
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`
@@ -212,45 +270,3 @@ Exchange Facebook login code for an access token
```
---
## .env
Enviroment variables required
### Ports
```ini
portHttp=3010
portWs=3020
```
### Spotify API
```ini
spotifyClientId=ID
spotifyClientSecret=SECRET
```
### Facebok API
```ini
fbAppId=ID
fbSecret=SECRET
```
### Mongo DB
```ini
dbHost=IP
dbPort=PORT
dbName=DB
dbAuth=COLL
dbUser=USER
dbPass=PASSWORD
```
### Other
```ini
timeValid=monday
```
+73 -31
View File
@@ -1,9 +1,9 @@
import Jwt from 'jsonwebtoken'
import cache from './cache.js'
import {
getTrack,
putTrack,
updateTrack,
countTrackVotes,
getUserVote,
updateUserVote,
@@ -13,6 +13,7 @@ import {
getQuery,
setQuery,
} from './mongo.js'
import redis from './redis.js'
import { byId, byQuery } from './spotify.js'
import Track from './Track.js'
@@ -36,26 +37,24 @@ function broadcast(cats) {
}
const current = {
next: { tid: '6BfbSHE9ytCTF910g3wNdj' },
next: { tid: null },
status: {
tid: '3OcyTN8Nz3bdne5aq9mMR5',
tid: null,
progress: 0,
duration: 29598,
paused: false,
duration: 0,
paused: true,
timestamp: new Date(),
},
previous: {
combo: [
['0VdSlJ7owUK1MuS8Kp7LdE', '2021-09-09T21:41:44.528Z'],
['5svu5mLA4U2kdxPj1tLJ2I', '2021-09-09T21:41:44.528Z'],
],
combo: [],
},
}
const maxPrevious = 20
var topList = [],
lastTop = -1
lastTop = -1,
votesSince = 0
const db = {
/**
@@ -71,22 +70,21 @@ const db = {
get: (id) => {
return new Promise((resolve, reject) => {
// try to find in redis
cache.get(id).then((data) => {
redis.get(id).then((data) => {
if (data) {
resolve(JSON.parse(data))
} else {
// if not found, query db
getTrack(id)
.then((tdata) => {
cache.set(id, JSON.stringify(tdata))
redis.set(id, JSON.stringify(tdata))
resolve(new Track(tdata))
})
.catch((dbErr) => {
// track not found in DB, fetch online
byId(id)
.then((track) => {
cache.set(id, JSON.stringify(track))
putTrack(track)
putTrack(track).then((tdata) => redis.set(id, tdata))
resolve(track)
})
.catch((spotifyErr) => {
@@ -116,7 +114,12 @@ const db = {
})
},
getUserTrack: getUserVote,
putUserTrack: updateUserVote,
putUserTrack: (...params) => {
return updateUserVote(...params).then((ok) => {
if (ok) votesSince++
return ok
})
},
},
users: {
getUser: getUser,
@@ -128,7 +131,7 @@ const db = {
*/
verifyJwt: (jwt) => {
return new Promise((resolve, reject) => {
Jwt.verify(jwt ?? '', process.env.fbSecret, (err, decoded) => {
Jwt.verify(jwt ?? '', process.env.FB_SECRET, (err, decoded) => {
if (err) return reject(err)
resolve(decoded)
})
@@ -150,23 +153,35 @@ const db = {
get lastCount() {
return lastTop
},
get changed() {
return
},
/**
* Get current Top tracks
* @returns {Promise<[]>} Array of Track ids
* @returns {Promise<{}>} Array of Track ids and Fresh flag
*/
get: () => {
return new Promise((resolve, reject) => {
let now = new Date().getTime()
if (now - lastTop > 1e3) {
if (now - lastTop > 60e3 || votesSince >= 2) {
countAllVotes()
.then((top) => {
topList = top
lastTop = now
resolve(top)
return Promise.all(top.map((tid) => getTrack(tid)))
})
.then((top) => {
return top.filter(({ banned }) => !banned).map(({ id }) => id)
})
.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(topList)
} else resolve({ top: topList, fresh: false })
})
},
getTrackRank: getTrackRank,
@@ -212,15 +227,25 @@ const db = {
},
set status(chunk) {
if (current.status.tid != chunk?.tid) {
// add new [tid, date]
current.previous.combo.unshift([
current.status.tid,
current.status.timestamp,
])
// pop on overfill
if (current.previous.combo.length > maxPrevious)
current.previous.combo.pop()
// console.log(current.status.tid, chunk?.tid)
if (current.status.tid != chunk?.tid && current.status.tid) {
// skip duplicates
let last = current.previous.combo[0] ?? [null]
if (last[0] !== current.status.tid) {
// add new [tid, date]
current.previous.combo.unshift([
current.status.tid,
current.status.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() }
@@ -248,6 +273,10 @@ const db = {
return current.previous
},
set top(chunk) {
current.top = chunk
},
update(data) {
if (!Array.isArray(data)) data = [data]
@@ -258,6 +287,19 @@ const db = {
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))
})
},
},
}
export default db
+26 -17
View File
@@ -4,27 +4,27 @@ services:
api:
build: .
restart: always
container_name: api
environment:
portHttp: 3010
dbHost: db
dbPort: 27017
dbName: radio-rolnik
dbAuth: admin
dbUser: root
dbPass: supersecurepassword123
portWs: 3020
CACHE_HOST: cache
HTTP_PORT: 3010
# WS_PORT: 3020
DB_HOST: mongo
DB_PORT: 27017
DB_NAME: radio-rolnik
DB_USER: root
DB_PASS: supersecurepassword123
CACHE_HOST: redis
CACHE_PORT: 6379
ports:
- 3010:3010
- 3020:3020
depends_on:
- db
- mongo
links:
- db
db:
image: mongo:4.4
container_name: db
- mongo
mongo:
image: mongo:5.0
container_name: mongo
restart: always
environment:
MONGO_INITDB_ROOT_USERNAME: root
@@ -33,11 +33,20 @@ services:
- ./database:/data/db
ports:
- 27017:27017
cache:
command: --quiet
redis:
image: redis:6.2-alpine
container_name: cache
container_name: redis
restart: always
environment:
ALLOW_EMPTY_PASSWORD: yes
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
+21 -27
View File
@@ -11,55 +11,49 @@ 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'
dotenv.config()
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.portHttp)
app.set('port', process.env.HTTP_PORT)
app.use('/track', track)
app.use('/search', search)
app.use('/vote', vote)
app.use('/login', login)
app.use('/player', player)
app.use('/admin', admin)
www.listen(process.env.portHttp)
http.listen(process.env.HTTP_PORT)
www.on('error', function (error) {
http.on('error', function (error) {
if (error.syscall !== 'listen') {
throw error
}
console.info(`Error: port ${process.env.portHttp}: ${error.code}`)
console.info(`Error: port ${process.env.HTTP_PORT}: ${error.code}`)
})
www.on('listening', function () {
console.info(`www: listening on ${process.env.portHttp}`)
http.on('listening', function () {
console.info(`http: listening on ${process.env.HTTP_PORT}`)
})
var i = 0
setInterval(async () => {
let { top, fresh } = await db.top.get()
// setInterval(async () => {
// db.current.update([
// {
// cat: 'status',
// content: {
// tid: db.top.list[i],
// },
// },
// {
// cat: 'top',
// content: {
// tids: await db.top.get(),
// timestamp: db.top.lastCount,
// },
// },
// ])
// i++
// if (i >= db.top.list.length) i = 0
// }, 10e3)
if (fresh) {
db.current.update({
cat: 'top',
content: {
tids: top,
timestamp: db.top.lastCount,
},
})
}
}, 2e3)
+29 -9
View File
@@ -8,11 +8,18 @@ import Vote from './models/Vote.js'
import User from './models/User.js'
import Search from './models/Search.js'
const { dbHost, dbPort, dbName, dbAuth, dbUser, dbPass } = process.env
const {
DB_HOST,
DB_PORT,
DB_NAME,
dbAuth = 'admin',
DB_USER,
DB_PASS,
} = process.env
mongoose.connect(`mongodb://${dbHost}:${dbPort}/${dbName}`, {
user: dbUser,
pass: dbPass,
mongoose.connect(`mongodb://${DB_HOST}:${DB_PORT}/${DB_NAME}`, {
user: DB_USER,
pass: DB_PASS,
authSource: dbAuth,
useNewUrlParser: true,
useUnifiedTopology: true,
@@ -26,7 +33,7 @@ database.on('error', (err) => {
})
database.once('open', () => {
console.info(`db: connected`)
console.info(`mongo: connected`)
})
// #### Tracks #### #### #### #### #### #### #### ####
@@ -50,7 +57,7 @@ function getTrack(id) {
/**
* Add track to database
* @param {Track} track new track
* @returns {Object} tdata
* @returns {Promise<{}>} track data
*/
function putTrack(track) {
return new Promise((resolve, reject) => {
@@ -62,7 +69,17 @@ function putTrack(track) {
})
}
export { getTrack, putTrack }
/**
* 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 #### #### #### ######## #### #### ####
@@ -72,8 +89,11 @@ export { getTrack, putTrack }
* @type Date
*/
const timeValid = (() => {
switch (process.env.timeValid) {
switch (process.env.TOP_TIME_VALID) {
default:
case 'period':
let now = new Date()
return new Date(now.getTime() - process.env.TOP_TIME_VALUE * 1e3)
case 'monday':
var monday = new Date()
monday.setHours(0, 0, 0)
@@ -81,7 +101,7 @@ const timeValid = (() => {
return monday
case 'date':
let date = new Date(...JSON.parse(process.env.valid_date))
let date = new Date(...JSON.parse(process.env.TOP_TIME_VALUE))
return date
}
})()
+28
View File
@@ -0,0 +1,28 @@
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";
}
}
-93
View File
@@ -4,15 +4,6 @@
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"@ksolo/spotify-search": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@ksolo/spotify-search/-/spotify-search-1.0.0.tgz",
"integrity": "sha512-8Ud6chwN3FRqDgup7Fo2iHFcYzedp63cxvIrrqnt8PU74TzvKe4gKFwBv5O3H/skWONtrk3sz3X2HPO1Tg0s3Q==",
"requires": {
"axios": "^0.21.1",
"buffer": "^6.0.3"
}
},
"@sindresorhus/is": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.2.0.tgz",
@@ -146,24 +137,11 @@
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
"integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k="
},
"axios": {
"version": "0.21.4",
"resolved": "https://registry.npmjs.org/axios/-/axios-0.21.4.tgz",
"integrity": "sha512-ut5vewkiu8jjGBdqpM44XxjuCjq9LAKeHVmoVfHVzy8eHgxxq8SbAVQNovDA8mVi05kP0Ea/n/UzcSHcTJQfNg==",
"requires": {
"follow-redirects": "^1.14.0"
}
},
"balanced-match": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="
},
"base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="
},
"binary-extensions": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz",
@@ -257,15 +235,6 @@
"resolved": "https://registry.npmjs.org/bson/-/bson-1.1.6.tgz",
"integrity": "sha512-EvVNVeGo4tHxwi8L6bPj3y3itEvStdwvvlojVxxbyYfoaxJ6keLgrTuKdyfEAszFK+H3olzBuafE0yoh0D1gdg=="
},
"buffer": {
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",
"integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",
"requires": {
"base64-js": "^1.3.1",
"ieee754": "^1.2.1"
}
},
"buffer-equal-constant-time": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
@@ -452,14 +421,6 @@
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",
"integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ=="
},
"cross-fetch": {
"version": "3.1.4",
"resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-3.1.4.tgz",
"integrity": "sha512-1eAtFWdIubi6T4XPy6ei9iUFoKpUkIF971QLN8lIvvvwueI65+Nw5haMNKUwfJxabqlIIDODJKGrQ66gxC0PbQ==",
"requires": {
"node-fetch": "2.6.1"
}
},
"crypto-random-string": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/crypto-random-string/-/crypto-random-string-2.0.0.tgz",
@@ -681,11 +642,6 @@
}
}
},
"follow-redirects": {
"version": "1.14.4",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.4.tgz",
"integrity": "sha512-zwGkiSXC1MUJG/qmeIFH2HBJx9u0V46QGUe3YR1fXG8bXQxq7fLj0RjLZQ5nubr9qNJUZrH+xUcwXEoXNpfS+g=="
},
"form-data": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.1.tgz",
@@ -802,11 +758,6 @@
"resolved": "https://registry.npmjs.org/has-yarn/-/has-yarn-2.1.0.tgz",
"integrity": "sha512-UqBRqi4ju7T+TqGNdqAO0PaSVGsDGJUBQvk9eUWNGRY1CFGDzYhLWoM7JQEemnlvVcv/YEmc2wNW8BC24EnUsw=="
},
"himalaya": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/himalaya/-/himalaya-1.1.0.tgz",
"integrity": "sha512-LLase1dHCRMel68/HZTFft0N0wti0epHr3nNY7ynpLbyZpmrKMQ8YIpiOV77TM97cNpC8Wb2n6f66IRggwdWPw=="
},
"http-cache-semantics": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.1.0.tgz",
@@ -848,11 +799,6 @@
"safer-buffer": ">= 2.1.2 < 3"
}
},
"ieee754": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
"integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="
},
"ignore-by-default": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/ignore-by-default/-/ignore-by-default-1.0.1.tgz",
@@ -1231,11 +1177,6 @@
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.2.tgz",
"integrity": "sha512-hZXc7K2e+PgeI1eDBe/10Ard4ekbfrrqG8Ep+8Jmf4JID2bNg7NvCPOZN+kfF574pFQI7mum2AUqDidoKqcTOw=="
},
"node-fetch": {
"version": "2.6.1",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.1.tgz",
"integrity": "sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw=="
},
"nodemon": {
"version": "2.0.13",
"resolved": "https://registry.npmjs.org/nodemon/-/nodemon-2.0.13.tgz",
@@ -1766,32 +1707,6 @@
"memory-pager": "^1.0.2"
}
},
"spotify-to-yt": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/spotify-to-yt/-/spotify-to-yt-1.0.5.tgz",
"integrity": "sha512-tjudSnTkTDR8eAqylVbo35BFp+ogYpFEkZxsjh59NXw7UvAJ87sZG5b0WroFjJ0XeAriMTj1A7ZDO2VABjRrwg==",
"requires": {
"@ksolo/spotify-search": "^1.0.0",
"spotify-uri": "^2.2.0",
"spotify-url-info": "^2.2.3",
"youtube-sr": "^4.1.5"
}
},
"spotify-uri": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/spotify-uri/-/spotify-uri-2.2.0.tgz",
"integrity": "sha512-uUybj02bfyfCoZ0MJ80MkqbKxtIVRJfbRGk05KJFq1li3zb7yNfN1f+TAw4wcXgp7jLWExeiw2wyPQXZ8PHtfg=="
},
"spotify-url-info": {
"version": "2.2.3",
"resolved": "https://registry.npmjs.org/spotify-url-info/-/spotify-url-info-2.2.3.tgz",
"integrity": "sha512-cZTE5nOnaAjIiaHG9psVYqKXWOlNUIgSU2e+bNInRaYZNgmVgOcKH0D7V1nSER3gv3h5BXvOo0EJTtrMQQo1bA==",
"requires": {
"cross-fetch": "~3.1.4",
"himalaya": "~1.1.0",
"spotify-uri": "~2.2.0"
}
},
"spotify-web-api-node": {
"version": "5.0.2",
"resolved": "https://registry.npmjs.org/spotify-web-api-node/-/spotify-web-api-node-5.0.2.tgz",
@@ -2113,14 +2028,6 @@
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
"integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="
},
"youtube-sr": {
"version": "4.1.7",
"resolved": "https://registry.npmjs.org/youtube-sr/-/youtube-sr-4.1.7.tgz",
"integrity": "sha512-OKbm+561Fq5RlnUtJBmPhnyfS6Zon44zdPhY1v/Y9vpAHzqdfxomD43yc0ZQv6zNsVzSlAkGeWhoweNd6DUUjQ==",
"requires": {
"node-fetch": "^2.6.1"
}
}
}
}
-1
View File
@@ -34,7 +34,6 @@
"mongoose": "^5.13.9",
"nodemon": "^2.0.13",
"redis": "^3.1.2",
"spotify-to-yt": "^1.0.5",
"spotify-web-api-node": "^5.0.2",
"ws": "^8.2.2"
}
+4 -1
View File
@@ -9,7 +9,7 @@ const hostName = process.env.CACHE_HOST
const client = redis.createClient({ host: hostName, port })
client.on('ready', function (error) {
console.error(`cache: connected`)
console.info(`cache: connected`)
})
const cache = {
@@ -24,6 +24,9 @@ const cache = {
})
},
set: (key, value) => {
if (typeof value !== 'string') {
value = JSON.stringify(value)
}
client.set(key, value)
},
}
+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
+38 -25
View File
@@ -8,8 +8,9 @@ dotenv.config()
const router = express.Router()
const appId = process.env.fbAppId,
secret = process.env.fbSecret
const appId = process.env.FB_APPID,
secret = process.env.FB_SECRET,
domain = process.env.HTTP_DOMAIN
router.get('/token', ({ query: { code } }, res) => {
if (code === undefined) return res.status(400).end('Facebook code required')
@@ -17,32 +18,18 @@ 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://radio.rolniknysa.pl/api/login/token'}&client_secret=${secret}&code=${code}`
`https://graph.facebook.com/v12.0/oauth/access_token?client_id=${appId}&redirect_uri=https://${domain}/api/login/token&client_secret=${secret}&code=${code}`
)
.json()
.then(({ access_token, expires_in }) => {
got(`https://graph.facebook.com/me?access_token=${access_token}`)
.json()
.then(({ name, id }) => {
const jwt = Jwt.sign(
{
name,
id,
},
secret
)
res.end(
`<body>Logowanie...</body><script>window.onload=function(){opener.exit(${JSON.stringify(
{ jwt }
)})}</script>`
)
db.users
.getUser(id)
.then((user) => {
if (user === null)
db.users.newUser({
return db.users.newUser({
name,
id,
accessToken: access_token,
@@ -50,14 +37,40 @@ router.get('/token', ({ query: { code } }, res) => {
new Date().getTime() + expires_in * 1e3
),
})
else return user
})
.then(({ name, id, perms }) => {
const payload = {
name,
id,
perms,
},
jwt = Jwt.sign(payload, 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) => console.error(err))
})
.catch((err) => {
res
.status(400)
.end('There was an error processing your profile information')
console.error(err)
})
})
.catch((err) => {
+8 -17
View File
@@ -1,9 +1,7 @@
import dotenv from 'dotenv'
import express from 'express'
import spotifyToYt from 'spotify-to-yt'
import db from '../db.js'
import Track from '../Track.js'
dotenv.config()
@@ -15,14 +13,14 @@ function update(data) {
db.current.update(data)
}
const playerSecret = 'Bearer ' + process.env.playerSecret
const playerSecret = 'Bearer ' + process.env.PLAYER_SECRET
// set current track
router.put(
'/set/status',
(
{
body: { tid, progress = null, duration = null, paused = null },
body: { tid = null, progress = null, duration = null, paused = null },
headers: { authorization },
},
res
@@ -33,9 +31,9 @@ router.put(
if (authorization != playerSecret)
return res.status(403).end('Token invalid')
if (tid === undefined) return res.status(400).end('"tid" field required')
if (tid.length < Track.length) return res.status(400).end('Invalid tid')
if (tid !== null)
if (typeof tid !== 'string')
return res.status(400).end('tid value invalid')
if (progress !== null)
if (typeof progress !== 'number')
@@ -52,7 +50,7 @@ router.put(
update({
cat: 'status',
content: {
tid,
...(tid !== null && { tid }),
...(progress !== null && { progress }),
...(duration !== null && { duration }),
...(paused !== null && { paused }),
@@ -75,8 +73,6 @@ router.put(
if (tid === undefined) return res.status(400).end('"tid" field required')
if (tid.length < Track.length) return res.status(400).end('Invalid tid')
update({
cat: 'next',
content: { tid },
@@ -92,13 +88,8 @@ router.get('/get/top/', ({ headers: { authorization } }, res) => {
if (authorization != playerSecret) return res.status(403).end('Token invalid')
db.top.get().then((top) => {
Promise.all(
top.map((tid) => spotifyToYt.trackGet(`spotify:track:${tid}`))
).then((yts) => {
top.map((tid, i) => (yts[i].tid = tid))
res.json(yts)
})
db.top.get().then(({ top }) => {
res.json(top)
})
})
+2 -2
View File
@@ -4,7 +4,7 @@ import db from './db.js'
dotenv.config()
const port = process.env.portWs,
const port = process.env.WS_PORT,
wss = new WebSocketServer({ port: port })
console.info('ws: listening on ' + port)
@@ -35,7 +35,7 @@ wss.on('connection', async function connection(ws, req) {
},
{
cat: 'top',
tids: await db.top.get(),
tids: (await db.top.get()).top,
timestamp: db.top.lastCount,
},
{
+3 -3
View File
@@ -6,8 +6,8 @@ import Track from './Track.js'
dotenv.config()
const spotify = new SpotifyWebApi({
clientId: process.env.spotifyClientId,
clientSecret: process.env.spotifyClientSecret,
clientId: process.env.SPOTIFY_CLIENT_ID,
clientSecret: process.env.SPOTIFY_CLIENT_SECRET,
})
function grantToken() {
@@ -15,7 +15,7 @@ function grantToken() {
.clientCredentialsGrant()
.then(
function ({ body: { access_token, expires_in } }) {
console.info('spotify: access token granted ' + expires_in)
console.info('spotify: access token granted')
spotify.setAccessToken(access_token)