Compare commits
42
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6273dd4b3b | ||
|
|
8c6d5d23d0 | ||
|
|
1bc3fb8008 | ||
|
|
4680aaeba6 | ||
|
|
4ce16a20ad | ||
|
|
54dec17ef1 | ||
|
|
b3bc6942ed | ||
|
|
6b64955eac | ||
|
|
260007ca5b | ||
|
|
4dba724336 | ||
|
|
8c2034ce5b | ||
|
|
21ed1e3c20 | ||
|
|
2caf7d2e9b | ||
|
|
744c6af92c | ||
|
|
304757862a | ||
|
|
ff1215127b | ||
|
|
ebef81eda3 | ||
|
|
899aa3abc2 | ||
|
|
bc5c9aa29a | ||
|
|
353a88bc9c | ||
|
|
390dac6dc1 | ||
|
|
b08ef20da2 | ||
|
|
8faf99de37 | ||
|
|
79501a700a | ||
|
|
31bac16737 | ||
|
|
757a65884d | ||
|
|
138d10de16 | ||
|
|
bbd950fc46 | ||
|
|
830a7175f5 | ||
|
|
490d097e01 | ||
|
|
17ab445bb0 | ||
|
|
0650c278ae | ||
|
|
51694245ae | ||
|
|
3f25547362 | ||
|
|
af9934d476 | ||
|
|
27e76f7270 | ||
|
|
102ce46727 | ||
|
|
e2bb5fc87a | ||
|
|
1535747758 | ||
|
|
e5c275eefd | ||
|
|
11c6a50104 | ||
|
|
d078efa23b |
No files matched your search
@@ -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"
|
||||
}
|
||||
@@ -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"
|
||||
|
||||
+3
-2
@@ -1,5 +1,6 @@
|
||||
node_modules/
|
||||
*cred.json
|
||||
.vscode/
|
||||
.env
|
||||
old/
|
||||
.env.*
|
||||
old/
|
||||
database
|
||||
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"search.exclude": {
|
||||
"**/.git": true,
|
||||
"**/node_modules": true,
|
||||
"**/docs": true,
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
FROM node:14-stretch AS build
|
||||
WORKDIR /build
|
||||
COPY package-lock.json package.json ./
|
||||
RUN npm ci
|
||||
COPY . .
|
||||
|
||||
|
||||
FROM node:14-alpine AS deploy
|
||||
USER node
|
||||
WORKDIR /home/node/src
|
||||
COPY --from=build --chown=node:node /build .
|
||||
CMD ["node", "index.js"]
|
||||
@@ -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>
|
||||
```
|
||||
|
||||
---
|
||||
@@ -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
|
||||
@@ -1,3 +1,337 @@
|
||||
var db = {}
|
||||
import Jwt from 'jsonwebtoken'
|
||||
|
||||
import database from './mongo.js'
|
||||
|
||||
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'
|
||||
|
||||
/**
|
||||
* 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 ?? '', process.env.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
|
||||
@@ -0,0 +1,52 @@
|
||||
version: '3.1'
|
||||
|
||||
services:
|
||||
api:
|
||||
build: .
|
||||
restart: always
|
||||
container_name: api
|
||||
environment:
|
||||
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:
|
||||
- mongo
|
||||
links:
|
||||
- mongo
|
||||
mongo:
|
||||
image: mongo:5.0
|
||||
container_name: mongo
|
||||
restart: always
|
||||
environment:
|
||||
MONGO_INITDB_ROOT_USERNAME: root
|
||||
MONGO_INITDB_ROOT_PASSWORD: supersecurepassword123
|
||||
volumes:
|
||||
- ./database:/data/db
|
||||
ports:
|
||||
- 27017:27017
|
||||
command: --quiet
|
||||
redis:
|
||||
image: redis:6.2-alpine
|
||||
container_name: 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
|
||||
@@ -0,0 +1 @@
|
||||
docs.radio-rolnik.mtps.pl
|
||||
@@ -0,0 +1,15 @@
|
||||
import dotenv from 'dotenv'
|
||||
|
||||
const env = process.env.NODE_ENV,
|
||||
dotfile = {
|
||||
production: '.env',
|
||||
development: '.env.dev',
|
||||
}[env ?? 'production']
|
||||
|
||||
console.info(`env: ${env}`)
|
||||
|
||||
const config = dotenv.config({ path: `./${dotfile}` })
|
||||
|
||||
if (config.error) throw `enviroment file ${dotfile} not found`
|
||||
|
||||
export default config
|
||||
@@ -0,0 +1,8 @@
|
||||
class DbError extends Error {
|
||||
constructor(name, message, ...args) {
|
||||
super(message, ...args)
|
||||
this.name = name ?? 'DbError'
|
||||
}
|
||||
}
|
||||
|
||||
export { DbError }
|
||||
@@ -1,43 +1,60 @@
|
||||
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 { broadcast } from './socket.js'
|
||||
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'
|
||||
|
||||
dotenv.config()
|
||||
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'
|
||||
|
||||
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', process.env.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(process.env.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 ${process.env.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 ${process.env.HTTP_PORT}`)
|
||||
})
|
||||
|
||||
setInterval(() => {
|
||||
db.top.get().then(({ top, fresh }) => {
|
||||
if (fresh) {
|
||||
db.current.update({
|
||||
cat: 'top',
|
||||
content: {
|
||||
tids: top,
|
||||
timestamp: db.top.lastCount,
|
||||
},
|
||||
})
|
||||
}
|
||||
})
|
||||
}, 2e3)
|
||||
@@ -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 }
|
||||
@@ -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 }
|
||||
@@ -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 }
|
||||
@@ -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 }
|
||||
@@ -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 }
|
||||
@@ -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 }
|
||||
@@ -0,0 +1,31 @@
|
||||
import mongoose from 'mongoose'
|
||||
|
||||
const {
|
||||
DB_HOST,
|
||||
DB_PORT,
|
||||
DB_NAME,
|
||||
dbAuth = 'admin',
|
||||
DB_USER,
|
||||
DB_PASS,
|
||||
} = process.env
|
||||
|
||||
mongoose.connect(`mongodb://${DB_HOST}:${DB_PORT}/${DB_NAME}`, {
|
||||
user: DB_USER,
|
||||
pass: DB_PASS,
|
||||
authSource: dbAuth,
|
||||
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
|
||||
@@ -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 }
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
import Vote from '../models/Vote.js'
|
||||
|
||||
/**
|
||||
* 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,
|
||||
}
|
||||
+28
@@ -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";
|
||||
}
|
||||
|
||||
}
|
||||
Generated
+1387
-271
File diff suppressed because it is too large.
Load diff
+8
-2
@@ -25,10 +25,16 @@
|
||||
},
|
||||
"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",
|
||||
"mongoose": "^5.10.7",
|
||||
"spotify-web-api-node": "^5.0.2"
|
||||
"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"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import redis from 'redis'
|
||||
|
||||
const port = process.env.CACHE_PORT
|
||||
const hostName = process.env.CACHE_HOST
|
||||
|
||||
const client = redis.createClient({ host: hostName, 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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1,79 @@
|
||||
import express from 'express'
|
||||
import got from 'got'
|
||||
import Jwt from 'jsonwebtoken'
|
||||
import db from '../db.js'
|
||||
|
||||
const router = express.Router()
|
||||
|
||||
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')
|
||||
if (code.length < 1)
|
||||
return res.status(400).end('Facebook code needs to be of non zero length')
|
||||
|
||||
got(
|
||||
`https://graph.facebook.com/v12.0/oauth/access_token?client_id=${appId}&redirect_uri=https://${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 }) => {
|
||||
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, 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
|
||||
@@ -0,0 +1,108 @@
|
||||
import express from 'express'
|
||||
|
||||
import db, { parseTop } from '../db.js'
|
||||
import { countAllVotes } from '../mongo/votes.js'
|
||||
|
||||
const router = express.Router()
|
||||
|
||||
function update(data) {
|
||||
if (!Array.isArray(data)) data = [data]
|
||||
|
||||
db.current.update(data)
|
||||
}
|
||||
|
||||
const playerSecret = 'Bearer ' + process.env.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
@@ -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
|
||||
@@ -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
@@ -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
@@ -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
|
||||
@@ -0,0 +1,51 @@
|
||||
import WebSocket, { WebSocketServer } from 'ws'
|
||||
import db from './db.js'
|
||||
|
||||
const port = process.env.WS_PORT,
|
||||
wss = new WebSocketServer({ port: 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 }
|
||||
+41
-22
@@ -3,51 +3,70 @@ import SpotifyWebApi from 'spotify-web-api-node'
|
||||
import Track from './Track.js'
|
||||
|
||||
const spotify = new SpotifyWebApi({
|
||||
clientId: 'c9cd1ede71914999a75fbea35313c1a4',
|
||||
clientSecret: '13858e98eb264cf78251072f2ea5e96d',
|
||||
clientId: process.env.SPOTIFY_CLIENT_ID,
|
||||
clientSecret: process.env.SPOTIFY_CLIENT_SECRET,
|
||||
})
|
||||
|
||||
spotify.clientCredentialsGrant().then(
|
||||
function (data) {
|
||||
console.log('Spotify: access token granted')
|
||||
function grantToken() {
|
||||
spotify
|
||||
.clientCredentialsGrant()
|
||||
.then(
|
||||
function ({ body: { access_token, expires_in } }) {
|
||||
console.info('spotify: access token granted')
|
||||
|
||||
// Save the access token so that it's used in future calls
|
||||
spotify.setAccessToken(data.body['access_token'])
|
||||
},
|
||||
function (err) {
|
||||
throw err
|
||||
}
|
||||
)
|
||||
spotify.setAccessToken(access_token)
|
||||
|
||||
setTimeout(grantToken, expires_in * 1e3)
|
||||
},
|
||||
function (err) {
|
||||
throw err
|
||||
}
|
||||
)
|
||||
.catch((err) => {
|
||||
console.error(err)
|
||||
})
|
||||
}
|
||||
|
||||
grantToken()
|
||||
|
||||
function byId(id) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (typeof id != 'string')
|
||||
return reject(new Error('Incorrect id, must by type String'))
|
||||
if (id.length < 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))
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user