From b02fc7b6072c7b070043caaa377a4511ab3c41fa Mon Sep 17 00:00:00 2001 From: Gabriel Augendre Date: Sat, 7 May 2016 18:54:05 +0200 Subject: [PATCH] Refactor server-side code for clarity --- src/server.js | 51 ++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 46 insertions(+), 5 deletions(-) diff --git a/src/server.js b/src/server.js index 4eb5c3d..1d5287f 100644 --- a/src/server.js +++ b/src/server.js @@ -12,6 +12,7 @@ * https://developer.spotify.com/web-api/authorization-guide/#authorization_code_flow */ +'use strict'; var express = require('express'); // Express web server framework var request = require('request'); // "Request" library var querystring = require('querystring'); @@ -44,7 +45,7 @@ var stateKey = 'spotify_auth_state'; var app = express(); if (environment == 'prod' || environment == 'production') { - app.use(enforce.HTTPS({ trustProtoHeader: true })); + app.use(enforce.HTTPS({trustProtoHeader: true})); } app.use(express.static(__dirname + '/public')) @@ -189,10 +190,7 @@ app.get('/pl/:uId/:plId', function (req, res) { var i = index + 1; while (i < array.length) { var other = array[i]; - if (item.track.id == other.track.id) { - dups.push(item); - } - else if (item.track.name.toLowerCase() == other.track.name.toLowerCase() && item.track.artists[0].id == other.track.artists[0].id) { + if (areDups(item.track, other.track)) { dups.push(item); } i++; @@ -206,6 +204,49 @@ app.get('/pl/:uId/:plId', function (req, res) { }); }); +/** + * @typedef {Object} track + * @property {number} id + * @property {string} name + * @property {[artist]} artists + */ + +/** + * @typedef {Object} artist + * @property {number} id + * @property {string} name + */ + +/** + * Check if two tracks are duplicates + * @param {track} track1 + * @param {track} track2 + * @return {boolean} True if the two are duplicates. False otherwise + */ +function areDups(track1, track2) { + var name1 = track1.name.toLowerCase(); + var name2 = track2.name.toLowerCase(); + if (track1.id == track2.id) { + return true; + } + else if (haveCommonArtist(track1, track2)) { + if (name1 == name2) { + return true; + } + } + return false; +} + +/** + * Check if two tracks have at least one artist in common based on artist id. + * @param {track} track1 + * @param {track} track2 + * @return {boolean} True if they have at least one artist in common. False otherwise. + */ +function haveCommonArtist(track1, track2) { + return track1.artists[0].id == track2.artists[0].id; +} + function getAllPages(authOptions, data, callback) { request.get(authOptions, function (error, response, body) { if (!error && response.statusCode === 200) {