Merge pull request #426 from chme/web_lastfm_newlayout

Integrate last.fm into web interface
This commit is contained in:
ejurgensen 2017-10-28 13:16:25 +02:00 committed by GitHub
commit c7016df02e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 457 additions and 163 deletions

View File

@ -68,42 +68,39 @@
<!-- <!--
############# Content section ############# ############# Status section #############
--> -->
<section class="section"> <section class="section">
<div class="container"> <div class="container">
<div class="columns"> <!-- Section-heading -->
<div class="columns is-centered fd-section-heading">
<div class="column is-10"><h1 class="is-uppercase is-size-7">Status</h1></div>
</div>
<div class="column"> <!-- Library update -->
<div class="card"> <div class="columns is-centered fd-section-content">
<header class="card-header"> <div class="column is-3">
<p class="card-header-title"> <h2 class="title is-5">
<span class="icon" v-show="library.updating"><i class="fa fa-refresh fa-spin"></i></span> <span class="icon" v-show="library.updating"><i class="fa fa-refresh fa-spin"></i>
<span class="icon" v-show="!library.updating"><i class="fa fa-refresh"></i></span> </span><span class="icon" v-show="!library.updating"><i class="fa fa-music"></i></span>
Update library Library
</p> </h2>
</header> </div>
<div class="card-content">
<div class="content"> <div class="column is-7 content">
Scan new and modified items into your library. <a class="button" v-on:click="update" v-show="!library.updating">Update library</a>
<p v-show="library.updating">Update in progress ...</p>
</div> </div>
</div> </div>
<footer class="card-footer">
<a class="card-footer-item is-primary" v-on:click="update" v-show="!library.updating">Update</a>
<span class="card-footer-item" v-show="library.updating">Update in progress ...</span>
</footer>
</div> <!-- card update library -->
</div> <!-- column -->
<!-- Pairing -->
<div class="columns is-centered fd-section-content">
<div class="column is-3">
<h2 class="title is-5"><span class="icon"><i class="fa fa-mobile"></i></span> Remote Pairing</h2>
</div>
<div class="column"> <div class="column is-7 content">
<div class="card"> <!-- Paring request active -->
<header class="card-header">
<p class="card-header-title">
<span class="icon"><i class="fa fa-mobile"></i></span> Remote pairing
</p>
</header>
<div class="card-content">
<div class="content" v-show="pairing.active"> <div class="content" v-show="pairing.active">
<p>Remote pairing request from <b>{{pairing.remote}}</b></p> <p>Remote pairing request from <b>{{pairing.remote}}</b></p>
<form v-on:submit.prevent="kickoffPairing"> <form v-on:submit.prevent="kickoffPairing">
@ -117,28 +114,40 @@
</div> </div>
</form> </form>
</div> </div>
<!-- No pairing requests -->
<div class="content" v-show="!pairing.active"> <div class="content" v-show="!pairing.active">
<p>No active pairing request.</p> <p>No active pairing request.</p>
<a class="button" v-on:click="loadPairing" v-show="!config.websocket_port">Refresh</a> <a class="button" v-on:click="loadPairing" v-show="!config.websocket_port">Refresh</a>
</div> </div>
</div> </div>
</div> <!-- card remote pairing --> </div>
</div> <!-- column -->
</div>
</section>
<div class="column"> <!--
<div class="card" v-show="spotify.enabled"> ############# Online accounts & services section #############
<header class="card-header"> -->
<p class="card-header-title"> <section class="section">
<span class="icon"><i class="fa fa-spotify"></i></span> Spotify <div class="container">
</p> <!-- Section-heading -->
</header> <div class="columns is-centered fd-section-heading">
<div class="card-content"> <div class="column is-10"><h1 class="is-uppercase is-size-7">Online accounts &amp; services</h1></div>
</div>
<!-- Spotify -->
<div class="columns is-centered fd-section-content" v-show="spotify.enabled">
<div class="column is-3">
<h2 class="title is-5"><span class="icon"><i class="fa fa-spotify"></i></span> Spotify</h2>
</div>
<div class="column is-7 content">
<div class="content" v-show="!spotify.libspotify_installed"> <div class="content" v-show="!spotify.libspotify_installed">
<p><b>libspotify</b> is not installed (required for playing spotify tracks)</p> <p><b>libspotify</b> is not installed (required for playing spotify tracks)</p>
</div> </div>
<div class="content" v-show="spotify.libspotify_installed"> <div class="content" v-show="spotify.libspotify_installed">
<div v-show="!spotify.libspotify_logged_in"><p><b>libspotify</b> (requires Spotify premium account, enables playback of Spotify songs):</p> <!-- libspotify -->
<div v-show="!spotify.libspotify_logged_in"><p><b>libspotify</b> (requires Spotify premium account, enables playback of Spotify songs)</p>
<form v-on:submit.prevent="loginLibspotify"> <form v-on:submit.prevent="loginLibspotify">
<div class="field has-addons"> <div class="field has-addons">
<div class="control"> <div class="control">
@ -157,7 +166,7 @@
</form> </form>
</div> </div>
<p v-show="spotify.libspotify_logged_in"><b>libspotify</b> (requires Spotify premium account, enables playback of Spotify songs): logged in as <b>{{ spotify.libspotify_user }}</b></p> <p v-show="spotify.libspotify_logged_in"><b>libspotify</b> (requires Spotify premium account, enables playback of Spotify songs): logged in as <b>{{ spotify.libspotify_user }}</b></p>
<hr> <!-- Spotify web api -->
<div v-show="!spotify.webapi_token_valid"> <div v-show="!spotify.webapi_token_valid">
<p><b>Spotify Web API</b> access is required to add saved albums and playlists to your library.</p> <p><b>Spotify Web API</b> access is required to add saved albums and playlists to your library.</p>
<a class="button" v-bind:href="spotify.oauth_uri">Authorize Web API access</a> <a class="button" v-bind:href="spotify.oauth_uri">Authorize Web API access</a>
@ -168,13 +177,49 @@
</div> </div>
</div> </div>
</div> </div>
</div> <!-- card spotify --> </div>
</div> <!-- column -->
</div> <!-- columns --> <!-- Last.fm -->
</div> <!-- container --> <div class="columns is-centered fd-section-content" v-show="lastfm.enabled">
<div class="column is-3">
<h2 class="title is-5"><span class="icon"><i class="fa fa-lastfm"></i></span> Last.fm</h2>
</div>
<div class="column is-7 content">
<!-- Scrobbling enabled -->
<div class="content" v-show="lastfm.scrobbling_enabled">
<a class="button" v-on:click="logoutLastfm">Stop scrobbling</a>
</div>
<!-- Scrobbling NOT enabled -->
<div class="content" v-show="!lastfm.scrobbling_enabled">
<p><b>Last.fm</b> (enable scrobbling)</p>
<form v-on:submit.prevent="loginLastfm">
<div class="field has-addons">
<div class="control">
<input class="input" type="text" placeholder="Username" v-model="lastfm_login.user">
<p class="help is-danger">{{ lastfm_login.errors.user }}</p>
</div>
<div class="control">
<input class="input" type="password" placeholder="Password" v-model="lastfm_login.password">
<p class="help is-danger">{{ lastfm_login.errors.password }}</p>
</div>
<div class="control">
<button class="button" type="submit">Login</button>
</div>
</div>
<p class="help is-danger">{{ lastfm_login.errors.error }}</p>
</form>
</div>
</div>
</div>
</div>
</section> </section>
<!--
############# Footer #############
-->
<footer class="footer"> <footer class="footer">
<div class="container"> <div class="container">
<div class="content has-text-centered"> <div class="content has-text-centered">
@ -190,7 +235,7 @@
</div> <!-- #root --> </div> <!-- #root -->
<script src="/js/vue.min.js"></script> <script src="/js/vue.js"></script>
<script src="/js/axios.min.js"></script> <script src="/js/axios.min.js"></script>
<script src="/js/forked-daapd.js"></script> <script src="/js/forked-daapd.js"></script>

