diff --git a/.gitignore b/.gitignore index 49c6f73..87c9ad3 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ server/sound/ *.db -start.bat \ No newline at end of file +start.bat +.env +venv/ \ No newline at end of file diff --git a/Client/ext/popper.js b/Client/ext/popper.js new file mode 100644 index 0000000..19a42b9 --- /dev/null +++ b/Client/ext/popper.js @@ -0,0 +1,134 @@ +function Pop() { + // var cssRuleFile = "/src/css/style.css"; // will be the link once this css file became available online + var cssRuleFile = "https://cookieconsent.popupsmart.com/src/css/style.css"; // will be the link once this css file became available online + + let lnk = document.createElement("link"); + lnk.setAttribute("rel", "stylesheet"); + lnk.setAttribute("type", "text/css"); + lnk.setAttribute("href", cssRuleFile); + document.getElementsByTagName("head")[0].appendChild(lnk); + + let styl = "undefined"; + var conDivObj; + + var fadeInTime = 10; // If needed could be served as an customizable option to the user + var fadeOutTime = 10; + + let cookie = { + name: "cookieconsent_status", + path: "/", + expiryDays: 365 * 24 * 60 * 60 * 5000, + }; + + let content = { + /// Add a field for link color + message: + "This website uses cookies to ensure you get the best experience on our website.", + btnText: "Got it!", + mode: " banner bottom", + theme: " theme-classic", + palette: " palette1", + link: "Learn more", + href: "https://www.cookiesandyou.com", + target: "_blank", + }; + + let createPopUp = function () { + console.log(content); + if (typeof conDivObj === "undefined") { + conDivObj = document.createElement("DIV"); + conDivObj.style.opacity = 0; + conDivObj.setAttribute("id", "spopupCont"); + } + conDivObj.innerHTML = + '
' + + content.message + + '" + + content.link + + '
' + + content.btnText + + '
Powered by Popupsmart
'; + + document.body.appendChild(conDivObj); + fadeIn(conDivObj); + + document + .getElementById("cookie-btn") + .addEventListener("click", function () { + saveCookie(); + fadeOut(conDivObj); + }); + }; + + let fadeOut = function (element) { + var op = 1; + var timer = setInterval(function () { + if (op <= 0.1) { + clearInterval(timer); + conDivObj.parentElement.removeChild(conDivObj); + } + element.style.opacity = op; + element.style.filter = "alpha(opacity=" + op * 100 + ")"; + op -= op * 0.1; + }, fadeOutTime); + }; + let fadeIn = function (element) { + var op = 0.1; + var timer = setInterval(function () { + if (op >= 1) { + clearInterval(timer); + } + element.style.opacity = op; + element.style.filter = "alpha(opacity=" + op * 100 + ")"; + op += op * 0.1; + }, fadeInTime); + }; + + let checkCookie = function (key) { + var keyValue = document.cookie.match("(^|;) ?" + key + "=([^;]*)(;|$)"); + return keyValue ? true : false; + }; + + let saveCookie = function () { + var expires = new Date(); + expires.setTime(expires.getTime() + cookie.expiryDays); + document.cookie = + cookie.name + + "=" + + "ok" + + ";expires=" + + expires.toUTCString() + + "path=" + + cookie.path; + }; + + this.init = function (param) { + if (checkCookie(cookie.name)) return; + + if (typeof param === "object") { + if ("ButtonText" in param) content.btnText = param.ButtonText; + if ("Mode" in param) content.mode = " " + param.Mode; + if ("Theme" in param) content.theme = " " + param.Theme; + if ("Palette" in param) content.palette = " " + param.Palette; + if ("Message" in param) content.message = param.Message; + if ("LinkText" in param) content.link = param.LinkText; + if ("Location" in param) content.href = param.Location; + if ("Target" in param) content.target = param.Target; + if ("Time" in param) + setTimeout(function () { + createPopUp(); + }, param.Time * 1000); + else createPopUp(); + } + }; +} +window.start = new Pop(); diff --git a/Client/ext/qrcode.min.js b/Client/ext/qrcode.min.js new file mode 100644 index 0000000..993e88f --- /dev/null +++ b/Client/ext/qrcode.min.js @@ -0,0 +1 @@ +var QRCode;!function(){function a(a){this.mode=c.MODE_8BIT_BYTE,this.data=a,this.parsedData=[];for(var b=[],d=0,e=this.data.length;e>d;d++){var f=this.data.charCodeAt(d);f>65536?(b[0]=240|(1835008&f)>>>18,b[1]=128|(258048&f)>>>12,b[2]=128|(4032&f)>>>6,b[3]=128|63&f):f>2048?(b[0]=224|(61440&f)>>>12,b[1]=128|(4032&f)>>>6,b[2]=128|63&f):f>128?(b[0]=192|(1984&f)>>>6,b[1]=128|63&f):b[0]=f,this.parsedData=this.parsedData.concat(b)}this.parsedData.length!=this.data.length&&(this.parsedData.unshift(191),this.parsedData.unshift(187),this.parsedData.unshift(239))}function b(a,b){this.typeNumber=a,this.errorCorrectLevel=b,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}function i(a,b){if(void 0==a.length)throw new Error(a.length+"/"+b);for(var c=0;c=f;f++){var h=0;switch(b){case d.L:h=l[f][0];break;case d.M:h=l[f][1];break;case d.Q:h=l[f][2];break;case d.H:h=l[f][3]}if(h>=e)break;c++}if(c>l.length)throw new Error("Too long data");return c}function s(a){var b=encodeURI(a).toString().replace(/\%[0-9a-fA-F]{2}/g,"a");return b.length+(b.length!=a?3:0)}a.prototype={getLength:function(){return this.parsedData.length},write:function(a){for(var b=0,c=this.parsedData.length;c>b;b++)a.put(this.parsedData[b],8)}},b.prototype={addData:function(b){var c=new a(b);this.dataList.push(c),this.dataCache=null},isDark:function(a,b){if(0>a||this.moduleCount<=a||0>b||this.moduleCount<=b)throw new Error(a+","+b);return this.modules[a][b]},getModuleCount:function(){return this.moduleCount},make:function(){this.makeImpl(!1,this.getBestMaskPattern())},makeImpl:function(a,c){this.moduleCount=4*this.typeNumber+17,this.modules=new Array(this.moduleCount);for(var d=0;d=7&&this.setupTypeNumber(a),null==this.dataCache&&(this.dataCache=b.createData(this.typeNumber,this.errorCorrectLevel,this.dataList)),this.mapData(this.dataCache,c)},setupPositionProbePattern:function(a,b){for(var c=-1;7>=c;c++)if(!(-1>=a+c||this.moduleCount<=a+c))for(var d=-1;7>=d;d++)-1>=b+d||this.moduleCount<=b+d||(this.modules[a+c][b+d]=c>=0&&6>=c&&(0==d||6==d)||d>=0&&6>=d&&(0==c||6==c)||c>=2&&4>=c&&d>=2&&4>=d?!0:!1)},getBestMaskPattern:function(){for(var a=0,b=0,c=0;8>c;c++){this.makeImpl(!0,c);var d=f.getLostPoint(this);(0==c||a>d)&&(a=d,b=c)}return b},createMovieClip:function(a,b,c){var d=a.createEmptyMovieClip(b,c),e=1;this.make();for(var f=0;f=g;g++)for(var h=-2;2>=h;h++)this.modules[d+g][e+h]=-2==g||2==g||-2==h||2==h||0==g&&0==h?!0:!1}},setupTypeNumber:function(a){for(var b=f.getBCHTypeNumber(this.typeNumber),c=0;18>c;c++){var d=!a&&1==(1&b>>c);this.modules[Math.floor(c/3)][c%3+this.moduleCount-8-3]=d}for(var c=0;18>c;c++){var d=!a&&1==(1&b>>c);this.modules[c%3+this.moduleCount-8-3][Math.floor(c/3)]=d}},setupTypeInfo:function(a,b){for(var c=this.errorCorrectLevel<<3|b,d=f.getBCHTypeInfo(c),e=0;15>e;e++){var g=!a&&1==(1&d>>e);6>e?this.modules[e][8]=g:8>e?this.modules[e+1][8]=g:this.modules[this.moduleCount-15+e][8]=g}for(var e=0;15>e;e++){var g=!a&&1==(1&d>>e);8>e?this.modules[8][this.moduleCount-e-1]=g:9>e?this.modules[8][15-e-1+1]=g:this.modules[8][15-e-1]=g}this.modules[this.moduleCount-8][8]=!a},mapData:function(a,b){for(var c=-1,d=this.moduleCount-1,e=7,g=0,h=this.moduleCount-1;h>0;h-=2)for(6==h&&h--;;){for(var i=0;2>i;i++)if(null==this.modules[d][h-i]){var j=!1;g>>e));var k=f.getMask(b,d,h-i);k&&(j=!j),this.modules[d][h-i]=j,e--,-1==e&&(g++,e=7)}if(d+=c,0>d||this.moduleCount<=d){d-=c,c=-c;break}}}},b.PAD0=236,b.PAD1=17,b.createData=function(a,c,d){for(var e=j.getRSBlocks(a,c),g=new k,h=0;h8*l)throw new Error("code length overflow. ("+g.getLengthInBits()+">"+8*l+")");for(g.getLengthInBits()+4<=8*l&&g.put(0,4);0!=g.getLengthInBits()%8;)g.putBit(!1);for(;;){if(g.getLengthInBits()>=8*l)break;if(g.put(b.PAD0,8),g.getLengthInBits()>=8*l)break;g.put(b.PAD1,8)}return b.createBytes(g,e)},b.createBytes=function(a,b){for(var c=0,d=0,e=0,g=new Array(b.length),h=new Array(b.length),j=0;j=0?p.get(q):0}}for(var r=0,m=0;mm;m++)for(var j=0;jm;m++)for(var j=0;j=0;)b^=f.G15<=0;)b^=f.G18<>>=1;return b},getPatternPosition:function(a){return f.PATTERN_POSITION_TABLE[a-1]},getMask:function(a,b,c){switch(a){case e.PATTERN000:return 0==(b+c)%2;case e.PATTERN001:return 0==b%2;case e.PATTERN010:return 0==c%3;case e.PATTERN011:return 0==(b+c)%3;case e.PATTERN100:return 0==(Math.floor(b/2)+Math.floor(c/3))%2;case e.PATTERN101:return 0==b*c%2+b*c%3;case e.PATTERN110:return 0==(b*c%2+b*c%3)%2;case e.PATTERN111:return 0==(b*c%3+(b+c)%2)%2;default:throw new Error("bad maskPattern:"+a)}},getErrorCorrectPolynomial:function(a){for(var b=new i([1],0),c=0;a>c;c++)b=b.multiply(new i([1,g.gexp(c)],0));return b},getLengthInBits:function(a,b){if(b>=1&&10>b)switch(a){case c.MODE_NUMBER:return 10;case c.MODE_ALPHA_NUM:return 9;case c.MODE_8BIT_BYTE:return 8;case c.MODE_KANJI:return 8;default:throw new Error("mode:"+a)}else if(27>b)switch(a){case c.MODE_NUMBER:return 12;case c.MODE_ALPHA_NUM:return 11;case c.MODE_8BIT_BYTE:return 16;case c.MODE_KANJI:return 10;default:throw new Error("mode:"+a)}else{if(!(41>b))throw new Error("type:"+b);switch(a){case c.MODE_NUMBER:return 14;case c.MODE_ALPHA_NUM:return 13;case c.MODE_8BIT_BYTE:return 16;case c.MODE_KANJI:return 12;default:throw new Error("mode:"+a)}}},getLostPoint:function(a){for(var b=a.getModuleCount(),c=0,d=0;b>d;d++)for(var e=0;b>e;e++){for(var f=0,g=a.isDark(d,e),h=-1;1>=h;h++)if(!(0>d+h||d+h>=b))for(var i=-1;1>=i;i++)0>e+i||e+i>=b||(0!=h||0!=i)&&g==a.isDark(d+h,e+i)&&f++;f>5&&(c+=3+f-5)}for(var d=0;b-1>d;d++)for(var e=0;b-1>e;e++){var j=0;a.isDark(d,e)&&j++,a.isDark(d+1,e)&&j++,a.isDark(d,e+1)&&j++,a.isDark(d+1,e+1)&&j++,(0==j||4==j)&&(c+=3)}for(var d=0;b>d;d++)for(var e=0;b-6>e;e++)a.isDark(d,e)&&!a.isDark(d,e+1)&&a.isDark(d,e+2)&&a.isDark(d,e+3)&&a.isDark(d,e+4)&&!a.isDark(d,e+5)&&a.isDark(d,e+6)&&(c+=40);for(var e=0;b>e;e++)for(var d=0;b-6>d;d++)a.isDark(d,e)&&!a.isDark(d+1,e)&&a.isDark(d+2,e)&&a.isDark(d+3,e)&&a.isDark(d+4,e)&&!a.isDark(d+5,e)&&a.isDark(d+6,e)&&(c+=40);for(var k=0,e=0;b>e;e++)for(var d=0;b>d;d++)a.isDark(d,e)&&k++;var l=Math.abs(100*k/b/b-50)/5;return c+=10*l}},g={glog:function(a){if(1>a)throw new Error("glog("+a+")");return g.LOG_TABLE[a]},gexp:function(a){for(;0>a;)a+=255;for(;a>=256;)a-=255;return g.EXP_TABLE[a]},EXP_TABLE:new Array(256),LOG_TABLE:new Array(256)},h=0;8>h;h++)g.EXP_TABLE[h]=1<h;h++)g.EXP_TABLE[h]=g.EXP_TABLE[h-4]^g.EXP_TABLE[h-5]^g.EXP_TABLE[h-6]^g.EXP_TABLE[h-8];for(var h=0;255>h;h++)g.LOG_TABLE[g.EXP_TABLE[h]]=h;i.prototype={get:function(a){return this.num[a]},getLength:function(){return this.num.length},multiply:function(a){for(var b=new Array(this.getLength()+a.getLength()-1),c=0;cf;f++)for(var g=c[3*f+0],h=c[3*f+1],i=c[3*f+2],k=0;g>k;k++)e.push(new j(h,i));return e},j.getRsBlockTable=function(a,b){switch(b){case d.L:return j.RS_BLOCK_TABLE[4*(a-1)+0];case d.M:return j.RS_BLOCK_TABLE[4*(a-1)+1];case d.Q:return j.RS_BLOCK_TABLE[4*(a-1)+2];case d.H:return j.RS_BLOCK_TABLE[4*(a-1)+3];default:return void 0}},k.prototype={get:function(a){var b=Math.floor(a/8);return 1==(1&this.buffer[b]>>>7-a%8)},put:function(a,b){for(var c=0;b>c;c++)this.putBit(1==(1&a>>>b-c-1))},getLengthInBits:function(){return this.length},putBit:function(a){var b=Math.floor(this.length/8);this.buffer.length<=b&&this.buffer.push(0),a&&(this.buffer[b]|=128>>>this.length%8),this.length++}};var l=[[17,14,11,7],[32,26,20,14],[53,42,32,24],[78,62,46,34],[106,84,60,44],[134,106,74,58],[154,122,86,64],[192,152,108,84],[230,180,130,98],[271,213,151,119],[321,251,177,137],[367,287,203,155],[425,331,241,177],[458,362,258,194],[520,412,292,220],[586,450,322,250],[644,504,364,280],[718,560,394,310],[792,624,442,338],[858,666,482,382],[929,711,509,403],[1003,779,565,439],[1091,857,611,461],[1171,911,661,511],[1273,997,715,535],[1367,1059,751,593],[1465,1125,805,625],[1528,1190,868,658],[1628,1264,908,698],[1732,1370,982,742],[1840,1452,1030,790],[1952,1538,1112,842],[2068,1628,1168,898],[2188,1722,1228,958],[2303,1809,1283,983],[2431,1911,1351,1051],[2563,1989,1423,1093],[2699,2099,1499,1139],[2809,2213,1579,1219],[2953,2331,1663,1273]],o=function(){var a=function(a,b){this._el=a,this._htOption=b};return a.prototype.draw=function(a){function g(a,b){var c=document.createElementNS("http://www.w3.org/2000/svg",a);for(var d in b)b.hasOwnProperty(d)&&c.setAttribute(d,b[d]);return c}var b=this._htOption,c=this._el,d=a.getModuleCount();Math.floor(b.width/d),Math.floor(b.height/d),this.clear();var h=g("svg",{viewBox:"0 0 "+String(d)+" "+String(d),width:"100%",height:"100%",fill:b.colorLight});h.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:xlink","http://www.w3.org/1999/xlink"),c.appendChild(h),h.appendChild(g("rect",{fill:b.colorDark,width:"1",height:"1",id:"template"}));for(var i=0;d>i;i++)for(var j=0;d>j;j++)if(a.isDark(i,j)){var k=g("use",{x:String(i),y:String(j)});k.setAttributeNS("http://www.w3.org/1999/xlink","href","#template"),h.appendChild(k)}},a.prototype.clear=function(){for(;this._el.hasChildNodes();)this._el.removeChild(this._el.lastChild)},a}(),p="svg"===document.documentElement.tagName.toLowerCase(),q=p?o:m()?function(){function a(){this._elImage.src=this._elCanvas.toDataURL("image/png"),this._elImage.style.display="block",this._elCanvas.style.display="none"}function d(a,b){var c=this;if(c._fFail=b,c._fSuccess=a,null===c._bSupportDataURI){var d=document.createElement("img"),e=function(){c._bSupportDataURI=!1,c._fFail&&_fFail.call(c)},f=function(){c._bSupportDataURI=!0,c._fSuccess&&c._fSuccess.call(c)};return d.onabort=e,d.onerror=e,d.onload=f,d.src="data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==",void 0}c._bSupportDataURI===!0&&c._fSuccess?c._fSuccess.call(c):c._bSupportDataURI===!1&&c._fFail&&c._fFail.call(c)}if(this._android&&this._android<=2.1){var b=1/window.devicePixelRatio,c=CanvasRenderingContext2D.prototype.drawImage;CanvasRenderingContext2D.prototype.drawImage=function(a,d,e,f,g,h,i,j){if("nodeName"in a&&/img/i.test(a.nodeName))for(var l=arguments.length-1;l>=1;l--)arguments[l]=arguments[l]*b;else"undefined"==typeof j&&(arguments[1]*=b,arguments[2]*=b,arguments[3]*=b,arguments[4]*=b);c.apply(this,arguments)}}var e=function(a,b){this._bIsPainted=!1,this._android=n(),this._htOption=b,this._elCanvas=document.createElement("canvas"),this._elCanvas.width=b.width,this._elCanvas.height=b.height,a.appendChild(this._elCanvas),this._el=a,this._oContext=this._elCanvas.getContext("2d"),this._bIsPainted=!1,this._elImage=document.createElement("img"),this._elImage.style.display="none",this._el.appendChild(this._elImage),this._bSupportDataURI=null};return e.prototype.draw=function(a){var b=this._elImage,c=this._oContext,d=this._htOption,e=a.getModuleCount(),f=d.width/e,g=d.height/e,h=Math.round(f),i=Math.round(g);b.style.display="none",this.clear();for(var j=0;e>j;j++)for(var k=0;e>k;k++){var l=a.isDark(j,k),m=k*f,n=j*g;c.strokeStyle=l?d.colorDark:d.colorLight,c.lineWidth=1,c.fillStyle=l?d.colorDark:d.colorLight,c.fillRect(m,n,f,g),c.strokeRect(Math.floor(m)+.5,Math.floor(n)+.5,h,i),c.strokeRect(Math.ceil(m)-.5,Math.ceil(n)-.5,h,i)}this._bIsPainted=!0},e.prototype.makeImage=function(){this._bIsPainted&&d.call(this,a)},e.prototype.isPainted=function(){return this._bIsPainted},e.prototype.clear=function(){this._oContext.clearRect(0,0,this._elCanvas.width,this._elCanvas.height),this._bIsPainted=!1},e.prototype.round=function(a){return a?Math.floor(1e3*a)/1e3:a},e}():function(){var a=function(a,b){this._el=a,this._htOption=b};return a.prototype.draw=function(a){for(var b=this._htOption,c=this._el,d=a.getModuleCount(),e=Math.floor(b.width/d),f=Math.floor(b.height/d),g=[''],h=0;d>h;h++){g.push("");for(var i=0;d>i;i++)g.push('');g.push("")}g.push("
"),c.innerHTML=g.join("");var j=c.childNodes[0],k=(b.width-j.offsetWidth)/2,l=(b.height-j.offsetHeight)/2;k>0&&l>0&&(j.style.margin=l+"px "+k+"px")},a.prototype.clear=function(){this._el.innerHTML=""},a}();QRCode=function(a,b){if(this._htOption={width:256,height:256,typeNumber:4,colorDark:"#000000",colorLight:"#ffffff",correctLevel:d.H},"string"==typeof b&&(b={text:b}),b)for(var c in b)this._htOption[c]=b[c];"string"==typeof a&&(a=document.getElementById(a)),this._android=n(),this._el=a,this._oQRCode=null,this._oDrawing=new q(this._el,this._htOption),this._htOption.text&&this.makeCode(this._htOption.text)},QRCode.prototype.makeCode=function(a){this._oQRCode=new b(r(a,this._htOption.correctLevel),this._htOption.correctLevel),this._oQRCode.addData(a),this._oQRCode.make(),this._el.title=a,this._oDrawing.draw(this._oQRCode),this.makeImage()},QRCode.prototype.makeImage=function(){"function"==typeof this._oDrawing.makeImage&&(!this._android||this._android>=3)&&this._oDrawing.makeImage()},QRCode.prototype.clear=function(){this._oDrawing.clear()},QRCode.CorrectLevel=d}(); \ No newline at end of file diff --git a/Client/images/play-pause-old.png b/Client/images/play-pause-old.png new file mode 100644 index 0000000..3796891 Binary files /dev/null and b/Client/images/play-pause-old.png differ diff --git a/Client/images/play-pause.png b/Client/images/play-pause.png index 3796891..89fa081 100644 Binary files a/Client/images/play-pause.png and b/Client/images/play-pause.png differ diff --git a/Client/index.html b/Client/index.html index 6012ac4..3a86b52 100644 --- a/Client/index.html +++ b/Client/index.html @@ -5,10 +5,14 @@ + + + + - +

Jukebox Remote

@@ -22,12 +26,12 @@ changes visibility with JS-->
-

Search to find songs!

+

Search to find songs!

Client Settings (Saved to device)

-

Server IP:

IP of the device running the song server

@@ -81,26 +84,50 @@ changes visibility with JS-->

Volume of the music

-
+

Share the remote:

- +

This shares the IP and URL you are currently connected to

-

Version 1.0.2

-

PartyJukebox is under an AGPLV3 liscense. You can access the source code here.

+

Admin Settings

+

Note: Admin password must have been set from the server

+
+

Admin Password:

+

Enter to use admin restricted functions

+ +
+
+

Fine action control:

+

A check means that action is avalible to everyone

+
+
+
+
+
+
+
+ +
+
+
+

Clear the playlist

+

Wipe the playlist, except the currently playing song. With PartyMode enabled, a second song will be added back randomly

+ +
+

PartyJukebox is under an AGPLV3 liscense. You can access the source code here.

- settings
- playlist - play pause - skip - search - + Playlist + Play pause + Skip + Search
- +
+ settings +
+ \ No newline at end of file diff --git a/Client/scripts.js b/Client/scripts.js index a63ee01..58e923b 100644 --- a/Client/scripts.js +++ b/Client/scripts.js @@ -1,5 +1,37 @@ -let ip -let alertTime = 2 +// set all the global stuff +let ip; +let alertTime = 2; +let adminPass = ""; +let justSkipped = false; +let justChangedSetting = false; +const ERR_NO_ADMIN = 401; +const VALID_FILE_EXT = ["mp3","flac","wav"]; + +let playlistTimeTimer=null; +let playlistElapsedSeconds=0; +let playlistSongLength=-1; +let currentlyPlaying = false; + +const params = new URLSearchParams(location.search); + +let darkmodetemp = getCookie("darkmode"); +if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) { + darkmodetemp = "true"; +} +if(darkmodetemp === "") { + darkmodetemp = params.get("darkmode") +} +if (darkmodetemp === "true") { + // i know this is gonna cause weird blinking + // maybe the dark mode function should be loaded before any content, would that work? + // NEW JS FILE ????? exciting stuff + // im thinking a few new js files + // you know like good design separating stuff + // yeah but i need the getCookie function in both the darkmode.js and this one, so im gonna make a + // getcookie.js + toggleDark("None"); +} + async function alertText(text="Song Added!") { alertbox = document.getElementById("alert"); alertbox.innerHTML = text; @@ -10,29 +42,54 @@ async function alertText(text="Song Added!") { } // a lot of this is kinda waffly because i was trying to get // it to return the right stuff and javascript is asyrcronouse (boo) -async function getFromServer(bodyInfo, source="") { +async function getFromServer(bodyInfo, source="", secure=false, password=adminPass) { try{ - const response = await fetch("http://"+ip+"/"+source, { + if (bodyInfo != null) { + // the currently set password is always included in every request + bodyInfo["password"] = password; + } + let href = ""; + if(secure) { + href = "https://"+ip+"/" + source; + } else { + href = "http://"+ip+"/" + source; + } + const response = await fetch(href, { method: "POST", body: JSON.stringify(bodyInfo), headers: { "Content-type": "application/json; charset=UTF-8" } }); - const data = await response.json(); + + let data = await response.json(); // original json + if (response.status == ERR_NO_ADMIN) { + // im suprised i didn't comment on this already but this is kinda lame desing + // its not wrong but you know + // it is easy which i like + alertText("Error: Admin restricted action") + } else if(!response.ok){ + throw new Error(data.error); + alertText("Error: "+data.error); + } + // we add some information from the response just in case it is needed + data["ok"] = response.ok; + data["status"] = response.status; + // console.log(data); return await data; } catch(e) { - if (e == "TypeError: Failed to fetch"){ - alertText("error: Can't Connect to Server (is the ip set?)") + // console.log("error print here:"); + // console.log(e); + if (e.toString().includes("TypeError: Failed to fetch")){ + alertText("Error: Can't Connect to Server (is the ip set?)") } else { - alertText("error: " + e) + alertText(e); } const response=null; return response; } } - //cookie reader is taken from internet because cookies ae too complicated for me //i still understand how it works though promise just i see no reason to write this from scratch function getCookie(cname) { @@ -51,37 +108,56 @@ function getCookie(cname) { return ""; } //someone more organised than me would have set all these html elements to variables so they dont have to get them 50 times +// also someone who likes things not being dumb more than me would have separated the client and server buttons async function controlButton(buttonType) { - if (buttonType == "pp") { - getFromServer({control: "play-pause"}, "controls") - } else if (buttonType == "sk") { - getFromServer({control: "skip"}, "controls") - if (document.getElementById("playlist-mode").style.display == "block") { - generateVisualPlaylist("skip-button"); + if (buttonType == "pp") { // Play-Pause button + let result = await getFromServer({control: "play-pause"}, "controls"); + // console.log(result); + currentlyPlaying = result["data"]["playingState"]; + } else if (buttonType == "sk") { // Skip button + // clearInterval(playlistTimeTimer); + let returnCode = await getFromServer({control: "skip"}, "controls"); + // console.log(returnCode["ok"]) + if(returnCode["ok"]) { + if (document.getElementById("playlist-mode").style.display == "block") { + skipInPlaylist(); + playlistElapsedSeconds = 0; + justSkipped = true; + } } - } else if (buttonType == "pl") { + } else if (buttonType == "pl") { // Playlist button + clearInterval(playlistTimeTimer); document.getElementById("songlist").innerHTML = ""; document.getElementById("playlist").innerHTML = "

"; document.getElementById("playlist-mode").style.display = "block"; document.getElementById("songlist-mode").style.display = "none"; document.getElementById("settings-mode").style.display = "none"; generateVisualPlaylist(); - } else if (buttonType == "se") { + } else if (buttonType == "se") { //SearchMode button + clearInterval(playlistTimeTimer); document.getElementById("songlist").innerHTML = "

Search to find songs!

"; document.getElementById("playlist").innerHTML = ""; document.getElementById("playlist-mode").style.display = "none"; document.getElementById("songlist-mode").style.display = "block"; document.getElementById("settings-mode").style.display = "none"; - } else if (buttonType == "st") { + } else if (buttonType == "st") { //Settings button + clearInterval(playlistTimeTimer); document.getElementById("songlist").innerHTML = ""; document.getElementById("playlist").innerHTML = ""; document.getElementById("playlist-mode").style.display = "none"; document.getElementById("songlist-mode").style.display = "none"; document.getElementById("settings-mode").style.display = "block"; checkSettings() - } else if (buttonType = "pm") { - await getFromServer({setting: "partymode-toggle"}, "settings") - checkSettings(true) + } else if (buttonType == "pm") { //Partymode toggle (in settings) + let response = await getFromServer({setting: "partymode-toggle"}, "settings") + if(response.ok) { + justChangedSetting = true; + checkSettings(); + } else { + // dont think anything is needed here + } + } else { + alertText("Error: You pushed a button that does not exist"); } @@ -94,15 +170,16 @@ function searchSongsEnter(e) { } async function searchSongs(searchTerm){ - let optionslist = [] document.getElementById("songlist").innerHTML = "" - searchResults = await getFromServer({search:searchTerm},"search").then() + let fetchResults = await getFromServer({search:searchTerm},"search").then(); + let searchResults = fetchResults.data; //generate the visual song list for(var fileName in searchResults) { let currentSongInJSON = searchResults[fileName] let newItem = document.createElement("div"); newItem.className = "item"; newItem.id = fileName; + newItem.tabIndex = 0; let image = document.createElement("img"); try { if (currentSongInJSON["art"] == null) { @@ -120,6 +197,13 @@ async function searchSongs(searchTerm){ newItem.appendChild(image); newItem.appendChild(head3); newItem.appendChild(head4); + // I like this concept but i'm leaving it out for now + if(currentSongInJSON.lossless === 1) { + let losslesstag = document.createElement("p"); + losslesstag.textContent = "Ⓛ"; + losslesstag.classList.add("lossless-tag"); + newItem.appendChild(losslesstag); + } document.getElementById("songlist").appendChild(newItem); } @@ -128,6 +212,7 @@ async function searchSongs(searchTerm){ document.getElementById("songlist").innerHTML = "

We might not have that one...

"; } } + function alertTimeEnter(e){ if (e.key == "Enter") { e.preventDefault(); @@ -143,7 +228,11 @@ function alertTimeSet(time) { function ipSetEnter(e){ if (e.key == "Enter") { - e.preventDefault(); + e.preventDefault(); + // why on gosh's green earth am i sending a value here? + // im gonna get rid of all these individual "enter" dectectors and do something + // like i did for the keyboard selection of elements + // basically just if(e==click || e.key == enter) ipSetter(document.getElementById("iptextbox").value) } } @@ -164,23 +253,68 @@ function ipSetter(){ alertText("Your IP is now set to "+ipBox+" at port 19054 (Default)") } } + // anytime the server ip changes the qrcode should change to use it qrCodeGenerate() } function qrCodeGenerate() { let tempURL = "http://" + document.location.href.split("/")[2] + "/?ip=" + ip; - document.getElementById("qrcode").innerHTML = "" + document.getElementById("qrcode").innerHTML = ""; + // get the current foreground and background + let dark = window.getComputedStyle(document.body).getPropertyValue("--text-color"); + let light = window.getComputedStyle(document.body).getPropertyValue("--bg-main"); new QRCode(document.getElementById("qrcode"), { text: tempURL, width: 256, height: 256, - colorDark : "#000000", - colorLight : "#eeeeee", + colorDark : dark, + colorLight : light, correctLevel : QRCode.CorrectLevel.H }); } +async function displayElapsedPlaylistTime(elapsed=0,length=-1) { + if(currentlyPlaying) { + if(Math.floor(elapsed) > Math.floor(length) && typeof length === "number" && typeof elapsed === "number"){ + // console.log("somethingShouldBeHappening") + playlistElapsedSeconds = 0; + generateVisualPlaylist(); + } + let mins = Math.floor(elapsed/60); + let secs = Math.floor(elapsed%60); + let durMins = Math.floor(length/60); + let durSecs = Math.floor(length%60); + let timeLeft = document.getElementById("elapsed-time-display"); + if(mins > durMins) { + mins = durMins; + if(secs > durSecs) { + secs = durSecs; + } + } + + timeLeft.innerHTML = mins.toString() +":"+ secs.toLocaleString('en-US', {minimumIntegerDigits: 2,useGrouping: false}) + "/"+ durMins.toString()+":"+durSecs.toLocaleString('en-US', {minimumIntegerDigits: 2,useGrouping: false}); + playlistElapsedSeconds++; + } +} + +async function updateSingleSetting(data) { + let toBeChanged = data["settingToChange"]; + if (toBeChanged === "partymode") { + document.getElementById("partymode-button").textContent = data["newData"]; + } else if (toBeChanged === "perms") { + let currentAdminPerms = data["newData"]; + document.getElementById("addsongsettingcheckbox").checked = currentAdminPerms["AS"]; + document.getElementById("skipsongsettingcheckbox").checked = currentAdminPerms["SK"]; + document.getElementById("playpausesettingcheckbox").checked = currentAdminPerms["PP"]; + document.getElementById("partymodesettingcheckbox").checked = currentAdminPerms["PM"]; + document.getElementById("volumechangesettingcheckbox").checked = currentAdminPerms["VOL"]; + document.getElementById("duplicateallowesettingcheckbox").checked = currentAdminPerms["DUP"]; + } else if (toBeChanged === "volume") { + document.getElementById("volumerange").value = data["newData"]; + } +} + async function checkSettings(skipServer=false) { //check client stuff first so if the server doesn't exist it can still be changed and seen if (ip.slice(-5)=="19054") { @@ -192,7 +326,16 @@ async function checkSettings(skipServer=false) { qrCodeGenerate() document.getElementById("alerttimetextbox").value = alertTime partyButtonState = document.getElementById("partymode-button").innerHTML; - x = await getFromServer({setting: "getsettings"}, "settings"); + let nodeList = document.getElementById("admincheckholder").children + // temporary + for (let i=0; i"; - playlist = await getFromServer(null, "playlist"); + data = await getFromServer(null, "playlist"); + playlist = data["data"]["playlist"]; + currentlyPlaying = data["data"]["playingState"] playlist = Object.values(playlist).map(obj => { const filename = Object.keys(obj)[0]; // Get the filename const songData = obj[filename]; // Get the song metadata return { filename, ...songData }; // Merge filename with song data }); if (playlist.length==0){ + clearInterval(playlistTimeTimer); document.getElementById("playlist-alert").innerHTML = "Nothing's Queued..." } else { - if (conditions=="skip-button") { + if (conditions==="skip-button") { playlist.shift() if (playlist.length==0){ document.getElementById("playlist-alert").innerHTML = "Nothing's Queued..." @@ -229,6 +454,7 @@ async function generateVisualPlaylist(conditions="") { let newItem = document.createElement("div"); newItem.className = "item"; newItem.id = fileName; + newItem.tabIndex = 0; let image = document.createElement("img"); try { if (playlist[i]["art"] == null) { @@ -246,20 +472,11 @@ async function generateVisualPlaylist(conditions="") { let head5 = document.createElement("h5"); let timeLeft =document.createElement("h5"); timeLeft.style.fontWeight = 100; - try { - if (i == 0) { - head5.innerHTML="Playing"; - if ((conditions != "skip-button")) { - let mins = Math.floor(playlist[i]["time"]/60); - let secs = Math.floor(playlist[i]["time"]%60); - let durMins = Math.floor(playlist[i]["length"]/60); - let durSecs = Math.floor(playlist[i]["length"]%60); - timeLeft.innerHTML = mins.toString() +":"+ secs.toLocaleString('en-US', {minimumIntegerDigits: 2,useGrouping: false}) + "/"+ durMins.toString()+":"+durSecs.toLocaleString('en-US', {minimumIntegerDigits: 2,useGrouping: false}); - } - } - }catch(err){ - // i dont know why there's a try catch here but i'm leaving it i dont want to break something - console.log(err) + if(i== 0) { + // they can all have the text, doesn't really matter, but only the first one + // should get the ids since its the one we want to mess with + head5.id = "playing-indicator-text"; + timeLeft.id = "elapsed-time-display"; } let textdiv = document.createElement("div") textdiv.className="text" @@ -270,36 +487,122 @@ async function generateVisualPlaylist(conditions="") { textdiv.appendChild(head5); newItem.appendChild(textdiv); document.getElementById("playlist").appendChild(newItem); + try { + if (i == 0) { // Only the first song in the loop gets a time + head5.innerHTML="Playing"; + if ((conditions != "skip-button")) { + playlistElapsedSeconds = playlist[0]["time"]; + playlistSongLength = playlist[0]["length"]; + displayElapsedPlaylistTime(playlistElapsedSeconds,playlistSongLength); + clearInterval(playlistTimeTimer); + } + } + }catch(err){ + // i dont know why there's a try catch here but i'm leaving it i dont want to break something + console.error(err) + } } - } + playlistTimeTimer = setInterval(() => { + displayElapsedPlaylistTime(playlistElapsedSeconds,playlistSongLength); + },1000) + } } async function submitSong(songid) { - getFromServer({song: songid}, "songadd") - alertText("Added to Queue") + let returncode = await getFromServer({song: songid}, "songadd"); + if(returncode["status"] === ERR_NO_ADMIN) { + // right now the error is alerted in getFromServer, maybe will change that + } else if(returncode["status"]!==200) { + alertText("That song's already in the queue! Hang on!") + } else { + alertText("Added to Queue"); + } } function checkWhatSongWasClicked(e) { - itemId = e.srcElement.id; - if ((itemId.length-itemId.lastIndexOf("image") == 5) && itemId.lastIndexOf("image")!=-1) { - itemId = itemId.slice(0,-6) + if(e.type == "click" || e.key == "Enter") { + itemId = e.srcElement.id; + if ((itemId.length-itemId.lastIndexOf("image") == 5) && itemId.lastIndexOf("image")!=-1) { + itemId = itemId.slice(0,-6) + } + let filenameSep = itemId.split('.') + //i feel like later kristy won't apreciate this + //one of my files was "file.MP3" so it didn't work + //windows be like + if (VALID_FILE_EXT.includes(filenameSep[filenameSep.length-1].toLowerCase())) { + submitSong(itemId); + } } - //i feel like later kristy won't apreciate this - //one of my files was "file.MP3" so it didn't work - //windows be like - if (itemId.slice(-4).toLowerCase() == ".mp3") { - submitSong(itemId); - } } + function toggleDark(e) { let x = document.getElementById("test-body").classList if (!(x.contains("dark-mode"))) { - document.getElementById("darkmode-button").innerHTML = "On" + document.cookie = "darkmode=true; path=/;"; + document.getElementById("darkmode-button").innerHTML = "On"; x.add("dark-mode"); } else { - document.getElementById("darkmode-button").innerHTML = "Off" + document.cookie = "darkmode=false; path=/;"; + document.getElementById("darkmode-button").innerHTML = "Off"; x.remove("dark-mode"); } - + qrCodeGenerate(); +} + +// async function sha256(message) { +// // Encode the message as UTF-8 +// const msgBuffer = new TextEncoder().encode(message); + +// // Hash the message +// const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer); + +// // Convert ArrayBuffer to hex string +// const hashArray = Array.from(new Uint8Array(hashBuffer)); +// const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join(''); + +// return hashHex; +// } + +async function adminPassEnter(e) { + if (e.key == "Enter") { + e.preventDefault(); + let enteredpass = document.getElementById("adminpasswordbox").value; + if(enteredpass === "") { + adminPass = ""; // an empty pass is technically meant to represent not having one + // this isn't stritly necesarry but i dont wanna break anything that might depend on this being true + } else { + adminPass= await sha256(document.getElementById("adminpasswordbox").value); + } + alertText("Admin Password Updated"); + } +} + +async function submitPerms(e) { + let tempData = {} + tempData["PP"] = document.getElementById("playpausesettingcheckbox").checked; + tempData["SK"] = document.getElementById("skipsongsettingcheckbox").checked; + tempData["AS"] = document.getElementById("addsongsettingcheckbox").checked; + tempData["PM"] = document.getElementById("partymodesettingcheckbox").checked; + tempData["VOL"] = document.getElementById("volumechangesettingcheckbox").checked; + tempData["DUP"] = document.getElementById("duplicateallowesettingcheckbox").checked; + let returncode = await getFromServer({"setting":"perms","admin":tempData},"settings"); + if (!(returncode["ok"])) { + // if you aren't allowed to check the box then toggle it again + // its not perfect if you spam click, but it gets the point across to the user + let clickedBox = e.srcElement; + clickedBox.checked = !clickedBox.checked; + } else { + justChangedSetting = true; + } +} + +async function clearPlaylist() { + let returncode = await getFromServer({control:"clear"},"controls"); + if(returncode == ERR_NO_ADMIN || returncode == null) { + // alertText("Admin Restricted ") + // there's an admin restrict alert built into getFromServer + } else { + alertText("Playlist Cleared!"); + } } let optionslist = [] @@ -313,20 +616,31 @@ document.addEventListener('keydown', function(e){ }}) document.getElementById("playlist-mode").style.display = "none"; document.getElementById("settings-mode").style.display = "none"; -//.ontouch for mobile?? -document.getElementById("volumerange").onchange = async function() { - let returnValue = await getFromServer({setting:"volume",level:this.value}, "settings") - if (returnValue["volumePassed"] !=0) { +document.getElementById("volumerange").onchange = async function(e) { + // there is no reason for this not to be a defined function + // FIX THIS + let returnValue = await getFromServer({setting:"volume",level:e.target.value}, "settings") + if (returnValue["status"] == ERR_NO_ADMIN) { + // alertText("Error: Admin restricted action"); + // there's an admin restrict alert built into getFromServer + // i wanna put the volume slider back to where it was but idk a good way to keep the previous volume + checkSettings(false); + } else if (returnValue["data"]["volumePassed"] !=0) { + // i forgot about this, i had to do this because it confused the crap out of me one time + // vlc doesn't let you change the volume of nothing, which makes sense if you think about it alertText("Nothing is playing") document.getElementById("volumerange").value = -1 - } - else if (this.value == 0) { + } else if (this.value == 0) { alertText("The volume is now set to 0 (Pause?)") } else { alertText("The volume is now set to " + this.value.toString()) } } + + +//bit of a cheat code for clearing the alerts when they don't clear normally +document.getElementById("title").addEventListener('click',function(){document.getElementById("alert").innerHTML = ""}) document.getElementById("settings-button").addEventListener('click',function(){controlButton("st")}); document.getElementById("play-pause-button").addEventListener('click', function(){controlButton("pp")}); document.getElementById("playlist-button").addEventListener('click', function(){controlButton("pl")}); @@ -336,18 +650,24 @@ document.getElementById("go-search").addEventListener('click', function(){search document.getElementById("songsearch").addEventListener('keydown', function(e){searchSongsEnter(e)}); document.getElementById("iptextbox").addEventListener('keydown', function(e){ipSetEnter(e)}); document.getElementById("alerttimetextbox").addEventListener('keydown', function(e){alertTimeEnter(e)}); +document.getElementById("adminpasswordbox").addEventListener('keydown',function(e){adminPassEnter(e)}); +document.getElementById("admincheckholder").addEventListener('click',function(e){submitPerms(e)}); document.getElementById("partymode-button").addEventListener('click',function(){controlButton("pm")}) +document.getElementById("darkmode-button").addEventListener('click',function(){toggleDark()}) +document.getElementById("clear-button").addEventListener('click',function(){clearPlaylist()}) //sets the fact that clicking a song needs to return its id to the function to find it +document.getElementById("songlist").addEventListener('keydown', function(e){checkWhatSongWasClicked(e)}); document.getElementById("songlist").addEventListener('click', function(e){checkWhatSongWasClicked(e)}); + //makes the controls look mostly normal on all screens, best solution i could find, idk man -let tempWidth = document.getElementById('controls').clientWidth; -document.getElementById("controls").style.marginLeft = "-"+String(parseInt(tempWidth/2))+"px"; -// document.getElementById("darkmode-button").addEventListener('click',function(){toggleDark()}) +// replaced this with "transform" css stuff +// let tempWidth = document.getElementById('controls').clientWidth; +// document.getElementById("controls").style.marginLeft = "-"+String(parseInt(tempWidth/2))+"px"; + //for my use case (my immediate family), they dont know how to set an ip //using this allows the creator of the link for, a qr code for example, to set the ip before distributing the code, and it would all work smoothly //example (http://192.168.1.100:8000/?ip=192.168.1.100:19054 sets the ip to the same host at the default port) //the port must be set manually using this method, but only has to be done once for the url that ends up being shared -let params = new URLSearchParams(location.search); //tries the url first, then the cookie, then the default ip = params.get("ip") @@ -357,6 +677,8 @@ if (ip == null || ip=="") { if (ip==null || ip==""){ ip = "" } + +// saving the cookies (don't tell the EU) document.cookie = "ip="+ip+"; path=/;" alertTime = getCookie("alertTime") @@ -366,4 +688,43 @@ if (alertTime == "") { document.cookie = "alertTime="+alertTime+"; path=/;" } // this is the code that makes the qr code at the very start -qrCodeGenerate() \ No newline at end of file +qrCodeGenerate() + +// socket testing stuff + +socket = io("http://"+ip,{ + reconnectionAttemps: 5, + timeout: 10000, +}); + +socket.on("songAdd", function(data) { + // console.log("recieved data from songAdd"); + // console.log(data); + addToPlaylist(data); +}) + +socket.on("timeUpdate", function(data) { + // console.log("recieved data from timeUpdate"); + // console.log(data); + playlistElapsedSeconds = data["elapsedTime"]; + currentlyPlaying = data["playingState"] +}); + +socket.on("skipSong",() => { + if(justSkipped === false) { + skipInPlaylist(); + } else { + justSkipped = false; + } +}) + +socket.on("settingsChange",(data) => { + // console.log(data); + if(justChangedSetting) { + // console.log("working"); + justChangedSetting = false; + } else { + // checkSettings(); + updateSingleSetting(data); + } +}); \ No newline at end of file diff --git a/Client/styles.css b/Client/styles.css index 803c5df..70bd991 100644 --- a/Client/styles.css +++ b/Client/styles.css @@ -1,20 +1,47 @@ -/* testing */ +/* dark mode stuff */ .dark-mode { - background-color: #333333; - color:#ffffff; + --bg-main: #333333; + --bg-item: #3f3f3f; + --bg-inputs: #2a2a2a; + --text-color: #ffffff; /* -webkit-filter:invert(100%); filter:progid:DXImageTransform.Microsoft.BasicImage(invert='1'); */ } +.dark-mode .control-button { + filter: invert(100%) brightness(0.9) +} + +:root { + --bg-main: #eeeeee; + --bg-item: #dddddd; + --bg-inputs: #ffffff; + --text-color: #000000; + color: var(--text-color); +} + +/* In hindsight i should have just used p's with classes to decide size, but whatever +Should probably fix that at some point, this is like the least accessible site ever */ +h1,h2,h3,h4,h5,p,input,button,label { + color: var(--text-color); +} + +input, button { + background-color: var(--bg-inputs); +} + /* Things that are always visible */ + body { - background-color: #EEEEEE; + background-color: var(--bg-main); } + * { - font-family: 'arial'; + font-family: 'Arial',sans-serif; } + .italic { font-style: italic; } @@ -35,7 +62,8 @@ h4 { left: 50%; bottom: 0; margin: 0 auto; - background-color:inherit; + transform: translateX(-50%); + background-color:var(--bg-main); } .alert { @@ -44,23 +72,29 @@ h4 { width: 100%; text-align: center; z-index: 1000; - background-color: #EEEEEEd6; + background-color: color-mix(in srgb, var(--bg-main), transparent 16%); } -.settings-button { - width: 15%; +.settings-button-holder { + width:15%; max-width: 90px; position:fixed; top:0; right:0; margin: 3px; - background:inherit; + background-color: var(--bg-main); /* This is a circle background for the circle settings button So it can display over other text and such */ border-radius: 50%; } -.control-button{ +.settings-button { + width: 100%; + + +} + +.controls > .control-button{ width:20%; max-width: 110px; margin: auto 2%; @@ -72,22 +106,26 @@ h4 { text-align: center; } +.item { + /* Only actually applies to playlist and search because settings item has "inherit" bg-colour */ + background-color: var(--bg-item); +} + /* Songlist stuff */ .songlist { width: 80%; - min-width: 300px; + min-width: 400px; margin:auto auto 150px; display: flex; flex-wrap: wrap; } .songlist > .item{ - border: 1px solid #333333; + border: 1px solid var(--bg-item); width:30%; max-width: 150px; margin: 5px auto; min-width: 75px; - background-color: inherit; } .songlist > .item > img{ @@ -98,6 +136,8 @@ h4 { .songlist > .item > h3, .songlist > .item > h4{ margin-left: 2px; margin-right: 2px; + margin: 5px; + word-wrap: break-word; } .searchbox-holder { @@ -109,11 +149,18 @@ h4 { .searchbox { width: 65%; margin: 1px; + margin-bottom: 16px; } .go-search { width: 20%; min-width: 50px; } + +.lossless-tag { + width:16px; + padding: 1px; + margin-left: auto; +} /* playlist mode stuff */ .playlist { @@ -123,7 +170,7 @@ h4 { } .playlist > .item{ - border: 1px solid #333333; + border: 1px solid var(--bg-item); display: flex; max-width: 50em; min-width: 200px; @@ -132,6 +179,7 @@ h4 { } .playlist > .item > .text { + padding: 3px; display: inline-block; margin: 0px 3px; } @@ -146,7 +194,7 @@ h4 { } .playlist > .item > .text > * { - margin:5% 2px; + margin:2px; } /* settings stuff */ @@ -160,12 +208,12 @@ h4 { .settings > .item { margin-left: 10%; width:fit-content; - + background-color: var(--bg-main); } .settings > .item:not(:last-child) { padding-bottom: 10px; - border-bottom: 1px solid #333333; + border-bottom: 1px solid var(--bg-item); } .settings > .item.no-line { @@ -177,8 +225,16 @@ h4 { border-bottom: 0; } +.settings > .item > h2 { + margin-bottom: 4px; +} + +.settings > .item > p { + margin-top: 0px +} + .versionNumber { - font-size: 8px; + font-size: 11px; font-style: italic; text-align: left; width: 80%; diff --git a/Server/databaseGenerator.py b/Server/databaseGenerator.py index e83cbc3..ebf8263 100644 --- a/Server/databaseGenerator.py +++ b/Server/databaseGenerator.py @@ -1,27 +1,29 @@ -import os from mutagen.easyid3 import EasyID3 from mutagen.mp3 import MP3 +import mutagen.flac +import mutagen.wave import sqlite3 as sql -import requests, ast, time, math, argparse +import requests, ast, time, math, argparse, dotenv, os loading = ["-","\\","|","/"] parser=argparse.ArgumentParser(description="Options for the generation of the song database") -parser.add_argument('-k','--apikey', help='String: LastFM api key', default="") +# parser.add_argument('-k','--apikey', help='String: LastFM api key', default="") parser.add_argument('-m', '--mode', help='new/update: Remake database or update current', default= "update") parser.add_argument('-a', '--art', help="True/False: Add art to the database using LastFm (takes minimum 0.25s per song)", default="True") parser.add_argument('-d','--directory',help="Directory of the song files", default="./sound/") args = parser.parse_args() -apikeylastfm = args.apikey +dotenv.load_dotenv() +apikeylastfm = os.getenv("API_KEY") +soundLocation = os.getenv("DIRECTORY") +# apikeylastfm = args.apikey if args.directory[-1] == "/" or args.directory[-1] == "\\": soundLocation = args.directory elif "/" in args.directory: soundLocation = args.directory + "/" else: soundLocation = args.directory + "\\" -# if you want to set the api key/sound directory permenantly for your setup just uncomment the next line -# apikeylastfm = "KeyHere" -# soundLocation = "directoryHere" + songFiles = os.listdir(soundLocation) fileOfDB = sql.connect("songDatabase.db") songDatabase = fileOfDB.cursor() @@ -33,7 +35,7 @@ except: songDatabase.execute("UPDATE meta SET data = ? WHERE id = 'songDirectory'", (soundLocation,)) if args.mode.lower() == "update": #Create if not exists - songDatabase.execute("CREATE TABLE IF NOT EXISTS songs (filename TEXT PRIMARY KEY, title TEXT, artist TEXT, art TEXT, length INTEGER);") + songDatabase.execute("CREATE TABLE IF NOT EXISTS songs (filename TEXT PRIMARY KEY, title TEXT, artist TEXT, art TEXT, length INTEGER, lossless INTEGER);") songDatabase.execute("SELECT filename FROM songs;") dBfilelist = songDatabase.fetchall() dBfilelistSet = set() @@ -48,44 +50,61 @@ if args.mode.lower() == "update": print("new songs: " + ", ".join(songFiles)) elif args.mode.lower()=="new": songDatabase.execute("DROP TABLE IF EXISTS songs;") - songDatabase.execute("CREATE TABLE songs (filename TEXT PRIMARY KEY, title TEXT, artist TEXT, art TEXT, length INTEGER);") + songDatabase.execute("CREATE TABLE songs (filename TEXT PRIMARY KEY, title TEXT, artist TEXT, art TEXT, length INTEGER, lossless INTEGER);") else: raise ValueError("Must be \"new\" or \"update\"") -if args.art.lower() == "true" and not(args.apikey == ""): - x = len(songFiles)*0.25 - if x > 60: - print("ETA "+ str(x/60) + " minutes") +if args.art.lower() == "true" and not(apikeylastfm == ""): + eta = len(songFiles)*0.25 + if eta > 60: + print(f"ETA {eta/60:.2f} minutes") else: - print("ETA "+ str(x) + " seconds") + print(f"ETA {eta} seconds") + +# will be used soon +validFormats = ["mp3","flac","wav"] for i in songFiles: - if i[-4:].lower() != ".mp3": - # skip any non-mp3's (like directories or cover art) + # songFiles is the list of filenames, so i is the filename of each song + global song + filenamesplit = i.split(".") + extension = filenamesplit[len(filenamesplit)-1] + lossless = 0 # sqlite doesn't have booleans. what is this, C? + if not(extension.lower() in validFormats): + # skip any non music files (like directories or cover art) continue try: # get the metadata - song = EasyID3(soundLocation+i) + if(extension.lower() == "mp3"): + song = EasyID3(soundLocation+i) + elif(extension.lower() == "flac"): + song = mutagen.flac.FLAC(soundLocation+i) + lossless = 1 + elif(extension.lower() in ["wav","wave"]): + # Im actually pretty sure waves can't have metadata, but whatevz + song = mutagen.wave.WAVE(soundLocation+i) + lossless = 1 title = song['title'][0] artist = song['artist'][0] except: if "_" in i: - # if metadata is missing, try to use file name following title_artist.mp3 + # if metadata is missing, try to use file name following "title_artist.mp3" song = i.split("_") title = song[0] artist = song[1].split(".")[0] elif "-" in i: - # if there's no underscore, try artist - title.mp3 + # if there's no underscore, try "artist - title.mp3" song = i.split("-") title = song[1].split(".")[0] artist = song[0] title = title.strip() artist = artist.strip() else: - #if the file is not formatted with an underscore, the title is the file name + #if the file is not formatted with an underscore or hyphen, the title is the file name title = i artist = None - if args.art.lower() == "true" and not(args.apikey == ""): + if args.art.lower() == "true" and not(apikeylastfm == "") and artist: + # and artist just means anything that only has the x.mp3 title won't bother to check since it'll never exist on last fm try: # get the images from last fm, try 2 different sizes image = ast.literal_eval(requests.post(url="http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key="+apikeylastfm+"&artist="+artist+"&track="+title+"&format=json").text)["track"]["album"]["image"][2]["#text"] @@ -93,21 +112,29 @@ for i in songFiles: image = ast.literal_eval(requests.post(url="http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key="+apikeylastfm+"&artist="+artist+"&track="+title+"&format=json").text)["track"]["album"]["image"][1]["#text"] if image == "": image = None - time.sleep(0.25) + time.sleep(0.01) except: image=None else: image=None try: - length = math.ceil(MP3(soundLocation+i).info.length) + if extension.lower() in ['flac','wave','wav']: + length = math.ceil(song.info.length) + elif extension.lower() == "mp3": + # for some reason ID3 and mutagen.mp3 get different info + # artist and title are in id3() and length is in mp3() + # I dunno why + length = MP3(soundLocation+i).info.length except: length = 0 if len(songFiles) != 1: index = (songFiles.index(i))%4 print("\r" + str(loading[index] + str(math.floor((songFiles.index(i)/(len(songFiles)-1))*100))+ "%"), end='', flush=True) - # each "song" is stored as a dictionary/JSON entry following the format seen in the readME - songDatabase.execute(f"INSERT INTO songs (filename, title, artist, art, length) VALUES (?,?,?,?,?)",(i,title,artist,image,length)) - - + # each "song" is stored as a SQLite entry following the format seen below + songDatabase.execute(f"INSERT INTO songs (filename, title, artist, art, length, lossless) VALUES (?,?,?,?,?,?)",(i,title,artist,image,length,lossless)) +songDatabase.execute("DROP TABLE IF EXISTS virtualSongs;") +songDatabase.execute("CREATE VIRTUAL TABLE virtualSongs USING fts5(filename, title, artist, art, length, lossless);") +songDatabase.execute("INSERT INTO virtualSongs SELECT * FROM songs;") fileOfDB.commit() +fileOfDB.close() \ No newline at end of file diff --git a/Server/example.env b/Server/example.env new file mode 100644 index 0000000..8167158 --- /dev/null +++ b/Server/example.env @@ -0,0 +1,7 @@ +API_KEY= +DIRECTORY=./sound +SERVER_PORT=19054 + +#API_KEY = a lastfm api key +#Directory = either a relative or concrete directory, default is subdirectory "sound", should work on unix and windows +#server_port= the port for the webbybits.py flask server \ No newline at end of file diff --git a/Server/webbyBits.py b/Server/webbyBits.py index 614e1b4..0e0560f 100644 --- a/Server/webbyBits.py +++ b/Server/webbyBits.py @@ -1,14 +1,40 @@ +import eventlet +eventlet.monkey_patch() from flask import Flask from flask import request from flask_cors import CORS +from flask_socketio import SocketIO import sqlite3 as sql -import vlc,threading,time,random, argparse +import vlc,threading,time,random,argparse,dotenv,os,hashlib,string + # Argparse Stuff parser=argparse.ArgumentParser(description="Options for the Webby Bits") -# this is no longer needed assuming my file works correctly with the generator -# parser.add_argument('-d','--directory',help="Directory of the song files (make sure this matches the directory used for the databaseGenerator)", default="./sound/") -parser.add_argument('-p','--port',help="Port to host on, not the same as the web (client) port",default='19054') -portTheUserPicked=parser.parse_args().port +# parser.add_argument('-p','--port',help="Port to host on, not the same as the web (client) port",default='19054') +parser.add_argument('-a','--admin',help="Add an admin password to be used in the client. DO NOT use a password you use elsewhere",default="") +args = parser.parse_args() +dotenv.load_dotenv() +portTheUserPicked=os.getenv("SERVER_PORT") + +ERR_NO_ADMIN = ({"error":"no-admin","data":None},401) +ERR_200 = ({"error":"OK","data":None},200) +ERR_MISSING_ARGS = ({"error":"Request missing required arguments","data":None}),400 +if args.admin: + ADMIN_PASS = hashlib.sha256(bytes(args.admin,'utf-8')).hexdigest() +else: + tempPass = ''.join(random.choices(string.ascii_letters + string.digits +"?"+"!",k=20)) + print("No adminPass was set, the auto generated one is: "+tempPass) + ADMIN_PASS = hashlib.sha256(bytes(tempPass,'utf-8')).hexdigest() + +# True = everyone, False = admin only. Change in client while in use. +# play-pause,skip,addsong,partymode,volume in order +controlPerms = { + "PP":True, + "SK":True, + "AS":True, + "PM":True, + "VOL":True, + "DUP":True # Not implemented, allow duplicate songs in queue +} fileofDB = sql.connect("songDatabase.db") songDatabase = fileofDB.cursor() @@ -16,20 +42,15 @@ songDatabase = fileofDB.cursor() #song directory songDatabase.execute("SELECT * FROM meta WHERE id='songDirectory';") soundLocation = songDatabase.fetchall()[0][1] - if soundLocation[-1] == "/" or soundLocation[-1] == "\\": pass elif "/" in soundLocation: soundLocation += "/" else: soundLocation += "\\" -print(soundLocation) #Create Virtual table for searching -songDatabase.execute("DROP TABLE virtualSongs;") -songDatabase.execute("CREATE VIRTUAL TABLE virtualSongs USING fts5(filename, title, artist, art, length);") -songDatabase.execute("INSERT INTO virtualSongs SELECT * FROM songs;") -fileofDB.commit() -fileofDB.close() +#I'm not sure why i don't do this in the databaseGenerator, but it also takes like 3 seconds so i'm not messing with it rn + #Initializing all the global stuff random.seed() global partyMode @@ -40,35 +61,69 @@ songNext = None skipNow = False playlist = [] playlistLock = threading.Lock() -fakeplayer = vlc.Instance() -player = fakeplayer.media_player_new() +vlcInstance = vlc.Instance() +player = vlcInstance.media_player_new() # for client side volume to work as well as possible, set system volume to 100 and control in app player.audio_set_volume(100) app = Flask(__name__) -# because you are posting from another domain to this one, you need CORS +# because you are POSTing from another domain to this one, you need CORS CORS(app) +# Replace the star with the frontend domain if you dislike being hacked +socketio = SocketIO(app, cors_allowed_origins="*") def queueSong(song): with playlistLock: playlist.append(song) + socketio.emit("songAdd",getSongInfo(song)) + +def getSongInfo(song): + fileofDB = sql.connect("songDatabase.db") + songDatabase = fileofDB.cursor() + songDatabase.execute("SELECT * FROM songs WHERE filename = ?",[song]) + result = songDatabase.fetchall()[0] + # again, this is still using the old JSON format to avoid client changes + k = { + "title": result[1], + "artist": result[2], + "art": result[3], + "length": result[4] + } + fileofDB.close() + return {song:k} + # this is a loop that plays the songs and checks for playlist changes, skips, ect. +counter = 0 +isPlaying = False def playQueuedSongs(): global skipNow global songNext global partyMode + global counter + global isPlaying while True: with playlistLock: - z = str(player.get_state()) - - if playlist and (z == "State.Ended" or z== "State.Stopped" or z == "State.NothingSpecial" or skipNow == True): + counter+=1 + if(counter > 2): + playingState = str(player.get_state()) == "State.Playing" + socketio.emit('timeUpdate',{"elapsedTime":player.get_time()/1000,"playingState":playingState}) + counter = 0 + playerState = str(player.get_state()) + endStates = ["State.Ended","State.Stopped","State.NothingSpecial"] + if playlist and (playerState in endStates or skipNow == True): # New song is in the queue and (the previous song is over or skip has been pressed) player.stop() skipNow = False songNext = playlist.pop(0) - media = fakeplayer.media_new(soundLocation+songNext) + media = vlcInstance.media_new(soundLocation+songNext) player.set_media(media) player.play() - elif (skipNow==True or (z == "State.Ended" or z == "State.NothingSpecial" or z=="State.Stopped")): + isPlaying = True + socketio.emit("skipSong",None) + elif (skipNow==True or (playerState in endStates)): + if(isPlaying): + socketio.emit("skipSong",None) + isPlaying = False + # print(playerState) # skip was pressed and there are no new songs skipNow=False songNext = None @@ -79,83 +134,151 @@ def playQueuedSongs(): songDatabase.execute("SELECT * FROM songs ORDER BY RANDOM() LIMIT 1;") result = songDatabase.fetchall() # adds the random songs for party mode - # the above 2 means this only applies if (a song is playing (or paused)) and the queue is empty + # the above 2 means this only applies if (a song is playing or paused) and (the queue is empty) playlist.append(result[0][0]) + socketio.emit('songAdd',getSongInfo(result[0][0])) # check for new songs every second - # I just didn't want to eat too much processing looping + # I just didn't want to eat too much processing looping + # this also has another useful affect that skips get "queued" to only 1 per second, that way somebody usually can't skip twice accidentally time.sleep(1) -# start the media player thread -queueThread = threading.Thread(target=playQueuedSongs) -queueThread.daemon = True -queueThread.start() + +@socketio.on("connect") +def handleConnect(): + pass @app.route("/controls", methods=['POST']) def playerControls(): # recieve control inputs (play/pause and skip) from the webUI global skipNow - global media global partyMode recieveData=request.get_json(force=True) - if recieveData["control"] != None: + try: if recieveData["control"] == "play-pause": - player.pause() - return "200" + if ADMIN_PASS == recieveData['password'] or controlPerms["PP"]: + playingState = str(player.get_state())=="State.Playing" + player.pause() + return {"error":"ok","data":{"playingState":not(playingState)}},200 + else: + playingState = str(player.get_state())=="State.Playing" + return {"error":"Admin Restricted Action","data":{"playingState":playingState}},401 elif recieveData["control"] == "skip": - skipNow = True - # print(str(player.get_state())) - return "200" + if ADMIN_PASS == recieveData['password'] or controlPerms["SK"]: + skipNow = True + return ERR_200 + else: + return ERR_NO_ADMIN + # Maybe i should have put this next one in the "settings" section + elif recieveData["control"] == "clear": + if ADMIN_PASS == recieveData['password']: # this is only ever allowed with the adminpassword + with playlistLock: + playlist.clear() + return ERR_200 + else: + return ERR_NO_ADMIN else: - return "400" + return {"error":"Not a valid control","data":None},400 + except KeyError: + return ERR_MISSING_ARGS @app.route("/settings", methods=['POST']) def settingsControl(): + global controlPerms # set the volume and partymode global partyMode global player recieveData = request.get_json(force=True) - if recieveData["setting"] == "volume": - volumePassed = player.audio_set_volume(int(recieveData["level"])) - return {"volumePassed":volumePassed} - elif recieveData["setting"] == "partymode-toggle": - partyMode = not(partyMode) - return "200" - elif recieveData["setting"] == "getsettings": - # probably should have made this a different request type or something but it works - x = {"partymode":partyMode,"volume":player.audio_get_volume()} - return x - else: - return "400" + try: + if recieveData["setting"] == "volume": + if ADMIN_PASS == recieveData['password'] or controlPerms["VOL"]: + volumeLevel = int(recieveData["level"]) + if(volumeLevel <= 100 and volumeLevel >= 0): + volumePassed = player.audio_set_volume(volumeLevel) + if(volumePassed == 0): + # only emit a signal i the volume really changed + socketio.emit("settingsChange",{"settingToChange":"volume","newData":volumeLevel}) + return {"error":"ok","data":{"volumePassed":volumePassed}},200 + else: + return {"error":"Invalid volume level","data":None},422 + else: + return ERR_NO_ADMIN + elif recieveData["setting"] == "partymode-toggle": + if ADMIN_PASS == recieveData['password'] or controlPerms["PM"]: + partyMode = not(partyMode) + partyModeStr = "On" if partyMode else "Off" + socketio.emit("settingsChange",{"settingToChange":"partymode","newData":partyModeStr}) + return ERR_200 + else: + return ERR_NO_ADMIN + elif recieveData["setting"] == "perms": + if ADMIN_PASS == recieveData["password"]: + controlPerms = recieveData["admin"] + # print(recieveData["admin"]) + socketio.emit("settingsChange",{"settingToChange":"perms","newData":controlPerms}) + return ERR_200 + else: + return ERR_NO_ADMIN + elif recieveData["setting"] == "getsettings": + # probably should have made this a different request type or something but it works + return {"error":"ok","data":{"partymode":partyMode,"volume":player.audio_get_volume(),"admin":controlPerms}},200 + else: + return {"error":"Not a valid setting","data":None},400 + except: + return ERR_MISSING_ARGS @app.route("/search", methods=['POST']) def searchSongDB(): recieveData=request.get_json(force=True) fileofDB = sql.connect("songDatabase.db") songDatabase = fileofDB.cursor() - results = [] - if (recieveData['search'] == ""): - songDatabase.execute("SELECT * FROM virtualSongs") - results = songDatabase.fetchall() - else: - songDatabase.execute("SELECT * FROM virtualSongs WHERE virtualSongs MATCH ?",[recieveData['search']]) - results = songDatabase.fetchall() - tempdata = {} - # this is a temporary solution so i dont have to change the - for i in results: - tempdata[i[0]] = { - "title": i[1], - "artist": i[2], - "art": i[3], - "length": i[4] - } - # print(tempData) - fileofDB.close() - return tempdata + try: + results = [] + # print(recieveData["search"]) + if (recieveData['search'] == ""): + songDatabase.execute("SELECT * FROM virtualSongs") + results = songDatabase.fetchall() + else: + songDatabase.execute("SELECT * FROM virtualSongs WHERE virtualSongs MATCH ?",['"' + recieveData['search']+'"']) + results = songDatabase.fetchall() + tempdata = {} + # this is a temporary solution so i dont have to change the client + for i in results: + tempdata[i[0]] = { + "title": i[1], + "artist": i[2], + "art": i[3], + "length": i[4], + "lossless":i[5] + } + fileofDB.close() + + return {"error":"ok","data":tempdata},200 + except KeyError: + fileofDB.close() + return ERR_MISSING_ARGS + except sql.OperationalError as e: + print(e) + fileofDB.close() + return ({"error":"Database error (Try another search?)","data":None},500) + @app.route("/songadd", methods=["POST"]) def songadd(): recieveData=request.get_json(force=True) - queueSong(recieveData['song']) - return "200" + try: + if (ADMIN_PASS == recieveData['password']) or controlPerms["AS"]: + # Password exists and is correct, or it's not restricted + if not(controlPerms["DUP"]) and (recieveData['song'] in playlist) and not(ADMIN_PASS == recieveData['password']): + return {"error":"This song is already in the queue, hang on!","data":None},409 + else: + queueSong(recieveData['song']) + return ERR_200 + else: + # the password is incorrect (technically a password not existing falls into the above case because controlPerms is never changed) + return ERR_NO_ADMIN + except KeyError as e: + print(e) + return ERR_MISSING_ARGS + @app.route("/playlist", methods=["POST"]) def getPlaylist(): global songNext @@ -187,10 +310,19 @@ def getPlaylist(): "length": result[4] } tempPlaylist.append({i:k}) - # print(tempPlaylist) fileofDB.close() - return tempPlaylist + playingState = False + if(str(player.get_state())=="State.Playing"): + playingState = True + # print(playingState) + return {"error":"ok","data":{"playlist":tempPlaylist,"playingState":playingState}},200 if __name__ == "__main__": - app.run(host='0.0.0.0', port=portTheUserPicked) + # There's not really a whole lot of point to a main function for something like this, you'd never use any of these methods + # elsewhere, but its just good practice i guess + # start the media player thread + queueThread = threading.Thread(target=playQueuedSongs) + queueThread.daemon = True + queueThread.start() + socketio.run(app=app,host='0.0.0.0', port=portTheUserPicked) \ No newline at end of file diff --git a/readme.md b/readme.md index e63bcbd..2589f25 100644 --- a/readme.md +++ b/readme.md @@ -10,24 +10,33 @@ The main advantage compared to doing something similar using Spotify is that you ### Client Setup: The client is a web application that can be hosted on any server, it need not be the same device running the music player. * If the app is being setup for a large group, you can distribute the url (via QR code, for example) with `?ip=YOURSERVERHOSTNAME:19054` set as an attribute after the url. +* You can also add `?darkmode=(true/false)` to set the default colour scheme, but this will be overwritten by the users saved choice in the cookie if they change it themselves ### Server Setup: **Pre-setup:** If you want the songs to have art associated with them, it is all hosted on and retrieved from LastFM, and you will need to sign up for a developer app, and put your key in the database generator \ \ -The server side consists of 3 files: +The server side consists of 3 files and a directory: ``` sound/ databaseGenerator.py webbyBits.py +.env ``` 1. Place mp3 files in the `sound/` folder -2. Open `databaseGenerator.py` and put your LastFM API key in at the top or at runtime using `-k APIKey` (*optional*) -3. Run `databaseGenerator.py` +2. Rename `example.env` to `.env` and... + - Set the location where your audio files are (Default: `./sound/`) + - Set the LastFM API key (Optional) + - Change the port of the webbybits server (Default: `19054` ) +3. Run `databaseGenerator.py` (Will try to use LastFM API key) * *The `databaseGenerator.py` will index all mp3 files, and save the information to `songDatabase.db`* * *If getting images, this process may take a long time with a large amount of mp3 files* 4. Run `webbyBits.py` - * *The port can be customized at runtime using* `-p portNumber` *as an atribute* + * *The port can be customized by editing the `.env` file* + * *You can add an admin password at runtime with* `-a AdminPass` *as an atribute* + * ***NOTE: Do not reuse ANY password for this, it is hashed but 100% unsecure. The best option is just a random string you write down once*** + * If this attribute isn't included a random string will be generated as the admin password + * This is intended for protecting certain features for small closed events, not for public security You can now connect with the client and use the app as normal. \ *Make sure you have turned down/off any other apps that might make noise or notification sounds* \ @@ -39,24 +48,31 @@ These are specific details on each section of the app, and how to use them - `sound/` contains all mp3 files by default - `databaseGenerator.py` scans through mp3 files and gets information about them - `Filename, Title, Artist, Art, Length` are all saved - - *If the title and artist are not in the mp3 metadata, it looks for a format of* `TITLE_ARTIST.mp3` *then of* `ARTIST - TITLE.mp3` *and otherwise defaults to the file name as the title, and no artist* + - *If the title and artist are not in the file metadata, it looks for a format of* `TITLE_ARTIST.mp3` *then of* `ARTIST - TITLE.mp3` *and otherwise defaults to the file name as the title, and no artist* - Art is retrieved from LastFM - Running with `--mode (update/new)` either updates the current database and adds new songs/removes deleted songs, or recreates the entire database (update is default, and is faster in art mode) - Running with `--art (True/False)` retrieves art from LastFM or doesn't (True is default) - *Can only generate one song / 0.25 seconds, to avoid pinging the LastFM server too much* - - Running with `--apikey (KEYhere)` sets the LastFM key for that run - - If this is set to an empty string (Default) the app runs in non-art mode - - Running with `--directory (directoryOfmp3s)` allows for sound files to be in a different place - - Default `"./sound/"` - - _This setting might be kinda iffy on Linux. You're on Linux just go and edit it if you have issues_ - - ~~__Make certain you only use forward slashes in your directory, even on Windows__~~ I think this should be fine now i'll check later + - Directory to index for music files can be set in the `.env` file - `songDatabase.db` stores all the information about each song in a SQLite database with tables `songs` and `meta` - `webbyBits.py` imports the database, runs all music playing, and accepts all commands from clients - Searches return matching songs - Accepts Play-Pause and Skip commands - Uses port 19054 by default - - `--port (port)` changes the port for that run - - The default port can be changed in the file + - Can be changed in the `.env` file + - Running with `--admin (admin password)` sets an admin password for moderation on the client + - ***Note: Do not reuse a password, the password is hashed before being sent over the network, but I still wouldn't bet my house on it, no security is guaranteed*** + - Anyone who knows the admin password can enter it on the client and change the abilities of any non-admin users (for example to limit skipping) + - The total set of features that can be restricted is + - Skip track + - Play-pause toggle + - Add track to queue + - Partymode toggle + - Change volume + - Add duplicate track to queue + - This is a seperate toggle, but is based on the setting "Add track to queue" + - Basically if you can't add at all, you can't add a duplicate either (obviously) + - When this argument is left out a random string is generated and printed in console to be the admin password (so keep the console window hidden if you don't want to use it) ### Client: ![image](./Screenshot_MAIN.png) \ @@ -65,13 +81,30 @@ From left to right: - The currently playing song is identified, and has the duration listed - The play-pause button toggles playing - The skip button goes to the next track + - *No "previous" button is a design decision (It's a feature not a bug)* - The search button opens the search screen (pictured) - The settings button (top right) opens the settings menu + - Dark mode sets a dark mode and stores a cookie to keep you in dark mode after refreshing - Server IP allows you to change the ip that the site connects to - Alert time changes how long error/confirmation messages are shown for (Default 2s) - Party Mode adds new songs to the queue when the queue has only 1 song in it - Volume controls the VLC volume of the connected server - *Because the volume can be controlled in the client, for best usage set your device volume as high as possible and turn it down using this slider* - QR code to allow others to connect to and use the Remote + - Admin password can be set to restrict actions for general users, or avoid the set restrictions -*See `LICENSE.md` for redistribution details. \ No newline at end of file +### A quick note on the password feature + +The exact process of the password's plaintext scope is as follows + +- On the server, you type in the password on the server in the console, the python script takes that plaintext, hashes it, then stores that hash as a variable. The plaintext is also technically a variable, but it's not accessed after that initial hashing. (It's also going to be visible in your console history) + +- On the client, you type in the password and press enter. A function reads the value of the password box, saves the hash of that password to a variable, and sends it with all your requests. The plaintext is still stored in the inputbox, but if you delete it and don't press enter on the box again, the hash will be stored without keeping the plaintext. (I may change this behaviour so this box auto-clears when enter is pressed, maybe) + +None of this is "secure", but it's better than sending plaintext passwords, which is what I was doing before. Hypothetically somebody who intercepted your packet where you sent the password can't get back the original plaintext, just the hash. + +## External Credits + - QR Code Generator: JS file found [here](https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js) + - Cookie Popup: JS file found [here](https://cookieconsent.popupsmart.com/src/js/popper.js) + +*See `LICENSE.md` for redistribution and editing details.* diff --git a/requirements.txt b/requirements.txt index 73c4c0a..ac8054e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,16 +1,25 @@ -blinker==1.8.2 -certifi==2024.2.2 -charset-normalizer==3.3.2 -click==8.1.7 +bidict==0.23.1 +blinker==1.9.0 +certifi==2026.1.4 +charset-normalizer==3.4.4 +click==8.3.1 colorama==0.4.6 -Flask==3.0.3 -Flask-Cors==4.0.1 -idna==3.7 +dotenv==0.9.9 +Flask==3.1.2 +flask-cors==6.0.2 +Flask-SocketIO==5.6.0 +h11==0.16.0 +idna==3.11 itsdangerous==2.2.0 -Jinja2==3.1.4 -MarkupSafe==2.1.5 +Jinja2==3.1.6 +MarkupSafe==3.0.3 mutagen==1.47.0 -python-vlc==3.0.20123 -requests==2.32.2 -urllib3==2.2.1 -Werkzeug==3.0.3 +python-dotenv==1.2.1 +python-engineio==4.13.1 +python-socketio==5.16.1 +python-vlc==3.0.21203 +requests==2.32.5 +simple-websocket==1.1.0 +urllib3==2.6.3 +Werkzeug==3.1.5 +wsproto==1.3.2 diff --git a/wishlist.md b/wishlist.md new file mode 100644 index 0000000..6b1cbe5 --- /dev/null +++ b/wishlist.md @@ -0,0 +1,35 @@ +# Wishlist +*Features I would like to add, will be completed in any order* +- [ ] Loading indicator while awaiting server stuff +- [ ] Refactoring existing code + - [x] Remove old comments + - [ ] Update the SQL -> Server -> Client pipeline when searching and building playlist + - [ ] Verify all if-else sequences are correct and not redundant +- [ ] Security Updates + - [x] `.env` file for the api keys and other runtime info to be set, rather than in the `.py` files + - [x] Hashing rather than plaintext sending passwords (that way at least the password text itself isn't transmitted over the network) + - [ ] Actually use SSL, for posting (CORS seems like an issue) +- [ ] Accessibility + - [ ] Better use of semantic HTML tags + - [ ] Full keyboard control (tab, enter to select, tab between control buttons) +- [ ] GUI update for client + - [x] Playlist items look cleaner + - [x] Dark mode + - [ ] New Icons + - [ ] Google material design (Not sure I want this anymore) +- [ ] "Credit" system so each client can only add a set number of songs + - Based on time period, number in queue, other possible ideas for credits + - Without a login system there's no easy way to give credits to specific clients (and a login is beyond scope of what I want to do) + - Potentially a "redemption code" system, which can be tracked client side + - All of this is very hackable without a server-side login. + +## Completed Features +These will still be updated, but they're in a state that I am happy with them +- [x] Admin password +- [x] Websockets / some method of updating the time remaining to any client on the playlist screen + - [x] Set a timeout to change the time (to start) + - [x] Send updates to the playlist in real time when songs are added + - [x] Update the playlist's html without destroying it (create 1 new element) + - [x] Tell clients looking at the playlist when the song has been paused (so they can pause the local timers) + - [x] Settings updates + - [x] Without re-posting the server (contain update data in websocket ping) \ No newline at end of file