Compare commits

..

119 commits

Author SHA1 Message Date
a2433e0e5e rearranged, started using different wgsi server 2026-03-04 19:51:28 -05:00
8d78960f0b Added text hint to QR code in settings 2026-03-04 14:28:27 -05:00
f35b074543 Added lossless tag to search 2026-03-04 14:28:12 -05:00
d96014c24d Change back to CRLF, since basically everything else is
For some reason github thinks this is binary, promise it isn't
2026-03-02 17:24:54 -05:00
3690a66ef2 Small modifications, CRLF to LF 2026-02-11 09:50:31 -05:00
a72e91ce32
Merge pull request #7 from kristy-fournier/timerChanges
Sockets allowing for live updates rather than complete rebuilds of the client
2026-02-11 09:39:36 -05:00
192a84deed Update Wishlist, sockets are done 2026-02-11 09:38:45 -05:00
725cc3eb89 Re-freeze pip with minimum requirements 2026-02-11 09:36:32 -05:00
f556f17cce Few fixes that i'm going to un-re-fix later 2026-02-11 09:36:19 -05:00
f2204ee7ed Add versions and socketio 2026-02-11 09:12:00 -05:00
4cd5b33f84 Merge branch 'timerChanges' of https://github.com/kristy-fournier/PartyJukebox into timerChanges 2026-02-11 09:07:04 -05:00
566ce9cd73 Sockets are finished to an acceptable level 2026-02-11 09:06:02 -05:00
664cbda8f2 Merge branch 'timerChanges' of https://github.com/kristy-fournier/PartyJukebox into timerChanges 2026-02-10 20:06:14 -05:00
37bdd33aff Removed a false comment 2026-02-10 20:04:45 -05:00
554ba1b206 Merge branch 'main' into timerChanges 2026-02-09 14:18:37 -05:00
d8b261dcb7 Adjusted details relating to new features 2026-02-09 10:12:38 -05:00
4b3e64bd1a Updated readme 2026-02-08 20:34:50 -05:00
6effff1dc5 Adding a placeholder for future socket stuff 2026-02-02 10:58:31 -05:00
86a37a89c6 secure getFromServer is possible 2026-02-01 23:35:47 -05:00
95efd937f6 Update wishlist.md 2026-02-01 22:22:07 -05:00
8cb8b61397 Update wishlist.md 2026-02-01 22:21:02 -05:00
17632d4dea New settings socket, Different controls css 2026-02-01 22:20:05 -05:00
4c24f13c09 Update readme, slight gramatical change 2026-02-01 22:19:13 -05:00
87687506b1 Playlist update instead of refresh, time/skip sync
- Playlist destroys and creates members on the fly
- Updates time live, and ensures skips aren't detected twice

Im sure there are still bugs, but ill find them as i go
I am also still going to refactor this, so it''s not going to be merged into main for a while
2026-01-31 11:24:02 -05:00
f064183b9a Sockets are implemented
need a lot of fixes but are in a mostly working state as of now
2026-01-31 00:08:53 -05:00
384b369eee Update scripts.js 2026-01-30 22:06:43 -05:00
f17ab0c426 broken timer lololol 2026-01-29 17:53:25 -05:00
f37b2b7691 Added client side access to dupe prevention
Still some bugs but ill work through them
2026-01-29 17:09:00 -05:00
62caee7fd8 adaptive qr code, dark mode and more
- Dark mode is set based on user browser info
- QR Code changes colours based on dark or light mode
- "DUP" controlPerm for preventing duplicates in the future
  - Fully implemented in the server but not yet the client
