-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxbmc.js
516 lines (471 loc) · 21.7 KB
/
xbmc.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
exports.action = function (data, callback, config, SARAH) {
// Retrieve config
var api_url;
config = config.modules.xbmc;
if ((!config.api_url_xbmc_music)||(!config.api_url_xbmc_video)) {
return callback({ 'tts': 'Configuration XBMC invalide' });
}
if (data.xbmc=='music') { xbmc_api_url=config.api_url_xbmc_music;}
else if (data.xbmc=='video') { xbmc_api_url=config.api_url_xbmc_video;}
else {return callback({ 'tts': 'Choix du XBMC inconnu!'});}
switch (data.action) {
case 'introspect':
doAction(introspect, xbmc_api_url, callback);
break;
case 'xml_artist':
doXML(xml_artist, xbmc_api_url, callback);
break;
case 'xml_genre':
doXML(xml_genre, xbmc_api_url, callback);
break;
case 'xml_serie':
doXML(xml_serie, xbmc_api_url, callback);
break;
case 'playlist':
var filter = {"and": []};
if (data.genre) {
filter.and.push({"field": "genre", "operator": "contains", "value": data.genre});
}
if (data.artist) {
filter.and.push({"field": "artist", "operator": "contains", "value": data.artist});
}
if (data.title) {
filter.and.push({"field": "title", "operator": "contains", "value": data.title});
}
if (data.dictation) {
var regexp = /sarah\srecherche\s(\w+)/gi
var match = regexp.exec(data.dictation);
if (match) {
filter = {"or": []};
filter.or.push({"field": "title", "operator": "contains", "value": match[1]});
filter.or.push({"field": "artist", "operator": "contains", "value": match[1]});
}
}
doPlaylist(filter, xbmc_api_url, callback);
break;
case 'artist':
var filter = {"and": []};
if (data.artist) {
filter.and.push({"field": "artist", "operator": "contains", "value": data.artist});
}
doPlaylist(filter, xbmc_api_url, callback);
break;
case 'tvshowtitle':
doPlaylistSerie(data.showid ,xbmc_api_url , callback);
break;
case 'play':
doAction(play, xbmc_api_url, callback);
break;
case 'playvideo':
doAction(playvideo, xbmc_api_url, callback);
break;
case 'next':
doAction(next, xbmc_api_url, callback);
break;
case 'prev':
doAction(prev, xbmc_api_url, callback);
break;
case 'player':
doAction(player, xbmc_api_url, callback);
break;
case 'volup':
doAction(volup, xbmc_api_url, callback);
break;
case 'volmid':
doAction(volmid, xbmc_api_url, callback);
break;
case 'voldown':
doAction(voldown, xbmc_api_url, callback);
break;
case 'whatIsPlaying':
doAction(activePlayer, config, callback, function(json){
if (json.result)
{
var action = "";
if (json.result[0].playerid == 0)
{
action = audioPlayer;
}
else
{
action = videoPlayer;
}
doAction(action, config, callback, function(json){
if (json.result.item.title && json.result.item.artist)
{
var speech = json.result.item.title + ' de ' + json.result.item.artist;
return callback({'tts':speech});
}
else if (json.result.item.title)
{
return callback({'tts':json.result.item.title});
}
else if (json.result.item.artist)
{
return callback({'tts':json.result.item.artist});
}
else
{
return callback({ 'tts' : "Je n'ai pas trouvé d'information" });
}
});
}
else
{
return callback({ 'tts' : "Je n'ai pas trouvé d'information" });
}
});
break;
case 'ExecuteAction':
params={ "jsonrpc": "2.0", "method": "Input.ExecuteAction", "params": {"action": data.value}, "id": 1 };
if (typeof(data.repeter)=='undefined') {repeter=1; } else {repeter=data.repeter; } // repeter à 1 par défaut.
//console.log(repeter);
for (var i=0;i<repeter;i++)
{
if (i==0){doAction(params, xbmc_api_url, callback);}else{doAction(params, xbmc_api_url);}
}
break;
case 'chercheligne':
test=false;
index=0;
var lirelabel=function (test){
if (test==false) {
index=index+1;
params={ "jsonrpc": "2.0", "method": "Input.ExecuteAction", "params": {"action": "down"}, "id": 1 };
doAction(params, xbmc_api_url, callback, function(rs2) {
//console.dir(rs2);
par={"jsonrpc": "2.0", "method": "GUI.GetProperties", "params": { "properties": ["currentcontrol"]}, "id": 1}
setTimeout(function(){
doAction(par, xbmc_api_url, callback, function(res){
reponselabel=res.result.currentcontrol.label
console.log(index+ ' - ' +reponselabel);
if ((reponselabel==(data.parameters))||(reponselabel=='[..]')||(index>500)) {return lirelabel(true);} else {return lirelabel(false);} // 500= sécurité
// les [] viennent dans le résultat pour des titres/artiste mais pour les boutons d'un sous-menu
});
}, 2); // le temps de "pause" est nécessaire sinon xbmc renvois parfois le label précédent, malgré un down effectué!
});
}
else {return true;}
}
if (data.parameters) {
lirelabel( false,function (res5) {
//console.log(res5);
callback();
});
}
else
{
consol.log('il manque data.parameters');
callback();
}
//callback();
break;
case 'ActivateWindow':
if (data.parameters) {
params={ "jsonrpc": "2.0", "method": "GUI.ActivateWindow", "params": {"window": data.window , "parameters": [ data.parameters ]}, "id": 1 };
}
else
{
params={ "jsonrpc": "2.0", "method": "GUI.ActivateWindow", "params": {"window": data.window}, "id": 1 };
}
doAction(params, xbmc_api_url, callback);
break;
default:
callback({});
break;
}
}
// -------------------------------------------
// QUERIES
// Doc: http://wiki.xbmc.org/index.php?title=JSON-RPC_API
// -------------------------------------------
// Introspect
var introspect = { "jsonrpc": "2.0", "method": "JSONRPC.Introspect", "params": { "filter": { "id": "AudioLibrary.GetSongs", "type": "method" } }, "id": 1 }
// XML Generation
var xml_artist = {"jsonrpc": "2.0", "method": "AudioLibrary.GetArtists", "params": {}, "id": 1}
var xml_genre = {"jsonrpc": "2.0", "method": "AudioLibrary.GetGenres", "params": {}, "id": 1}
var xml_serie={"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {}, "id": 1}
// Toggle play / pause in current player
var play = {"jsonrpc": "2.0", "method": "Player.PlayPause", "params": { "playerid": 0 }, "id": 1};
var player = {"jsonrpc": "2.0", "method": "Player.GetActivePlayers", "id": 1}
// Toggle play / pause in current player video
var playvideo = {"jsonrpc": "2.0", "method": "Player.PlayPause", "params": { "playerid": 1 }, "id": 1};
var goscreen = {"jsonrpc": "2.0", "method":"GUI.ShowNotification", "params": {"title":"Message de moi!","message":"Message de Sarah, Il faut sortir les poubelle!","image":"warning"}, "id": 1};
// Previous / Next item in current player
var next = {"jsonrpc": "2.0", "method": "Player.GoTo", "params": { "playerid": 0, "to": "next" }, "id": 1}
var prev = {"jsonrpc": "2.0", "method": "Player.GoTo", "params": { "playerid": 0, "to": "previous" }, "id": 1}
// Set Volume in current player
var volup = {"jsonrpc": "2.0", "method": "Application.SetVolume", "params": { "volume": 100}, "id": 1}
var volmid = {"jsonrpc": "2.0", "method": "Application.SetVolume", "params": { "volume": 80}, "id": 1}
var voldown = {"jsonrpc": "2.0", "method": "Application.SetVolume", "params": { "volume": 50}, "id": 1}
// Query library
var genres = {"jsonrpc": "2.0", "method": "AudioLibrary.GetGenres", "params": {"properties": ["title"], "limits": { "start": 0, "end": 20 }, "sort": { "method": "label", "order": "ascending" }}, "id": "AudioLibrary.GetGenres"}
var albums = {"jsonrpc": "2.0", "method": "AudioLibrary.GetAlbums", "params": {"properties": ["artist", "artistid", "albumlabel", "year", "thumbnail", "genre"], "limits": { "start": 0, "end": 20 }, "sort": { "method": "label", "order": "ascending" }}, "id": "AudioLibrary.GetAlbumsByGenre"}
var songs = {"jsonrpc": "2.0", "method": "AudioLibrary.GetSongs", "params": {"properties": ["title", "genre", "artist", "duration", "album", "track" ], "limits": { "start": 0, "end": 25 }, "sort": { "order": "ascending", "method": "track", "ignorearticle": true } }, "id": "libSongs"}
var saison={"jsonrpc": "2.0", "method": "VideoLibrary.GetSeasons","params": { "tvshowid": 1 ,"properties": ["season", "thumbnail"]}, "id": 1}
var episode = {"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes","params": { "tvshowid": 1 , "season": 1 ,"properties": ["title", "firstaired", "playcount", "runtime", "season", "episode", "file", "streamdetails", "lastplayed", "uniqueid"], "limits": { "start" : 0, "end": 25 }, "sort": { "order": "ascending", "method": "track", "ignorearticle": true }}, "id": 1}
// Playlist
var playlist = {"jsonrpc": "2.0", "method": "Playlist.GetItems", "params": { "properties": ["title", "album", "artist", "duration"], "playlistid": 0 }, "id": 1}
var clearlist = {"jsonrpc": "2.0", "id": 0, "method": "Playlist.Clear", "params": {"playlistid": 0}}
var addtolist = {"jsonrpc": "2.0", "id": 1, "method": "Playlist.Add", "params": {"playlistid": 0, "item": {"songid": 10}}}
var runlist = {"jsonrpc": "2.0", "id": 2, "method": "Player.Open", "params": {"item": {"playlistid": 0}}}
// Séries
var playserie = {"jsonrpc": "2.0", "method": "Player.Open", "params": { "item": {"file":""} , "options":{ "resume":true } }, "id": 3}
// What is playing
var activePlayer = {"jsonrpc": "2.0", "method": "Player.GetActivePlayers", "id": 1}
var audioPlayer = {"jsonrpc": "2.0", "method": "Player.GetItem", "params": { "properties": ["title", "album", "artist", "duration", "thumbnail", "file", "fanart", "streamdetails"], "playerid": 0 }, "id": "AudioGetItem"}
var videoPlayer = {"jsonrpc": "2.0", "method": "Player.GetItem", "params": { "properties": ["title", "album", "artist", "season", "episode", "duration", "showtitle", "tvshowid", "thumbnail", "file", "fanart", "streamdetails"], "playerid": 1 }, "id": "VideoGetItem"}
doPlaylistSerie = function (id, xbmc_api_url, callback){
var asyncEpisode=function(l_episode,reponse) {
if (l_episode) {
//console.log("saison = "+l_episode.season +" episode = "+l_episode.episode + " last view = "+l_episode.lastplayed + " Playcount = "+l_episode.playcount);
if (l_episode.playcount == 0) { return reponse(l_episode);} // si épisode non vu => renvois l'episode
return asyncEpisode(les_episodes.shift(),reponse);// sinon poursuit à l'épisode suivant
}
else {return reponse(false);} // tous les épisodes de cette saison ont été vus
}
var asyncSaison=function(la_saison,reponse) {
if (la_saison) {
episode.params.season=parseInt(la_saison.season);
// récupération des épisodes
sendJSONRequest(xbmc_api_url, episode , function(res){
les_episodes=res.result.episodes
asyncEpisode(les_episodes.shift(), function (reponse_episode) {
if (reponse_episode==false) {return asyncSaison(les_saisons.shift(),reponse);} // si FALSE alors poursuit à la saison suivante
else {return reponse(reponse_episode);} // renvois l'épisode trouvé
});
});
}
else {return reponse(false);} // aucun épisode d'aucune série trouvée.
}
saison.params.tvshowid = parseInt(id);
episode.params.tvshowid = parseInt(id);
// récupération des saisons
sendJSONRequest(xbmc_api_url, saison ,function(res){
les_saisons=res.result.seasons;
asyncSaison(les_saisons.shift(), function(reponse) {
if (reponse==false) { callback({'tts':'Tous les épisodes ont été visionnés!'}); }
else {
playserie.params.item.file = reponse.file
doAction ( playserie , xbmc_api_url );
callback({'tts':'lecture de l\'épisode '+reponse.episode+' de la saison '+reponse.season+"."});
}
});
});
}
var doPlaylist = function (filter, xbmc_api_url, callback) {
// Apply filter
songs.params['filter'] = filter;
// Search songs
doAction(songs, xbmc_api_url, callback, function (json) {
// No results
if (!json.result.songs) {
callback({ 'tts': "Je n'ai pas trouvé de résultats" })
return false;
}
// Clear playlist
doAction(clearlist, xbmc_api_url);
// Iterate
json.result.songs.forEach(function (song) {
// console.log(song.title);
addtolist.params.item.songid = song.songid;
doAction(addtolist, xbmc_api_url);
});
doAction(runlist, xbmc_api_url);
return true; // call callback
})
}
var doAction = function (req, xbmc_api_url, callback, hook) {
//console.dir(req);
// Send a simple JSON request
sendJSONRequest(xbmc_api_url, req, function (res) {
if (!handleJSONResponse(res, callback)) {
return;
}
// Do stuff
if (hook) {
try {
if (!hook(res)) {
return;
}
} catch (ex) {
console.log(res);
}
}
// Otherwise
if (callback) {
callback({})
}
;
});
}
var doXML = function (req, xbmc_api_url, callback, hook) {
// Send a simple JSON request
sendJSONRequest(xbmc_api_url, req, function (res) {
if (res) {
// Generation XML Artist
if ((typeof res.result.artists != 'undefined') && (typeof res.result.limits != 'undefined')) {
var ligneitem = '';
var lignehtml = '';
var lignehtmlpresent = '';
var fs = require('fs');
var fileXML = 'plugins/xbmc/xbmc.xml';
//efface la zone génération automatique
var xml = fs.readFileSync(fileXML, 'utf8');
var replace = '§ -->\n <item>ARTIST<tag>out.action._attributes.tts = "Le fichier XML n\'a jamais été généré!"</tag></item>\n<!-- §';
var regexp = new RegExp('§[^§]+§', 'gm');
var xml = xml.replace(regexp, replace);
fs.writeFileSync(fileXML, xml, 'utf8');
console.log('XBMC plugin: Zone génération automatique artiste effacée.')
// Génère la zone génération automatique sauf si artiste déjà présent
replace = '§ -->\n';
var present=0;
res.result.artists.forEach(function (value) {
// test si ligne déjà présente
lignetest = '<tag>out.action.artist = "' + value.label.replace(/&/gi, "&") + '"</tag>'
var regexp = new RegExp(lignetest, 'gm');
if (xml.match(regexp))
{
lignehtmlpresent += value.label.replace(/&/gi, "&") + '<br>'
present=present+1;
}
else {
lignehtml += value.label.replace(/&/gi, "&") + '<br>'
ligneitem = ' <item>' + value.label.replace(/&/gi, "and") + '<tag>out.action.artist = "' + value.label.replace(/&/gi, "&") + '"</tag></item>\n';
replace += (ligneitem);
}
});
var xml = fs.readFileSync(fileXML, 'utf8');
replace += ' <!-- §';
var regexp = new RegExp('§[^§]+§', 'gm');
var xml = xml.replace(regexp, replace);
fs.writeFileSync(fileXML, xml, 'utf8');
console.log('XBMC plugin: ' + (res.result.limits.total-present) + ' artistes générés dans xbmc.xml ( +'+present+' déjà personnalisés )');
callback({'tts': '<b>Traitement de ' +(res.result.limits.total)+' artistes dans xbmc.xml<br><br>'+present+' personnalisés:</b><br>'+lignehtmlpresent+'<br><b>'+(res.result.limits.total-present)+' Mises à jour:</b><br>' + lignehtml})
}
// Generation XML Genre
else if ((typeof res.result.genres != 'undefined') && (typeof res.result.limits != 'undefined')) {
var ligneitem = '';
var lignehtml = '';
var lignehtmlpresent = '';
var fs = require('fs');
var fileXML = 'plugins/xbmc/xbmc.xml';
//efface la zone génération automatique
var xml = fs.readFileSync(fileXML, 'utf8');
var replace = '¤ -->\n <item>GENRE<tag>out.action._attributes.tts = "Le fichier XML n\'a jamais été généré!"</tag></item>\n<!-- ¤';
var regexp = new RegExp('¤[^¤]+¤', 'gm');
var xml = xml.replace(regexp, replace);
fs.writeFileSync(fileXML, xml, 'utf8');
console.log('XBMC plugin: Zone génération automatique genre effacée.')
// Génère la zone génération automatique sauf si artiste déjà présent
replace = '¤ -->\n';
var present=0;
res.result.genres.forEach(function (value) {
// test si ligne déjà présente
lignetest = '<tag>out.action.genre = "' + value.label.replace(/&/gi, "&") + '"</tag>'
var regexp = new RegExp(lignetest, 'gm');
if (xml.match(regexp))
{
lignehtmlpresent += value.label.replace(/&/gi, "&") + '<br>'
present=present+1;
}
else {
lignehtml += value.label.replace(/&/gi, "&") + '<br>'
ligneitem = ' <item>' + value.label.replace(/&/gi, "and") + '<tag>out.action.genre = "' + value.label.replace(/&/gi, "&") + '"</tag></item>\n';
replace += (ligneitem);
}
});
var xml = fs.readFileSync(fileXML, 'utf8');
replace += ' <!-- ¤';
var regexp = new RegExp('¤[^¤]+¤', 'gm');
var xml = xml.replace(regexp, replace);
fs.writeFileSync(fileXML, xml, 'utf8');
console.log('XBMC plugin: ' + (res.result.limits.total-present) + ' genres générés dans xbmc.xml ( +'+present+' déjà personnalisés )');
callback({'tts': '<b>Traitement de ' +(res.result.limits.total)+' genres dans xbmc.xml<br><br>'+present+' personnalisés:</b><br>'+lignehtmlpresent+'<br><b>'+(res.result.limits.total-present)+' Mises à jour:</b><br>' + lignehtml})
}
// Generation XML Series
else if ((typeof res.result.tvshows != 'undefined') && (typeof res.result.limits != 'undefined')){
var ligneitem = '';
var lignehtml = '';
var lignehtmlpresent = '';
var fs = require('fs');
var fileXML = 'plugins/xbmc/xbmc.xml';
//efface la zone génération automatique
var xml = fs.readFileSync(fileXML, 'utf8');
var replace = '£ -->\n <item>SERIE<tag>out.action._attributes.tts = "Le fichier XML n\'a jamais été généré!"</tag></item>\n<!-- £';
var regexp = new RegExp('£[^£]+£', 'gm');
var xml = xml.replace(regexp, replace);
fs.writeFileSync(fileXML, xml, 'utf8');
console.log('XBMC plugin: Zone génération automatique série effacée.')
// Génère la zone génération automatique sauf si série déjà présente
var replace = '£ -->\n'; // zone a remplacer
var present=0;
res.result.tvshows.forEach(function(value) { //value contient label ou id
// test si ligne déjà présente
lignetest = '<tag>out.action.showid = "'+value.tvshowid+'"</tag>'
var regexp = new RegExp(lignetest, 'gm');
if (xml.match(regexp))
{
lignehtmlpresent += value.label.replace(/&/gi, "&") + '<br>'
present=present+1;
}
else {
lignehtml += value.label.replace(/&/gi, "&") + '<br>'
ligneitem = ' <item>' + value.label.replace(/&/gi, "and") + '<tag>out.action.showid = "' + value.tvshowid + '"</tag></item>\n';
replace += (ligneitem);
}
});
var xml = fs.readFileSync(fileXML,'utf8');
replace += ' <!-- £';
//console.log(replace);
var regexp = new RegExp('£[^£]+£','gm');
var xml = xml.replace(regexp,replace);
//console.log(xml);
fs.writeFileSync(fileXML, xml, 'utf8');
console.log('XBMC plugin: ' + (res.result.limits.total-present) + ' série générées dans xbmc.xml ( +'+present+' déjà personnalisées )');
callback({'tts': '<b>Traitement de ' +(res.result.limits.total)+' séries dans xbmc.xml<br><br>'+present+' personnalisées:</b><br>'+lignehtmlpresent+'<br><b>'+(res.result.limits.total-present)+' Mises à jour:</b><br>' + lignehtml})
}
// Otherwise
else if (callback) {
callback({'tts': 'Erreur: aucune importation effectuée!'})
}
;
}
else {
callback({'tts': 'Erreur!'})
}
});
}
// -------------------------------------------
// JSON
// -------------------------------------------
var sendJSONRequest = function (url, reqJSON, callback) {
var request = require('request');
request({
'uri': url,
'method': 'POST',
'json': reqJSON
},
function (err, response, json) {
if (err || response.statusCode != 200) {
return callback(false);
}
// Log the response
// console.log(json);
// Return the response
callback(json);
});
}
// xbmc_api_url
var handleJSONResponse = function (res, callback) {
//console.dir(res);
// Request error
if (!res) {
return callback({ 'tts': "Je n'ai pas pu contacter le serveur" });
}
// XBMC error
if (res.error) {
return callback({ 'tts': "Je n'ai pas pu executer l'action" });
}
return true;
}