From 49efa7dac12e6c281f0fab59107dc3bbbda5773b Mon Sep 17 00:00:00 2001
From: IrosTheBeggar
Date: Sun, 29 Jan 2017 21:38:02 -0500
Subject: [PATCH] Code Cleanup
---
modules/jukebox.js | 94 +++++----
public/img/x.svg | 3 +
public/js/{ => lib}/aurora.js | 0
public/js/{ => lib}/cookie.js | 0
public/js/{ => lib}/flac.js | 0
public/js/{ => lib}/howler.core.min.js | 0
public/js/{ => lib}/vue-sortable.js | 0
public/js/mstream.api.js | 223 ++++++++++++++++++++-
public/js/mstream.js | 260 +++++++++++++------------
public/mstream.html | 11 +-
10 files changed, 418 insertions(+), 173 deletions(-)
create mode 100644 public/img/x.svg
rename public/js/{ => lib}/aurora.js (100%)
rename public/js/{ => lib}/cookie.js (100%)
mode change 100755 => 100644
rename public/js/{ => lib}/flac.js (100%)
rename public/js/{ => lib}/howler.core.min.js (100%)
rename public/js/{ => lib}/vue-sortable.js (100%)
diff --git a/modules/jukebox.js b/modules/jukebox.js
index 6e908c1..95f8373 100644
--- a/modules/jukebox.js
+++ b/modules/jukebox.js
@@ -1,16 +1,15 @@
-// TODO: Properly integrate this
-//https://gist.github.com/martinsik/2031681
-
// Websocket Server
const WebSocketServer = require('ws').Server;
-
// list of currently connected clients (users)
var clients = { };
+// TODO: Any code in here will be limitted in functionality
+var guests = { };
exports.setup = function(mstream, server, program){
+
const wss = new WebSocketServer({ server: server });
// This callback function is called every time someone
// tries to connect to the WebSocket server
@@ -18,77 +17,98 @@ exports.setup = function(mstream, server, program){
// accept connection - you should check 'request.origin' to make sure that
// client is connecting from your website
- // var connection = request.accept(null, request.origin);
console.log((new Date()) + ' Connection accepted.');
// Generate code and assure it doesn't exist
- var code;
- var n = 0;
- while (true) {
- code = Math.floor(Math.random()*90000) + 10000;
- if(!(code in clients)){
- break;
- }
- if(n === 10){
- console.log('Failed to create ID for jukebox.');
- // FIXME: Close connection
- return;
- }
- n++;
+ var code = createAccountNumber(10000);
+ var guestcode = createAccountNumber(10000);
+
+
+ // Handle code failures
+ if(code === false || guestcode === false){
+ connection.send(JSON.stringify( { error: 'Failed To Create Instance'} ));
+ return;
}
- // Send Code
- connection.send(JSON.stringify( { code: code} ));
+
+
// Add code to clients object
clients[code] = connection;
+ // Connect guest code to standard code
+ guests[guestcode] = code;
+
+
+ // Send Code
+ connection.send(JSON.stringify( { code: code, guestCode: guestcode} ));
// user sent some message
connection.on('message', function(message) {
- if (message.type === 'utf8') { // accept only text
- // Send client code back
- connection.send(JSON.stringify( { code: code} ));
-
- // FIXME: Will need some work to add more commands
- }
+ // Send client code back
+ connection.send(JSON.stringify( { code: code, guestCode: guestcode} ));
});
// user disconnected
connection.on('close', function(connection) {
+
// Remove client from array
+ delete guests[guestcode];
delete clients[code];
});
+
});
+ // Function for creating account numbers
+ function createAccountNumber(limit = 100000){
+ // TODO: Check that limit is reasonably sized integer
+
+ var n = 0;
+ while (true) {
+ code = Math.floor(Math.random() * (limit * 9)) + limit;
+ if(!(code in clients) && !(code in guests)){
+ break;
+ }
+ if(n === 10){
+ console.log('Failed to create ID for jukebox.');
+ // FIXME: Try again with a larger number size
+ return false;
+ }
+ n++;
+ }
+
+ return code;
+ }
+
// TODO: Get Album Art calls
mstream.post( '/push-to-client', function(req, res){
// Get client id
- console.log(req.body.json);
const json = JSON.parse(req.body.json);
- console.log(json);
- console.log(json.code);
- console.log(json.command);
-
// Check if client ID exists
- const clientCode = json.code;
+ var clientCode = json.code;
const command = json.command;
- console.log(clientCode);
- console.log(clientCode);
- console.log(clientCode);
- console.log(command);
- if(!(clientCode in clients)){
+ //
+ if(!(clientCode in clients) && !(clientCode in guests)){
res.status(500).json({ error: 'Client code not found' });
+ return;
}
// TODO: Check if command logic makes sense
+
+ if(clientCode in guests){
+ // TODO: Check that command does not vioalt guest conditions
+
+ clientCode = guests[clientCode];
+ }
+
+
// Push commands to client
clients[clientCode].send(JSON.stringify({command:command}));
diff --git a/public/img/x.svg b/public/img/x.svg
new file mode 100644
index 0000000..29e90e9
--- /dev/null
+++ b/public/img/x.svg
@@ -0,0 +1,3 @@
+
+
+
\ No newline at end of file
diff --git a/public/js/aurora.js b/public/js/lib/aurora.js
similarity index 100%
rename from public/js/aurora.js
rename to public/js/lib/aurora.js
diff --git a/public/js/cookie.js b/public/js/lib/cookie.js
old mode 100755
new mode 100644
similarity index 100%
rename from public/js/cookie.js
rename to public/js/lib/cookie.js
diff --git a/public/js/flac.js b/public/js/lib/flac.js
similarity index 100%
rename from public/js/flac.js
rename to public/js/lib/flac.js
diff --git a/public/js/howler.core.min.js b/public/js/lib/howler.core.min.js
similarity index 100%
rename from public/js/howler.core.min.js
rename to public/js/lib/howler.core.min.js
diff --git a/public/js/vue-sortable.js b/public/js/lib/vue-sortable.js
similarity index 100%
rename from public/js/vue-sortable.js
rename to public/js/lib/vue-sortable.js
diff --git a/public/js/mstream.api.js b/public/js/mstream.api.js
index 482dd69..434b74a 100644
--- a/public/js/mstream.api.js
+++ b/public/js/mstream.api.js
@@ -6,20 +6,226 @@ var MSTREAMAPI = (function () {
mstreamModule.currentServer = {
host:"",
username:"",
- password:"",
+ password:"", // TODO: Don't include this?
+ token: false,
}
+
+
+
+ var dataList = [];
+
+ // dataItem = {
+ // type: '',
+ // data:'',
+ //
+ //}
+
+
+
+
+
+ var fileExplorerArray = {
+ // This goes by the following pattern
+ // path-segemnt: scroll pos
+
+ // music: 70
+ // folder: 20
+ // ACDC: 0
+ // Greatest Hits: 0
+ };
+
+ function getDirectoryContents(filepath){
+ // Construct the directory string
+ var directoryString = "";
+ for (var i = 0; i < fileExplorerArray.length; i++) {
+ directoryString += fileExplorerArray[i] + "/";
+ }
+
+ // If the scraper option is checked, then tell dirparer to use getID3
+ $.post('dirparser', {dir: directoryString, filetypes: filetypes}, function(response) {
+ clearDatalist();
+
+ var parsedResponse = $.parseJSON(dir);
+ var path = parsedResponse.path;
+
+ $.each(parsedResponse.contents, function() {
+
+ dataList.push(
+ {
+ type: this.type,
+ path: path + this.name,
+ artist: false, // TODO:
+ title: false // TODO:
+ }
+ );
+
+ });
+ });
+ }
+
+
+
+
+
+ // TODO Move this to a secondary module that's initiated when it's assured the MSTREAM module is looded
+ mstreamModule.savePlaylist = function(saveThis){
+ // TODO: Verify all data in saveThis
+
+ if(saveThis.length == 0){
+ return;
+ }
+
+ // Get playlist from MSTREAM
+ // var playlist = MSTREAM.whatever
+
+ // Get user entered title
+ // var title = '';
+
+
+
+ // Check for special characters
+ if(/^[a-zA-Z0-9-_ ]*$/.test(title) == false) {
+ // TODO: Warn User
+ return false;
+ }
+
+ // loop through array and add each file to the playlist
+ // $.each( playlistArray, function() {
+ // // TODO:
+ // });
+
+
+
+ $.ajax({
+ type: "POST",
+ url: "saveplaylist",
+ data: {
+ title:title,
+ stuff:saveThis // TODO: Change this on server end
+ },
+ })
+ .done(function( msg ) {
+
+ if(msg == 1){
+ // ???
+ }
+ if(msg == 0){
+ // .. ???
+ }
+
+ });
+
+ // TODO: error handeling
+ }
+
+
+
+
+ mstreamModule.getAllPlaylists = function(){
+ var request = $.ajax({
+ url: "getallplaylists",
+ type: "GET"
+ });
+
+ request.done(function( msg ) {
+ clearDatalist();
+ var parsedResponse = $.parseJSON(msg);
+
+ //parse through the json array and make an array of corresponding divs
+ var playlists = [];
+ $.each(parsedResponse, function() {
+ dataList.push(
+ {
+ type: 'playlist',
+ name: this.name
+ }
+ );
+ });
+ });
+
+ request.fail(function( jqXHR, textStatus ) {
+ // TODO:
+ });
+ }
+
+
+ // TODO: Can thie be cahnged to a reset of the variable
+ function clearDatalist(){
+ while(dataList.length > 0){
+ dataList.pop();
+ }
+ }
+
+
+
+
+
+ mstreamModule.deletePlaylist = function(playlistNameString){
+ // Send to server
+ var request = $.ajax({
+ url: "deleteplaylist",
+ type: "GET",
+ data: {playlistname: playlistNameString}
+ });
+
+ request.done(function( msg ) {
+ // TODO: Update datalist
+ });
+
+ request.fail(function( jqXHR, textStatus ) {
+ // TODO:
+ });
+ }
+
+
+
+
+
+
+ mstreamModule.getPlaylistContents = function(playlistNameString){
+
+ // Make an AJAX call to get the contents of the playlist
+ $.ajax({
+ type: "GET",
+ url: "loadplaylist",
+ data: {playlistname: playlistNameString},
+ dataType: 'json',
+ })
+ .done(function( msg ) {
+ // Add the playlist name to the modal
+
+ // Clear the playlist
+
+ // Append the playlist items to the playlist
+ $.each( msg, function(i ,item) {
+
+ });
+ });
+ }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
mstreamModule.getSharedPlaylist = function(){
// Get the URL parameters
console.log(window.location.pathname);
- console.log(window.location.pathname);
- console.log(window.location.pathname);
- console.log(window.location.pathname);
- console.log(window.location.pathname);
- console.log(window.location.pathname);
- console.log(window.location.pathname);
-
+
// Call the api with the the short token
@@ -27,6 +233,7 @@ var MSTREAMAPI = (function () {
}
+
// Return an object that is assigned to Module
return mstreamModule;
}());
diff --git a/public/js/mstream.js b/public/js/mstream.js
index 8cbfb43..7bb2e73 100755
--- a/public/js/mstream.js
+++ b/public/js/mstream.js
@@ -1,35 +1,123 @@
$(document).ready(function(){
+ // jukebox global variable
+ var jukebox = {
+ connection: false,
+ live: false,
+ guestCode: false,
+ adminCode: false,
+ error: false,
+ accessAddress: false
+ };
+
+
+ // The jukebox panel
+ $('#jukebox_mode').on('click', function(){
+ // Hide the directory bar
+ $('.directoryTitle').hide();
+ // Change the panel name
+ $('.panel_one_name').html('Jukebox Mode');
+ // clear the list
+ $('#filelist').empty();
+ $('#filelist').removeClass('scrollBoxHeight1');
+ $('#filelist').removeClass('scrollBoxHeight2');
+ $('#filelist').addClass('scrollBoxHeight2');
+
+ // TODO: Check if connection has been established
+ // setup correct html
+ var newHtml = '';
+ if(jukebox.live !== false && jukebox.connection !== false){
+ newHtml = createJukeboxPanel();
+
+ }else{
+ newHtml = '\
+ \
+ Jukebox Mode will allow you to control this page of mStream remotely \
+ Click the button to enable Jukebox Mode \
+
CONNECT IT!
\
+
';
+ }
+
+ // Add the content
+ $('#filelist').html(newHtml);
+
+ });
+
+
+ // Build the database
+ $('body').on('click', '.jukebox_connect', function(){
+ $(this).prop("disabled", true);
+ createWebsocket();
+
+ // Wait a while and display the status
+ setTimeout(function(){
+ // TODO: Check that status has changed
+
+ createJukeboxPanel();
+ },800);
+
+ });
+
+
+ function createJukeboxPanel(){
+ var returnHtml = '';
+
+ if(jukebox.error !== false){
+ // TODO: WARN THE USE
+ returnHtml = '';
+ return returnHtml;
+ }
+
+ if(jukebox.adminCode){
+ returnHtml += '
Code: ' + jukebox.adminCode + '
';
+ }
+
+ if(jukebox.guestCode){
+ returnHtml += 'Guest Code: ' + jukebox.guestCode + '
\
+ Hide Admin Code / Lock
';
+ }else{
+ returnHtml += ' Create Guest Account
';
+ }
+
+ returnHtml += '';
+ return returnHtml;
+ }
-
-
-
-
+ function createWebsocket(){
+ if(jukebox.live ===true ){
+ return false;
+ }
+ jukebox.live = true;
// if user is running mozilla then use it's built-in WebSocket
window.WebSocket = window.WebSocket || window.MozWebSocket;
// if browser doesn't support WebSocket, just show some notification and exit
if (!window.WebSocket) {
- console.log('No Websocket Support!');
+ // TODO: Make a better warning
+ console.log('No Websocket Support!');
return;
}
- // open connection
- var connection = new WebSocket('ws://localhost:3031');
+ // TODO: Check if websocket has already been created
- connection.onopen = function () {
- console.log('CONNECTION OPENNED');
+ // TODO: Get proper url
+ // open connection
+ jukebox.connection = new WebSocket('ws://localhost:3031');
+
+ jukebox.connection.onopen = function () {
+ console.log('CONNECTION OPENNED');
};
- connection.onerror = function (error) {
- console.log('CONNECTION ERROR!!!!!!!!!!!!');
+ jukebox.connection.onerror = function (error) {
+ // TODO: Error Code
+ console.log('CONNECTION ERROR!!!!!!!!!!!!');
};
// most important part - incoming messages
- connection.onmessage = function (message) {
+ jukebox.connection.onmessage = function (message) {
// try to parse JSON message. Because we know that the server always returns
// JSON this should work without any problem but we should make sure that
// the massage is not chunked or otherwise damaged.
@@ -40,12 +128,39 @@ $(document).ready(function(){
return;
}
- console.log(json);
+ // TODO: Handle Code
+ console.log(json.code);
+ if(json.code){
+ jukebox.adminCode = json.code;
+ console.log(jukebox.adminCode);
+ }
+
+ if(json.guestCode){
+ jukebox.guestCode = json.guestCode;
+ }
+
+
+ console.log(json);
if( json.command && json.command.action && json.command.action === 'next'){
console.log('NEXTTTTTTTTTTTTTTTTTTTTTT')
MSTREAM.nextSong();
}
};
+ }
+
+
+ $('body').on('click', '.jukebox_create_guest', function(){
+ console.log('SEND GUEST');
+ jukebox.connection.send( JSON.stringify( {action:'create-guest'}) );
+ });
+
+ function sendMessage(message){
+ jukebox.connection.send(JSON.stringify(message));
+ }
+
+
+
+
@@ -201,49 +316,8 @@ $(document).ready(function(){
// Adds file to the now playing playlist
// There is no longer addfile1
function addFile2(that){
- // var filename = $(that).attr("id");
- // var file_location = $(that).data("file_location");
- // if(accessKey){
- // file_location += '?token=' + accessKey;
- // }
- // var filetype = $(that).data("filetype");
- //
- // var title = $(that).find('span.title').html();
- //
- // // The current var gets added to the class of the new playlist item
- // var current = '';
- //
- // // this checks if jplayer is playing something
- // // console.log($("#jquery_jplayer_1").data().jPlayer.status.paused);
- //
- // // if the playlist is empty and no media is currently playing
- // //if ($('#playlist li').length == 0 && $("#jquery_jplayer_1").data().jPlayer.status.paused == true){
- // if ($('#playlist li').length == 0 ){ // TODO:
- //
- // // Set this playlist item as the current one and que it in jplayer
- // current = ' current';
- // jPlayerSetMedia(file_location, filetype);
- // // $('#jquery_jplayer_1').jPlayer("play");
- // }
- //
- // // Add html to the end of the playlist
- // $('ul#playlist').append(
- // $(' ', {
- // 'data-filetype': filetype,
- // 'data-songurl': file_location,
- // 'class': 'dragable' + current,
- // html: ''+title+' X '
- // })
- // );
- //
- // $('#playlist').sortable();
-
var file_location = $(that).data("file_location");
-
- console.log(file_location)
MSTREAM.addSong(file_location);
-
-
}
@@ -444,7 +518,6 @@ $('#search-explorer').on('click', function(){
if(!$('#search_folders').hasClass('hide')){
$( "#search_folders" ).focus();
-
}
});
@@ -501,15 +574,14 @@ $('#search-explorer').on('click', function(){
$('#save_playlist').prop("disabled",false);
$('#close_save_playlist').trigger("click");
});
- // TODO: error handeling
+ // TODO: error handeling
});
// Get all playlists
$('.get_all_playlists').on('click', function(){
-
// Hide the directory bar
$('.directoryTitle').hide();
// Change the panel name
@@ -523,8 +595,6 @@ $('#search-explorer').on('click', function(){
fileExplorerScrollPosition = [];
-
-
var request = $.ajax({
url: "getallplaylists",
type: "GET"
@@ -540,47 +610,9 @@ $('#search-explorer').on('click', function(){
playlists.push(''+this.name+' x
');
});
- // Ad playlists to the left panel
+ // Add playlists to the left panel
$('#filelist').html(playlists);
-
- });
-
- request.fail(function( jqXHR, textStatus ) {
- // alert( "Request failed: " + textStatus );
-
- $('#filelist').html('Something went wrong
');
- });
-
- });
-
-
-$("#filelist").on('click', '.deletePlaylist', function(){
- // Get Playlist ID
- var playlistname = $(this).data('playlistname');
-
-
- // Send to server
- var request = $.ajax({
- url: "deleteplaylist",
- type: "GET",
- data: {playlistname: playlistname}
- });
-
- request.done(function( msg ) {
-
- });
-
- request.fail(function( jqXHR, textStatus ) {
- // TODO:
- });
-
- $(this).parent().remove();
-
-});
-
-
-// load up a playlist
-$("#filelist").on('click', '.playlistz', function() {
+ }); 'click', '.playlistz', function() {
var playlistname = $(this).data('playlistname');
var name = $(this).html();
@@ -770,9 +802,8 @@ $("#filelist").on('click', '.playlistz', function() {
});
request.done(function( msg ) {
- console.log(msg);
+
var parsedAlbums = $.parseJSON(msg);
- // console.log(dirty);
//clear the list
$('#filelist').empty();
@@ -816,7 +847,7 @@ $("#filelist").on('click', '.playlistz', function() {
//parse through the json array and make an array of corresponding divs
var filelist = [];
$.each(parsedMessage, function() {
- console.log(this);
+
if(this.title==null){
filelist.push('♬ '+this.filename+'
');
}
@@ -857,9 +888,7 @@ $("#filelist").on('click', '.playlistz', function() {
});
request.done(function( msg ) {
- console.log(msg);
var parsedArtists = $.parseJSON(msg);
- // console.log(dirty);
//clear the list
$('#filelist').empty();
@@ -882,14 +911,9 @@ $("#filelist").on('click', '.playlistz', function() {
});
$("#filelist").on('click', '.artistz', function() {
-
var artist = $(this).data('artist');
fileExplorerScrollPosition = [];
-
-
- // $('.directoryTitle').hide();
-
var request = $.ajax({
url: "db/artists-albums",
type: "POST",
@@ -899,21 +923,16 @@ $("#filelist").on('click', '.playlistz', function() {
request.done(function( msg ) {
var parsedMessage = $.parseJSON(msg);
-
//clear the list
$('#filelist').empty();
-
var albums = [];
$.each(parsedMessage.albums, function(index, value) {
albums.push(''+value+'
');
});
-
$('#filelist').html(albums);
$('.panel_one_name').html('Artists->Albums');
-
-
});
request.fail(function( jqXHR, textStatus ) {
@@ -952,34 +971,29 @@ $("#filelist").on('click', '.playlistz', function() {
request.done(function( msg ) {
var parsedMessage = $.parseJSON(msg);
-
var htmlString = '';
if(parsedMessage.artists.length > 0){
htmlString += 'Artists ';
$.each(parsedMessage.artists, function(index, value) {
- htmlString += ''+value+'
';
- });
+ htmlString += ''+value+'
';
+ });
}
if(parsedMessage.albums.length > 0){
htmlString += 'Albums ';
$.each(parsedMessage.albums, function(index, value) {
- htmlString += ''+value+'
';
- });
+ htmlString += ''+value+'
';
+ });
}
$('#filelist').html(htmlString);
-
-
});
request.fail(function( jqXHR, textStatus ) {
$('#filelist').html("Search Failed. Your database may not be setup
");
-
});
}
});
-
});
diff --git a/public/mstream.html b/public/mstream.html
index a675d36..31d4896 100755
--- a/public/mstream.html
+++ b/public/mstream.html
@@ -27,7 +27,7 @@
-
+
@@ -37,7 +37,7 @@
-
+
@@ -46,9 +46,9 @@
DO NOT Change to order these are loaded in
You do not need to worry about how these work
-->
-
-
-
+
+
+
@@ -155,6 +155,7 @@
Database
Search
+ Jukebox