DancingDuck/server/server.js
2022-06-03 09:26:09 +02:00

223 lines
6.5 KiB
JavaScript

// Start Date: 2021/10/11 15:00:00
const port = 3000;
/*
const axios = require('axios');
const cheerio = require('cheerio');
*/
const RIF = require('reddit-image-fetcher');
/*
const GPA = require('global-agent');
const NPA = GPA.createGlobalProxyAgent();
NPA.HTTP_PROXY = 'http://webproxy.bs.ptb.de:8080';
NPA.HTTPS_PROXY = 'http://webproxy.bs.ptb.de:8080';
*/
const fs = require('fs');
const cSave = __dirname+'/count.save';
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const { exec } = require('child_process');
const app = express();
const clientPath = __dirname+'/../client';
console.log('Serving static from ' + clientPath);
app.use(express.static(clientPath));
const server = http.createServer(app);
const io = socketio(server);
app.post('/receiveUpdate', (req, res) => {
res.status(200).json({success:true});
let updater = exec(`sh ${__dirname}/../gitUpdate.sh`, (error, stdout, stderr) => {
console.log(stdout);
console.error(stderr);
if (error !== null) {
console.error(`exec error: ${error}`);
}
});
});
function sleep(ms) {
return new Promise(r => {
setTimeout(r, ms);
});
}
function saveCount() {
let actualCount = Math.floor((new Date() - new Date("2021/10/11 15:00:00")) / 5600);
if (duckCount < actualCount || typeof duckCount != "number") { duckCount = actualCount; }
console.log("Newly Calculated: "+actualCount+"; Saved Count: "+duckCount);
fs.writeFile(cSave, duckCount.toString(), e=>{if(e){console.log("Error writing to SAVE file on", new Date());}});
}
server.on('error', err => {
console.error('Server error:', err);
});
server.on('close', saveCount);
server.listen(port, () => {
console.log('Server Started on Port '+port);
fs.readFile(cSave, {encoding: 'utf-8'}, (e,d)=>{
if(e){console.log("Error reading from SAVE file on", new Date());return;}
console.log("Loaded Count:", d);
duckCount = parseInt(d);
});
setInterval(()=>{duckCount++;},5600);
setInterval(saveCount,336000);
// setTimeout(()=>{console.clear();},10000);
});
let duckCount = 0;
let duckClients = Array();
io.on('connection', socket => {
let id = -1;
console.log("New Client has connected.");
while (true) {
let current = Math.floor(Math.random()*89+10);
let isUsed = false;
for (let i = 0; i < duckClients.length; i++) {
if (duckClients[i].uid == current) {
isUsed = true;
break;
}
}
if (!isUsed) {
id = current;
break;
}
}
if (id != -1) {
console.log('Handing ID', id);
socket.emit('connected', duckCount, id);
duckClients.push({socket, id});
}
socket.on('disconnect', () => {
for (let i = 0; i < duckClients.length; i++) {
if (duckClients[i].socket == socket) {
console.log("Disconnecting DUCK User. ID", duckClients[i].id);
duckClients.splice(i, 1);
break;
}
}
});
socket.on('updateCount', c => {
duckCount = c;
saveCount();
});
socket.on('saveCount', saveCount);
socket.on('duckUpdate', (c, p)=>{
// console.log("Received Update Task.");
if (c < duckCount) {
// console.log("Searching Client with ID:", p);
for (let i = 0; i < duckClients.length; i++) {
if (duckClients[i].id == p) {
// console.log("Updating Client with ID:", p);
duckClients[i].socket.emit('update', duckCount);
break;
}
}
}
});
socket.on('duckRIF', async (s, t) => {
let imgSrc = "", subreddit = "";
if (s.length > 0) {
console.log("Spreading Reddit-Image(/-s) (from subs.: '" + s.join(', ') + "') after:", t, "ms.");
let gotResult = false;
await RIF.fetch({
type: 'custom',
total: 50,
subreddit: s
}).then(r=>{
gotResult = true;
if (r && r != null) {
if (r.length > 0) {
const index = Math.floor(r.length * Math.random());
if (!r[index].NSFW && r[index].image != "") {
imgSrc = r[index].image;
subreddit = r[index].subreddit;
}
}
}
}).catch(e=>{
gotResult = true;
consle.log("Error on 'RIF':",e);
});
while (!gotResult) {
await sleep(100);
}
/*
let data;
axios.get(
"https://reddit.com/r/" + s
).then(r => {
data = r.data;
gotResult = true;
}).catch(e => {
gotResult = true;
console.log("Error on 'Axios':", e);
});
const $ = cheerio.load(data);
const urlMeme = $("._2_tDEnGMLxpM6uOa2kaDB3.ImageBox-image.media-element._1XWObl-3b9tPy64oaG6fax");
const indexValue = Math.floor(Math.random()*urlMeme.length);
imgSrc = urlMeme[indexValue].attribs.src;
*/
}
if (imgSrc != "") {
duckClients.forEach(c => {
c.socket.emit('message', imgSrc, subreddit, t);
});
}
});
socket.on('duckMessage', (inID, outName, msg) => {
let inName = inID;
for (let i = 0; i < duckClients.length; i++) {
if (duckClients[i].id == inID && duckClients[i].nickname) {
inName = duckClients[i].nickname;
break;
}
}
let outID = outName;
for (let i = 0; i < duckClients.length; i++) {
if (duckClients[i].nickname == outName) {
outID = duckClients[i].id;
break;
}
}
for (let i = 0; i < duckClients.length; i++) {
if (duckClients[i].id == outID) {
duckClients[i].socket.emit('receiveMessage', inName, msg);
break;
}
}
});
socket.on('duckRename', (id, nn) => {
for (let i = 0; i < duckClients.length; i++) {
if (duckClients[i].id == id) {
duckClients[i].nickname = nn;
break;
}
}
});
});