2026-01-29 16:51:01 -05:00
cda152852c Minor changes 2026-01-26 15:32:28 -05:00
7d45d9498e fixed search errors 2026-01-26 15:32:00 -05:00
bcf3f28cb0
Merge pull request #6 from kristy-fournier/responseCodes
http responses are entirely rewritten
2026-01-26 12:31:24 -05:00
fce09edfc5 Added proper handling of internal errors (should be no 500s anywhere) 2026-01-26 12:30:08 -05:00
2002dd1afa removed broken timer, finalised new responses 2026-01-26 12:15:56 -05:00
417ecc8ced messing around, will fix later 2026-01-26 10:50:59 -05:00
00550cca85 I got distracted and broke something but the responses should be good now 2026-01-26 10:39:17 -05:00
0b64a6f297 Okay the backend should be done so im committing now
im gonna fix the frontend next
2026-01-26 10:09:26 -05:00
9bdac82f10 In the thick of changing the responses to requests 2026-01-25 19:04:02 -05:00
347feae50a added to requirements.txt, updated readme 2026-01-22 18:57:03 -05:00
bcd6807a34 Duplicate song queue adds can be blocked 2026-01-22 00:31:53 -05:00
1e1eac4aa4 Added a "clear playlist" admin function on the client 2026-01-22 00:10:59 -05:00
6a04ac30f5 slight layout update, mostly relevant for mobile 2026-01-21 23:45:14 -05:00
0dba7fd8cf Added to wishlist
websockets for playlist to send updates without full refresh
2026-01-21 20:06:07 -05:00
85257808a3 Updates to readme, fixed darkmode cookie bug 2026-01-21 20:02:35 -05:00
4f39417852 added hashing, updated parts of readme to explain env file
also added some tabby stuff, but its not done yet
2026-01-21 19:27:49 -05:00
37945ccced updated example.env
also rearranged imports and wishlist
2026-01-21 18:36:41 -05:00
ae428239a7 Start of updating icons 2026-01-21 18:28:40 -05:00
5772edf88a Using dotenv, refactored some stuff, made making database slightly faster with art 2026-01-21 16:49:04 -05:00
0cd6b4ce2e Keep dark mode state in a cookie
im gonna make this suck less later
2026-01-21 16:46:01 -05:00
838789e687 I lied i added a bit to the wishlist 2026-01-21 16:03:29 -05:00
ded406abcd update wishlist 2026-01-21 16:00:47 -05:00
ab09058c3d Dark mode is working to a level where i am happy with it
Note: i did ask gemini for some help on this, but understand and still wrote everything out
2026-01-21 15:57:35 -05:00
d33ee77693 Moved the creation of the virtual table to the databasegenerator.py 2026-01-21 15:56:55 -05:00
758f399636 tab to songs and playlist items
this actually isnt accessible, but it is something to think about. I don't personally know anyone who needs tab navigation but i know it's good to have and use
2025-10-17 15:49:02 -04:00
7958b4e8bd made the search items not have text go out of the box 2025-10-17 15:44:10 -04:00
6ece2d3ea1 refactored, fixed mp3 length bug, added lossless tag to database 2025-10-17 15:32:19 -04:00
faac93b1f6 flac and wav support 2025-10-10 18:39:56 -04:00
86e3e9cce8 Rearranged and removed comments 2025-10-10 15:30:01 -04:00
b20f0ecad0 Client is now 100% hosted on the included files
no more web references (so you don't need internet access on a closed network)
2025-10-10 15:28:49 -04:00
dcfe7115fa Playlist items text is spaced not stupidly
Playlist Items look like not garbage now
I gave them a giant margin and forgot about it. should be good now
the item holders have padding instead for the edges
2025-10-07 16:36:06 -04:00
e08e9cbcca Fixed a bunch of bugs to make adminpass complete
also added a bunch of comments and a new item design (css) that i'm probably going to undo
2025-10-06 12:47:58 -04:00
d72320aae4 Renamed some dumb variables, started wishlist 2025-10-05 23:27:04 -04:00
0034708091
Merge pull request #5 from kristy-fournier/admin-mode
Admin mode
2025-10-05 09:06:34 -04:00
86fde79305 make VERY CLEAR the password feature is not secure 2025-10-05 09:04:24 -04:00
d24aca7f39 made very clear passwords are not secure 2025-10-05 09:02:48 -04:00
189cafd08a Readme update
Should be good to be pushed to main now
2025-10-03 19:03:49 -04:00
76971ea75e Done adding admin password
Just gotta do documentation
2025-10-03 18:51:12 -04:00
1733a485b4 99% done
also added some new comments and notes about future design changes
2025-10-03 17:26:12 -04:00
36c2286b41 Update readme.md 2025-10-03 15:32:14 -04:00
1910b30acc everything but the auto-updating settings should be working
and also skipping isnt working on the playlist page
2025-07-18 20:13:18 -04:00
f41255e456 added server side password verification to everything that needs it 2025-07-18 19:21:21 -04:00
d110657d8f Added base of password system and check for adding a song 2025-07-18 18:31:46 -04:00
ea0380e3eb changed a for loop to fix for testing 2025-07-18 18:31:22 -04:00
26e8e93785 Fixed adminperms labels 2025-07-18 18:31:02 -04:00
a291e4626a added options 2025-07-12 22:09:18 -04:00
9c35196867
Merge pull request #4 from kristy-fournier/sqlite
Complete backend redesign to using SQLite
2025-07-06 14:00:53 -04:00
824bbdea45 added new file format for artist/song info 2025-07-06 13:55:30 -04:00
776ebbbd34 soundlocation is used for the file playing 2025-07-06 13:42:31 -04:00
d63847761c Fixes to partymode and playlist retrival 2025-07-06 13:16:12 -04:00
2d26d0d63a change readme for new database 2025-07-06 12:50:31 -04:00
ea183794c1 SQLite is Completely done, json is not used at all anymore 2025-07-06 12:46:01 -04:00
488f426d02 The database generator can make a functional SQLite database 2025-07-01 21:08:56 -04:00
d5481cbc57 Added AGPLv3 reference to the actual web app to make it compliant i think
if anyone actually knows how this liscense works please do a PR
2025-03-27 16:15:54 -04:00
fc49e710ee Add AGPL3 license 2025-03-25 15:30:12 -04:00
152325c9ed Update readme.md 2025-03-11 10:31:51 -04:00
a7c9f8ec4b updated manifest for PWA
solved some more issues, added some more issues, you know how it goes
2025-03-11 10:10:07 -04:00
0f81492332 Removed a comment for an issue i fixed 2025-03-10 13:42:38 -04:00
3e770fe66d added a colon 2025-03-10 12:55:38 -04:00
058d1a9a3c Not defaulting to new mode 2025-03-10 12:40:38 -04:00
3bb92bfc73
Merge pull request #3 from kristy-fournier/dev
Update mode working again
2025-03-10 10:33:05 -04:00
83fbdc7658 Update mode back to working, non mp3's are not added to the database 2025-03-10 10:32:27 -04:00
44bd5dc481 Remove "update" database mode temporarily 2025-03-10 10:05:07 -04:00
247c684b58 bleh 2025-03-10 10:01:40 -04:00
49c1b0bf25 trying to fix deleteymode, work in progress 2025-03-07 21:33:05 -05:00
49d50462ab made the qrcode generator a function
its now called when the ip is changed too, so you don't need to refresh
2025-03-06 11:24:06 -05:00
7505bc28d3 Volume cannot be changed when player isn't playing 2025-03-06 10:45:51 -05:00
48d4577c53 made a few more items per line visible on desktop 2025-03-06 10:22:12 -05:00
42e78ca977 Empty search error displayed 2025-03-06 10:14:17 -05:00
dfc068abf3
Merge pull request #2 from kristy-fournier/dev
Completely redid database layout
2025-03-05 15:50:35 -05:00
018fc7579d changed some prints 2025-03-05 15:50:14 -05:00
b0c1fa979f removed some unnecesary console logs 2025-03-05 15:37:32 -05:00
03bb059558 Fixed the freaking bug in ordering
i went from array, to json, to realising json can't have duplicates, to now converting the json back to an array (with the help of chatgpt D: )
Its fine though it works now
2025-03-05 15:34:28 -05:00
cf8796a3a1 Playlist mode, adding songs work in new format 2025-03-05 15:18:05 -05:00
9a3008b29e Update readme to match new generator use 2025-03-05 11:15:33 -05:00
968d30897e New JSON layout 2025-03-05 11:07:55 -05:00
f23ddc79ca added new minor details 2025-03-03 10:37:07 -05:00
44fcd881fc Changed error message 2025-03-03 10:17:42 -05:00
072d04930a fixed a bug in the client js 2025-01-21 20:41:47 -05:00
bdcb955165 dark mode testing 2025-01-19 19:14:18 -05:00
b1f1a38748 Finally
Changing the settings on mobile actually  works as intended
also other rearranging of the backend or whatever
2025-01-19 11:16:54 -05:00
1802ec3b79 renamed a variable
also crashing out in the comments
2025-01-15 11:19:44 -05:00
7c580b7bef tons of comment updates
probaby gonna make some incompatible changes soon to the format of the songDatabase
2024-11-27 17:21:39 -05:00
da423f49aa just updating some comments 2024-11-27 15:59:30 -05:00
39ed9fb5cb Update readme.md 2024-11-09 00:08:26 -05:00
fc12e5e1d1 Update readme.md
changed my mind on some wording
2024-11-08 23:18:40 -05:00
dc0cfd80a0 I made the directory where the mp3 files are a variable, so they can be stored on an external drive for example 2024-11-08 23:15:37 -05:00
5f4e2365a2 added comment 2024-10-22 13:18:08 -04:00
c6d457efbf added qrcode generator in settings 2024-10-17 16:26:17 -04:00
9a9e54f4b9 Update readme.md
added --port option to the server section
2024-10-17 15:52:05 -04:00
22 changed files with 1928 additions and 355 deletions

6
.gitignore vendored
View file

@ -1,3 +1,5 @@
server/sound/ server/sound/
server/songDatabase.json *.db
start.bat start.bat
.env
venv/

134
Client/ext/popper.js Normal file
View file

@ -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 =
'<div id="poper" class="window ' +
content.mode +
content.theme +
content.palette +
'"><span id="msg" class="message">' +
content.message +
'<a id="plcy-lnk" class="policylink" href="' +
content.href +
'"' +
" target=" +
content.target +
">" +
content.link +
'</a></span><div id="btn" class="compliance"><a id="cookie-btn" class="spopupbtnok" >' +
content.btnText +
'</a></div><span class="credit"><a href="https://popupsmart.com" target="_blank"><svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 60 60" fill="currentColor"><path id="popupsmart" d="M56.627,12.279a22.441,22.441,0,0,0-9.549-9.074c-4.122-2.088-8.951-3.2-15.722-3.2H28.644c-6.769,0-11.6,1.112-15.72,3.2a22.425,22.425,0,0,0-9.551,9.072C1.174,16.191,0,20.783,0,27.214v5.578c0,6.434,1.173,11.024,3.373,14.934A22.412,22.412,0,0,0,12.924,56.8c4.12,2.094,8.949,3.206,15.72,3.206h2.711c6.771,0,11.6-1.112,15.72-3.206a22.427,22.427,0,0,0,9.551-9.072c2.2-3.91,3.373-8.5,3.373-14.934V27.216C60,20.78,58.827,16.19,56.627,12.279ZM30,45.006c-.237,0-.473-.005-.708-.015l-.211-.012c-.14-.008-.28-.019-.419-.031-.123-.011-.245-.022-.367-.036l-.191-.024a14.979,14.979,0,0,1-2.672-.59V44.3a14.861,14.861,0,0,1-6.294-3.955,1.406,1.406,0,1,0-2.036,1.94,17.648,17.648,0,0,0,8.33,4.944v.354a5.214,5.214,0,1,1-10.428,0V30.046c0-.013,0-.026,0-.039a15,15,0,1,1,15,15Z" transform="translate(0 -0.005)"></path></svg><span>Powered by Popupsmart</span></a></span></div>';
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();

1
Client/ext/qrcode.min.js vendored Normal file

File diff suppressed because one or more lines are too long

BIN
Client/images/Icon-144.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

After

Width:  |  Height:  |  Size: 22 KiB

Before After
Before After

View file

@ -5,10 +5,14 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<link rel="stylesheet" href="styles.css"> <link rel="stylesheet" href="styles.css">
<link rel="manifest" href="manifest.json" /> <link rel="manifest" href="manifest.json" />
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-sha256/0.11.0/sha256.min.js"></script>
<!-- above allows use of sha256() on http -->
<script src="https://cdn.socket.io/4.7.5/socket.io.min.js"></script>
</head> </head>
<body> <body id="test-body">
<!--Cookie Popup(does it matter if im not tracking them? i have no idea)--> <!--Cookie Popup(does it matter if im not tracking them? i have no idea)-->
<script type="text/javascript" src="https://cookieconsent.popupsmart.com/src/js/popper.js"></script><script> window.start.init({Palette:"palette2",Mode:"floating left",Theme:"classic",LinkText:" Learn More!",Message:"This website uses cookies to save necessary data to your device, and no tracking is performed.",Time:"0",})</script> <script type="text/javascript" src="/ext/popper.js"></script><script> window.start.init({Palette:"palette2",Mode:"floating left",Theme:"classic",LinkText:" Learn More!",Message:"This website uses cookies to save necessary data to your device, and no tracking is performed.",Time:"0",})</script>
<div class="intro"> <div class="intro">
<h1 id="title">Jukebox Remote</h1> <h1 id="title">Jukebox Remote</h1>
@ -19,15 +23,15 @@
changes visibility with JS--> changes visibility with JS-->
<div class="songlist-mode" id="songlist-mode"> <div class="songlist-mode" id="songlist-mode">
<div class="searchbox-holder"> <div class="searchbox-holder">
<input type="text" autocomplete="off" placeholder="Search" id="songsearch" class="searchbox"><button class="go-search" id="go-search">Go!</button> <input type="text" autocomplete="off" placeholder="Search" id="songsearch" enterkeyhint="Search" class="searchbox"><button class="go-search" id="go-search">Go!</button>
</div> </div>
<div class="songlist" id="songlist"> <div class="songlist" id="songlist">
<h1>Search to find songs!</h1> <h1 style="margin-top: 0px;">Search to find songs!</h1>
<!-- Placeholder for the song items <!-- Placeholder for the song items
These are generated using javascript for search These are generated using javascript for search
<div class="item"> <div class="item">
<img src="search.png"></img> <img src="placeholder.png"></img>
<h3><span>Song title</span></h3> <h3><span>Song title</span></h3>
<h4>Artist</h4> <h4>Artist</h4>
</div> </div>
@ -52,24 +56,23 @@ changes visibility with JS-->
<!-- Because settings involves no generation ( all the settings are known), it is filled out always, just dissapears--> <!-- Because settings involves no generation ( all the settings are known), it is filled out always, just dissapears-->
<div class="settings-mode" id="settings-mode"> <div class="settings-mode" id="settings-mode">
<div class="settings" id="settings"> <div class="settings" id="settings">
<h1 >Client Settings (Saved to device)</h1> <h1>Client Settings (Saved to device)</h1>
<!--
<div class="item"> <div class="item">
<h2 for="darkmode-button">Dark Mode:</h2> <h2 for="darkmode-button">Dark Mode:</h2>
<p class="italic">opposite of light mode</p> <p class="italic">Opposite of light mode</p>
<button title="darkmode-button" id="darkmode-button">Off</button> <button title="darkmode-button" id="darkmode-button">Off</button>
</div> </div>
-->
<div class="item"> <div class="item">
<h2 for="iptextbox">Server IP:</h2> <h2 for="iptextbox">Server IP:</h2>
<p class="italic">IP of the device running the song server</p> <p class="italic">IP of the device running the song server</p>
<input title="iptextbox" style="width:200px" type="text" id="iptextbox"> <input title="iptextbox" style="width:200px" type="text" id="iptextbox" enterkeyhint="Done">
</div> </div>
<div class="item"> <div class="item">
<h2 for="alerttimetextbox">Alert Time:</h2> <h2 for="alerttimetextbox">Alert Time:</h2>
<p class="italic">How long alerts stay on screen for (seconds)</p> <p class="italic">How long alerts stay on screen for (seconds)</p>
<input title="alerttimetextbox" style="width:50px" type="text" id="alerttimetextbox" value="2"> <input title="alerttimetextbox" style="width:50px" type="text" id="alerttimetextbox" value="2" enterkeyhint="Done">
</div> </div>
<h1>Server Settings (Saved to server)</h1> <h1>Server Settings (Saved to server)</h1>
<div class="item"> <div class="item">
<h2 for="partymode-button">Party Mode:</h2> <h2 for="partymode-button">Party Mode:</h2>
@ -81,17 +84,50 @@ changes visibility with JS-->
<p class="italic">Volume of the music</p> <p class="italic">Volume of the music</p>
<input type="range" min="0" max="100" step="1" title="volumerange" id="volumerange"> <input type="range" min="0" max="100" step="1" title="volumerange" id="volumerange">
</div> </div>
<div class="item">
<h2>Share the remote:</h2>
<p class="italic">This shares the IP and URL you are currently connected to</p>
<div id="qrcode" alt="QR code to the remote URL"></div>
</div>
<h1>Admin Settings</h1>
<p class="italic">Note: Admin password must have been set from the server</p>
<div class="item">
<h2>Admin Password:</h2>
<p class="italic">Enter to use admin restricted functions</p>
<input placeholder="Wordpass12" type="password" title="Admin password box" id="adminpasswordbox" enterkeyhint="done">
</div>
<div class=item>
<h2>Fine action control:</h2>
<p class="italic">A check means that action is avalible to everyone</p>
<div id="admincheckholder">
<input type="checkbox" title="addsongcheck" id="addsongsettingcheckbox"><label for="addsongsettingcheckbox">Add songs to queue</label><br>
<input type="checkbox" title="skipsongcheck" id="skipsongsettingcheckbox"><label for="skipsongsettingcheckbox">Skip songs</label><br>
<input type="checkbox" title="playpausecheck" id="playpausesettingcheckbox"><label for="playpausesettingcheckbox">Play/pause</label><br>
<input type="checkbox" title="partymodecheck" id="partymodesettingcheckbox"><label for="partymodesettingcheckbox">Toggle Party Mode</label><br>
<input type="checkbox" title="volumechangecheck" id="volumechangesettingcheckbox"><label for="volumechangesettingcheckbox">Change volume</label><br>
<input type="checkbox" title="duplicateallowcheck" id="duplicateallowesettingcheckbox"><label for="duplicateallowsettingcheck">Add duplicate songs</label><br>
</div>
</div>
<div class="item">
<h2>Clear the playlist</h2>
<p class="italic" >Wipe the playlist, except the currently playing song. With PartyMode enabled, a second song will be added back randomly</p>
<button id="clear-button">Clear Playlist</button>
</div>
<p class="versionNumber">PartyJukebox is under an <a href="https://github.com/kristy-fournier/PartyJukebox/blob/main/LICENSE.md" target="_blank">AGPLV3</a> liscense. You can access the source code <a href=https://github.com/kristy-fournier/PartyJukebox target="_blank">here</a>.</p>
</div> </div>
</div> </div>
<!--All the buttons are down here but settings is just doing its own thing--> <!--All the buttons are down here but settings is just doing its own thing-->
<img class="settings-button" id="settings-button" src="./images/settings.png" alt="settings"></img>
<div id="controls" class="controls"> <div id="controls" class="controls">
<img class="control-button" id="playlist-button" src="./images/playlist.png" alt="playlist"></img> <img tabindex=0 class="control-button" id="playlist-button" src="./images/playlist.png" alt="Playlist"></img>
<img class="control-button" id="play-pause-button" src="./images/play-pause.png" alt="play pause"></img> <img tabindex=0 class="control-button" id="play-pause-button" src="./images/play-pause.png" alt="Play pause"></img>
<img class="control-button" id="skip-button" src="./images/skip.png" alt="skip"></img> <img tabindex=0 class="control-button" id="skip-button" src="./images/skip.png" alt="Skip"></img>
<img class="control-button" id="search-button" src="./images/search.png" alt="search"></img> <img tabindex=0 class="control-button" id="search-button" src="./images/search.png" alt="Search"></img>
</div> </div>
<div class="settings-button-holder">
<img tabindex=0 class="settings-button control-button" id="settings-button" src="./images/settings.png" alt="settings"></img>
</div>
<script src="/ext/qrcode.min.js" integrity="sha512-CNgIRecGo7nphbeZ04Sc13ka07paqdeTu0WR1IM4kNcpmBAUSHSQX0FslNhTDadL4O5SAGapGt4FodqL8My0mA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="scripts.js"></script> <script src="scripts.js"></script>
</body> </body>
</html> </html>

View file

@ -1,6 +1,7 @@
{ {
"name": "Jukebox Remote", "name": "Jukebox Remote",
"short_name": "Jukebox Remote", "short_name": "Jukebox Remote",
"description": "Controller for the PartyJukebox server app.",
"start_url": "index.html", "start_url": "index.html",
"display": "standalone", "display": "standalone",
"background_color": "#eeeeee", "background_color": "#eeeeee",
@ -10,6 +11,25 @@
{ {
"src": "/favicon.ico", "src": "/favicon.ico",
"type": "image/ico", "sizes": "100x100" "type": "image/ico", "sizes": "100x100"
},
{
"src":"images/Icon-144.png",
"type": "image/png",
"sizes": "144x144"
}
],
"screenshots": [
{
"src": "images/Screenshot-Main-Desktop.png",
"sizes" : "1919x1199",
"type": "image/png",
"form_factor": "wide"
},
{
"src": "images/Screenshot-Main-Mobile.png",
"type": "image/png",
"sizes": "485x859",
"form_factor": "narrow"
} }
] ]
} }

