forked from OmerTu/GoogleHomeKodi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
430 lines (361 loc) · 14 KB
/
server.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
// server.js
// where your node app starts
// init project
require('dotenv').load();
var express = require('express');
var app = express();
var Fuse = require('fuse.js')
var Kodi = require('./kodi-connection/node.js');
var kodi = new Kodi(process.env.KODI_IP, process.env.KODI_PORT, process.env.KODI_USER, process.env.KODI_PASSWORD);
// Set option for fuzzy search
var fuzzySearchOptions = {
caseSensitive: false, // Don't care about case whenever we're searching titles by speech
includeScore: false, // Don't need the score, the first item has the highest probability
shouldSort: true, // Should be true, since we want result[0] to be the item with the highest probability
threshold: 0.4, // 0 = perfect match, 1 = match all..
location: 0,
distance: 100,
maxPatternLength: 64,
keys: ['label']
}
app.use(express.static('public'));
var validateRequest = function(req, res, processRequest){
var jsonString = '';
var requestToken = '';
var jsonBody;
if (req == null || req.query == req) {
console.log("403 - Unauthorized request");
res.sendStatus(403);
return;
}
req.on('data', function (data) {
jsonString += data;
});
req.on('end', function () {
if (jsonString != '') {
jsonBody = JSON.parse(jsonString);
if (jsonBody != null) {
requestToken = jsonBody['token'];
console.log("Request token = " + requestToken);
if (requestToken == process.env.AUTH_TOKEN) {
console.log("Authentication succeeded");
processRequest(req, res);
return;
}
}
}
console.log("401 - Authentication failed");
res.sendStatus(401);
});
};
// Pause or Resume video player
app.get("/playpause", function (request, response) {
validateRequest(request, response, kodiPlayPause)
});
var kodiPlayPause = function(request, response) {
console.log("Play/Pause request received");
kodi.Player.PlayPause({playerid:1});
response.sendStatus(200);
};
// Stop video player
app.get("/stop", function (request, response) {
validateRequest(request, response, kodiStop)
});
var kodiStop = function(request, response) {
console.log("Stop request received");
kodi.Player.Stop({playerid:1});
response.sendStatus(200);
};
//Seek forward x seconds
app.get("/seekforward", function(request, response) {
validateRequest(request,response,kodiSeek)
});
var kodiSeek = function(request, response){
var seekForward = request.query.q.trim();
kodi.Player.Seek({"playerid":1,"value":{"seconds":parseInt(seekForward)} });
response.sendStatus(200);
};
// mute or unmute kodi
app.get("/mute", function (request, response) {
validateRequest(request, response, kodiMuteToggle)
});
var kodiMuteToggle = function(request, response) {
console.log("mute/unmute request received");
kodi.Application.SetMute({"mute":"toggle"});
response.sendStatus(200);
};
// set kodi volume
app.get("/volume", function (request, response) {
validateRequest(request, response, kodiSetVolume)
});
var kodiSetVolume = function(request, response) {
var setVolume = request.query.q.trim();
console.log("set volume to \"" + setVolume + "\" percent request received");
kodi.Application.SetVolume({"volume":parseInt(setVolume)});
response.sendStatus(200);
};
// Turn on TV and Switch to Kodi's HDMI input
app.get("/activatetv", function (request, response) {
validateRequest(request, response, kodiActivateTv)
});
var kodiActivateTv = function(request, response) {
console.log("Activate TV request received");
var params = {
addonid: "script.json-cec",
params: {
command: "activate"
}
};
kodi.Addons.ExecuteAddon(params);
};
var tryActivateTv = function() {
if (process.env.ACTIVATE_TV != null && process.env.ACTIVATE_TV == "true") {
console.log("Activating TV first..");
kodiActivateTv(null, null);
}
};
// Parse request to watch a movie
// Request format: http://[THIS_SERVER_IP_ADDRESS]/playmovie?q=[MOVIE_NAME]
app.get("/playmovie", function (request, response) {
validateRequest(request, response, kodiPlayMovie)
});
var kodiPlayMovie = function(request, response) {
tryActivateTv();
var movieTitle = request.query.q.trim();
console.log("Movie request received to play \"" + movieTitle + "\"");
kodi.VideoLibrary.GetMovies()
.then(function(movies) {
if(!(movies && movies.result && movies.result.movies && movies.result.movies.length > 0)) {
throw new Error('no results');
}
// Create the fuzzy search object
var fuse = new Fuse(movies.result.movies, fuzzySearchOptions)
var searchResult = fuse.search(movieTitle)
// If there's a result
if (searchResult.length > 0) {
var movieFound = searchResult[0];
console.log("Found movie \"" + movieFound.label + "\" (" + movieFound.movieid + ")");
return kodi.Player.Open({item: { movieid: movieFound.movieid }});
} else {
throw new Error("Couldn\'t find movie \"" + movieTitle + "\"");
}
})
.catch(function(e) {
console.log(e);
});
response.sendStatus(200);
};
// Parse request to watch your next unwatched episode for a given tv show
// Request format: http://[THIS_SERVER_IP_ADDRESS]/playtvshow?q=[TV_SHOW_NAME]
app.get("/playtvshow", function (request, response) {
validateRequest(request, response, kodiPlayTvshow)
});
var kodiPlayTvshow = function(request, response) {
tryActivateTv();
var param = {
tvshowTitle: request.query.q.trim().toLowerCase()
};
console.log("TV Show request received to play \"" + param["tvshowTitle"] + "\"");
kodiFindTvshow (request, response, kodiPlayNextUnwatchedEpisode, param);
};
// Parse request to watch a specific episode for a given tv show
// Request format: http://[THIS_SERVER_IP_ADDRESS]/playepisode?q[TV_SHOW_NAME]season[SEASON_NUMBER]episode&e[EPISODE_NUMBER]
// For example, if IP was 1.1.1.1 a request to watch season 2 episode 3 in tv show named 'bla' looks like:
// http://1.1.1.1/playepisode?q=bla+season+2+episode&e=3
app.get("/playepisode", function (request, response) {
validateRequest(request, response, kodiPlayEpisodeHandler)
});
var kodiPlayEpisodeHandler = function(request, response) {
tryActivateTv();
var requestPartOne = request.query.q.split("season");
var param = {
tvshowTitle: requestPartOne[0].trim().toLowerCase(),
seasonNum: requestPartOne[1].trim().toLowerCase(),
episodeNum: request.query.e
};
console.log("Specific Episode request received to play \"" + param["tvshowTitle"] + "\" Season " + param["seasonNum"] + " Episode " + param["episodeNum"]);
kodiFindTvshow (request, response, kodiPlaySpecificEpisode, param);
};
var kodiFindTvshow = function(req, res, nextAction, param) {
kodi.VideoLibrary.GetTVShows()
.then(
function(shows) {
if(!(shows && shows.result && shows.result.tvshows && shows.result.tvshows.length > 0)) {
throw new Error('no results');
}
// Create the fuzzy search object
var fuse = new Fuse(shows.result.tvshows, fuzzySearchOptions)
var searchResult = fuse.search(param["tvshowTitle"])
// If there's a result
if (searchResult.length > 0 && searchResult[0].tvshowid != null) {
var tvshowFound = searchResult[0];
console.log("Found tv show \"" + tvshowFound.label + "\" (" + tvshowFound.tvshowid + ")");
param["tvshowid"] = tvshowFound.tvshowid;
nextAction (req, res, param);
} else {
throw new Error("Couldn\'t find tv show \"" + param["tvshowTitle"] + "\"");
}
}
)
.catch(function(e) {
console.log(e);
})
};
var kodiPlayNextUnwatchedEpisode = function(req, res, RequestParams) {
console.log("Searching for next episode of Show ID " + RequestParams["tvshowid"] + "...");
// Build filter to search unwatched episodes
var param = {
tvshowid: RequestParams["tvshowid"],
properties: ['playcount', 'showtitle', 'season', 'episode'],
// Sort the result so we can grab the first unwatched episode
sort: {
order: 'ascending',
method: 'episode',
ignorearticle: true
}
}
kodi.VideoLibrary.GetEpisodes(param)
.then(function (episodeResult) {
if(!(episodeResult && episodeResult.result && episodeResult.result.episodes && episodeResult.result.episodes.length > 0)) {
throw new Error('no results');
}
var episodes = episodeResult.result.episodes;
// Check if there are episodes for this TV show
if (episodes) {
console.log("found episodes..");
// Check whether we have seen this episode already
var firstUnplayedEpisode = episodes.filter(function (item) {
return item.playcount === 0
})
if (firstUnplayedEpisode.length > 0) {
var episdoeToPlay = firstUnplayedEpisode[0]; // Resolve the first unplayed episode
console.log("Playing season " + episdoeToPlay.season + " episode " + episdoeToPlay.episode + " (ID: " + episdoeToPlay.episodeid + ")");
var param = {
item: {
episodeid: episdoeToPlay.episodeid
}
}
return kodi.Player.Open(param);
}
}
})
.catch(function(e) {
console.log(e);
});
res.sendStatus(200);
};
var kodiPlaySpecificEpisode = function(req, res, RequestParams) {
console.log("Searching Season " + RequestParams["seasonNum"] + ", episode " + RequestParams["episodeNum"] + " of Show ID " + RequestParams["tvshowid"] + "...");
// Build filter to search for specific season number
var param = {
tvshowid: RequestParams["tvshowid"],
//episode: requestedEpisodeNum,
season: parseInt(RequestParams["seasonNum"]),
properties: ['playcount', 'showtitle', 'season', 'episode']
}
kodi.VideoLibrary.GetEpisodes(param)
.then(function (episodeResult) {
if(!(episodeResult && episodeResult.result && episodeResult.result.episodes && episodeResult.result.episodes.length > 0)) {
throw new Error('no results');
}
var episodes = episodeResult.result.episodes;
// Check if there are episodes for this TV show
if (episodes) {
console.log("found episodes..");
// Check for the episode number requested
var matchedEpisodes = episodes.filter(function (item) {
return item.episode === parseInt(RequestParams["episodeNum"])
})
if (matchedEpisodes.length > 0) {
var episdoeToPlay = matchedEpisodes[0];
console.log("Playing season " + episdoeToPlay.season + " episode " + episdoeToPlay.episode + " (ID: " + episdoeToPlay.episodeid + ")");
var param = {
item: {
episodeid: episdoeToPlay.episodeid
}
}
return kodi.Player.Open(param);
}
}
})
.catch(function(e) {
console.log(e);
});
res.sendStatus(200);
};
// Parse request to watch a PVR channel by name
// Request format: http://[THIS_SERVER_IP_ADDRESS]/playpvrchannelbyname?q=[CHANNEL_NAME]
app.get("/playpvrchannelbyname", function (request, response) {
validateRequest(request, response, kodiPlayChannelByName)
});
// Parse request to watch a PVR channel by number
// Request format: http://[THIS_SERVER_IP_ADDRESS]/playpvrchannelbynumber?q=[CHANNEL_NUMBER]
app.get("/playpvrchannelbynumber", function (request, response) {
validateRequest(request, response, kodiPlayChannelByNumber)
});
var kodiPlayChannelByName = function(request, response) {
tryActivateTv();
kodiPlayChannel(request, response, fuzzySearchOptions);
}
var kodiPlayChannelByNumber = function(request, response) {
tryActivateTv();
var pvrFuzzySearchOptions = JSON.parse(JSON.stringify(fuzzySearchOptions));
pvrFuzzySearchOptions.keys[0] = "channelnumber"
kodiPlayChannel(request, response, pvrFuzzySearchOptions);
}
var kodiPlayChannel = function(request, response, searchOptions) {
var reqChannel = request.query.q.trim();
console.log("PVR channel request received to play \"" + reqChannel + "\"");
// Build filter to search TV channel groups
var param = {
channeltype : "tv"
}
kodi.PVR.GetChannelGroups(param)
.then(function(channelGroups) {
if(!(channelGroups && channelGroups.result && channelGroups.result.channelgroups && channelGroups.result.channelgroups.length > 0)) {
throw new Error('no channels group were found. Perhaps PVR is not setup?');
}
// For each tv PVR channel group, search for all channels
var chGroups = channelGroups.result.channelgroups;
tryPlayingChannelInGroup(searchOptions, reqChannel, chGroups, 0);
})
.catch(function(e) {
console.log(e);
})
};
var tryPlayingChannelInGroup = function(searchOptions, reqChannel, chGroups, currGroupI) {
if (currGroupI < chGroups.length) {
// Build filter to search for all channel under the channel group
var param = {
channelgroupid : chGroups[currGroupI].channelgroupid
}
kodi.PVR.GetChannels(param)
.then(function(channels) {
if(!(channels && channels.result && channels.result.channels && channels.result.channels.length > 0)){
throw new Error('no channels were found');
}
var rChannels = channels.result.channels;
// Create the fuzzy search object
var fuse = new Fuse(rChannels, searchOptions)
var searchResult = fuse.search(reqChannel)
// If there's a result
if (searchResult.length > 0) {
var channelFound = searchResult[0];
console.log("Found PVR channel \"" + channelFound.label + "\" - " + channelFound.channelnumber + " (" + channelFound.channelid + ")");
return kodi.Player.Open({item: { channelid: channelFound.channelid }});
} else {
tryPlayingChannelInGroup(searchOptions, reqChannel, chGroups, currGroupI+1);
}
})
.catch(function(e) {
console.log(e);
})
}
};
app.get("/", function (request, response) {
response.sendFile(__dirname + '/views/index.html');
});
// listen for requests :)
var listener = app.listen(process.env.PORT, function () {
console.log('Your app is listening on port ' + listener.address().port);
});