View File

@ -1,3 +1,10 @@
[v-cloak] { [v-cloak] {
display: none; display: none;
} }
.fd-section-heading {
margin-bottom: 24px !important;
}
.fd-section-content + .fd-section-content {
margin-top: 24px !important;
}

View File

@ -8,7 +8,9 @@ var app = new Vue({
spotify: {}, spotify: {},
pairing: {}, pairing: {},
pairing_req: { pin: '' }, pairing_req: { pin: '' },
libspotify: { user: '', password: '', errors: { user: '', password: '', error: '' } } libspotify: { user: '', password: '', errors: { user: '', password: '', error: '' } },
lastfm: {},
lastfm_login: { user: '', password: '', errors: { user: '', password: '', error: '' } }
}, },
created: function () { created: function () {
@ -16,6 +18,7 @@ var app = new Vue({
this.loadLibrary(); this.loadLibrary();
this.loadSpotify(); this.loadSpotify();
this.loadPairing(); this.loadPairing();
this.loadLastfm();
}, },
methods: { methods: {
@ -37,6 +40,10 @@ var app = new Vue({
axios.get('/api/pairing').then(response => this.pairing = response.data); axios.get('/api/pairing').then(response => this.pairing = response.data);
}, },
loadLastfm: function() {
axios.get('/api/lastfm').then(response => this.lastfm = response.data);
},
update: function() { update: function() {
this.library.updating = true; this.library.updating = true;
axios.get('/api/update').then(console.log('Library is updating')); axios.get('/api/update').then(console.log('Library is updating'));
@ -66,6 +73,29 @@ var app = new Vue({
}); });
}, },
loginLastfm: function() {
axios.post('/api/lastfm-login', this.lastfm_login).then(response => {
this.lastfm_login.user = '';
this.lastfm_login.password = '';
this.lastfm_login.errors.user = '';
this.lastfm_login.errors.password = '';
this.lastfm_login.errors.error = '';
if (!response.data.success) {
this.lastfm_login.errors.user = response.data.errors.user;
this.lastfm_login.errors.password = response.data.errors.password;
this.lastfm_login.errors.error = response.data.errors.error;
}
});
},
logoutLastfm: function() {
axios.get('/api/lastfm-logout', this.lastfm_login).then(response => {
if (!this.config.websocket_port) {
this.loadLastfm();
}
});
},
connect: function() { connect: function() {
if (this.config.websocket_port <= 0) { if (this.config.websocket_port <= 0) {
console.log('Websocket disabled'); console.log('Websocket disabled');
@ -74,7 +104,7 @@ var app = new Vue({
var socket = new WebSocket('ws://' + document.domain + ':' + this.config.websocket_port, 'notify'); var socket = new WebSocket('ws://' + document.domain + ':' + this.config.websocket_port, 'notify');
const vm = this; const vm = this;
socket.onopen = function() { socket.onopen = function() {
socket.send(JSON.stringify({ notify: ['update', 'pairing', 'spotify']})); socket.send(JSON.stringify({ notify: ['update', 'pairing', 'spotify', 'lastfm']}));
socket.onmessage = function(response) { socket.onmessage = function(response) {
console.log(response.data); // upon message console.log(response.data); // upon message
var data = JSON.parse(response.data); var data = JSON.parse(response.data);
@ -87,6 +117,9 @@ var app = new Vue({
if (data.notify.includes('spotify')) { if (data.notify.includes('spotify')) {
vm.loadSpotify(); vm.loadSpotify();
} }
if (data.notify.includes('lastfm')) {
vm.loadLastfm();
}
}; };
}; };
} }

View File

@ -41,6 +41,9 @@
#include "conffile.h" #include "conffile.h"
#include "db.h" #include "db.h"
#include "httpd.h" #include "httpd.h"
#ifdef LASTFM
# include "lastfm.h"
#endif
#include "library.h" #include "library.h"
#include "logger.h" #include "logger.h"
#include "misc.h" #include "misc.h"
@ -416,6 +419,120 @@ jsonapi_reply_pairing(struct evhttp_request *req, struct evbuffer *evbuf, char *
return pairing_get(evbuf); return pairing_get(evbuf);
} }
static int
jsonapi_reply_lastfm(struct evhttp_request *req, struct evbuffer *evbuf, char *uri, struct evkeyvalq *query)
{
json_object *reply;
bool enabled = false;
bool scrobbling_enabled = false;
int ret;
#ifdef LASTFM
enabled = true;
scrobbling_enabled = lastfm_is_enabled();
#endif
reply = json_object_new_object();
json_object_object_add(reply, "enabled", json_object_new_boolean(enabled));
json_object_object_add(reply, "scrobbling_enabled", json_object_new_boolean(scrobbling_enabled));
ret = evbuffer_add_printf(evbuf, "%s", json_object_to_json_string(reply));
jparse_free(reply);
if (ret < 0)
{
DPRINTF(E_LOG, L_WEB, "LastFM: Couldn't add LastFM enabled to response buffer.\n");
return -1;
}
return 0;
}
/*
* Endpoint to log into LastFM
*/
static int
jsonapi_reply_lastfm_login(struct evhttp_request *req, struct evbuffer *evbuf, char *uri, struct evkeyvalq *query)
{
#ifdef LASTFM
struct evbuffer *in_evbuf;
json_object* request;
const char *user;
const char *password;
char *errmsg = NULL;
json_object* reply;
json_object* errors;
int ret;
DPRINTF(E_DBG, L_WEB, "Received LastFM login request\n");
in_evbuf = evhttp_request_get_input_buffer(req);
request = jparse_obj_from_evbuffer(in_evbuf);
if (!request)
{
DPRINTF(E_LOG, L_WEB, "Failed to parse incoming request\n");
return -1;
}
reply = json_object_new_object();
user = jparse_str_from_obj(request, "user");
password = jparse_str_from_obj(request, "password");
if (user && strlen(user) > 0 && password && strlen(password) > 0)
{
ret = lastfm_login_user(user, password, &errmsg);
if (ret < 0)
{
json_object_object_add(reply, "success", json_object_new_boolean(false));
errors = json_object_new_object();
if (errmsg)
json_object_object_add(errors, "error", json_object_new_string(errmsg));
else
json_object_object_add(errors, "error", json_object_new_string("Unknown error"));
json_object_object_add(reply, "errors", errors);
}
else
{
json_object_object_add(reply, "success", json_object_new_boolean(true));
}
free(errmsg);
}
else
{
DPRINTF(E_LOG, L_WEB, "No user or password in LastFM login post request\n");
json_object_object_add(reply, "success", json_object_new_boolean(false));
errors = json_object_new_object();
if (!user || strlen(user) == 0)
json_object_object_add(errors, "user", json_object_new_string("Username is required"));
if (!password || strlen(password) == 0)
json_object_object_add(errors, "password", json_object_new_string("Password is required"));
json_object_object_add(reply, "errors", errors);
}
ret = evbuffer_add_printf(evbuf, "%s", json_object_to_json_string(reply));
jparse_free(reply);
if (ret < 0)
{
DPRINTF(E_LOG, L_WEB, "LastFM: Couldn't add LastFM login data to response buffer.\n");
return -1;
}
#else
DPRINTF(E_LOG, L_WEB, "Received LastFM login request but was not compiled with enable-lastfm\n");
#endif
return 0;
}
static int
jsonapi_reply_lastfm_logout(struct evhttp_request *req, struct evbuffer *evbuf, char *uri, struct evkeyvalq *query)
{
#ifdef LASTFM
lastfm_logout();
#endif
return 0;
}
static struct uri_map adm_handlers[] = static struct uri_map adm_handlers[] =
{ {
{ .regexp = "^/api/config", .handler = jsonapi_reply_config }, { .regexp = "^/api/config", .handler = jsonapi_reply_config },
@ -424,6 +541,9 @@ static struct uri_map adm_handlers[] =
{ .regexp = "^/api/spotify-login", .handler = jsonapi_reply_spotify_login }, { .regexp = "^/api/spotify-login", .handler = jsonapi_reply_spotify_login },
{ .regexp = "^/api/spotify", .handler = jsonapi_reply_spotify }, { .regexp = "^/api/spotify", .handler = jsonapi_reply_spotify },
{ .regexp = "^/api/pairing", .handler = jsonapi_reply_pairing }, { .regexp = "^/api/pairing", .handler = jsonapi_reply_pairing },
{ .regexp = "^/api/lastfm-login", .handler = jsonapi_reply_lastfm_login },
{ .regexp = "^/api/lastfm-logout", .handler = jsonapi_reply_lastfm_logout },
{ .regexp = "^/api/lastfm", .handler = jsonapi_reply_lastfm },
{ .regexp = NULL, .handler = NULL } { .regexp = NULL, .handler = NULL }
}; };

View File

@ -28,6 +28,7 @@
#include <unistd.h> #include <unistd.h>
#include <time.h> #include <time.h>
#include <string.h> #include <string.h>
#include <stdbool.h>
#include <gcrypt.h> #include <gcrypt.h>
#include <mxml.h> #include <mxml.h>
@ -38,13 +39,14 @@
#include "db.h" #include "db.h"
#include "lastfm.h" #include "lastfm.h"
#include "listener.h"
#include "logger.h" #include "logger.h"
#include "misc.h" #include "misc.h"
#include "http.h" #include "http.h"
// LastFM becomes disabled if we get a scrobble, try initialising session, // LastFM becomes disabled if we get a scrobble, try initialising session,
// but can't (probably no session key in db because user does not use LastFM) // but can't (probably no session key in db because user does not use LastFM)
static int lastfm_disabled = 0; static bool lastfm_disabled = false;
/** /**
* The API key and secret (not so secret being open source) is specific to * The API key and secret (not so secret being open source) is specific to
@ -117,15 +119,15 @@ param_sign(struct keyval *kv)
/* --------------------------------- MAIN --------------------------------- */ /* --------------------------------- MAIN --------------------------------- */
static void static int
response_proces(struct http_client_ctx *ctx) response_process(struct http_client_ctx *ctx, char **errmsg)
{ {
mxml_node_t *tree; mxml_node_t *tree;
mxml_node_t *s_node; mxml_node_t *s_node;
mxml_node_t *e_node; mxml_node_t *e_node;
char *body; char *body;
char *errmsg;
char *sk; char *sk;
int ret;
// NULL-terminate the buffer // NULL-terminate the buffer
evbuffer_add(ctx->input_body, "", 1); evbuffer_add(ctx->input_body, "", 1);
@ -134,35 +136,39 @@ response_proces(struct http_client_ctx *ctx)
if (!body || (strlen(body) == 0)) if (!body || (strlen(body) == 0))
{ {
DPRINTF(E_LOG, L_LASTFM, "Empty response\n"); DPRINTF(E_LOG, L_LASTFM, "Empty response\n");
return; return -1;
} }
DPRINTF(E_SPAM, L_LASTFM, "LastFM response:\n%s\n", body);
tree = mxmlLoadString(NULL, body, MXML_OPAQUE_CALLBACK); tree = mxmlLoadString(NULL, body, MXML_OPAQUE_CALLBACK);
if (!tree) if (!tree)
return; {
DPRINTF(E_LOG, L_LASTFM, "Failed to parse LastFM response:\n%s\n", body);
return -1;
}
// Look for errors // Look for errors
e_node = mxmlFindElement(tree, tree, "error", NULL, NULL, MXML_DESCEND); e_node = mxmlFindElement(tree, tree, "error", NULL, NULL, MXML_DESCEND);
if (e_node) if (e_node)
{ {
errmsg = trimwhitespace(mxmlGetOpaque(e_node)); DPRINTF(E_LOG, L_LASTFM, "Request to LastFM failed: %s\n", mxmlGetOpaque(e_node));
DPRINTF(E_LOG, L_LASTFM, "Request to LastFM failed: %s\n", errmsg); DPRINTF(E_DBG, L_LASTFM, "LastFM response:\n%s\n", body);
if (errmsg) if (errmsg)
free(errmsg); *errmsg = trimwhitespace(mxmlGetOpaque(e_node));
mxmlDelete(tree); mxmlDelete(tree);
return; return -1;
} }
DPRINTF(E_SPAM, L_LASTFM, "LastFM response:\n%s\n", body);
// Was it a scrobble request? Then do nothing. TODO: Check for error messages // Was it a scrobble request? Then do nothing. TODO: Check for error messages
s_node = mxmlFindElement(tree, tree, "scrobbles", NULL, NULL, MXML_DESCEND); s_node = mxmlFindElement(tree, tree, "scrobbles", NULL, NULL, MXML_DESCEND);
if (s_node) if (s_node)
{ {
DPRINTF(E_DBG, L_LASTFM, "Scrobble callback\n"); DPRINTF(E_DBG, L_LASTFM, "Scrobble callback\n");
mxmlDelete(tree); mxmlDelete(tree);
return; return 0;
} }
// Otherwise an auth request, so get the session key // Otherwise an auth request, so get the session key
@ -171,7 +177,7 @@ response_proces(struct http_client_ctx *ctx)
{ {
DPRINTF(E_LOG, L_LASTFM, "Session key not found\n"); DPRINTF(E_LOG, L_LASTFM, "Session key not found\n");
mxmlDelete(tree); mxmlDelete(tree);
return; return -1;
} }
sk = trimwhitespace(mxmlGetOpaque(s_node)); sk = trimwhitespace(mxmlGetOpaque(s_node));
@ -184,28 +190,36 @@ response_proces(struct http_client_ctx *ctx)
free(lastfm_session_key); free(lastfm_session_key);
lastfm_session_key = sk; lastfm_session_key = sk;
lastfm_disabled = false;
ret = 0;
}
else
{
ret = -1;
} }
mxmlDelete(tree); mxmlDelete(tree);
return ret;
} }
/*
* Post request against the Last.fm api
*
* Important:
* The Last.fm API requires that we MD5 sign sorted parameters (without "format" parameters),
* therefor the keyval parameters must be sorted alphabetically by their key.
*
* @param url API endpoint url
* @param kv Alphabetically sorted post parameters
* @param errmsg (Optional) returns the error message (or NULL) if request failed
*/
static int static int
request_post(char *method, struct keyval *kv, int auth) request_post(const char *url, struct keyval *kv, char **errmsg)
{ {
struct http_client_ctx ctx; struct http_client_ctx ctx;
int ret; int ret;
ret = keyval_add(kv, "method", method);
if (ret < 0)
return -1;
if (!auth)
ret = keyval_add(kv, "sk", lastfm_session_key);
if (ret < 0)
return -1;
// API requires that we MD5 sign sorted param (without "format" param) // API requires that we MD5 sign sorted param (without "format" param)
keyval_sort(kv);
ret = param_sign(kv); ret = param_sign(kv);
if (ret < 0) if (ret < 0)
{ {
@ -222,14 +236,14 @@ request_post(char *method, struct keyval *kv, int auth)
return -1; return -1;
} }
ctx.url = auth ? auth_url : api_url; ctx.url = url;
ctx.input_body = evbuffer_new(); ctx.input_body = evbuffer_new();
ret = http_client_request(&ctx); ret = http_client_request(&ctx);
if (ret < 0) if (ret < 0)
goto out_free_ctx; goto out_free_ctx;
response_proces(&ctx); ret = response_process(&ctx, errmsg);
out_free_ctx: out_free_ctx:
free(ctx.output_body); free(ctx.output_body);
@ -275,15 +289,17 @@ scrobble(int id)
snprintf(trackNumber, sizeof(trackNumber), "%" PRIu32, mfi->track); snprintf(trackNumber, sizeof(trackNumber), "%" PRIu32, mfi->track);
snprintf(timestamp, sizeof(timestamp), "%" PRIi64, (int64_t)time(NULL)); snprintf(timestamp, sizeof(timestamp), "%" PRIi64, (int64_t)time(NULL));
ret = ( (keyval_add(kv, "api_key", lastfm_api_key) == 0) && ret = (
(keyval_add(kv, "sk", lastfm_session_key) == 0) &&
(keyval_add(kv, "artist", mfi->artist) == 0) &&
(keyval_add(kv, "track", mfi->title) == 0) &&
(keyval_add(kv, "album", mfi->album) == 0) && (keyval_add(kv, "album", mfi->album) == 0) &&
(keyval_add(kv, "albumArtist", mfi->album_artist) == 0) && (keyval_add(kv, "albumArtist", mfi->album_artist) == 0) &&
(keyval_add(kv, "api_key", lastfm_api_key) == 0) &&
(keyval_add(kv, "artist", mfi->artist) == 0) &&
(keyval_add(kv, "duration", duration) == 0) && (keyval_add(kv, "duration", duration) == 0) &&
(keyval_add(kv, "trackNumber", trackNumber) == 0) && (keyval_add(kv, "method", "track.scrobble") == 0) &&
(keyval_add(kv, "timestamp", timestamp) == 0) (keyval_add(kv, "sk", lastfm_session_key) == 0) &&
(keyval_add(kv, "timestamp", timestamp) == 0) &&
(keyval_add(kv, "track", mfi->title) == 0) &&
(keyval_add(kv, "trackNumber", trackNumber) == 0)
); );
free_mfi(mfi, 0); free_mfi(mfi, 0);
@ -297,7 +313,7 @@ scrobble(int id)
DPRINTF(E_INFO, L_LASTFM, "Scrobbling '%s' by '%s'\n", keyval_get(kv, "track"), keyval_get(kv, "artist")); DPRINTF(E_INFO, L_LASTFM, "Scrobbling '%s' by '%s'\n", keyval_get(kv, "track"), keyval_get(kv, "artist"));
ret = request_post("track.scrobble", kv, 0); ret = request_post(api_url, kv, NULL);
keyval_clear(kv); keyval_clear(kv);
free(kv); free(kv);
@ -314,40 +330,72 @@ scrobble(int id)
/* ---------------------------- Our lastfm API --------------------------- */ /* ---------------------------- Our lastfm API --------------------------- */
/* Thread: filescanner */ /* Thread: filescanner, httpd */
void static void
lastfm_login(char **arglist) stop_scrobbling()
{ {
struct keyval *kv;
int ret;
DPRINTF(E_LOG, L_LASTFM, "LastFM credentials file OK, logging in with username %s\n", arglist[0]);
// Delete any existing session key // Delete any existing session key
free(lastfm_session_key); free(lastfm_session_key);
lastfm_session_key = NULL; lastfm_session_key = NULL;
db_admin_delete("lastfm_sk"); // Disable LastFM, will be enabled after successful login request
lastfm_disabled = true;
// Enable LastFM now that we got a login attempt db_admin_delete("lastfm_sk");
lastfm_disabled = 0; }
/* Thread: filescanner, httpd */
int
lastfm_login_user(const char *user, const char *password, char **errmsg)
{
struct keyval *kv;
int ret;
DPRINTF(E_LOG, L_LASTFM, "LastFM credentials file OK, logging in with username %s\n", user);
// Stop active scrobbling session
stop_scrobbling();
kv = keyval_alloc(); kv = keyval_alloc();
if (!kv) if (!kv)
return; return -1;
ret = ( (keyval_add(kv, "api_key", lastfm_api_key) == 0) && ret = (
(keyval_add(kv, "username", arglist[0]) == 0) && (keyval_add(kv, "api_key", lastfm_api_key) == 0) &&
(keyval_add(kv, "password", arglist[1]) == 0) ); (keyval_add(kv, "method", "auth.getMobileSession") == 0) &&
(keyval_add(kv, "password", password) == 0) &&
(keyval_add(kv, "username", user) == 0)
);
if (!ret) if (!ret)
goto out_free_kv; goto out_free_kv;
// Send the login request // Send the login request
request_post("auth.getMobileSession", kv, 1); ret = request_post(auth_url, kv, errmsg);
out_free_kv: out_free_kv:
keyval_clear(kv); keyval_clear(kv);
free(kv); free(kv);
listener_notify(LISTENER_LASTFM);
return ret;
}
/* Thread: filescanner */
void
lastfm_login(char **arglist)
{
if (arglist)
lastfm_login_user(arglist[0], arglist[1], NULL);
else
lastfm_login_user(NULL, NULL, NULL);
}
void
lastfm_logout(void)
{
stop_scrobbling();
listener_notify(LISTENER_LASTFM);
} }
/* Thread: worker */ /* Thread: worker */
@ -360,17 +408,27 @@ lastfm_scrobble(int id)
if (lastfm_disabled) if (lastfm_disabled)
return -1; return -1;
// No session key in mem or in db
if (!lastfm_session_key)
lastfm_session_key = db_admin_get("lastfm_sk");
if (!lastfm_session_key)
{
DPRINTF(E_INFO, L_LASTFM, "No valid LastFM session key\n");
lastfm_disabled = 1;
return -1;
}
return scrobble(id); return scrobble(id);
} }
/* Thread: httpd */
bool
lastfm_is_enabled(void)
{
return !lastfm_disabled;
}
/* Thread: main */
int
lastfm_init(void)
{
lastfm_session_key = db_admin_get("lastfm_sk");
if (!lastfm_session_key)
{
DPRINTF(E_DBG, L_LASTFM, "No valid LastFM session key\n");
lastfm_disabled = true;
}
return 0;
}

View File

@ -2,10 +2,24 @@
#ifndef __LASTFM_H__ #ifndef __LASTFM_H__
#define __LASTFM_H__ #define __LASTFM_H__
#include <stdbool.h>
int
lastfm_login_user(const char *user, const char *password, char **errmsg);
void void
lastfm_login(char **arglist); lastfm_login(char **arglist);
void
lastfm_logout(void);
int int
lastfm_scrobble(int id); lastfm_scrobble(int id);
bool
lastfm_is_enabled(void);
int
lastfm_init(void);
#endif /* !__LASTFM_H__ */ #endif /* !__LASTFM_H__ */

View File

@ -24,6 +24,8 @@ enum listener_event_type
LISTENER_PAIRING = (1 << 8), LISTENER_PAIRING = (1 << 8),
/* Spotify status changes (login, logout) */ /* Spotify status changes (login, logout) */
LISTENER_SPOTIFY = (1 << 9), LISTENER_SPOTIFY = (1 << 9),
/* Last.fm status changes (enable/disable scrobbling) */
LISTENER_LASTFM = (1 << 10),
}; };
typedef void (*notify)(enum listener_event_type type); typedef void (*notify)(enum listener_event_type type);

View File

@ -70,6 +70,9 @@ GCRY_THREAD_OPTION_PTHREAD_IMPL;
#include "player.h" #include "player.h"
#include "worker.h" #include "worker.h"
#include "library.h" #include "library.h"
#ifdef LASTFM
# include "lastfm.h"
#endif
#ifdef HAVE_LIBCURL #ifdef HAVE_LIBCURL
# include <curl/curl.h> # include <curl/curl.h>
@ -784,6 +787,10 @@ main(int argc, char **argv)
mdns_no_mpd = 1; mdns_no_mpd = 1;
#endif #endif
#ifdef LASTFM
lastfm_init();
#endif
/* Start Remote pairing service */ /* Start Remote pairing service */
ret = remote_pairing_init(); ret = remote_pairing_init();
if (ret != 0) if (ret != 0)

View File

@ -137,6 +137,10 @@ process_notify_request(struct ws_session_data_notify *session_data, void *in, si
{ {
session_data->events |= LISTENER_SPOTIFY; session_data->events |= LISTENER_SPOTIFY;
} }
else if (0 == strcmp(event_type, "lastfm"))
{
session_data->events |= LISTENER_LASTFM;
}
} }
} }
} }
@ -177,6 +181,10 @@ send_notify_reply(short events, struct lws* wsi)
{ {
json_object_array_add(notify, json_object_new_string("spotify")); json_object_array_add(notify, json_object_new_string("spotify"));
} }
if (events & LISTENER_LASTFM)
{
json_object_array_add(notify, json_object_new_string("lastfm"));
}
reply = json_object_new_object(); reply = json_object_new_object();
json_object_object_add(reply, "notify", notify); json_object_object_add(reply, "notify", notify);
@ -258,7 +266,7 @@ static struct lws_protocols protocols[] =
static void * static void *
websocket(void *arg) websocket(void *arg)
{ {
listener_add(listener_cb, LISTENER_UPDATE | LISTENER_PAIRING | LISTENER_SPOTIFY); listener_add(listener_cb, LISTENER_UPDATE | LISTENER_PAIRING | LISTENER_SPOTIFY | LISTENER_LASTFM);
while(!ws_exit) while(!ws_exit)
{ {