View file

@ -1,5 +1,37 @@
let ip // set all the global stuff
let alertTime = 2 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!") { async function alertText(text="Song Added!") {
alertbox = document.getElementById("alert"); alertbox = document.getElementById("alert");
alertbox.innerHTML = text; 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 // a lot of this is kinda waffly because i was trying to get
// it to return the right stuff and javascript is asyrcronouse (boo) // 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{ 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", method: "POST",
body: JSON.stringify(bodyInfo), body: JSON.stringify(bodyInfo),
headers: { headers: {
"Content-type": "application/json; charset=UTF-8" "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; return await data;
} catch(e) { } catch(e) {
if (e == "TypeError: Failed to fetch"){ // console.log("error print here:");
alertText("error: NoConnect to Server (is the ip set?)") // console.log(e);
if (e.toString().includes("TypeError: Failed to fetch")){
alertText("Error: Can't Connect to Server (is the ip set?)")
} else { } else {
alertText("error: " + e) alertText(e);
} }
const response=null; const response=null;
return response; return response;
} }
} }
//cookie reader is taken from internet because cookies ae too complicated for me //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 //i still understand how it works though promise just i see no reason to write this from scratch
function getCookie(cname) { function getCookie(cname) {
@ -50,38 +107,57 @@ function getCookie(cname) {
} }
return ""; return "";
} }
//someone more organised than me would have set all these elements to variables so they dont have to get them 50 times //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) { async function controlButton(buttonType) {
if (buttonType == "pp") { if (buttonType == "pp") { // Play-Pause button
getFromServer({control: "play-pause"}, "controls") let result = await getFromServer({control: "play-pause"}, "controls");
} else if (buttonType == "sk") { // console.log(result);
getFromServer({control: "skip"}, "controls") currentlyPlaying = result["data"]["playingState"];
if (document.getElementById("playlist-mode").style.display == "block") { } else if (buttonType == "sk") { // Skip button
generateVisualPlaylist("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("songlist").innerHTML = "";
document.getElementById("playlist").innerHTML = "<h1 id=\"playlist-alert\"></h1>"; document.getElementById("playlist").innerHTML = "<h1 id=\"playlist-alert\"></h1>";
document.getElementById("playlist-mode").style.display = "block"; document.getElementById("playlist-mode").style.display = "block";
document.getElementById("songlist-mode").style.display = "none"; document.getElementById("songlist-mode").style.display = "none";
document.getElementById("settings-mode").style.display = "none"; document.getElementById("settings-mode").style.display = "none";
generateVisualPlaylist(); generateVisualPlaylist();
} else if (buttonType == "se") { } else if (buttonType == "se") { //SearchMode button
clearInterval(playlistTimeTimer);
document.getElementById("songlist").innerHTML = "<h1>Search to find songs!</h1>"; document.getElementById("songlist").innerHTML = "<h1>Search to find songs!</h1>";
document.getElementById("playlist").innerHTML = ""; document.getElementById("playlist").innerHTML = "";
document.getElementById("playlist-mode").style.display = "none"; document.getElementById("playlist-mode").style.display = "none";
document.getElementById("songlist-mode").style.display = "block"; document.getElementById("songlist-mode").style.display = "block";
document.getElementById("settings-mode").style.display = "none"; 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("songlist").innerHTML = "";
document.getElementById("playlist").innerHTML = ""; document.getElementById("playlist").innerHTML = "";
document.getElementById("playlist-mode").style.display = "none"; document.getElementById("playlist-mode").style.display = "none";
document.getElementById("songlist-mode").style.display = "none"; document.getElementById("songlist-mode").style.display = "none";
document.getElementById("settings-mode").style.display = "block"; document.getElementById("settings-mode").style.display = "block";
checkSettings() checkSettings()
} else if (buttonType = "pm") { } else if (buttonType == "pm") { //Partymode toggle (in settings)
await getFromServer({setting: "partymode-toggle"}, "settings") let response = await getFromServer({setting: "partymode-toggle"}, "settings")
checkSettings(true) 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,43 +170,49 @@ function searchSongsEnter(e) {
} }
async function searchSongs(searchTerm){ async function searchSongs(searchTerm){
let optionslist = []
document.getElementById("songlist").innerHTML = "" document.getElementById("songlist").innerHTML = ""
searchResults = await getFromServer({search:searchTerm},"search").then() let fetchResults = await getFromServer({search:searchTerm},"search").then();
for (let index in searchResults) { let searchResults = fetchResults.data;
optionslist.push([index,searchResults[index][0],searchResults[index][1],searchResults[index][2]]);
}
//generate the visual song list //generate the visual song list
for(let i = 0; i < optionslist.length; i++) { for(var fileName in searchResults) {
let currentSongInJSON = searchResults[fileName]
let newItem = document.createElement("div"); let newItem = document.createElement("div");
newItem.className = "item"; newItem.className = "item";
newItem.id = optionslist[i][3]; newItem.id = fileName;
newItem.tabIndex = 0;
let image = document.createElement("img"); let image = document.createElement("img");
try { try {
if (optionslist[i][2] == null) { if (currentSongInJSON["art"] == null) {
throw "no image lolz" throw "no image lolz"
} }
image.src = optionslist[i][2]; image.src = currentSongInJSON["art"];
} catch(err){ } catch(err){
image.src = "./images/placeholder.png"; image.src = "./images/placeholder.png";
} }
image.id = String(optionslist[i][3])+" image"; image.id = String(fileName)+" image";
let head3 = document.createElement("h3"); let head3 = document.createElement("h3");
head3.innerText = optionslist[i][0]; head3.innerText = currentSongInJSON["title"];
let head4 = document.createElement("h4"); let head4 = document.createElement("h4");
head4.innerText=optionslist[i][1]; head4.innerText = currentSongInJSON["artist"];
newItem.appendChild(image); newItem.appendChild(image);
newItem.appendChild(head3); newItem.appendChild(head3);
newItem.appendChild(head4); 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); document.getElementById("songlist").appendChild(newItem);
//display error if no results
} }
if (optionslist.length == 0) { if (JSON.stringify(searchResults)==JSON.stringify({})) {
//display error if no results
document.getElementById("songlist").innerHTML = "<h1>We might not have that one...</h1>"; document.getElementById("songlist").innerHTML = "<h1>We might not have that one...</h1>";
} }
} }
function alertTimeEnter(e){ function alertTimeEnter(e){
if (e.key == "Enter") { if (e.key == "Enter") {
e.preventDefault(); e.preventDefault();
@ -146,7 +228,11 @@ function alertTimeSet(time) {
function ipSetEnter(e){ function ipSetEnter(e){
if (e.key == "Enter") { 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) ipSetter(document.getElementById("iptextbox").value)
} }
} }
@ -167,19 +253,89 @@ function ipSetter(){
alertText("Your IP is now set to "+ipBox+" at port 19054 (Default)") 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 = "";
// 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 : 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) { async function checkSettings(skipServer=false) {
//check client stuff first so if the server doesn't exist it can still be changed and seen //check client stuff first so if the server doesn't exist it can still be changed and seen
if (ip.slice(-5)=="19054") { if (ip.slice(-5)=="19054") {
// don't show the port if it is the default
document.getElementById("iptextbox").value = ip.slice(0,-6) document.getElementById("iptextbox").value = ip.slice(0,-6)
} else { } else {
document.getElementById("iptextbox").value = ip; document.getElementById("iptextbox").value = ip;
} }
qrCodeGenerate()
document.getElementById("alerttimetextbox").value = alertTime document.getElementById("alerttimetextbox").value = alertTime
partyButtonState = document.getElementById("partymode-button").innerHTML; partyButtonState = document.getElementById("partymode-button").innerHTML;
x = await getFromServer({setting: "getsettings"}, "settings"); let nodeList = document.getElementById("admincheckholder").children
// temporary
for (let i=0; i<nodeList.length;i++) {
if (nodeList[i].type == 'checkbox') {
nodeList[i].checked = true;
}
}
//ping the server here
data = await getFromServer({setting: "getsettings"}, "settings");
x = data["data"];
if (!(skipServer) || partyButtonState=="N/A") { if (!(skipServer) || partyButtonState=="N/A") {
if (x["partymode"] == false) { if (x["partymode"] == false) {
document.getElementById("partymode-button").innerHTML = "Off"; document.getElementById("partymode-button").innerHTML = "Off";
@ -192,24 +348,113 @@ async function checkSettings(skipServer=false) {
document.getElementById("partymode-button").innerHTML = "Off"; document.getElementById("partymode-button").innerHTML = "Off";
} }
document.getElementById("volumerange").value = parseInt(x["volume"]) document.getElementById("volumerange").value = parseInt(x["volume"])
// do the admin checkboxes here
let currentAdminPerms = x["admin"];
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"];
}
async function addToPlaylist(songObject) {
i = document.getElementById("playlist").children.length-1
let newItem = document.createElement("div");
newItem.className = "item";
newItem.id = Object.keys(songObject)[0];
newItem.tabIndex = 0;
let image = document.createElement("img");
try {
if (songObject[newItem.id]["art"] == null) {
throw "no image lolz"
}
image.src = songObject[newItem.id]["art"];
} catch(err){
image.src = "./images/placeholder.png";
}
image.id = String(songObject[newItem.id])+" image";
let head3 = document.createElement("h3");
head3.innerText = songObject[newItem.id]["title"];
let head4 = document.createElement("h4");
head4.innerText= songObject[newItem.id]["artist"];
let head5 = document.createElement("h5");
let timeLeft =document.createElement("h5");
timeLeft.style.fontWeight = 100;
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"
newItem.appendChild(image);
textdiv.appendChild(head3);
textdiv.appendChild(head4);
textdiv.appendChild(timeLeft);
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";
playlistElapsedSeconds = playlist[0]["time"];
playlistSongLength = playlist[0]["length"];
displayElapsedPlaylistTime(playlistElapsedSeconds,playlistSongLength);
clearInterval(playlistTimeTimer);
}
} catch(e) {
console.log("I dunno something bad happened:"+e);
}
}
async function skipInPlaylist() {
playlistElapsedSeconds = 0;
let playlistChildren = document.getElementById("playlist").children;
if(playlistChildren[1].nodeName === "DIV") {
playlistChildren[1].remove();
}
playlistChildren = document.getElementById("playlist").children;
if(playlistChildren.length === 1) {
playlistChildren[0].innerText = "Nothing's Queued..."
} else {
let firstElementTextChildren = playlistChildren[1].children[1].children
// console.log(firstElementTextChildren);
firstElementTextChildren[2].id = "elapsed-time-display";
firstElementTextChildren[3].id = "playing-indicator-text";
firstElementTextChildren[3].textContent = "Playing";
}
displayElapsedPlaylistTime(playlistElapsedSeconds,playlistSongLength);
} }
async function generateVisualPlaylist(conditions="") { async function generateVisualPlaylist(conditions="") {
document.getElementById("playlist").innerHTML = "<h1 id=\"playlist-alert\"></h1>"; document.getElementById("playlist").innerHTML = "<h1 id=\"playlist-alert\"></h1>";
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){ if (playlist.length==0){
clearInterval(playlistTimeTimer);
document.getElementById("playlist-alert").innerHTML = "Nothing's Queued..." document.getElementById("playlist-alert").innerHTML = "Nothing's Queued..."
} else { } else {
if (conditions=="skip-button") { if (conditions==="skip-button") {
playlist.shift() playlist.shift()
if (playlist.length==0){ if (playlist.length==0){
document.getElementById("playlist-alert").innerHTML = "Nothing's Queued..." document.getElementById("playlist-alert").innerHTML = "Nothing's Queued..."
} }
} }
for (i in playlist) { for (let i in playlist) {
let fileName = playlist[i]["filename"]
let newItem = document.createElement("div"); let newItem = document.createElement("div");
newItem.className = "item"; newItem.className = "item";
newItem.id = playlist[i]["file"]; newItem.id = fileName;
newItem.tabIndex = 0;
let image = document.createElement("img"); let image = document.createElement("img");
try { try {
if (playlist[i]["art"] == null) { if (playlist[i]["art"] == null) {
@ -219,7 +464,7 @@ async function generateVisualPlaylist(conditions="") {
} catch(err){ } catch(err){
image.src = "./images/placeholder.png"; image.src = "./images/placeholder.png";
} }
image.id = String(playlist[i]["file"])+" image"; image.id = String(fileName)+" image";
let head3 = document.createElement("h3"); let head3 = document.createElement("h3");
head3.innerText = playlist[i]["title"]; head3.innerText = playlist[i]["title"];
let head4 = document.createElement("h4"); let head4 = document.createElement("h4");
@ -227,19 +472,11 @@ async function generateVisualPlaylist(conditions="") {
let head5 = document.createElement("h5"); let head5 = document.createElement("h5");
let timeLeft =document.createElement("h5"); let timeLeft =document.createElement("h5");
timeLeft.style.fontWeight = 100; timeLeft.style.fontWeight = 100;
try { if(i== 0) {
if (i == 0) { // they can all have the text, doesn't really matter, but only the first one
head5.innerHTML="Playing"; // should get the ids since its the one we want to mess with
if ((conditions != "skip-button")) { head5.id = "playing-indicator-text";
let mins = Math.floor(playlist[i]["time"]/60); timeLeft.id = "elapsed-time-display";
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){
console.log(err)
} }
let textdiv = document.createElement("div") let textdiv = document.createElement("div")
textdiv.className="text" textdiv.className="text"
@ -250,24 +487,122 @@ async function generateVisualPlaylist(conditions="") {
textdiv.appendChild(head5); textdiv.appendChild(head5);
newItem.appendChild(textdiv); newItem.appendChild(textdiv);
document.getElementById("playlist").appendChild(newItem); 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) { async function submitSong(songid) {
getFromServer({song: songid}, "songadd") let returncode = await getFromServer({song: songid}, "songadd");
alertText("Added to Queue") 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) { function checkWhatSongWasClicked(e) {
itemId = e.srcElement.id; if(e.type == "click" || e.key == "Enter") {
if ((itemId.length-itemId.lastIndexOf("image") == 5) && itemId.lastIndexOf("image")!=-1) { itemId = e.srcElement.id;
itemId = itemId.slice(0,-6) 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);
}
}
}
function toggleDark(e) {
let x = document.getElementById("test-body").classList
if (!(x.contains("dark-mode"))) {
document.cookie = "darkmode=true; path=/;";
document.getElementById("darkmode-button").innerHTML = "On";
x.add("dark-mode");
} else {
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!");
} }
//i feel like later dylan won't apreciate this
//one of my files was "file.MP3" so it didn't work
if (itemId.slice(-4).toLowerCase() == ".mp3") {
submitSong(itemId);
}
} }
let optionslist = [] let optionslist = []
@ -281,16 +616,31 @@ document.addEventListener('keydown', function(e){
}}) }})
document.getElementById("playlist-mode").style.display = "none"; document.getElementById("playlist-mode").style.display = "none";
document.getElementById("settings-mode").style.display = "none"; document.getElementById("settings-mode").style.display = "none";
//.ontouch for mobile?? document.getElementById("volumerange").onchange = async function(e) {
document.getElementById("volumerange").onchange = function() { // there is no reason for this not to be a defined function
getFromServer({setting:"volume",level:this.value}, "settings") // FIX THIS
if (this.value == 0) { 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) {
alertText("The volume is now set to 0 (Pause?)") alertText("The volume is now set to 0 (Pause?)")
} else { } else {
alertText("The volume is now set to " + this.value.toString()) 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("settings-button").addEventListener('click',function(){controlButton("st")});
document.getElementById("play-pause-button").addEventListener('click', function(){controlButton("pp")}); document.getElementById("play-pause-button").addEventListener('click', function(){controlButton("pp")});
document.getElementById("playlist-button").addEventListener('click', function(){controlButton("pl")}); document.getElementById("playlist-button").addEventListener('click', function(){controlButton("pl")});
@ -300,32 +650,81 @@ document.getElementById("go-search").addEventListener('click', function(){search
document.getElementById("songsearch").addEventListener('keydown', function(e){searchSongsEnter(e)}); document.getElementById("songsearch").addEventListener('keydown', function(e){searchSongsEnter(e)});
document.getElementById("iptextbox").addEventListener('keydown', function(e){ipSetEnter(e)}); document.getElementById("iptextbox").addEventListener('keydown', function(e){ipSetEnter(e)});
document.getElementById("alerttimetextbox").addEventListener('keydown', function(e){alertTimeEnter(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("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 //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)}); 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 //makes the controls look mostly normal on all screens, best solution i could find, idk man
let tempWidth = document.getElementById('controls').clientWidth; // replaced this with "transform" css stuff
document.getElementById("controls").style.marginLeft = "-"+String(parseInt(tempWidth/2))+"px"; // 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 //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 //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) //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 //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 //tries the url first, then the cookie, then the default
ip = params.get("ip") ip = params.get("ip")
if (ip == null || ip=="") { if (ip == null || ip=="") {
ip=getCookie("ip") ip=getCookie("ip")
} }
console.log(ip)
if (ip==null || ip==""){ if (ip==null || ip==""){
ip = "" ip = ""
} }
document.cookie = "ip="+ip+"; path=/;"
// saving the cookies (don't tell the EU)
document.cookie = "ip="+ip+"; path=/;"
alertTime = getCookie("alertTime") alertTime = getCookie("alertTime")
document.getElementById("alerttimetextbox").value = alertTime document.getElementById("alerttimetextbox").value = alertTime
if (alertTime == "") { if (alertTime == "") {
alertTime = 2; alertTime = 2;
document.cookie = "alertTime="+alertTime+"; path=/;" document.cookie = "alertTime="+alertTime+"; path=/;"
} }
// this is the code that makes the qr code at the very start
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);
}
});

View file

@ -1,13 +1,47 @@
/* testing */ /* dark mode stuff */
.dark-mode {
--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 */ /* Things that are always visible */
body { body {
background-color: #EEEEEE; background-color: var(--bg-main);
} }
* { * {
font-family: 'arial'; font-family: 'Arial',sans-serif;
} }
.italic { .italic {
font-style: italic; font-style: italic;
} }
@ -28,7 +62,8 @@ h4 {
left: 50%; left: 50%;
bottom: 0; bottom: 0;
margin: 0 auto; margin: 0 auto;
background-color:inherit; transform: translateX(-50%);
background-color:var(--bg-main);
} }
.alert { .alert {
@ -37,23 +72,29 @@ h4 {
width: 100%; width: 100%;
text-align: center; text-align: center;
z-index: 1000; z-index: 1000;
background-color: #EEEEEEd6; background-color: color-mix(in srgb, var(--bg-main), transparent 16%);
} }
.settings-button { .settings-button-holder {
width: 15%; width:15%;
max-width: 90px; max-width: 90px;
position:fixed; position:fixed;
top:0; top:0;
right:0; right:0;
margin: 3px; margin: 3px;
background:inherit; background-color: var(--bg-main);
/* This is a circle background for the circle settings button /* This is a circle background for the circle settings button
So it can display over other text and such */ So it can display over other text and such */
border-radius: 50%; border-radius: 50%;
} }
.control-button{ .settings-button {
width: 100%;
}
.controls > .control-button{
width:20%; width:20%;
max-width: 110px; max-width: 110px;
margin: auto 2%; margin: auto 2%;
@ -65,22 +106,26 @@ h4 {
text-align: center; 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 stuff */
.songlist { .songlist {
width: 60%; width: 80%;
min-width: 300px; min-width: 400px;
margin:auto auto 150px; margin:auto auto 150px;
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
} }
.songlist > .item{ .songlist > .item{
border: 1px solid #333333; border: 1px solid var(--bg-item);
width:30%; width:30%;
max-width: 200px; max-width: 150px;
margin: 5px auto; margin: 5px auto;
min-width: 100px; min-width: 75px;
background-color: inherit;
} }
.songlist > .item > img{ .songlist > .item > img{
@ -91,6 +136,8 @@ h4 {
.songlist > .item > h3, .songlist > .item > h4{ .songlist > .item > h3, .songlist > .item > h4{
margin-left: 2px; margin-left: 2px;
margin-right: 2px; margin-right: 2px;
margin: 5px;
word-wrap: break-word;
} }
.searchbox-holder { .searchbox-holder {
@ -102,11 +149,18 @@ h4 {
.searchbox { .searchbox {
width: 65%; width: 65%;
margin: 1px; margin: 1px;
margin-bottom: 16px;
} }
.go-search { .go-search {
width: 20%; width: 20%;
min-width: 50px; min-width: 50px;
} }
.lossless-tag {
width:16px;
padding: 1px;
margin-left: auto;
}
/* playlist mode stuff */ /* playlist mode stuff */
.playlist { .playlist {
@ -116,7 +170,7 @@ h4 {
} }
.playlist > .item{ .playlist > .item{
border: 1px solid #333333; border: 1px solid var(--bg-item);
display: flex; display: flex;
max-width: 50em; max-width: 50em;
min-width: 200px; min-width: 200px;
@ -125,6 +179,7 @@ h4 {
} }
.playlist > .item > .text { .playlist > .item > .text {
padding: 3px;
display: inline-block; display: inline-block;
margin: 0px 3px; margin: 0px 3px;
} }
@ -139,7 +194,7 @@ h4 {
} }
.playlist > .item > .text > * { .playlist > .item > .text > * {
margin:5% 2px; margin:2px;
} }
/* settings stuff */ /* settings stuff */
@ -153,18 +208,38 @@ h4 {
.settings > .item { .settings > .item {
margin-left: 10%; margin-left: 10%;
width:fit-content; width:fit-content;
background-color: var(--bg-main);
} }
.settings > .item:not(:last-child) { .settings > .item:not(:last-child) {
padding-bottom: 10px; padding-bottom: 10px;
border-bottom: 1px solid #333333; border-bottom: 1px solid var(--bg-item);
}
.settings > .item.no-line {
border-bottom: 0px none #00000000;
padding-bottom: 0px;
} }
.settings > .lastSet1 { .settings > .lastSet1 {
border-bottom: 0; border-bottom: 0;
} }
.settings > .item > h2 {
margin-bottom: 4px;
}
.settings > .item > p {
margin-top: 0px
}
.versionNumber {
font-size: 11px;
font-style: italic;
text-align: left;
width: 80%;
}
#volumerange { #volumerange {
background-color: #4477AA; background-color: #4477AA;
color: #4477ff; color: #4477ff;

661
LICENSE.md Normal file
View file

@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

View file

@ -1,4 +0,0 @@
{
"port": 19054,
"LastFMKey":""
}

View file

@ -1,12 +0,0 @@
"""
Assume that this file is being run at startup, and should do all the things needed
() Check USB for new mp3's
() Check USB for updated data files (api keys, ports, )
() Copy them to correct directory
() Make sure the audio device is set to the 3.5mm jack
() Run database updater if new files were found
() Run Server
() Run http module to host client
() Generate a qr code and display it somehow (maybe)
"""
import threading, os, shutil,

View file

@ -1,79 +1,140 @@
import os
from mutagen.easyid3 import EasyID3 from mutagen.easyid3 import EasyID3
from mutagen.mp3 import MP3 from mutagen.mp3 import MP3
import requests, ast, time, math, argparse, json import mutagen.flac
import mutagen.wave
import sqlite3 as sql
import requests, ast, time, math, argparse, dotenv, os
loading = ["-","\\","|","/"] loading = ["-","\\","|","/"]
songFiles = os.listdir(r'./sound')
parser=argparse.ArgumentParser(description="Options for the generation of the song database") 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('-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('-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() args = parser.parse_args()
apikeylastfm = args.apikey dotenv.load_dotenv()
# if you want to set the api key permenantly for your setup just uncomment the next line apikeylastfm = os.getenv("API_KEY")
# apikeylastfm = "KeyHere" soundLocation = os.getenv("DIRECTORY")
if args.mode == "update": # apikeylastfm = args.apikey
try: if args.directory[-1] == "/" or args.directory[-1] == "\\":
with open('songDatabase.json', 'r') as handle: soundLocation = args.directory
songDatabaseList = json.load(handle) elif "/" in args.directory:
except: soundLocation = args.directory + "/"
songDatabaseList=[] else:
soundLocation = args.directory + "\\"
for i in songDatabaseList: songFiles = os.listdir(soundLocation)
try: fileOfDB = sql.connect("songDatabase.db")
songFiles.index(i["file"]) != -1 songDatabase = fileOfDB.cursor()
except: # setting song directory
print("deleted: " + i["file"] + " from database") songDatabase.execute("CREATE TABLE IF NOT EXISTS meta (id TEXT PRIMARY KEY, data TEXT);")
songDatabaseList.pop(songDatabaseList.index(i)) try:
songDatabase.execute("INSERT INTO meta (id, data) VALUES (?,?)",("songDirectory",soundLocation))
for i in songDatabaseList: except:
songFiles.pop(songFiles.index(i["file"])) songDatabase.execute("UPDATE meta SET data = ? WHERE id = 'songDirectory'", (soundLocation,))
print("new songs: " + str(songFiles)) if args.mode.lower() == "update":
elif args.mode=="new": #Create if not exists
songDatabaseList = [] 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()
for i in dBfilelist:
dBfilelistSet.add(i[0])
# Delete nonexistant files
deleteySongs = list(dBfilelistSet - set(songFiles))
songDatabase.executemany("DELETE FROM songs WHERE filename = ?", [(item,) for item in deleteySongs]) # in this line it turns the list of strings into a list of tuples of strings
print("Deleted: " + ", ".join(deleteySongs)+ " from database")
# only include new files in list to be used
songFiles = list(set(songFiles) - dBfilelistSet)
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, lossless INTEGER);")
else:
raise ValueError("Must be \"new\" or \"update\"")
if args.art.lower() == "true": if args.art.lower() == "true" and not(apikeylastfm == ""):
x = len(songFiles)*0.25 eta = len(songFiles)*0.25
if x > 60: if eta > 60:
print("ETA "+ str(x/60) + " minutes") print(f"ETA {eta/60:.2f} minutes")
else: else:
print("ETA "+ str(x) + " seconds") print(f"ETA {eta} seconds")
# will be used soon
validFormats = ["mp3","flac","wav"]
for i in songFiles: for i in songFiles:
# 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: try:
song = EasyID3("sound/"+i) # get the metadata
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] title = song['title'][0]
artist = song['artist'][0] artist = song['artist'][0]
except: except:
try: if "_" in i:
# if metadata is missing, try to use file name following "title_artist.mp3"
song = i.split("_") song = i.split("_")
title = song[0] title = song[0]
artist = song[1].split(".")[0] artist = song[1].split(".")[0]
except: elif "-" in i:
# 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 or hyphen, the title is the file name
title = i title = i
artist = None 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: try:
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"] # 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"]
if image == "": if image == "":
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"] 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 == "": if image == "":
image = None image = None
time.sleep(0.25) time.sleep(0.01)
except: except:
image=None image=None
else: else:
image=None image=None
try: try:
length = math.ceil(MP3("sound/"+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: except:
length = 0 length = 0
if len(songFiles) != 1: if len(songFiles) != 1:
index = (songFiles.index(i))%4 index = (songFiles.index(i))%4
print("\r" + str(loading[index] + str(math.floor((songFiles.index(i)/(len(songFiles)-1))*100))+ "%"), end='', flush=True) 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 containing the below stuff, and each dictionary is put into a list # each "song" is stored as a SQLite entry following the format seen below
songDatabaseList.append({"file":i,"title":title,"artist":artist,"art":image,"length":length}) songDatabase.execute(f"INSERT INTO songs (filename, title, artist, art, length, lossless) VALUES (?,?,?,?,?,?)",(i,title,artist,image,length,lossless))
with open('songDatabase.json', 'w') as handle: songDatabase.execute("DROP TABLE IF EXISTS virtualSongs;")
json.dump(songDatabaseList, handle) 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()

7
Server/example.env Normal file
View file

@ -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

View file

@ -1,10 +1,57 @@
import eventlet
eventlet.monkey_patch()
from flask import Flask from flask import Flask
from flask import request from flask import request
from flask_cors import CORS from flask_cors import CORS
import json,vlc,threading,time,random, argparse from flask_socketio import SocketIO
import sqlite3 as sql
import vlc,threading,time,random,argparse,dotenv,os,hashlib,string
# Argparse Stuff
parser=argparse.ArgumentParser(description="Options for the Webby Bits") parser=argparse.ArgumentParser(description="Options for the Webby Bits")
parser.add_argument('-p','--port',help="Pick a port to host on, not the same as the web (client) port",default='19054') # 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('-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()
#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 += "\\"
#Create Virtual table for searching
#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() random.seed()
global partyMode global partyMode
global skipNow global skipNow
@ -14,118 +61,268 @@ songNext = None
skipNow = False skipNow = False
playlist = [] playlist = []
playlistLock = threading.Lock() playlistLock = threading.Lock()
fakeplayer = vlc.Instance() vlcInstance = vlc.Instance()
player = fakeplayer.media_player_new() player = vlcInstance.media_player_new()
# for client side volume to work as well as possible, set system volume to 100 and control in app # for client side volume to work as well as possible, set system volume to 100 and control in app
player.audio_set_volume(100) player.audio_set_volume(100)
app = Flask(__name__) app = Flask(__name__)
# because you are POSTing from another domain to this one, you need CORS
CORS(app) CORS(app)
with open('./songDatabase.json', 'r') as handle: # Replace the star with the frontend domain if you dislike being hacked
songDatabaseList = json.load(handle) socketio = SocketIO(app, cors_allowed_origins="*")
def queueSong(song): def queueSong(song):
with playlistLock: with playlistLock:
playlist.append(song) 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. # this is a loop that plays the songs and checks for playlist changes, skips, ect.
counter = 0
isPlaying = False
def playQueuedSongs(): def playQueuedSongs():
global skipNow global skipNow
global songNext global songNext
global partyMode global partyMode
global counter
global isPlaying
while True: while True:
with playlistLock: with playlistLock:
z = str(player.get_state()) counter+=1
if(counter > 2):
if playlist and (z == "State.Ended" or z== "State.Stopped" or z == "State.NothingSpecial" or skipNow == True): 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() player.stop()
skipNow = False skipNow = False
songNext = playlist.pop(0) songNext = playlist.pop(0)
media = fakeplayer.media_new("sound/"+songNext) media = vlcInstance.media_new(soundLocation+songNext)
player.set_media(media) player.set_media(media)
player.play() player.play()
elif (len(playlist) == 0) and skipNow==True: 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 skipNow=False
songNext = None songNext = None
player.stop() player.stop()
elif (len(playlist) == 0) and (z == "State.Ended" or z == "State.NothingSpecial" or z=="State.Stopped"): elif len(playlist)<1 and (partyMode == True):
songNext = None fileofDB = sql.connect("songDatabase.db")
elif (len(playlist)<1) and (partyMode == True): songDatabase = fileofDB.cursor()
playlist.append(random.choice(songDatabaseList)["file"]) 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)
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
# 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) time.sleep(1)
queueThread = threading.Thread(target=playQueuedSongs) @socketio.on("connect")
queueThread.daemon = True def handleConnect():
queueThread.start() pass
@app.route("/controls", methods=['POST']) @app.route("/controls", methods=['POST'])
def playerControls(): def playerControls():
# recieve control inputs (play/pause and skip) from the webUI
global skipNow global skipNow
global media
global partyMode global partyMode
recieveData=request.get_json(force=True) recieveData=request.get_json(force=True)
if recieveData["control"] != None: try:
if recieveData["control"] == "play-pause": if recieveData["control"] == "play-pause":
player.pause() if ADMIN_PASS == recieveData['password'] or controlPerms["PP"]:
return "200" 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": elif recieveData["control"] == "skip":
skipNow = True if ADMIN_PASS == recieveData['password'] or controlPerms["SK"]:
# print(str(player.get_state())) skipNow = True
return "200" 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: else:
return "400" return {"error":"Not a valid control","data":None},400
except KeyError:
return ERR_MISSING_ARGS
@app.route("/settings", methods=['POST']) @app.route("/settings", methods=['POST'])
def settingsControl(): def settingsControl():
global controlPerms
# set the volume and partymode
global partyMode global partyMode
global player
recieveData = request.get_json(force=True) recieveData = request.get_json(force=True)
if recieveData["setting"] == "volume": try:
player.audio_set_volume(int(recieveData["level"])) if recieveData["setting"] == "volume":
return "200" if ADMIN_PASS == recieveData['password'] or controlPerms["VOL"]:
elif recieveData["setting"] == "getsettings": volumeLevel = int(recieveData["level"])
x = {"partymode":partyMode,"volume":player.audio_get_volume()} if(volumeLevel <= 100 and volumeLevel >= 0):
return x volumePassed = player.audio_set_volume(volumeLevel)
elif recieveData["setting"] == "partymode-toggle": if(volumePassed == 0):
partyMode = not(partyMode) # only emit a signal i the volume really changed
return "200" socketio.emit("settingsChange",{"settingToChange":"volume","newData":volumeLevel})
else: return {"error":"ok","data":{"volumePassed":volumePassed}},200
return "400" 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']) @app.route("/search", methods=['POST'])
def searchSongDB(): def searchSongDB():
recieveData=request.get_json(force=True) recieveData=request.get_json(force=True)
# the way i put the data in a list was really dumb looking back, i could and should have used a list of dictioaries like i was before fileofDB = sql.connect("songDatabase.db")
# i might try to change it but this layout is embedded deep in the client songDatabase = fileofDB.cursor()
tempData = {} try:
for i in songDatabaseList: results = []
if ((i["title"].lower().find(recieveData['search'].lower())) > -1) or (recieveData['search'] == ""): # print(recieveData["search"])
tempData[i["title"]] = [i["artist"],i["art"],i["file"]] if (recieveData['search'] == ""):
try: songDatabase.execute("SELECT * FROM virtualSongs")
if (i["artist"].lower().find(recieveData['search'].lower()) > -1): results = songDatabase.fetchall()
tempData[i["title"]] = [i["artist"],i["art"],i["file"]] else:
except: songDatabase.execute("SELECT * FROM virtualSongs WHERE virtualSongs MATCH ?",['"' + recieveData['search']+'"'])
pass results = songDatabase.fetchall()
tempdata = {}
return 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"]) @app.route("/songadd", methods=["POST"])
def songadd(): def songadd():
recieveData=request.get_json(force=True) recieveData=request.get_json(force=True)
queueSong(recieveData['song']) try:
return "200" 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"]) @app.route("/playlist", methods=["POST"])
def getPlaylist(): def getPlaylist():
global songNext global songNext
fileofDB = sql.connect("songDatabase.db")
songDatabase = fileofDB.cursor()
tempPlaylist = [] tempPlaylist = []
for k in songDatabaseList: if songNext != None:
if k["file"] == songNext: # Adds the currently playing song
temp = k.copy() songDatabase.execute("SELECT * FROM songs WHERE filename = ?",[songNext])
temp["playing"] = True result = songDatabase.fetchall()[0]
temp["time"] = player.get_time()/1000 # again, this is still using the old JSON format to avoid client changes
tempPlaylist.append(temp) k = {
"title": result[1],
"artist": result[2],
"art": result[3],
"length": result[4]
}
temp = k.copy()
temp["playing"] = True
temp["time"] = player.get_time()/1000
tempPlaylist.append({songNext:temp})
for i in playlist: for i in playlist:
for j in songDatabaseList: songDatabase.execute("SELECT * FROM songs WHERE filename = ?",[i])
if j["file"] == i: result = songDatabase.fetchall()[0]
tempPlaylist.append(j) k = {
return tempPlaylist "title": result[1],
"artist": result[2],
"art": result[3],
"length": result[4]
}
tempPlaylist.append({i:k})
fileofDB.close()
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__": 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)

79
plan.md
View file

@ -1,79 +0,0 @@
# Self Running Part
To design a self-running app for your Raspberry Pi based on your requirements, heres a step-by-step plan that you can follow. I'll guide you through the steps without giving the full solution, so you can piece it together.
### Steps to Implement
1. **Automating Raspberry Pi Startup Actions:**
- **Systemd Service**: Use `systemd` to create a service that will automatically run when the Pi starts. This can manage your apps startup logic.
- **Startup Script**: Alternatively, you can create a simple shell script that runs on boot, either placed in `/etc/rc.local` or managed by `cron` with the `@reboot` directive.
2. **Detect USB Flash Drive on Boot:**
- **Automounting USB**: Set up the Raspberry Pi to automount flash drives when plugged in. Look into editing `/etc/fstab` or using the `usbmount` package.
- **Checking for MP3s**: Write Python logic that checks the mounted drives for files with `.mp3` extension. Use libraries like `os` or `pathlib` to scan directories.
3. **Copying MP3s to a Directory:**
- You can use the `shutil` library in Python to handle file copying.
- Ensure this logic only triggers when new files are found (so you dont overwrite your existing directory unnecessarily).
4. **Running the Database Generator:**
- Since you only want the database generator to run when needed, you can add a condition to check whether the MP3s were updated. For example, store a checksum or file modification time, and if there's a change, trigger the generator.
5. **Running the Flask Web Server:**
- After copying the files and running the database generator (if needed), the script should launch your Flask web server.
- Flask can be run as part of your startup service as well, once the other tasks are complete.
### Suggested Order of Operations
- On boot, run your startup script.
- Check for connected USB drives.
- If MP3s are found, copy them to the designated folder.
- Run the database generator only if new files are detected.
- Launch the Flask web server.
### Things to Consider:
- **Timing**: If theres a delay for the USB drive to mount, you might want to add a short wait period or a retry loop when checking for the flash drive.
- **Combining Files**: You can combine the MP3-checking, copying, and database generation logic into a single Python script. Then, it can conditionally call the database generator only when new files are added, before starting the Flask server.
# Raspberry Pi Image
To create a distributable Raspberry Pi image of your project, here's how you can go about it:
### Steps to Create a Distributable Image
1. **Set Up and Configure Your Raspberry Pi:**
- Start with a clean installation of **Raspberry Pi OS (32-bit)** since you're testing on 32-bit devices.
- Install and configure your jukebox project (ensure everything works correctly on the hardware).
- Set up any additional packages or dependencies that your project needs.
2. **Make Your Application Auto-Start:**
- Ensure your application (including the USB drive detection, MP3 copying, database generation, and Flask server) starts automatically on boot using `systemd` or another method like `cron` or `/etc/rc.local`.
- Test this setup by rebooting the Pi and checking if your application behaves as expected.
3. **Install Any Required Packages:**
- Install any third-party libraries or software required by your Python scripts (e.g., Flask, `shutil`, `usbmount`).
- Use a `requirements.txt` file (if using Pythons `pip`) to track the dependencies.
4. **Prepare the Image for Distribution:**
- Remove unnecessary files or software to make the image smaller and more efficient.
- Make sure all scripts, services, and permissions are set up properly for non-root users if required.
- Disable any development tools or services that shouldn't be included in the final image.
5. **Create a Backup of Your Raspberry Pi SD Card:**
- **Shutdown the Pi** after everything is set up and working.
- Remove the SD card and connect it to your PC or Mac using an SD card reader.
- Use a tool like `Raspberry Pi Imager`, `Win32DiskImager` (on Windows), or `dd` (on Linux/Mac) to create a backup of your SD card. This will allow you to create an image file (`.img`).
6. **Compress the Image:**
- Since SD card images can be large, compress the `.img` file using a tool like `gzip` or `7zip`. This will make it easier to distribute.
7. **Test the Image:**
- Flash the `.img` file back onto a new SD card and test it on another Raspberry Pi to ensure it boots up and runs your application properly without requiring additional configuration.
8. **Distribute the Image:**
- Once the image works as expected, you can distribute it by uploading it to a platform like Google Drive or Dropbox, where others can download it and flash it onto their Raspberry Pis.
### Things to Keep in Mind:
- **Image Size**: If your image is too large, users might need SD cards with more capacity. Trim down unnecessary files to reduce the size.
- **Updates**: Consider how users will receive future updates. You could include a mechanism in your app to check for updates or distribute new versions of the image as needed.
This should give you a distributable image that can be easily flashed and run on other Raspberry Pi devices!

View file

@ -10,24 +10,33 @@ The main advantage compared to doing something similar using Spotify is that you
### Client Setup: ### 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. 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. * 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: ### 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 \ **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/ sound/
databaseGenerator.py databaseGenerator.py
webbyBits.py webbyBits.py
.env
``` ```
1. Place mp3 files in the `sound/` folder 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*) 2. Rename `example.env` to `.env` and...
3. Run `databaseGenerator.py` - Set the location where your audio files are (Default: `./sound/`)
* *The `databaseGenerator.py` will index all mp3 files, and save the information to `songDatabase.json`* - 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* * *If getting images, this process may take a long time with a large amount of mp3 files*
4. Run `webbyBits.py` 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. \ 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* \ *Make sure you have turned down/off any other apps that might make noise or notification sounds* \
@ -36,32 +45,34 @@ Read on for specific information on each piece of the app.
## Details ## Details
These are specific details on each section of the app, and how to use them These are specific details on each section of the app, and how to use them
### Server: ### Server:
- `sound/` contains all mp3 files - `sound/` contains all mp3 files by default
- `databaseGenerator.py` scans through mp3 files and gets information about them - `databaseGenerator.py` scans through mp3 files and gets information about them
- `Filename, Title, Artist, Art, Length` are all saved - `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` *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 - Art is retrieved from LastFM
- Running with `--mode (update/new)` either updates the current database and only adds new songs, or recreates the entire database (update is default) - 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) - 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* - *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 - Directory to index for music files can be set in the `.env` file
- If this is set to an empty string (Default) the app runs in non-art mode - `songDatabase.db` stores all the information about each song in a SQLite database with tables `songs` and `meta`
- `songDatabase.json` stores all the information about each song in this format:
```
[
{
"file": "The Search_NF.mp3",
"title": "The Search",
"artist": "NF",
"art": "https://lastfm.freetls.fastly.net/i/u/64s/03125956378d531a44e1b7da89aae795.png",
"length": 292
}
]
```
- `webbyBits.py` imports the database, runs all music playing, and accepts all commands from clients - `webbyBits.py` imports the database, runs all music playing, and accepts all commands from clients
- Searches return matching songs - Searches return matching songs
- Accepts Play-Pause and Skip commands - Accepts Play-Pause and Skip commands
- Uses port 19054 by default - Uses port 19054 by default
- 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: ### Client:
![image](./Screenshot_MAIN.png) \ ![image](./Screenshot_MAIN.png) \
@ -70,10 +81,30 @@ From left to right:
- The currently playing song is identified, and has the duration listed - The currently playing song is identified, and has the duration listed
- The play-pause button toggles playing - The play-pause button toggles playing
- The skip button goes to the next track - 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 search button opens the search screen (pictured)
- The settings button (top right) opens the settings menu - 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 - 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) - 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 - 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 - 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* - *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
### 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.*

View file

@ -1,16 +1,25 @@
blinker==1.8.2 bidict==0.23.1
certifi==2024.2.2 blinker==1.9.0
charset-normalizer==3.3.2 certifi==2026.1.4
click==8.1.7 charset-normalizer==3.4.4
click==8.3.1
colorama==0.4.6 colorama==0.4.6
Flask==3.0.3 dotenv==0.9.9
Flask-Cors==4.0.1 Flask==3.1.2
idna==3.7 flask-cors==6.0.2
Flask-SocketIO==5.6.0
h11==0.16.0
idna==3.11
itsdangerous==2.2.0 itsdangerous==2.2.0
Jinja2==3.1.4 Jinja2==3.1.6
MarkupSafe==2.1.5 MarkupSafe==3.0.3
mutagen==1.47.0 mutagen==1.47.0
python-vlc==3.0.20123 python-dotenv==1.2.1
requests==2.32.2 python-engineio==4.13.1
urllib3==2.2.1 python-socketio==5.16.1
Werkzeug==3.0.3 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

35
wishlist.md Normal file
View file

@ -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)