-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy path__init__.py
3021 lines (2557 loc) · 101 KB
/
__init__.py
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
############################################################################
# This plugin will allow external calls, that the plugin can then handle
# See TODO doc for more details
#
# Made by
# dane22 & digitalhigh...Plex Community members
#
############################################################################
from __future__ import print_function
import StringIO
import datetime
import glob
import os
import sys
import threading
import time
import xml.etree.ElementTree as ET
import xmltodict
from monitor import Monitor
from zipfile import ZipFile, ZIP_DEFLATED
import pychromecast
from helpers import PathHelper
from helpers.system import SystemHelper
from helpers.variable import pms_path
from pychromecast.controllers.media import MediaController
from pychromecast.controllers.plex import PlexController
from subzero.lib.io import FileIO
import log_helper
from flex_container import FlexContainer
from lib import Plex
UNICODE_MAP = {
65535: 'ucs2',
1114111: 'ucs4'
}
META_TYPE_IDS = {
1: "movie",
2: "show",
3: "season",
4: "episode",
8: "artist",
9: "album",
10: "track",
12: "extra",
13: "photo",
15: "playlist",
18: "collection"
}
TAG_TYPE_ARRAY = {
1: "genre",
4: "director",
5: "writer",
6: "actor"
}
META_XML_TAGS = {
"movie": "Video",
"episode": "Video",
"track": "Track",
"photo": "Photo",
"show": "Directory",
"season": "Directory",
"album": "Directory",
"actor": "Directory",
"director": "Directory",
"artist": "Directory",
"genre": "Directory",
"collection": "Directory",
"playlist": "Playlist"
}
META_TYPE_NAMES = dict(map(reversed, META_TYPE_IDS.items()))
DEFAULT_CONTAINER_SIZE = 100000
DEFAULT_CONTAINER_START = 0
DATE_STRUCTURE = "%Y-%m-%d %H:%M:%S"
os_platform = False
path = None
# Dummy Imports for PyCharm
# import Framework.context
# from Framework.api.objectkit import ObjectContainer, DirectoryObject
# from Framework.docutils import Plugin, HTTP, Log, Request
# from Framework.docutils import Data
Dict['version'] = '1.1.106'
NAME = 'Flex TV'
VERSION = '1.1.106'
APP_PREFIX = '/applications/Cast'
CAST_PREFIX = '/chromecast'
STAT_PREFIX = '/stats'
ICON = 'flextv.png'
ICON_CAST = 'icon-cast.png'
ICON_CAST_AUDIO = 'icon-cast_audio.png'
ICON_CAST_VIDEO = 'icon-cast_video.png'
ICON_CAST_GROUP = 'icon-cast_group.png'
ICON_CAST_REFRESH = 'icon-cast_refresh.png'
ICON_PLEX_CLIENT = 'icon-plex_client.png'
TEST_CLIP = 'test.mp3'
PLUGIN_IDENTIFIER = "com.plexapp.plugins.FlexTV"
# Start function
def Start():
Plugin.AddViewGroup("Details", viewMode="InfoList", mediaType="items")
distribution = None
test_path = sys.path[0].rstrip("\Shared")
pms_path_name = pms_path()
db_path = os.path.join(pms_path_name, "Plug-in Support", "Databases", "com.plexapp.plugins.library.db")
Log.Debug("Setting DB path to '%s'" % db_path)
os.environ['LIBRARY_DB'] = db_path
os.environ["PMS_PATH"] = pms_path_name
libraries_path = sys.path[0].rstrip("\Shared")
loaded = insert_paths(distribution, libraries_path)
if loaded:
Log.Debug("Paths should be loaded!")
os.environ["Loaded"] = "True"
else:
Log.Debug("Unable to load path")
os.environ["Loaded"] = "False"
ObjectContainer.title1 = NAME
DirectoryObject.thumb = R(ICON)
HTTP.CacheTime = 5
if Data.Exists('device_json') is not True:
UpdateCache()
ValidatePrefs()
CacheTimer()
RestartTimer()
def CacheTimer(mins=10):
Log.Debug("Cache timer started, updatings in %s minutes, man", mins)
Thread.CreateTimer(mins, CacheTimer)
UpdateCache()
def RestartTimer():
hours = 4
restart_time = hours * 60 * 60
Log.Debug("Restart timer started, plugin will re-start in %s hours.", hours)
Thread.CreateTimer(restart_time, DispatchRestart)
def UpdateCache():
Log.Debug("UpdateCache calleds")
if Data.Exists('last_cache'):
cache_date = 1545730073
try:
cache_date = float(Data.Load('last_cache'))
except ValueError, e:
Log.Debug("Value error again " + Data.Load('last_cache'))
now = float(time.time())
if now > cache_date:
time_diff = now - cache_date
time_mins = time_diff / 60
if time_mins > 10:
Log.Debug("Scanning devices, it's been %s minutes since our last scan." % time_mins)
scan_devices()
else:
Log.Debug("Devices will be re-cached in %s minutes" % round(10 - time_mins))
else:
time_diff = cache_date - now
time_mins = 10 - round(time_diff / 60)
Log.Debug("Device scan set for %s minutes from now." % time_mins)
Log.Debug("Diffs are %s and %s and %s." % (cache_date, now, time_diff))
else:
scan_devices()
@handler(APP_PREFIX, NAME)
@handler(CAST_PREFIX, NAME)
@handler(STAT_PREFIX, NAME)
@route(APP_PREFIX + '/MainMenu')
def MainMenu(Rescanned=False):
"""
Main menu for the Plex UI
"""
Log.Debug("********** Starting MainMenu **********")
title = NAME + " - " + Dict['version']
cache_stamp = 1545730073
if Data.Exists('last_cache'):
last_cache = Data.Load('last_cache')
try:
cache_stamp = float(last_cache)
except ValueError, e:
Log.Debug("Value error")
time_string = datetime.datetime.fromtimestamp(cache_stamp).strftime(DATE_STRUCTURE)
title = "%s - %s - Last Scan: %s" % (NAME, Dict['version'], time_string)
oc = ObjectContainer(
title1=title,
no_cache=True,
no_history=True,
title_bar="Flex TV",
view_group="Details")
if Rescanned is True:
oc.message = "Rescan complete!"
#
do = DirectoryObject(
title="Rescan Devices",
thumb=R(ICON_CAST_REFRESH),
key=Callback(Rescan))
oc.add(do)
do = DirectoryObject(
title="Advanced",
thumb=R(ICON_CAST_REFRESH),
key=Callback(AdvancedMenu))
oc.add(do)
do = DirectoryObject(
title="Devices",
thumb=R(ICON_CAST),
key=Callback(Resources))
oc.add(do)
do = DirectoryObject(
title="Broadcast",
thumb=R(ICON_CAST_AUDIO),
key=Callback(Broadcast))
oc.add(do)
do = DirectoryObject(
title="Stats",
thumb=R(ICON_PLEX_CLIENT),
key=Callback(Statmenu))
oc.add(do)
return oc
@route(APP_PREFIX + '/ValidatePrefs')
def ValidatePrefs():
"""
Called by the framework every time a user changes the prefs
We add this dummy function, to avoid errors in the log
and stuff.
"""
dependencies = ["helpers", "monitor"]
log_helper.register_logging_handler(dependencies, level="DEBUG")
return
####################################
# These are our cast endpoints
@route(APP_PREFIX + '/devices')
@route(CAST_PREFIX + '/devices')
def Devices():
"""
Endpoint to scan LAN for cast devices
"""
Log.Debug('Fetchings /devices endpoint.')
# Grab our response header?
casts = fetch_devices()
mc = FlexContainer()
for cast in casts:
Log.Debug("Cast type is " + cast['type'])
if (cast['type'] == 'cast') | (cast['type'] == 'audio') | (cast['type'] == 'group'):
dc = FlexContainer("Device", cast, show_size=False)
mc.add(dc)
return mc
@route(APP_PREFIX + '/clients')
@route(CAST_PREFIX + '/clients')
def Clients():
"""
Endpoint to scan LAN for cast devices
"""
Log.Debug('Recieved a call to fetch all devices')
# Grab our response header?
casts = fetch_devices()
mc = FlexContainer()
for cast in casts:
dc = FlexContainer("Device", cast, show_size=False)
mc.add(dc)
return mc
@route(APP_PREFIX + '/resources')
@route(CAST_PREFIX + '/resources')
def Resources():
"""
Endpoint to scan LAN for cast devices
"""
Log.Debug('Recieved a call to fetch devices')
# Grab our response header?
casts = fetch_devices()
oc = ObjectContainer(
no_cache=True,
no_history=True,
view_group="Details")
for cast in casts:
cast_type = cast['type']
icon = ICON_CAST
if cast_type == "audio":
icon = ICON_CAST_AUDIO
if cast_type == "cast":
icon = ICON_CAST_VIDEO
if cast_type == "group":
icon = ICON_CAST_GROUP
if cast['app'] == "Plex Client":
icon = ICON_PLEX_CLIENT
do = DirectoryObject(
title=cast['name'],
duration=cast['status'],
tagline=cast['uri'],
summary=cast['app'],
key=Callback(Status, input_name=cast['name']),
thumb=R(icon))
oc.add(do)
return oc
@route(APP_PREFIX + '/rescan')
@route(CAST_PREFIX + '/rescan')
def Rescan():
"""
Endpoint to scan LAN for cast devices
"""
Log.Debug('Recieved a call to rescan devices')
# Grab our response header?
UpdateCache()
return MainMenu(True)
@route(CAST_PREFIX + '/play')
def Play():
"""
Endpoint to play media.
"""
Log.Debug('Recieved a call to play media.')
params = ['Clienturi', 'Contentid', 'Contenttype', 'Serverid', 'Serveruri',
'Username', 'Transienttoken', 'Queueid', 'Version', 'Primaryserverid',
'Primaryserveruri', 'Primaryservertoken']
values = sort_headers(params, False)
status = "Missing required headers and stuff"
msg = status
if values is not False:
Log.Debug("Holy crap, we have all the headers we need.")
client_uri = values['Clienturi'].split(':')
host = client_uri[0]
port = int(client_uri[1])
pc = False
msg = "No message received"
if 'Serverid' in values:
servers = fetch_servers()
for server in servers:
if server['id'] == values['Serverid']:
Log.Debug("Found a matching server!")
values['Serveruri'] = server['uri']
values['Version'] = server['version']
try:
cast = pychromecast.Chromecast(host, port)
cast.wait()
values['Type'] = cast.cast_type
pc = PlexController(cast)
cast.register_handler(pc)
Log.Debug("Sending values to play command: " + JSON.StringFromObject(values))
pc.play_media(values, log_data)
except pychromecast.LaunchError, pychromecast.PyChromecastError:
Log.Debug('Error connecting to host.')
status = "Error"
finally:
if pc is not False:
status = "Success"
oc = FlexContainer(attributes={
'Name': 'Playback Status',
'Status': status,
'Message': msg
})
return oc
@route(CAST_PREFIX + '/cmd')
def Cmd():
"""
Media control command(s).
Plex-specific commands use the format:
Required params:
Uri
Cmd
Vol(If setting volume, otherwise, ignored)
Where <COMMAND> is one of:
PLAY (resume)
PAUSE
STOP
STEPFORWARD
STEPBACKWARD Need to test, not in PHP cast app)
PREVIOUS
NEXT
MUTE
UNMUTE
VOLUME - also requires an int representing level from 0-100
"""
Log.Debug('Recieved a call to control playback')
params = sort_headers(['Uri', 'Cmd', 'Val'], False)
status = "Missing paramaters"
response = "Error"
if params is not False:
uri = params['Uri'].split(":")
cast = pychromecast.Chromecast(uri[0], int(uri[1]))
cast.wait()
pc = PlexController(cast)
Log.Debug("Handler namespace is %s" % pc.namespace)
cast.register_handler(pc)
Log.Debug("Handler namespace is %s" % pc.namespace)
cmd = params['Cmd']
Log.Debug("Command is " + cmd)
if cmd == "play":
pc.play()
if cmd == "pause":
pc.pause()
if cmd == "stop":
pc.stop()
if cmd == "next":
pc.next()
if (cmd == "offset") & ('Val' in params):
pc.seek(params["Val"])
if cmd == "previous":
pc.previous()
if cmd == "volume.mute":
pc.mute(True)
if cmd == "volume.unmute":
pc.mute(False)
if (cmd == "volume") & ('Val' in params):
pc.set_volume(params["Val"])
if cmd == "volume.down":
pc.volume_down()
if cmd == "volume.up":
pc.volume_up()
cast.disconnect()
response = "Command successful"
oc = ObjectContainer(
title1=response,
title2=status,
no_cache=True,
no_history=True)
return oc
@route(CAST_PREFIX + '/audio')
def Audio():
"""
Endpoint to cast audio to a specific device.
"""
Log.Debug('Recieved a call to play an audio clip.')
params = ['Uri', 'Path']
values = sort_headers(params, True)
status = "Missing required headers"
if values is not False:
Log.Debug("Holy crap, we have all the headers we need.")
client_uri = values['Uri'].split(":")
host = client_uri[0]
port = int(client_uri[1])
path = values['Path']
try:
cast = pychromecast.Chromecast(host, port)
cast.wait()
mc = cast.media_controller
mc.play_media(path, 'audio/mp3', )
except pychromecast.LaunchError, pychromecast.PyChromecastError:
Log.Debug('Error connecting to host.')
finally:
Log.Debug("We have a cast")
status = "Playback successful"
oc = ObjectContainer(
title1=status,
no_cache=True,
no_history=True)
return oc
@route(CAST_PREFIX + '/broadcast/test')
def Test():
values = {'Path': R(TEST_CLIP)}
casts = fetch_devices()
status = "Test successful!"
try:
for cast in casts:
if cast['type'] == "audio":
mc = MediaController()
Log.Debug("We should be broadcasting to " + cast['name'])
uri = cast['uri'].split(":")
cast = pychromecast.Chromecast(uri[0], int(uri[1]))
cast.wait()
cast.register_handler(mc)
mc.play_media(values['Path'], 'audio/mp3')
except pychromecast.LaunchError, pychromecast.PyChromecastError:
Log.Debug('Error connecting to host.')
status = "Test failed!"
finally:
Log.Debug("We have a cast")
oc = ObjectContainer(
title1=status,
no_cache=True,
no_history=True)
return oc
@route(CAST_PREFIX + '/broadcast')
def Broadcast():
"""
Send audio to *all* cast devices on the network
"""
Log.Debug('Recieved a call to broadcast an audio clip.')
params = ['Path']
values = sort_headers(params, True)
status = "No clip specified"
if values is not False:
do = False
casts = fetch_devices()
disconnect = []
controllers = []
try:
for cast in casts:
if cast['type'] == "audio":
mc = MediaController()
Log.Debug("We should be broadcasting to " + cast['name'])
uri = cast['uri'].split(":")
cast = pychromecast.Chromecast(uri[0], int(uri[1]))
cast.wait()
cast.register_handler(mc)
controllers.append(mc)
disconnect.append(cast)
for mc in controllers:
mc.play_media(values['Path'], 'audio/mp3', )
except pychromecast.LaunchError, pychromecast.PyChromecastError:
Log.Debug('Error connecting to host.')
finally:
for cast in disconnect:
cast.disconnect()
Log.Debug("We have a cast")
else:
do = DirectoryObject(
title='Test Broadcast',
tagline="Send a test broadcast to audio devices.",
key=Callback(Test))
status = "Foo"
oc = ObjectContainer(
title1=status,
no_cache=True,
no_history=True)
if do is not False:
oc.add(do)
return oc
####################################
# These are our /stat prefixes
@route(STAT_PREFIX + '/tag')
def All():
mc = build_tag_container("all")
return mc
@route(STAT_PREFIX + '/tag/actor')
def Actor():
mc = build_tag_container("actor")
return mc
@route(STAT_PREFIX + '/tag/director')
def Director():
mc = build_tag_container("director")
return mc
@route(STAT_PREFIX + '/tag/writer')
def Writer():
mc = build_tag_container("writer")
return mc
@route(STAT_PREFIX + '/tag/genre')
def Genre():
mc = build_tag_container("genre")
return mc
@route(STAT_PREFIX + '/tag/country')
def Country():
mc = build_tag_container("country")
return mc
@route(STAT_PREFIX + '/tag/mood')
def Mood():
mc = build_tag_container("mood")
return mc
@route(STAT_PREFIX + '/tag/autotag')
def Autotag():
mc = build_tag_container("autotag")
return mc
@route(STAT_PREFIX + '/tag/collection')
def Collection():
mc = build_tag_container("collection")
return mc
@route(STAT_PREFIX + '/tag/similar')
def Similar():
mc = build_tag_container("similar")
return mc
@route(STAT_PREFIX + '/tag/year')
def Year():
mc = build_tag_container("year")
return mc
@route(STAT_PREFIX + '/tag/contentRating')
def ContentRating():
mc = build_tag_container("contentRating")
return mc
@route(STAT_PREFIX + '/tag/studio')
def Studio():
mc = build_tag_container("studio")
return mc
# Rating (Reviews)
@route(STAT_PREFIX + '/tag/score')
def Score():
mc = build_tag_container("score")
return mc
@route(STAT_PREFIX + '/library')
def Library():
mc = FlexContainer()
Log.Debug("Here's where we fetch some library stats.")
sections = {}
recs = query_library_stats()
sizes = query_library_sizes()
records = recs[0]
sec_counts = recs[1]
for record in records:
section = record["sectionTitle"]
if section not in sections:
sections[section] = []
del (record["sectionTitle"])
sections[section].append(dict(record))
for name in sections:
Log.Debug("Looping through section '%s'" % name)
sec_id = sections[name][0]["section"]
sec_type = sections[name][0]["sectionType"]
section_types = {
1: "movie",
2: "show",
3: "music",
4: "photo",
8: "music",
13: "photo"
}
if sec_type in section_types:
sec_type = section_types[sec_type]
item_count = 0
play_count = 0
playable_count = 0
section_children = []
for record in sections[name]:
item_count += record["totalItems"]
if record['playCount'] is not None:
play_count += record['playCount']
if record["type"] in ["episode", "track", "movie"]:
playable_count = record["totalItems"]
item_type = str(record["type"]).capitalize()
record_data = {
"totalItems": record["totalItems"]
}
vc = FlexContainer(item_type, record_data, False)
if record["lastViewedAt"] is not None:
last_item = {
"title": record['title'],
"grandparentTitle": record['grandparentTitle'],
"art": record['art'],
"thumb": record['thumb'],
"ratingKey": record['ratingKey'],
"lastViewedAt": record['lastViewedAt'],
"username": record['username'],
"userId": record['userId']
}
li = FlexContainer("lastViewed", last_item, False)
vc.add(li)
section_children.append(vc)
section_data = {
"title": name,
"id": sec_id,
"totalItems": item_count,
"playableItems": playable_count,
"playCount": play_count,
"type": sec_type
}
for sec_size in sizes:
if sec_size['section_id'] == sec_id:
Log.Debug("Found a matching section size...foo")
section_data['mediaSize'] = sec_size['size']
sec_unique_played = sec_counts.get(str(sec_id)) or None
if sec_unique_played is not None:
Log.Debug("Hey, we got the unique count")
section_data["watchedItems"] = sec_unique_played["viewedItems"]
ac = FlexContainer("Section", section_data, False)
bc = section_data
for child in section_children:
ac.add(child)
mc.add(ac)
return mc
@route(STAT_PREFIX + '/library/growth')
def Growth():
headers = sort_headers(["Interval", "Start", "End", "Type"])
records = query_library_growth(headers)
total_array = {}
for record in records:
dates = str(record["addedAt"])[:-9].split("-")
year = str(dates[0])
month = str(dates[1])
day = str(dates[2])
year_array = total_array.get(year) or {}
month_array = year_array.get(month) or {}
day_array = month_array.get(day) or []
day_array.append(record)
month_array[day] = day_array
year_array[month] = month_array
total_array[year] = year_array
mc = FlexContainer()
grand_total = 0
types_all = {}
for y in range(0000, 3000):
y = str(y)
year_total = 0
if y in total_array:
types_year = {}
Log.Debug("Found a year %s" % y)
year_container = FlexContainer("Year", {"value": y})
year_array = total_array[y]
Log.Debug("Year Array: %s" % JSON.StringFromObject(year_array))
month_total = 0
os.environ['TZ'] = 'UTC'
for m in range(1, 12):
m = str(m).zfill(2)
if m in year_array:
types_month = {}
Log.Debug("Found a month %s" % m)
month_container = FlexContainer("Month", {"value": m})
month_array = year_array[m]
for d in range(1, 32):
d = str(d).zfill(2)
if d in month_array:
types_day = {}
Log.Debug("Found a day %s" % d)
day_container = FlexContainer("Day", {"value": d}, False)
records = month_array[d]
for record in records:
record_type = record["type"]
record["addedAt"] = int(time.mktime(time.strptime(record["addedAt"], "%Y-%m-%d %H:%M:%S")))
tag_name = META_XML_TAGS.get(record_type) or "Undefined"
ac = FlexContainer(tag_name, record, False)
temp_day_count = types_day.get(record_type) or 0
temp_month_count = types_month.get(record_type) or 0
temp_year_count = types_year.get(record_type) or 0
temp_all_count = types_all.get(record_type) or 0
types_day[record_type] = temp_day_count + 1
types_month[record_type] = temp_month_count + 1
types_year[record_type] = temp_year_count + 1
types_all[record_type] = temp_all_count + 1
day_container.add(ac)
month_total += day_container.size()
day_container.set("totalAdded", day_container.size())
for rec_type in types_day:
day_container.set("%sCount" % rec_type, types_day.get(rec_type))
month_container.add(day_container)
year_total += month_total
month_container.set("totalAdded", month_total)
for rec_type in types_month:
month_container.set("%sCount" % rec_type, types_month.get(rec_type))
year_container.add(month_container)
year_container.set("totalAdded", year_total)
for rec_type in types_year:
year_container.set("%sCount" % rec_type, types_year.get(rec_type))
grand_total += year_total
mc.add(year_container)
return mc
@route(STAT_PREFIX + '/library/popular')
def Popular():
results = query_library_popular()
mc = FlexContainer()
for section in results:
sc = FlexContainer('Hub', limit=True)
sc.set('hubIdentifier', section)
sc.set('title', section.capitalize())
for record in results[section]:
rec_type = record["type"]
tag_type = META_XML_TAGS.get(rec_type) or "Undefined"
rec_users = {}
if "users" in record:
rec_users = record["users"]
del record["users"]
if "userName" in record:
del record["userName"]
if "userId" in record:
del record["userId"]
me = FlexContainer(tag_type, record, show_size=False)
usc = FlexContainer("Users", show_size=False)
view_total = 0
for userName, userData in rec_users.items():
vc = FlexContainer("Views")
views = userData.get("views") or []
views = sorted(views, key=lambda z: z['dateViewed'], reverse=True)
if "views" in userData:
del userData["views"]
uc = FlexContainer("User", userData, show_size=False)
for view in views:
vsc = FlexContainer("View", view, show_size=False)
vc.add(vsc)
uc.add(vc)
uc.set("playCount", vc.size())
view_total += vc.size()
usc.add(uc)
usc.set('userCount', usc.size())
usc.set('playCount', view_total)
me.add(usc)
sc.add(me)
mc.add(sc)
return mc
@route(STAT_PREFIX + '/library/quality')
def Quality():
results = query_library_quality()
mc = FlexContainer()
Log.Debug("Record: %s" % JSON.StringFromObject(results))
for meta_type, records in results.items():
me = FlexContainer("Meta")
me.set("Type", meta_type)
records = results[meta_type]
for record in records:
mi = FlexContainer("Media", record, limit=True)
me.add(mi)
mc.add(me)
return mc
@route(STAT_PREFIX + '/system')
def System():
Log.Debug("Querying system specs")
headers = sort_headers(["Friendly"])
friendly = headers.get("Friendly") or False
mon = Monitor(friendly)
mem_data = mon.get_memory()
cpu_data = mon.get_cpu()
hdd_data = mon.get_disk()
net_data = mon.get_net()
mc = FlexContainer(show_size=False)
mem_container = FlexContainer("Mem", mem_data, show_size=False)
cpu_container = FlexContainer("Cpu", cpu_data, show_size=False)
hdd_container = FlexContainer("Hdd", show_size=False)
for disk_item in hdd_data:
dc = FlexContainer("Disk", disk_item, show_size=False)
hdd_container.add(dc)
net_container = FlexContainer("Net", show_size=False)
for nic in net_data:
if_container = FlexContainer("Interface", nic, show_size=False)
net_container.add(if_container)
mc.add(mem_container)
mc.add(cpu_container)
mc.add(hdd_container)
mc.add(net_container)
return mc
@route(STAT_PREFIX + '/user')
def User():
users = query_user_stats()
Log.Debug("Returning XML")
mc = FlexContainer()
if users is not None:
for user in users:
user_meta = user['meta']
user_devices = user['devices']
del user['meta']
del user['devices']
uc = FlexContainer("User", user, False)
sc = FlexContainer("Views", show_size=False)
for meta, items in user_meta.items():
vc = FlexContainer(meta, limit=True)
for item in items:
tag_name = META_XML_TAGS.get(item['type']) or "Undefined"
ic = FlexContainer(tag_name, item, show_size=False)
vc.add(ic)
sc.add(vc)
uc.add(sc)
chrome_data = None
dp = FlexContainer("Devices", None, False, limit=True)
for device in user_devices:
if device["deviceName"] != "Chrome":
dc = FlexContainer("Device", device, False)
dp.add(dc)
else:
chrome_bytes = 0
if chrome_data is None:
chrome_data = device
else:
chrome_bytes = device["totalBytes"] + chrome_data.get("totalBytes") or 0
chrome_data["totalBytes"] = chrome_bytes
if chrome_data is not None:
dc = FlexContainer("Device", chrome_data, False)
dp.add(dc)
uc.add(dp)
mc.add(uc)
Log.Debug("Still alive, returning data")
return mc