Code Cleanup

This commit is contained in:
IrosTheBeggar 2017-01-29 21:38:02 -05:00
parent cae27b37b9
commit 49efa7dac1
10 changed files with 418 additions and 173 deletions

View File

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

3
public/img/x.svg Normal file
View File

@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="52" height="52" viewBox="0 0 26 26">
<path d="M21.736,19.64l-2.098,2.096c-0.383,0.386-1.011,0.386-1.396,0l-5.241-5.239L7.76,21.735 c-0.385,0.386-1.014,0.386-1.397-0.002L4.264,19.64c-0.385-0.386-0.385-1.011,0-1.398L9.505,13l-5.24-5.24 c-0.384-0.387-0.384-1.016,0-1.398l2.098-2.097c0.384-0.388,1.013-0.388,1.397,0L13,9.506l5.242-5.241 c0.386-0.388,1.014-0.388,1.396,0l2.098,2.094c0.386,0.386,0.386,1.015,0.001,1.401L16.496,13l5.24,5.241 C22.121,18.629,22.121,19.254,21.736,19.64z"/>
</svg>

0
public/js/cookie.js → public/js/lib/cookie.js Executable file → Normal file
View File

View File

@ -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;
}());

View File

@ -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 = '\
<p class="jukebox-panel">\
Jukebox Mode will allow you to control this page of mStream remotely <br><br>\
Click the button to enable Jukebox Mode <br>\
<div class="jukebox_connect button"> CONNECT IT!</div>\
</p>';
}
// 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 = '<p class="jukebox-panel">';
if(jukebox.error !== false){
// TODO: WARN THE USE
returnHtml = '';
return returnHtml;
}
if(jukebox.adminCode){
returnHtml += '<div>Code: ' + jukebox.adminCode + '</div>';
}
if(jukebox.guestCode){
returnHtml += '<div>Guest Code: ' + jukebox.guestCode + '</div>\
<div>Hide Admin Code / Lock</div>';
}else{
returnHtml += '<div class="jukebox_create_guest button"> Create Guest Account</div>';
}
returnHtml += '</p>';
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(
// $('<li/>', {
// 'data-filetype': filetype,
// 'data-songurl': file_location,
// 'class': 'dragable' + current,
// html: '<span class="play1">'+title+'</span><a href="javascript:void(0)" class="closeit">X</a>'
// })
// );
//
// $('#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('<div data-playlistname="'+this.name+'" class="playlist_row_container"><span data-playlistname="'+this.name+'" class="playlistz force-width">'+this.name+'</span><span data-playlistname="'+this.name+'" class="deletePlaylist">x</span></div>');
});
// 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('<p>Something went wrong</p>');
});
});
$("#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('<div data-filetype="'+this.format+'" data-file_location="'+this.file_location+'" class="filez"><span class="pre-char">&#9836;</span> <span class="title">'+this.filename+'</span></div>');
}
@ -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('<div data-album="'+value+'" class="albumz">'+value+' </div>');
});
$('#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 += '<h2 class="search_subtitle"><strong>Artists</strong></h2>';
$.each(parsedMessage.artists, function(index, value) {
htmlString += '<div data-artist="'+value+'" class="artistz">'+value+' </div>';
});
htmlString += '<div data-artist="'+value+'" class="artistz">'+value+' </div>';
});
}
if(parsedMessage.albums.length > 0){
htmlString += '<h2 class="search_subtitle"><strong>Albums</strong></h2>';
$.each(parsedMessage.albums, function(index, value) {
htmlString += '<div data-album="'+value+'" class="albumz">'+value+' </div>';
});
htmlString += '<div data-album="'+value+'" class="albumz">'+value+' </div>';
});
}
$('#filelist').html(htmlString);
});
request.fail(function( jqXHR, textStatus ) {
$('#filelist').html("<p>Search Failed. Your database may not be setup</p>");
});
}
});
});

View File

@ -27,7 +27,7 @@
<script src="/public/js/modernizr.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript" src="/public/js/cookie.js"></script>
<script type="text/javascript" src="/public/js/lib/cookie.js"></script>
@ -37,7 +37,7 @@
<!-- Sortable JS -->
<script src="https://unpkg.com/sortablejs@latest"></script>
<!-- https://github.com/SortableJS/Vue.Draggable - v2.6 -->
<script src="/public/js/vue-sortable.js"></script>
<script src="/public/js/lib/vue-sortable.js"></script>
<link rel="stylesheet" media="screen" href="https://fontlibrary.org/face/8bit-wonder" type="text/css"/>
@ -46,9 +46,9 @@
DO NOT Change to order these are loaded in
You do not need to worry about how these work
-->
<script src="/public/js/aurora.js"></script>
<script src="/public/js/flac.js"></script>
<script src="/public/js/howler.core.min.js"></script>
<script src="/public/js/lib/aurora.js"></script>
<script src="/public/js/lib/flac.js"></script>
<script src="/public/js/lib/howler.core.min.js"></script>
<script src="/public/js/mstream.player.js"></script>
<script src="/public/js/mstream.api.js"></script>
@ -155,6 +155,7 @@
<li class="left-off-canvas-toggle" id="manage_database"><label>Database</label></li>
<li class="left-off-canvas-toggle" id="search_database"><label>Search</label></li>
<li class="left-off-canvas-toggle" id="jukebox_mode"><label>Jukebox</label></li>
</ul>
</aside>