-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathL_Emby1.lua
1935 lines (1786 loc) · 70.1 KB
/
L_Emby1.lua
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--[[
L_Emby1.lua - Core module for Emby
Copyright 2017,2018,2019 Patrick H. Rigney, All Rights Reserved.
This file is part of Emby. For license information, see LICENSE at https://github.com/toggledbits/Emby
--]]
--luacheck: std lua51,module,read globals luup,ignore 542 611 612 614 111/_,no max line length
module("L_Emby1", package.seeall)
local debugMode = false
local _PLUGIN_ID = 9181
local _PLUGIN_NAME = "Emby"
local _PLUGIN_VERSION = "1.3"
local _PLUGIN_URL = "https://www.toggledbits.com/emby"
local _CONFIGVERSION = 19192
local math = require "math"
local string = require "string"
local socket = require "socket"
local http = require "socket.http"
local ltn12 = require "ltn12"
local json = require "dkjson"
local MYSID = "urn:toggledbits-com:serviceId:Emby1"
local MYTYPE = "urn:schemas-toggledbits-com:device:Emby:1"
local SERVERSID = "urn:toggledbits-com:serviceId:EmbyServer1"
local SERVERTYPE = "urn:schemas-toggledbits-com:device:EmbyServer:1"
local SESSIONSID = "urn:toggledbits-com:serviceId:EmbySession1"
local SESSIONTYPE = "urn:schemas-toggledbits-com:device:EmbySession:1"
local tickTasks = {}
local maxEvents = 50
local devData = {}
local runStamp = 0
local pluginDevice = 0
local isALTUI = false
local isOpenLuup = false
local deferClear = false
local DISCOVERYPERIOD = 15
local function dump(t, seen)
if t == nil then return "nil" end
if seen == nil then seen = {} end
local sep = ""
local str = "{ "
for k,v in pairs(t) do
local val
if type(v) == "table" then
if seen[v] then val = "(recursion)"
else
seen[v] = true
val = dump(v, seen)
end
elseif type(v) == "string" then
if #v > 255 then val = string.format("%q", v:sub(1,252).."...")
else val = string.format("%q", v) end
elseif type(v) == "number" and (math.abs(v-os.time()) <= 86400) then
val = tostring(v) .. "(" .. os.date("%x.%X", v) .. ")"
else
val = tostring(v)
end
str = str .. sep .. k .. "=" .. val
sep = ", "
end
str = str .. " }"
return str
end
local function L(msg, ...) -- luacheck: ignore 212
local str
local level = 50
if type(msg) == "table" then
str = tostring(msg.prefix or _PLUGIN_NAME) .. ": " .. tostring(msg.msg)
level = msg.level or level
else
str = _PLUGIN_NAME .. ": " .. tostring(msg)
end
str = string.gsub(str, "%%(%d+)", function( n )
n = tonumber(n, 10)
if n < 1 or n > #arg then return "nil" end
local val = arg[n]
if type(val) == "table" then
return dump(val)
elseif type(val) == "string" then
return string.format("%q", val)
elseif type(val) == "number" and math.abs(val-os.time()) <= 86400 then
return tostring(val) .. "(" .. os.date("%x.%X", val) .. ")"
end
return tostring(val)
end
)
luup.log(str, level)
end
local function D(msg, ...)
if debugMode then
L( { msg=msg,prefix=(_PLUGIN_NAME .. "(debug)") }, ... )
end
end
local function checkVersion(dev)
local ui7Check = luup.variable_get(MYSID, "UI7Check", dev) or ""
if isOpenLuup then
return true
end
if luup.version_branch == 1 and luup.version_major == 7 then
if ui7Check == "" then
-- One-time init for UI7 or better
luup.variable_set( MYSID, "UI7Check", "true", dev )
end
return true
end
L({level=1,msg="firmware %1 (%2.%3.%4) not compatible"}, luup.version,
luup.version_branch, luup.version_major, luup.version_minor)
return false
end
local function urlencode( str )
str = tostring(str):gsub( "([^A-Za-z0-9_ -])", function( ch ) return string.format("%%%02x", string.byte( ch ) ) end )
return str:gsub( " ", "+" )
end
local function split( str, sep )
if sep == nil then sep = "," end
local arr = {}
if #str == 0 then return arr, 0 end
local rest = string.gsub( str or "", "([^" .. sep .. "]*)" .. sep, function( m ) table.insert( arr, m ) return "" end )
table.insert( arr, rest )
return arr, #arr
end
-- Shallow copy
local function shallowCopy( t )
local r = {}
for k,v in pairs(t) do
r[k] = v
end
return r
end
-- Array to map, where f(elem) returns key[,value]
local function map( arr, f, res )
res = res or {}
for _,x in ipairs( arr ) do
if f then
local k,v = f( x )
res[k] = (v == nil) and x or v
else
res[x] = x
end
end
return res
end
-- Initialize a variable if it does not already exist.
local function initVar( name, dflt, dev, sid )
assert( dev ~= nil, "initVar requires dev" )
assert( sid ~= nil, "initVar requires SID for "..name )
local currVal = luup.variable_get( sid, name, dev )
if currVal == nil then
luup.variable_set( sid, name, tostring(dflt), dev )
return tostring(dflt)
end
return currVal
end
-- Set variable, only if value has changed.
local function setVar( sid, name, val, dev )
val = (val == nil) and "" or tostring(val)
local s = luup.variable_get( sid, name, dev ) or ""
-- D("setVar(%1,%2,%3,%4) old value %5", sid, name, val, dev, s )
if s ~= val then
luup.variable_set( sid, name, val, dev )
end
return s
end
-- Get numeric variable, or return default value if not set or blank
local function getVarNumeric( name, dflt, dev, sid )
assert( dev ~= nil )
assert( name ~= nil )
assert( sid ~= nil )
local s = luup.variable_get( sid, name, dev ) or ""
if s == "" then return dflt end
s = tonumber(s)
return (s == nil) and dflt or s
end
-- Add an event to the event list. Prune the list for size.
local function addEvent( t )
local p = shallowCopy(t)
if p.event == nil then L({level=1,msg="addEvent(%1) missing 'event'"},t) end
if p.dev == nil then L({level=2,msg="addEvent(%1) missing 'dev'"},t) end
p.when = os.time()
p.time = os.date("%Y%m%dT%H%M%S")
local dev = p.dev or pluginDevice
if devData[tostring(dev)] == nil then devData[tostring(dev)] = {} end
devData[tostring(dev)].eventList = devData[tostring(dev)].eventList or {}
table.insert( devData[tostring(dev)].eventList, p )
if #devData[tostring(dev)].eventList > maxEvents then table.remove(devData[tostring(dev)].eventList, 1) end
end
-- Enabled?
local function isEnabled( dev )
return getVarNumeric( "Enabled", 1, dev, MYSID ) ~= 0
end
-- Schedule a timer tick for a future (absolute) time. If the time is sooner than
-- any currently scheduled time, the task tick is advanced; otherwise, it is
-- ignored (as the existing task will come sooner), unless repl=true, in which
-- case the existing task will be deferred until the provided time.
local function scheduleTick( tinfo, timeTick, flags )
D("scheduleTick(%1,%2,%3)", tinfo, timeTick, flags)
flags = flags or {}
local function nulltick(d,p) L({level=1, "nulltick(%1,%2)"},d,p) end
local tkey = tostring( type(tinfo) == "table" and tinfo.id or tinfo )
assert(tkey ~= nil)
if ( timeTick or 0 ) == 0 then
D("scheduleTick() clearing task %1", tinfo)
tickTasks[tkey] = nil
return
elseif tickTasks[tkey] then
-- timer already set, update
tickTasks[tkey].func = tinfo.func or tickTasks[tkey].func
tickTasks[tkey].args = tinfo.args or tickTasks[tkey].args
tickTasks[tkey].info = tinfo.info or tickTasks[tkey].info
if tickTasks[tkey].when == nil or timeTick < tickTasks[tkey].when or flags.replace then
-- Not scheduled, requested sooner than currently scheduled, or forced replacement
tickTasks[tkey].when = timeTick
end
D("scheduleTick() updated %1", tickTasks[tkey])
else
assert(tinfo.owner ~= nil)
assert(tinfo.func ~= nil)
tickTasks[tkey] = { id=tostring(tinfo.id), owner=tinfo.owner, when=timeTick, func=tinfo.func or nulltick, args=tinfo.args or {},
info=tinfo.info or "" } -- new task
D("scheduleTick() new task %1 at %2", tinfo, timeTick)
end
-- If new tick is earlier than next plugin tick, reschedule
tickTasks._plugin = tickTasks._plugin or {}
if tickTasks._plugin.when == nil or timeTick < tickTasks._plugin.when then
tickTasks._plugin.when = timeTick
local delay = timeTick - os.time()
if delay < 1 then delay = 1 end
D("scheduleTick() rescheduling plugin tick for %1", delay)
runStamp = runStamp + 1
luup.call_delay( "embyTaskTick", delay, runStamp )
end
return tkey
end
-- Schedule a timer tick for after a delay (seconds). See scheduleTick above
-- for additional info.
local function scheduleDelay( tinfo, delay, flags )
D("scheduleDelay(%1,%2,%3)", tinfo, delay, flags )
if delay < 1 then delay = 1 end
return scheduleTick( tinfo, delay+os.time(), flags )
end
local function gatewayStatus( m )
setVar( MYSID, "Message", m or "", pluginDevice )
end
local function getChildDevices( typ, parent, filter )
parent = parent or pluginDevice
local res = {}
for k,v in pairs(luup.devices) do
if v.device_num_parent == parent and ( typ == nil or v.device_type == typ ) and ( filter==nil or filter(k, v) ) then
table.insert( res, k )
end
end
return res
end
--[[ Prep for adding new children via the luup.chdev mechanism. The existingChildren
table (array) should contain device IDs of existing children that will be
preserved. Any existing child not listed will be dropped. If the table is nil,
all existing children in luup.devices will be preserved.
--]]
local function prepForNewChildren( existingChildren )
D("prepForNewChildren(%1)", existingChildren)
local dfMap = { [SERVERTYPE]="D_EmbyServer1.xml", [SESSIONTYPE]="D_EmbySession1.xml" }
if existingChildren == nil then
existingChildren = {}
for k,v in pairs( luup.devices ) do
if v.device_num_parent == pluginDevice then
assert(dfMap[v.device_type]~=nil, "BUG: device type missing from dfMap: "..v.device_type)
table.insert( existingChildren, k )
end
end
end
local ptr = luup.chdev.start( pluginDevice )
for _,k in ipairs( existingChildren ) do
local v = luup.devices[k]
assert(v)
assert(v.device_num_parent == pluginDevice)
D("prepForNewChildren() appending existing child %1 (%2/%3)", v.description, k, v.id)
luup.chdev.append( pluginDevice, ptr, v.id, v.description, "",
dfMap[v.device_type] or error("Invalid device type in child "..k),
"", "", false )
end
return ptr, existingChildren
end
local function doRequest(method, url, tHeaders, body, dev)
D("doRequest(%1,%2,%3,%4,%5)", method, url, tHeaders, body, dev)
assert(dev ~= nil)
method = method or "GET"
local headers = tHeaders and shallowCopy(tHeaders) or {}
if headers['X-Application'] == nil then headers['X-Application'] = "ToggledBits-Vera-Emby/" .. _PLUGIN_VERSION end
if headers['Accepts'] == nil then headers['Accepts'] = "application/json" end
-- A few other knobs we can turn
local timeout = getVarNumeric("Timeout", 30, dev, MYSID) -- ???
-- local maxlength = getVarNumeric("MaxLength", 262144, dev, DEVICESID) -- ???
-- Build post/put data
local src
if type(body) == "table" then
body = json.encode(body)
headers["Content-Type"] = "application/json"
D("doRequest() converted table to JSON body %1", body)
else
-- Caller should set Content-Type
end
headers["Content-Length"] = string.len(body or "")
if body ~= nil then
src = ltn12.source.string(body)
end
--[[
-- Basic Auth
local baUser = luup.variable_get( DEVICESID, "HTTPUser", dev ) or ""
if baUser ~= "" then
local baPass = luup.variable_get( DEVICESID, "HTTPPassword", dev ) or ""
baUser = baUser .. ":" .. baPass
local mime = require("mime")
headers.Authorization = "Basic " + mime.b64( baUser )
end
--]]
-- Make the request.
local respBody, httpStatus
local r = {}
http.TIMEOUT = timeout -- N.B. http not https, regardless
D("doRequest() requesting %2 %1, headers=%3", url, method, headers)
respBody, httpStatus = http.request{
url = url,
source = src,
sink = ltn12.sink.table(r),
method = method,
headers = headers,
redirect = false
}
D("doRequest() request returned httpStatus=%1, respBody=%2", httpStatus, respBody)
-- Since we're using the table sink, concatenate chunks to single string.
respBody = table.concat(r)
D("doRequest() response HTTP status %1, body=" .. respBody, httpStatus) -- use concat to avoid quoting
-- Handle special errors from socket library
if tonumber(httpStatus) == nil then
respBody = httpStatus
httpStatus = 500
end
-- See what happened. Anything 2xx we reduce to 200 (OK).
if httpStatus >= 200 and httpStatus <= 299 then
-- Success response with no data, take shortcut.
return true, respBody, 200
end
if httpStatus == 401 then L{level=1,msg="API responded with authentication failure; check access token."} end
return false, respBody, httpStatus
end
-- API request to server via local address
local function serverRequest( method, path, params, headers, body, dev )
D("serverRequest(%1,%2,%3,%4,%5,%6)", method, path, params, headers, body, dev)
assert(dev~=nil and luup.devices[dev].device_type==SERVERTYPE)
local ea = {}
for k,v in pairs(params or {}) do
table.insert( ea, k .. "=" .. urlencode(tostring(v)) )
end
if not (params and params.api_key) then
local key = luup.variable_get( SERVERSID, "APIKey", dev ) or ""
if key:find("^[xX]*$") then return false, nil, 401 end
table.insert( ea, "api_key=" .. urlencode(key) )
end
local fullurl = luup.variable_get( SERVERSID, "LocalAddress", dev ) or "http://localhost:8096"
fullurl = fullurl .. "/emby" .. path .. "?" .. table.concat( ea, "&" )
local success, resp, httpstat = doRequest( method or "GET", fullurl, headers, body, dev )
D("serverRequest() doRequest returned %1,%2,%3", success, resp, httpstat)
if success then
if (resp or "") == "" then
-- Empty response, which is OK
return success, nil, 200
end
if debugMode then
-- luup.log("Decoding json " .. tostring(#resp) .. " bytes:",2)
luup.log(resp,2)
local f = io.open( "/etc/cmh-ludl/emby-lastreply.json", "w" )
if f then f:write(resp) f:close() end
end
local data,pos,err = json.decode( resp )
if err then
D("serverRequest() response data could not be decoded at %1, %2 in %3", pos, err, resp)
return false, nil, 500
end
return true, data, httpstat
end
return success, resp, httpstat
end
local function isSessionCommandSupported( cmd, sessdev )
D("isSessionCommandSupported(%1,%2)", cmd, sessdev)
assert(luup.devices[sessdev] and luup.devices[sessdev].device_type == SESSIONTYPE)
local s = luup.variable_get( SESSIONSID, "SupportedCommands", sessdev ) or ""
if s == "" then return true end
return string.find( ","..s..",", ","..cmd.."," ) ~= nil
end
-- Initialize session
local function initSession( sess )
initVar( "Server", "0", sess, SESSIONSID )
initVar( "Offline", "1", sess, SESSIONSID )
initVar( "Visibility", "auto", sess, SESSIONSID )
initVar( "DeviceId", "", sess, SESSIONSID )
initVar( "DeviceName", "", sess, SESSIONSID )
initVar( "Client", "", sess, SESSIONSID )
initVar( "Version", "", sess, SESSIONSID )
initVar( "VolumePercent", "100", sess, SESSIONSID )
initVar( "DisplayPosition", "", sess, SESSIONSID )
initVar( "Mute", "0", sess, "urn:micasaverde-com:serviceId:Volume1" )
initVar( "SmartVolume", "0", sess, SESSIONSID )
initVar( "SmartMute", "0", sess, SESSIONSID )
initVar( "PlayingItemId", "", sess, SESSIONSID )
initVar( "PlayingItemType", "", sess, SESSIONSID )
initVar( "DisplayStatus", "", sess, SESSIONSID )
initVar( "TransportState", "STOPPED", sess, SESSIONSID )
initVar( "SmartSkipDefault", "", sess, SESSIONSID )
initVar( "SmartSkipGrace", "", sess, SESSIONSID )
if getVarNumeric( "Version", 0, sess, SESSIONSID ) < 000101 then
luup.attr_set( 'category_num', 15, sess )
end
setVar( SESSIONSID, "Version", _CONFIGVERSION, sess )
end
local function clearPlayingState( child )
setVar( SESSIONSID, "PlayingItemId", "", child )
setVar( SESSIONSID, "PlayingItemType", "", child )
setVar( SESSIONSID, "PlayingItemMediaType", "", child )
setVar( SESSIONSID, "PlayingItemTitle", "", child )
setVar( SESSIONSID, "PlayingItemArtist", "", child )
setVar( SESSIONSID, "PlayingItemAlbum", "", child )
setVar( SESSIONSID, "PlayingItemAlbumId", "", child )
setVar( SESSIONSID, "PlayingItemPosition", "0", child )
setVar( SESSIONSID, "PlayingItemRuntime", "0", child )
setVar( SESSIONSID, "PlayingItemChapters", "", child )
setVar( SESSIONSID, "DisplayPosition", "--:-- / --:--", child )
setVar( SESSIONSID, "DisplayStatus", "", child )
setVar( SESSIONSID, "TransportState", "STOPPED", child )
end
local function clearServerSessions( server )
local children = getChildDevices( SESSIONTYPE, nil, function( child ) return getVarNumeric( "Server", 0, child, SESSIONSID ) == server end )
for _,k in ipairs( children ) do
clearPlayingState( k )
end
end
local function clearChildren( pdev )
local children = getChildDevices( SERVERTYPE, pdev )
for _,k in ipairs( children ) do
clearServerSessions( k )
setVar( SERVERSID, "Message", "Stopped", k )
end
end
local function updateSession( sdata, session, server )
D("updateSession(%1,%2,%3)", "sdata", session, server)
setVar( SESSIONSID, "Offline", 0, session )
setVar( SESSIONSID, "Server", server, session )
setVar( SESSIONSID, "DeviceName", sdata.DeviceName, session )
setVar( SESSIONSID, "DeviceId", sdata.DeviceId, session )
setVar( SESSIONSID, "Version", sdata.ApplicationVersion, session )
setVar( SESSIONSID, "Client", sdata.Client, session )
setVar( SESSIONSID, "LastActivity", sdata.LastActivityDate, session )
D("updateSession() %1 name %2 (%3) PlayState %4", session, sdata.DeviceName, sdata.Client, sdata.PlayState)
if sdata.PlayState then
setVar( SESSIONSID, "VolumePercent", sdata.PlayState.VolumeLevel or "", session )
setVar( "urn:micasaverde-com:serviceId:Volume1", "Mute", sdata.PlayState.IsMuted and 1 or 0, session )
else
setVar( SESSIONSID, "VolumePercent", "", session )
setVar( "urn:micasaverde-com:serviceId:Volume1", "Mute", 0, session )
end
if sdata.SupportedCommands then
setVar( SESSIONSID, "SupportedCommands", table.concat( sdata.SupportedCommands, "," ), session )
else
setVar( SESSIONSID, "SupportedCommands", "", session )
end
if sdata.PlayableMediaTypes then
setVar( SESSIONSID, "PlayableMediaTypes", table.concat( sdata.PlayableMediaTypes, "," ), session )
else
setVar( SESSIONSID, "PlayableMediaTypes", "", session )
end
if sdata.NowPlayingItem then
D("updateSession() %1 playing %2", sdata.DeviceName, sdata.NowPlayingItem)
setVar( SESSIONSID, "PlayingItemId", sdata.NowPlayingItem.Id, session )
setVar( SESSIONSID, "PlayingItemType", sdata.NowPlayingItem.Type, session )
setVar( SESSIONSID, "PlayingItemMediaType", sdata.NowPlayingItem.MediaType, session )
setVar( SESSIONSID, "PlayingItemTitle", sdata.NowPlayingItem.Name, session )
setVar( SESSIONSID, "PlayingItemArtist", sdata.NowPlayingItem.AlbumArtist, session )
setVar( SESSIONSID, "PlayingItemAlbumId", sdata.NowPlayingItem.AlbumId, session )
setVar( SESSIONSID, "PlayingItemAlbum", sdata.NowPlayingItem.Album, session )
local status = sdata.NowPlayingItem.Name
if sdata.NowPlayingItem.MediaType == "Audio" then
status = status .. " (" .. (sdata.NowPlayingItem.Album or "?")
if ( sdata.NowPlayingItem.AlbumArtist or "" ) ~= "" then
status = status .. " - " .. sdata.NowPlayingItem.AlbumArtist
end
status = status .. ")"
end
setVar( SESSIONSID, "DisplayStatus", status, session )
local runtime = math.floor( (sdata.NowPlayingItem.RunTimeTicks or 0) / 10000 ) / 1000 -- frac seconds
setVar( SESSIONSID, "PlayingItemRuntime", runtime, session )
-- For video media, store any chapter data for "SmartSkip"
if (sdata.NowPlayingItem.MediaType or ""):lower() == "video" and #(sdata.NowPlayingItem.Chapters or {}) > 0 then
setVar( SESSIONSID, "PlayingItemChapters", json.encode( sdata.NowPlayingItem.Chapters ), session )
else
setVar( SESSIONSID, "PlayingItemChapters", "", session )
end
if sdata.PlayState then
local ts = sdata.PlayState.IsPaused and "PAUSED" or "PLAYING"
setVar( SESSIONSID, "TransportState", ts, session )
local pos = math.floor( (sdata.PlayState.PositionTicks or 0) / 10000 ) / 1000
setVar( SESSIONSID, "PlayingItemPosition", pos, session )
local dp = string.format( "%02d:%02d / %02d:%02d", math.floor( pos / 60 ), math.floor( pos ) % 60,
math.floor( runtime / 60 ), math.floor( runtime ) % 60 )
setVar( SESSIONSID, "DisplayPosition", dp, session )
setVar( SESSIONSID, "ResumePoint", sdata.NowPlayingItem.Id .. "," .. (sdata.PlayState.PositionTicks or 0), session )
setVar( SESSIONSID, "ResumeTitle", sdata.NowPlayingItem.Name or "", session )
end
else
D("updateSession() %1 not playing", sdata.DeviceName)
clearPlayingState( session )
end
end
local function matchesFilterList( str, lstr )
if ( lstr or "" ) == "" then return false end
local fl = split( lstr, "|" )
for _,f in ipairs( fl or {} ) do
if str:match( f ) then return true end
end
return false
end
local function isControllableSession( sess, server )
if not sess.SupportsRemoteControl then return false, 1 end
local client = tostring( sess.Client or "" ):lower()
if client:match( "^vera emby" ) then return false, 2 end
local s = luup.variable_get( SERVERSID, "FilterClients", server ) or ""
if matchesFilterList( client, s ) then return false, 3 end
s = luup.variable_get( SERVERSID, "FilterDeviceNames", server ) or ""
if matchesFilterList( tostring( sess.DeviceName or "" ):lower(), s ) then return false, 4 end
return true
end
local function updateSessions( server, taskid )
assert(taskid)
local anyPlaying = false
local ok, data, httpstat = serverRequest( "GET", "/Sessions", nil, nil, nil, server )
if not ok then
luup.set_failure( 1, server )
if httpstat == 401 then
-- Auth fail, can't recover.
setVar( SERVERSID, "Message", "Auth fail; re-do login.", server )
L({level=1,msg="Authentication failure with %1 (#%2). Redo login to obtain new token."},
luup.devices[server].description, server)
return
end
D("updateSessions() failed session query for %1", server)
local lastup = getVarNumeric( "LastUpdate", 0, server, SERVERSID )
local delta = os.time() - lastup
if delta < 120 then
setVar( SERVERSID, "Message", "Unreachable; retrying...", server )
else
clearServerSessions( server )
setVar( SERVERSID, "Message", "Down since " .. os.date("%x %X", lastup), server )
end
if delta >= 600 then L({level=2,msg="%1 (%2) unreachable since %3."}, luup.devices[server].description, server, os.date("%x %X", lastup)) end
scheduleDelay( taskid, (delta >= 600) and 120 or 30 )
return
else
luup.set_failure( 0, server )
setVar( SERVERSID, "LastUpdate", os.time(), server )
-- Create a map of child sessions for this server.
local cs = getChildDevices( SESSIONTYPE, nil, function( dev, _ )
local ps = getVarNumeric( "Server", 0, dev, SESSIONSID )
return ps == server
end )
local childSessions = map( cs, function( obj ) return luup.devices[obj].id end )
-- Iterate over response data
D("updateSessions() server returned %1 sessions", #(data or {}))
for _,sess in ipairs( data or {} ) do
if isControllableSession( sess, server ) then
D("updateSessions() updating session %1 (%2)", sess.DeviceName, sess.Id)
local child = childSessions[ sess.Id ]
if child then
-- luup.log(json.encode(sess),2)
childSessions[ sess.Id ] = nil
updateSession( sess, child, server )
anyPlaying = anyPlaying or ( sess.NowPlayingItem ~= nil )
local show = luup.variable_get( SESSIONSID, "Visibility", child ) or ""
if string.find(":show:hide:", show) then
luup.attr_set( "invisible", ( show == "hide" ) and "1" or "0", child )
elseif getVarNumeric( "HideIdle", 0, server, SERVERSID ) ~= 0 then
luup.attr_set( "invisible", ( sess.NowPlayingItem == nil ) and "1" or "0", child )
else
luup.attr_set( "invisible", "0", child )
end
else
L({level=2,msg="Child device not found for session %1 (%2) on %3 (%4), a %5 %6; you may need to run inventory on this server, or the child is not supported."},
sess.Id, sess.DeviceName, luup.devices[server].description, server,
sess.Client, sess.ApplicationVersion)
end
end
end
for k,v in pairs( childSessions ) do
D("updateSessions() clearing offline session %1 (dev #%2 %3)", k,
v, (luup.devices[v] or {}).description)
if setVar( SESSIONSID, "Offline", 1, v ) ~= "1" then
L({level=3,msg="Marking %1 (%2) offline (server return no data for active session request)"},
(luup.devices[v] or {}).description, v)
end
clearPlayingState( v )
setVar( SESSIONSID, "DisplayStatus", "Offline", v )
local show = luup.variable_get( SESSIONSID, "Visibility", v ) or ""
if string.find(":show:hide:", show) then
luup.attr_set( "invisible", ( show == "hide" ) and "1" or "0", v )
elseif getVarNumeric( "HideOffline", 0, server, SERVERSID ) ~= 0 then
luup.attr_set( "invisible", "1", v )
else
luup.attr_set( "invisible", "0", v )
end
end
end
-- If not playing and haven't played in 60 seconds, idle back.
local now = os.time()
local lastPlaying = getVarNumeric( "LastPlaying", 0, server, SERVERSID )
D("updateSession() server %1 lastPlaying %2 now %3 anyPlaying %4", server, lastPlaying, now, anyPlaying)
local idleTick = ( not anyPlaying ) and ( lastPlaying < (now-60) )
if anyPlaying then setVar( SERVERSID, "LastPlaying", now, server ) end
-- Reschedule for update -- ??? TIMING FIXME?
setVar( SERVERSID, "Message", idleTick and "Idle" or "Active", server )
local delay = getVarNumeric( idleTick and "SessionUpdateIntervalIdle" or "SessionUpdateIntervalPlaying", idleTick and 60 or 5, server, SERVERSID )
scheduleDelay( taskid, delay )
end
-- Inventory sessions using local server request
local function inventorySessions( server )
L("Launching session inventory for %1 (%2)", luup.devices[server].description, server)
local ok, data, httpstat = serverRequest( "GET", "/Sessions", nil, nil, nil, server )
if not ok then
D("inventorySessions() failed session query for %1, will retry...", server)
luup.set_failure( 1, server )
if httpstat == 401 then
-- Auth fail, can't recover.
clearServerSessions( server )
setVar( SERVERSID, "Message", "Auth fail; re-do login.", server )
L({level=1,msg="Authentication failure with %1 (#%2). Redo login to obtain new token."},
luup.devices[server].description, server)
return
end
L({level=2,msg="Server unreachable for session inventory (%1). Scheduling retry."}, httpstat)
setVar( SERVERSID, "Message", "Unreachable; retrying...", server )
scheduleDelay( { id=tostring(server), owner=server, info="inventoryretry", func=inventorySessions }, 120 )
return
else
luup.set_failure( 0, server )
-- Returns array (hopefully) of sessions (as dev nums) belonging to this server.
local cs = getChildDevices( SESSIONTYPE, nil, function( dev, _ )
local ps = getVarNumeric( "Server", 0, dev, SESSIONSID )
return ps == server
end )
-- Create map
local childSessions = map( cs, function( obj ) return luup.devices[obj].id end )
D("inventorySessions() childSessions=%1", childSessions)
local newSessions = {}
for _,sess in ipairs( data or {} ) do
local canDo,reason = isControllableSession( sess, server )
if not canDo then
L("Session %1 (%2) client %3 version %4, not supported/filtered (%5)",
sess.DeviceName, sess.Id, sess.Client, sess.ApplicationVersion, reason)
else
local child = childSessions[ sess.Id ]
if not child then
L("New session %1 (%2), client %3 version %4 (will be added)",
sess.DeviceName, sess.Id, sess.Client, sess.ApplicationVersion)
table.insert( newSessions, sess )
else
L("Existing session %1 (%2), client %3 version %4 (updating)",
sess.DeviceName, sess.Id, sess.Client, sess.ApplicationVersion)
childSessions[ sess.Id ] = nil -- remove from map
initSession( child )
updateSession( sess, child, server )
end
end
end
-- Anything left in map wasn't returned by query, so assume offline.
for k,v in pairs( childSessions ) do
L("Session %3 (dev #%2, id %1) missing from server response; marking offline.",
k, v, (luup.devices[v] or {}).description)
clearPlayingState( v )
setVar( SESSIONSID, "Offline", 1, v )
setVar( SESSIONSID, "DisplayStatus", "Offline", v )
if getVarNumeric( "HideOffline", 0, server, SERVERSID ) ~= 0 then
luup.attr_set( "invisible", "1", v )
end
end
-- If we have newly discovered sessions, add them as children (causes Luup restart)
if #newSessions > 0 then
addEvent{ dev=server, event="inventory", new=#newSessions }
L({level=2,msg="Discovered %1 new sessions on %2 (#%3), adding and restarting..."}, #newSessions,
luup.devices[server].description, server)
local ptr = prepForNewChildren()
-- Create children for newly-discovered session(s)
for _,sess in ipairs( newSessions ) do
L("Appending session %1 (%2) client %3", sess.DeviceName, sess.Id, sess.Client)
luup.chdev.append( pluginDevice, ptr, sess.Id, sess.DeviceName or sess.Id, "",
"D_EmbySession1.xml",
"",
SESSIONSID .. ",Server="..server,
false )
end
-- Finished
L({level=2,msg="New sessions have been created for %1 (%2), a Luup reload will occur!"},
luup.devices[server].description, server)
luup.chdev.sync( pluginDevice, ptr ) -- should reload
end
end
-- Reschedule for update
scheduleDelay( { id=tostring(server), owner=server, info="sessionupdate", func=updateSessions }, 5 )
end
-- One-time init for server
local function initServer( server )
D("initServer(%1)", server)
initVar( "Message", "", server, SERVERSID )
initVar( "LastUpdate", "0", server, SERVERSID )
initVar( "APIKey", "", server, SERVERSID )
initVar( "UserId", "", server, SERVERSID )
initVar( "SessionUpdateIntervalIdle", "", server, SERVERSID )
initVar( "SessionUpdateIntervalPlaying", "", server, SERVERSID )
initVar( "SmartSkipDefault", "", server, SERVERSID )
initVar( "SmartSkipGrace", "", server, SERVERSID )
initVar( "HideOffline", "0", server, SERVERSID )
initVar( "HideIdle", "0", server, SERVERSID )
initVar( "Bookmarks", "{}", server, SERVERSID )
initVar( "FilterClients", "^emby mobile", server, SERVERSID )
initVar( "FilterDeviceNames", "", server, SERVERSID )
if getVarNumeric( "Version", 0, server, SERVERSID ) < 000101 then
luup.attr_set( 'category_num', 1, server )
end
setVar( SERVERSID, "Version", _CONFIGVERSION, server )
end
-- Start server
local function startServer( server )
D("startServer(%1)", server)
local apikey = luup.variable_get( SERVERSID, "APIKey", server ) or ""
if string.find( apikey, "^[xX]*$" ) then
addEvent{ dev=server, event="startfail", reason="Not authenticated" }
setVar( SERVERSID, "Message", "Please log in.", server )
luup.set_failure( 1, server )
return
end
local ok, data, httpstat = serverRequest( "GET", "/System/Info", nil, nil, nil, server )
if not ok then
luup.set_failure( 1, server )
if httpstat == 401 then
addEvent{ dev=server, event="startfail", reason="Invalid auth data" }
setVar( SERVERSID, "Message", "Can't authenticate. Check API Key.", server )
luup.set_failure( 1, server )
else
addEvent{ dev=server, event="startfail", reason="Query fail: "..tostring(httpstat) }
setVar( SERVERSID, "Message", "Can't get system data (" .. tostring(httpstat) .. "), will retry later", server )
scheduleDelay( { id=tostring(server), info="deferstart", owner=server, func=startServer }, getVarNumeric( "RetryInterval", 120, pluginDevice, MYSID ) )
end
else
-- Do something...
setVar( SERVERSID, "ServerName", data.ServerName or "", server )
setVar( SERVERSID, "Version", data.Version or "", server )
setVar( SERVERSID, "Platform", data.OperatingSystemDisplayName or data.OperatingSystem, server )
setVar( SERVERSID, "OS", data.OperatingSystem, server )
local okmsg = string.format("Version %s on %s", data.Version or "?", data.OperatingSystem or "?")
local id = luup.attr_get( "altid", server )
if data.Id and id ~= data.Id then
addEvent{ dev=server, event="startfail", reason="Server ID changed from "..tostring(id).." to "..tostring(data.Id) }
L({level=2,msg="Emby server at %1 ID changed, was %2 now %3, repairing..."}, data.ServerName, id, data.Id)
setVar( SERVERSID, "Message", "ID mismatch; attempting repair.", server )
luup.set_failure( 1, server )
luup.attr_set( "altid", data.Id, server )
luup.reload()
return
end
-- Check server software version
local pt = split( tostring(data.Version or ""), "%." )
local rev = (tonumber(pt[1]) or 0) + (tonumber(pt[2]) or 0) / 10
D("startServer() checking server %1 software rev %2", data.ServerName, rev)
if rev < 3.4 then
L({level=1,msg="Emby server %1 unsupported; please upgrade to 3.4 or higher."}, data.ServerName)
addEvent{ dev=server, event="startfail", reason="Server version unsupported " .. tostring(data.Version) }
setVar( SERVERSID, "Message", "Server version unsupported", server )
luup.set_failure( 1, server )
return
end
-- Launch!
addEvent{ dev=server, event="start", message="Successful startup" }
luup.set_failure( 0, server )
if getVarNumeric( "StartupInventory", 1, pluginDevice, MYSID ) ~= 0 then
setVar( SERVERSID, "Message", "Taking session inventory...", server )
inventorySessions( server )
else
scheduleDelay( { id=tostring(server), owner=server, info="sessionupdate", func=updateSessions }, 5 )
end
setVar( SERVERSID, "Message", okmsg, server )
end
end
-- Check servers
local function startServers( dev )
D("startServers()")
local servers = getChildDevices( SERVERTYPE, dev )
for _,server in ipairs( servers ) do
luup.variable_set( SERVERSID, "Message", "Starting...", server)
initServer( server )
startServer( server )
end
end
--[[
D I S C O V E R Y A N D C O N N E C T I O N
--]]
local function askLuci(p)
D("askLuci(%1)", p)
local uci = require("uci")
if uci then
local ctx = uci.cursor(nil, "/var/state")
if ctx then
return ctx:get(unpack((split(p,"%."))))
else
D("askLuci() can't get context")
end
else
D("askLuci() no UCI module")
end
return nil
end
-- Query UCI for WAN IP4 IP
local function getSystemIP4Addr( dev ) -- luacheck: ignore 212
local vera_ip = askLuci("network.wan.ipaddr")
D("getSystemIP4Addr() got %1 from Luci", vera_ip)
if not vera_ip then
-- Fallback method
local p = io.popen("/usr/bin/GetNetworkState.sh wan_ip")
vera_ip = p:read("*a") or ""
p:close()
D("getSystemIP4Addr() got system ip4addr %1 using fallback", vera_ip)
end
return vera_ip:gsub("%c","")
end
-- Query UCI for WAN IP4 netmask
local function getSystemIP4Mask( dev ) -- luacheck: ignore 212
local mask = askLuci("network.wan.netmask");
D("getSystemIP4Mask() got %1 from Luci", mask)
if not mask then
-- Fallback method
local p = io.popen("/usr/bin/GetNetworkState.sh wan_netmask")
mask = p:read("*a") or ""
p:close()
D("getSystemIP4Addr() got system ip4mask %1 using fallback", mask)
end
return mask:gsub("%c","")
end
-- Compute broadcast address (IP4)
local function getSystemIP4BCast( dev )
local broadcast = luup.variable_get( MYSID, "DiscoveryBroadcast", dev ) or ""
if broadcast ~= "" then
return broadcast
end
if isOpenLuup then
gatewayStatus( "openLuup must set DiscoveryBroadcast first" )
error("You must set DiscoveryBroadcast in the Emby Plugin device to your network broadcast address.")
end
-- Do it the hard way.
local vera_ip = getSystemIP4Addr( dev )
local mask = getSystemIP4Mask( dev )
D("getSystemIP4BCast() sys ip %1 netmask %2", vera_ip, mask)
local a1,a2,a3,a4 = vera_ip:match("^(%d+)%.(%d+)%.(%d+)%.(%d+)")
local m1,m2,m3,m4 = mask:match("^(%d+)%.(%d+)%.(%d+)%.(%d+)")
local bit = require("bit")
-- Yeah. This is my jam, baby!
a1 = bit.bor(bit.band(a1,m1), bit.bxor(m1,255))
a2 = bit.bor(bit.band(a2,m1), bit.bxor(m2,255))
a3 = bit.bor(bit.band(a3,m3), bit.bxor(m3,255))
a4 = bit.bor(bit.band(a4,m4), bit.bxor(m4,255))
broadcast = string.format("%d.%d.%d.%d", a1, a2, a3, a4)
D("getSystemIP4BCast() computed broadcast address is %1", broadcast)
return broadcast
end
-- Process discovery responses
local function processDiscoveryResponses( dev )
if #(devData[tostring(dev)].discoveryResponses or {}) < 1 then
return
end
for _,ndev in ipairs(devData[tostring(dev)].discoveryResponses) do
if not ndev.Id then
end
end
local ptr,existing = prepForNewChildren()
local seen = map( existing, function( n ) return luup.devices[n].id end )
local hasNew = false
for _,ndev in ipairs(devData[tostring(dev)].discoveryResponses) do
if not seen[ndev.Id] then
L("Adding %1...", ndev.Name or ndev.Address)
luup.chdev.append( pluginDevice, ptr,
ndev.Id or ndev.Address, -- id (altid)
ndev.Name or ("Server@"..ndev.Address), -- description
"", -- device type
"D_EmbyServer1.xml", -- device file
"", -- impl file
SERVERSID .. ",LocalAddress=" .. ndev.Address, -- state vars
false -- embedded
)
hasNew = true
end
end
-- Close children. This will cause a Luup reload if something changed.
if hasNew then
L("New server(s) added, reload coming!")
gatewayStatus("New server(s) added, reloading...")
else
gatewayStatus("No new servers discovered.")
end
luup.chdev.sync( pluginDevice, ptr )
end
-- Handle discovery message
local function handleDiscoveryMessage( response, dev )
local data,pos,err = json.decode( response )
if data == nil or err then
D("handleDiscoveryMessage() JSON error at %1: %2", pos, err)
D("handleDiscoveryMessage() ignoring unparseable response: %1", response)
elseif data.Address ~= nil and data.Id ~= nil and data.Name ~= nil then
devData[tostring(dev)].discoveryResponses = devData[tostring(dev)].discoveryResponses or {}
table.insert( devData[tostring(dev)].discoveryResponses, data )
else
D("handleDiscoveryMessage() ignoring non-compliant response: %1", response)
end
end
-- Tick for UDP discovery.
local function udpDiscoveryTask( dev, taskid )
D("udpDiscoveryTask(%1,%2)", dev, taskid)