Merge pull request #1 from PhilippeGeek/master

Works with Angular.js is better
This commit is contained in:
Gabriel Augendre 2016-04-17 23:37:50 +02:00
commit e42a630bdd
7 changed files with 200 additions and 241 deletions

11
app.js
View file

@ -91,16 +91,9 @@ app.get('/callback', function (req, res) {
refresh_token = body.refresh_token; refresh_token = body.refresh_token;
// we can also pass the token to the browser to make requests from there // we can also pass the token to the browser to make requests from there
res.redirect('/#' + res.send('<script>window.token = { access_token: "'+access_token+'", refresh_token: "'+refresh_token+'" };</script>')
querystring.stringify({
access_token: access_token,
refresh_token: refresh_token
}));
} else { } else {
res.redirect('/#' + res.send('<script>window.token = { access_token: "", refresh_token: "" };</script>')
querystring.stringify({
error: 'invalid_token'
}));
} }
}); });
} }

View file

@ -1,76 +1,47 @@
<!doctype html> <!doctype html>
<html> <html ng-app="app">
<head> <head>
<title>Spotify Duplicate Finder</title> <title>Spotify Duplicate Finder</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css"> <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/font-awesome/3.0.2/css/font-awesome.css"> <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/font-awesome/3.0.2/css/font-awesome.css">
<link rel="stylesheet" href="./style.css"> <link rel="stylesheet" href="./style.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
</head> </head>
<body> <body>
<div class="container"> <nav class="navbar navbar-default navbar-static-top" role="navigation">
<h1>Duplicates finder <div class="container-fluid">
<button class="btn btn-default has-spinner" id="obtain-new-token"> <!-- Brand and toggle get grouped for better mobile display -->
Refresh token <span class="spinner"><i class="icon-spin icon-refresh"></i></span> <div class="navbar-header">
</button> <a class="navbar-brand" href="#">DuplicateFinder</a>
<span id="login">
<a href="/login" class="btn btn-lg btn-success">Log in with Spotify</a>
</span>
</h1>
<div id="error"></div>
<div id="loggedin">
<div id="user-profile">
</div> </div>
<div class="media"> <!-- Collect the nav links, forms, and other content for toggling -->
<div class="pull-left"> <div>
<h2 id="playlists-title">Playlists <ul class="nav navbar-nav">
<button class="btn btn-default has-spinner" id="get-playlists"> <li class="active"><a href="#">Finder</a></li>
Refresh <span class="spinner"><i class="icon-spin icon-refresh"></i></span> </ul>
</button> <ul class="nav navbar-nav navbar-right" ng-controller="AuthCtrl">
</h2> <li ng-if="access_token == ''">
<div id="playlists"> <a ng-click="login()" href="#"><b>Login With Spotify</b></a>
</div> </li>
</div> <li ng-if="access_token != ''">
<div class="media-body"> <a ng-click="refresh()" href="#">Refresh my token</a>
<div id="dups"> </li>
</div> <li ng-if="access_token != ''">
</div> <a ng-click="logout()" href="#"><b>Logout</b></a>
</div> </li>
</div> </ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<div class="container">
<ui-view></ui-view>
</div> </div>
<script id="playlists-template" type="text/x-handlebars-template"> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.4/angular.js"></script>
{{#list playlists}} <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.18/angular-ui-router.js"></script>
<a class="pl_item list-group-item has-spinner" href="/pl/{{pl_uid}}/{{pl_id}}"> <script src="https://cdnjs.cloudflare.com/ajax/libs/ngStorage/0.3.6/ngStorage.min.js"></script>
{{pl_name}}
<span class="spinner"><i class="icon-spin icon-refresh"></i></span>
<i class="glyphicon glyphicon-chevron-right"></i>
</a>
{{/list}}
</script>
<script id="user-profile-template" type="text/x-handlebars-template">
Logged in as {{display_name}}
</script>
<script id="dups-template" type="text/x-handlebars-template">
<h2>Duplicates in {{pl_name}}</h2>
{{message}}
{{#list dups}}
<div class="list-group-item">{{dup_trackname}} - {{dup_artist}}</div>
{{/list}}
</script>
<script id="error-template" type="text/x-handlebars-template">
<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span
aria-hidden="true">&times;</span></button>
<strong>{{err_title}}</strong> {{{err_content}}}.
</div>
</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0-alpha.1/handlebars.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script> <script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"
integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS"

View file

@ -0,0 +1,8 @@
<h2>Duplicates in {{playlistName}}</h2>
<div ng-if="loaded == false">Loading...</div>
<div ng-if="tracks.length == 0 && loaded">No duplicate found</div>
<div ng-if="tracks.length > 0 && loaded">
<div class="list-group-item" ng-repeat="t in tracks">
{{t.track.name}} - <span ng-repeat="artist in t.track.artists">{{artist == t.track.artists[0]?'':', '}}{{artist.name}}</span>
</div>
</div>

View file

@ -0,0 +1 @@
<p>Please connect to Spotify to access to the app.</p>

View file

@ -0,0 +1,4 @@
<div class="container row">
<div class="col-md-3"><ui-view name="playlist"></ui-view></div>
<div class="col-md-9"><ui-view name="dups"></ui-view></div>
</div>

View file

@ -0,0 +1,8 @@
<div class="clearfix">
<h2 class="pull-left">Playlist</h2>
</div>
<div class="list-group ">
<a ng-class="current.playlistId == playlist.id?'list-group-item active':'list-group-item'" ng-repeat="playlist in playlists" ng-click="open(playlist)">
{{playlist.name}}
</a>
</div>

View file

@ -1,182 +1,156 @@
'use strict'; 'use strict';
var access_token; (function(){
var refresh_token;
var error;
var userProfileSource = document.getElementById('user-profile-template').innerHTML, var app = angular.module('app',['ui.router', 'ngStorage']);
userProfileTemplate = Handlebars.compile(userProfileSource),
userProfilePlaceholder = document.getElementById('user-profile');
var playlistsSource = document.getElementById('playlists-template').innerHTML, app.config(['$stateProvider','$urlRouterProvider',function($stateProvider, $urlRouterProvider){
playlistsTemplate = Handlebars.compile(playlistsSource), $stateProvider
playlistsPlaceholder = document.getElementById('playlists'); .state('finder_public',{
templateUrl:'partials/home.html',
var dupsSource = document.getElementById('dups-template').innerHTML, url: '/',
dupsTemplate = Handlebars.compile(dupsSource), controller: 'HomeCtrl'
dupsPlaceholder = document.getElementById('dups');
var errorSource = document.getElementById('error-template').innerHTML,
errorTemplate = Handlebars.compile(errorSource),
errorPlaceholder = document.getElementById('error');
(function () {
/**
* Obtains parameters from the hash of the URL
* @return Object
*/
function getHashParams() {
var hashParams = {};
var e, r = /([^&;=]+)=?([^&;]*)/g,
q = window.location.hash.substring(1);
while (e = r.exec(q)) {
hashParams[e[1]] = decodeURIComponent(e[2]);
}
return hashParams;
}
Handlebars.registerHelper('list', function (items, options) {
var out = "<div class='list-group'>";
for (var i = 0, l = items.length; i < l; i++) {
out = out + options.fn(items[i]);
}
return out + "</div>";
});
var params = getHashParams();
access_token = params.access_token;
refresh_token = params.refresh_token;
error = params.error;
if (error) {
errorPlaceholder.innerHTML = errorTemplate({
err_title: 'Error!',
err_content: 'There was an error during the authentication. Feel free to <a href="https://github.com/Crocmagnon/Spotify-Duplicate-Finder/issues" class="alert-link">open an issue</a>.'
});
} else {
if (access_token) {
getPersonnalInfo(true, userProfilePlaceholder, userProfileTemplate);
} else {
// render initial screen
$('#login').show();
$('#loggedin').hide();
}
document.getElementById('get-playlists').addEventListener('click', function () {
var button = $(this);
button.addClass('loading');
$.ajax({
url: '/get_playlists',
data: {
'access_token': access_token
}
}).done(function (data) {
var pl = data.data.map(function (item) {
return {
pl_uid: item.owner.id,
pl_name: item.name,
pl_id: item.id
}
});
button.removeClass('loading');
$('#dups').hide();
playlistsPlaceholder.innerHTML = playlistsTemplate({
playlists: pl
});
}) })
}, false); .state('finder',{
abstract: true,
$(document).on('click', '.pl_item', function (e) { templateUrl:'partials/logged.html',
e.preventDefault(); url: '/finder',
var pl_name = $(this).text(); controller: 'MainCtrl'
$('.pl_item').removeClass('active');
var currentElement = $(this);
currentElement.addClass('active');
currentElement.addClass('loading');
$('#dups').hide();
$.ajax({
url: $(this).attr('href'),
data: {
'access_token': access_token
}
}).done(function (data) {
var dups = data.data.map(function (item) {
return {
dup_trackname: item.track.name,
dup_artist: item.track.artists[0].name
}
});
currentElement.removeClass('loading');
if (data.data.length > 0) {
dupsPlaceholder.innerHTML = dupsTemplate({
dups: dups,
pl_name: pl_name
});
}
else {
dupsPlaceholder.innerHTML = dupsTemplate({
dups: [],
message: "No duplicate found.",
pl_name: pl_name
});
}
$('#dups').show();
}) })
}); .state('finder.playlist',{
url: '/playlist',
$(document).on('click', '#obtain-new-token', function () { views: {
refreshToken(); playlist:{
}); templateUrl: 'partials/playlist.html',
controller: 'PlaylistCtrl'
},
dups:{
template: ''
} }
}
})
.state('finder.playlist.dups',{
url: '/:uid/:id/:playlist',
views: {
'dups@finder': {
templateUrl: 'partials/dups.html',
controller: 'DupsCtrl'
}
}
});
$urlRouterProvider.otherwise("/");
}]);
app.run(['$rootScope', '$state', '$localStorage',function($rootScope, $state, $localStorage){
$rootScope.$storage = $localStorage.$default({
access_token: "",
refresh_token: ""
});
$rootScope.access_token = $rootScope.$storage.access_token;
$rootScope.refresh_token = $rootScope.$storage.refresh_token;
$rootScope.$watch('access_token', function(newVal, oldVal, scope){
$rootScope.$storage.access_token = $rootScope.access_token;
$rootScope.$storage.refresh_token = $rootScope.refresh_token;
if(oldVal == "" && newVal != ""){
$state.go('finder.playlist');
} else if (oldVal != "" && newVal == ""){
$state.go('finder_public');
}
});
$rootScope.$on('$stateChangeStart',
function (event, toState) {
if ((toState.name != "finder_public") && $rootScope.access_token == "") {
event.preventDefault();
$state.go('finder_public');
}
});
}]);
app.controller("HomeCtrl",['$scope',function($scope){
}]);
app.controller("MainCtrl",['$scope', '$state',function($scope, $state){
$scope.current = {playlistId: undefined};
}]);
app.controller("PlaylistCtrl",['$scope', '$http', '$state',function($scope, $http, $state){
$scope.playlists = [];
$scope.load = function(){
$http.get('/get_playlists', {
params:{
access_token: $scope.access_token
}
}).then(function(result){
var r = result.data;
if(r.data){
$scope.playlists = r.data;
}
})
};
$scope.open = function(playlist) {
$scope.current.playlistId = playlist.id;
$state.go('finder.playlist.dups',{uid: playlist.owner.id, id: playlist.id, playlist: encodeURIComponent(playlist.name)})
};
$scope.load();
}]);
app.controller("DupsCtrl",['$scope', '$stateParams', '$http',function($scope, $stateParams, $http){
$scope.uid = $stateParams['uid'];
$scope.id = $stateParams['id'];
$scope.playlistName = decodeURIComponent($stateParams.playlist);
$scope.current.playlistId = $scope.id;
$scope.tracks = [];
$scope.loaded = false;
$scope.load = function () {
$http.get('/pl/' + $scope.uid + '/' + $scope.id, {
params: {
access_token: $scope.access_token
}
}).then(function(result) {
var r = result.data;
$scope.tracks = r.data;
$scope.loaded = true;
});
};
$scope.load();
}]);
app.controller('AuthCtrl',['$scope', '$rootScope', '$interval', '$http', function($scope, $rootScope, $interval, $http){
$scope.login = function(){
var openUrl = '/login';
window.$windowScope = $scope;
$scope.popup = window.open(openUrl, "Authenticate Account", "width=500, height=500");
var checker = $interval(function(){
if($scope.popup.closed){
$interval.cancel(checker);
} else if ($scope.popup.token != undefined && $scope.popup.token != null) {
$rootScope.access_token = $scope.popup.token.access_token;
$rootScope.refresh_token = $scope.popup.token.refresh_token;
$scope.popup.close();
$interval.cancel(checker);
}
}, 500);
return false;
};
$scope.logout = function(){
$rootScope.refresh_token = "";
$rootScope.access_token = "";
};
$scope.refresh = function(){
if($rootScope.refresh_token)
$http.get('/refresh_token',{params: {refresh_token: $rootScope.refresh_token}})
.then(function(result){
$rootScope.access_token = result.data.access_token || "";
}, function(failResult){
$rootScope.access_token = "";
$rootScope.refresh_token = "";
});
return false;
}
}])
})(); })();
function refreshToken() {
var button = $('#obtain-new-token');
button.addClass('loading');
$.ajax({
url: '/refresh_token',
data: {
'refresh_token': refresh_token
}
}).done(function (data) {
access_token = data.access_token;
button.removeClass('loading');
});
}
function getPersonnalInfo(first, userProfilePlaceholder, userProfileTemplate) {
$.ajax({
url: 'https://api.spotify.com/v1/me',
headers: {
'Authorization': 'Bearer ' + access_token
},
success: function (response) {
userProfilePlaceholder.innerHTML = userProfileTemplate(response);
$('#login').hide();
$('#obtain-new-token').show();
$('#loggedin').show();
},
error: function (response) {
if (response.status == 401) {
if (first) {
refreshToken();
getPersonnalInfo(false, userProfilePlaceholder, userProfileTemplate);
}
else {
errorPlaceholder.innerHTML = errorTemplate({
err_title: 'Error!',
err_content: 'Error while refreshing token. Please <a href="/" class="alert-link">return to login</a>.'
});
}
}
}
});
}