Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Persist server state #31

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions server/FileUtils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import fs from 'fs'

export default class FileUtils {
constructor() {}

static readJSONFromPath(filepath) {
let retObj
try {
console.log(`Reading from ${filepath}...`)
let file = fs.readFileSync(filepath, 'utf8')
retObj = JSON.parse(file)
console.log(`Successfully parsed: ${JSON.stringify(retObj)}`)
} catch (e) {
console.log(`Error reading from ${filepath}}: ${e}`)
}
return retObj
}

static readJSONArray(filepath) {
let retArr = []
try {
console.log(`Reading from ${filepath}...`)
let data = fs.readFileSync(filepath, 'utf8')
let datArr = data.split("\n")
for (let i = 0; i < datArr.length; i++) {
try {
retArr[i] = JSON.parse(datArr[i])
console.log(`Item index ${i} of ${filepath}: ${datArr[i]}`)
} catch (e) {
console.log(`Error parsing item ${i}: ${datArr[i]}`)
}
}
console.log(`Finished reading ${filepath}`)
} catch (e) {
console.log(`Error reading from ${filepath}}: ${e}`)
}
return retArr
}

static arrayOfJSONToString(arr) {
let retString = ""
for (const element of arr) {
retString += JSON.stringify(element) + "\n"
}
return retString.trimEnd()
}

static writeToPath(filepath, data) {
console.log(`Writing to ${filepath}`)
fs.writeFileSync(filepath, data, { flag: 'w' }, (err) => {
if (err) {
console.log(`Error writing ${data} to ${filepath}: ${err}`)
}
})
}
}
10 changes: 9 additions & 1 deletion server/PriorityQ.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,15 @@ export default class PriorityQ {
//
pollingRate = 50

constructor() { }
constructor() {}

initFromObject(object) {
// doesn't avoid deep copy issues. mostly for reading in from json object
this.qMap = object.qMap
this.users = object.users
this.head = object.head
this.length = object.length
}

push(song) {
if (!this.inUse) {
Expand Down
66 changes: 49 additions & 17 deletions server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,23 @@ const { Server, OPEN } = pkg
import fetch from 'node-fetch';
import Song from './Song.js';
import PriorityQ from './PriorityQ.js';
import FileUtils from './FileUtils.js'

const wss = new Server({ port: 3030 });

const BASE_PATH = process.env.DSC_BASE_PATH
const songQPath = `${BASE_PATH}/songq.json`
const chatPath = `${BASE_PATH}/chat.txt`
const songHistoryPath = `${BASE_PATH}/song_history.txt`

const userList = [];

const messages = [];
var messages = [];
const MAX_MESSAGES = 200;

const songQueue = new PriorityQ(); //handle max song queue limit on frontend
const songQueue = new PriorityQ() //handle max song queue limit on frontend

const songHistory = [];
var songHistory = [];
const MAX_SONGS_IN_HISTORY = 100;

let nowPlaying = {};
Expand All @@ -34,6 +40,30 @@ const timerInterval = setInterval(() => {
}
}, 1000);

{
// in method for single try/catch
try {
messages = FileUtils.readJSONArray(chatPath)
songHistory = FileUtils.readJSONArray(songHistoryPath)

const songQFromFile = FileUtils.readJSONFromPath(songQPath)
if (songQFromFile) { songQueue.initFromObject(songQFromFile) }
} catch (e) {
console.log(`Error reading state from files: ${e}`)
}
}

const persistChat = () => {
let messagesString = FileUtils.arrayOfJSONToString(messages)
FileUtils.writeToPath(chatPath, messagesString)
}

const persistSongState = () => {
let songHistoryString = FileUtils.arrayOfJSONToString(songHistory)
FileUtils.writeToPath(songHistoryPath, songHistoryString)
FileUtils.writeToPath(songQPath, JSON.stringify(songQueue))
}

const broadcast = (data) => {
wss.clients.forEach((client) => {
if (client.readyState === OPEN) {
Expand Down Expand Up @@ -104,14 +134,15 @@ const addMessage = (message) => {
}
);

persistChat()
broadcast(data);
};

const getOEmbedData = async (url) => {
// hacky way to check if soundcloud
if (url.includes('soundcloud.')) {
const fetchUrl = `https://www.soundcloud.com/oembed?url=${url}&format=json`;

const response = await fetch(fetchUrl);

return response.json();
Expand All @@ -128,8 +159,6 @@ const getOEmbedData = async (url) => {
};

const addSong = async (username, url, label, duration) => {
// TODO: order the queue so that each user takes turn playing songs, maybe not necessarily here

// create song object
let newSong = new Song(username, url, label, duration);

Expand All @@ -139,11 +168,11 @@ const addSong = async (username, url, label, duration) => {

//hacky way to fix react-player not being able to play the same url twice in a row
// -- adding ?in to the end of the url seems to still let it play for both yt and sc
if (songQueue.length > 0 && songQueue.getSongAtIndex(songQueue.length - 1).url === url) {
if (songQueue.length > 0 && songQueue.getSongAtIndex(songQueue.length - 1).url === url) {
newSong.url = `${url}?in`;
newSong.label = oEmbedData.title;
}
}

else {
newSong.label = oEmbedData.title
};
Expand All @@ -154,13 +183,14 @@ const addSong = async (username, url, label, duration) => {

let flatQ = songQueue.flatten()
const data = JSON.stringify(

{
type: 'addSong',
songQueue: flatQ
}
);

persistSongState()
broadcast(data);
};

Expand All @@ -181,16 +211,17 @@ const removeSong = (index) => {
}
);

persistSongState()
broadcast(data);
};

const nextSong = () => {
nowPlaying = {};
seekTime = 0;

const timestamp = new Date().toLocaleTimeString([], { hour12: false, hour: '2-digit', minute: '2-digit' });
songHistory.unshift({...songQueue.shift(), timestamp});
const timestamp = new Date().toLocaleTimeString([], { hour12: false, hour: '2-digit', minute: '2-digit' });
songHistory.unshift({ ...songQueue.shift(), timestamp });

if (songHistory.length > MAX_SONGS_IN_HISTORY) {
songHistory.pop();
};
Expand All @@ -205,6 +236,7 @@ const nextSong = () => {
}
);

persistSongState()
broadcast(data);
};

Expand All @@ -214,9 +246,9 @@ wss.on('connection', (ws) => {

ws.on('message', (data) => {
console.log(data);

// HH:mm format
const timestamp = new Date().toLocaleTimeString([], { hour12: false, hour: '2-digit', minute: '2-digit' });
const timestamp = new Date().toLocaleTimeString([], { hour12: false, hour: '2-digit', minute: '2-digit' });

const clientMessage = JSON.parse(data);
switch (clientMessage.type) {
Expand All @@ -235,7 +267,7 @@ wss.on('connection', (ws) => {
case 'chat':
addMessage({
message: clientMessage.message,
username,
username,
type: 'chat',
timestamp
});
Expand Down Expand Up @@ -272,7 +304,7 @@ wss.on('connection', (ws) => {

ws.on('close', () => {
// HH:mm format
const timestamp = new Date().toLocaleTimeString([], { hour12: false, hour: '2-digit', minute: '2-digit' });
const timestamp = new Date().toLocaleTimeString([], { hour12: false, hour: '2-digit', minute: '2-digit' });

addMessage({
username,
Expand Down