-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice.py
More file actions
924 lines (814 loc) · 41.7 KB
/
service.py
File metadata and controls
924 lines (814 loc) · 41.7 KB
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
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Zomboided
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Service module for Zomboided Tools add-on
import xbmc
import xbmcgui
import xbmcaddon
import xbmcvfs
import os
import time
import datetime
import calendar
from libs.utility import ifDebug, setDebug, debugTrace, errorTrace, infoTrace, newPrint, now
from libs.vpnapi import VPNAPI
from libs.common import fixKeymaps, getSleep, setSleep, getSleepReq, setSleepReq, setSleepReqTime, clearSleep, setSleepRemaining, getSleepRemaining
from libs.common import getSleepReqTime, SLEEP_OFF, SLEEP_END, SLEEP_DELAY_TIME, clearAlert, addAlert, activeAlert, forceSleepLock, freeSleepLock
from libs.common import recordAction, getButtonCommands, makeButtonsFile, fixAutostart, hasInternet, syncClock
setDebug(False)
# This is here to avoid a known Python locking bug https://bugs.python.org/issue7980
for i in range(1, 10):
try:
datetime.datetime(*(time.strptime('2018-01-01', '%Y-%m-%d')[0:6]))
break
except Exception as e:
errorTrace("service.py", "Couldn't call strptime cleanly during initialisation, call" + str(i))
errorTrace("service.py", str(e))
xbmc.sleep(3000)
debugTrace("-- Entered service.py --")
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
# Number of actions enabled in the settings screen
ACTION_COUNT = 10
# Like an action, but in the land of nod
SLEEP_ACTION = "Zzzz"
# Used in parse timer
TODAY = -1
TOMORROW = 0
# Set the addon name for use in the dialogs
addon = xbmcaddon.Addon()
addon_name = addon.getAddonInfo('name')
# Playlist check variables
playback_duration_check = False
playback_duration_minutes = 0
pause_duration_minutes = 0
playback_time_check = False
playback_time = 0
playlist_detection_delay = 0
playlist_time_check = False
playlist_max_minutes = 0
playlist_count_check = False
playlist_max_count = 0
playlist_min_count = 0
addon_check_freq = 0
file_check_freq = 0
refresh_check_freq = 0
# Timers
sleep_timer = 0
sleep_done = False
idle_duration_minutes = 0
enable_idle_time = 0
pause_timer = 0
action_timer = 0
action_timer_number = 0
addon_timer = 0
addon_timer_start = 0
addon_timer_end = 0
last_boot = 0
playback_timer = 0
file_timer = 0
file_timer_start = 0
file_timer_end = 0
clock_timer = 0
clock_timer_start = 0
clock_timer_end = 0
clock_sync = False
clock_sync_force = False
refresh_timer = 0
auto_sleep_start = 0
auto_sleep_end = 0
# Monitor class which will get called when the settings change
class KodiMonitor(xbmc.Monitor):
# This gets called every time a setting is changed either programmatically or via the settings dialog.
def onSettingsChanged( self ):
#debugTrace("Requested update to service process via settings monitor")
updateSettings("onSettingsChanged", False)
# FIXME Can I run the updates settings to read from a file (and back up to one), and also allow offsetting
# Pick through the addon settings and translate them to variables we'll be using
def updateSettings(caller, wait):
global playback_duration_check
global playback_duration_minutes
global pause_duration_minutes
global idle_duration_minutes
global playback_time_check
global playback_time
global playlist_detection_delay
global playlist_time_check
global playlist_max_minutes
global playlist_count_check
global playlist_max_count
global playlist_min_count
global action_timer
global action_timer_number
global addon_timer
global addon_timer_start
global addon_timer_end
global addon_check_freq
global file_timer
global file_timer_start
global file_timer_end
global file_check_freq
global clock_timer
global clock_timer_start
global clock_timer_end
global clock_check_freq
global clock_sync
global refresh_timer
global refresh_check_freq
global auto_sleep_start
global auto_sleep_end
if not updatesAllowed() and not wait: return
# Wait for 60 seconds, then carry on anyway
for i in range(1, 60):
if updatesAllowed(): break
xbmc.sleep(1000)
if i == 59: errorTrace("service.py", "updateSettings was called from " + caller + " with wait, but could not get a lock to update after 60 seconds")
debugTrace("updateSettings called from " + caller)
refresh_timer = 0
allowUpdates(False)
addon = xbmcaddon.Addon()
# Refresh the play limit settings
if addon.getSetting("stop_playback_duration") == "true": playback_duration_check = True
else: playback_duration_check = False
playback_duration_minutes = int(addon.getSetting("stop_playback_mins"))
if addon.getSetting("stop_playback_after") == "true": playback_time_check = True
else: playback_time_check = False
playback_time = addon.getSetting("stop_playback_time")
# Refresh the playlist settings
if addon.getSetting("stop_playlist_time") == "true": playlist_time_check = True
else: playlist_time_check = False
playlist_max_minutes = int(addon.getSetting("stop_playlist_mins"))
if addon.getSetting("stop_playlist_videos") == "true": playlist_count_check = True
else: playlist_count_check = False
playlist_max_count = int(addon.getSetting("stop_playlist_count"))
playlist_min_count = int(addon.getSetting("detect_playlist_minimum"))
playlist_detection_delay = int(addon.getSetting("detect_playlist_gap"))
pause_duration_minutes = int(addon.getSetting("stop_playback_pause"))
idle_duration_minutes = int(addon.getSetting("sleep_inactivity"))
# The warning timers should be 10 second increments so fix if it's not
for i in range(1, (ACTION_COUNT + 1)):
fixWarnTime("action_warn_" + str(i))
fixWarnTime("sleep_warn")
addon = xbmcaddon.Addon()
# Refresh the action settings
action_timer = 0
action_timer_number = 0
for i in range(0, ACTION_COUNT):
# Check the timer settings
j = str(i+1)
# Start counting periodical timers from the time they were set. If it's not
# a periodical timer, then reset it so it starts from now next time it's set
if addon.getSetting("action_timer_freq_" + j) == "Periodically":
if addon.getSetting("action_period_last_" + j) == "":
addon.setSetting("action_period_last_" + j, str(now()))
begin = int(addon.getSetting("action_period_last_" + j))
else:
addon.setSetting("action_period_last_" + j, "")
begin = 0
next_action_timer = parseTimer("Action Timer " + j,
addon.getSetting("action_timer_freq_" + j),
addon.getSetting("action_time_" + j),
addon.getSetting("action_day_" + j),
addon.getSetting("action_date_" + j),
addon.getSetting("action_period_" + j),
begin)
# Determine if this time is the nearest one and use it if it is
if (action_timer == 0 and not next_action_timer == 0) or (next_action_timer > 0 and next_action_timer < action_timer):
action_timer_number = i + 1
action_timer = next_action_timer
if addon.getSetting("action_addon_enabled_" + j) == "true":
selected = addon.getSetting("action_addon_" + j)
last = addon.getSetting("addon_name_" + j)
if not selected == last: addon_timer = addon_check_freq + 1
t = now()
# Frequency add-ons are checked
addon_check_freq = int(addon.getSetting("addon_check"))*60
addon_timer_start, addon_timer_end = parseTimePeriod(t, "Addon Check", addon.getSetting("addon_check_start"), addon.getSetting("addon_check_end"))
# Frequency files are checked
file_check_freq = int(addon.getSetting("file_check"))*60
file_timer_start, file_timer_end = parseTimePeriod(t, "File Check", addon.getSetting("file_check_start"), addon.getSetting("file_check_end"))
# Frequency clock is checked
clock_check_freq = int(addon.getSetting("clock_check"))*60
clock_timer_start, clock_timer_end = parseTimePeriod(t, "Clock Check", addon.getSetting("clock_check_start"), addon.getSetting("clock_check_end"))
if addon.getSetting("clock_resync") == "true": clock_sync = True;
else: clock_sync = False;
# Auto sleep timers
auto_sleep_start, auto_sleep_end = parseTimePeriod(t, "Auto Sleep", addon.getSetting("auto_sleep_start"), addon.getSetting("auto_sleep_end"))
# Settings get refreshed infrequently, just in case...
refresh_check_freq = int(addon.getSetting("refresh_check"))*60
if not action_timer_number == 0:
debugTrace("Action timer " + str(action_timer_number) + " is the first timer with " + str(action_timer))
else:
debugTrace("No action timers are set")
if addon.getSetting("button_enabled") == "true":
# Create the buttons file and make it autostart
getButtonCommands()
xbmc.sleep(500)
addon = xbmcaddon.Addon()
if makeButtonsFile():
debugTrace("Created a new button file")
if fixAutostart(): debugTrace("Updated autostart to run zbutton.py")
allowUpdates(True)
def allowUpdates(bool):
xbmc.sleep(1000)
if bool:
xbmcgui.Window(10000).setProperty("Zomboided_Tools_Settings_Updates", "True")
else:
xbmcgui.Window(10000).setProperty("Zomboided_Tools_Settings_Updates", "False")
xbmc.sleep(1000)
return
def updatesAllowed():
if xbmcgui.Window(10000).getProperty("Zomboided_Tools_Settings_Updates") == "False": return False
return True
# Fix the warning timer settings if necessary
def fixWarnTime(warning):
w = int(addon.getSetting(warning))
if w > 0:
if w > 10: new_w = int(w / 10) * 10
else: new_w = 10
if not w == new_w: addon.setSetting(warning, str(new_w))
def parseTimer(type, freq, rtime, day, date, period, begin):
debugTrace("Parsing " + type + ". Frequency is " + freq + ", time is + " + rtime + ", day is " + day + ", date is " + date + ", period is " + period + ", begin is " + str(begin))
if freq == "" or freq == "Off":
return 0
else:
# Assume timer is today at the defined reboot time
timer = time.strftime("%d %m %Y") + " " + rtime
# Parse the timer starting from a given time, or now
if begin > 0:
t = begin
else:
t = now()
# Make some datetime objects representing now, last boot time and the timer
current_dt = datetime.datetime.fromtimestamp(t)
last_dt = datetime.datetime.fromtimestamp(last_boot)
timer_dt = datetime.datetime(*(time.strptime(timer, "%d %m %Y %H:%M")[0:6]))
# Adjust timer based on the frequency
if freq == "Daily":
# If the timer is in the past, add a day
if timer_dt < current_dt and not begin == TODAY:
d = datetime.timedelta(days = 1)
timer_dt = timer_dt + d
elif freq == "Weekly":
# Calculate the next boot day
current_day = current_dt.weekday()
timer_day = days.index(day)
if current_day > timer_day:
adjust_day = 7 - (current_day - timer_day)
elif current_day < timer_day:
adjust_day = timer_day - current_day
else:
# Same day, if it's in the past, add a week
if timer_dt < current_dt: adjust_day = 7
else: adjust_day = 0
# Adjust the timer the required number of days
if adjust_day > 0:
d = datetime.timedelta(days = adjust_day)
timer_dt = timer_dt + d
elif freq == "Monthly":
new_day = int(date)
if (current_dt.day > new_day) or (current_dt.day == new_day and timer_dt < current_dt):
if current_dt.month == 12:
timer_dt = timer_dt.replace(month = 1)
timer_dt = timer_dt.replace(year = timer_dt.year + 1)
else:
timer_dt = timer_dt.replace(month = timer_dt.month + 1)
_, max_day = calendar.monthrange(timer_dt.year, timer_dt.month)
if new_day > max_day: new_day = max_day
timer_dt = timer_dt.replace(day = new_day)
elif freq == "Periodically":
timer_dt == datetime.datetime.combine(last_dt.date(), timer_dt.timetz())
d = datetime.timedelta(days = int(period))
timer_dt = timer_dt + d
else:
errorTrace("service.py", "Couldn't parse timer, no timer set")
return 0
# Calculate the difference between the dates and return the timer value in epoch seconds
debugTrace("Starting time is " + str(current_dt) + ", last reboot is " + str(last_dt) + ", timer is " + str(timer_dt))
diff_seconds = int((timer_dt - current_dt).total_seconds())
return (t + diff_seconds)
def parseTimePeriod(t, timer_name, start_time, end_time):
happy = False
start = TODAY
while not happy:
timer_start = parseTimer(timer_name + " Start", "Daily", start_time, "", "", "", start)
timer_end = parseTimer(timer_name + " End", "Daily", end_time, "", "", "", timer_start)
# If the scheduled time is in the past, try again for the next day
if timer_end < t: start = TOMORROW
else: happy = True
return int(timer_start), int(timer_end)
# Player class which will be called when the playback state changes
class KodiPlayer(xbmc.Player):
playlist_playing = False
playlist_max = 0
playlist_count = 0
playlist_ended = 0
playing_file = False
def __init__ (self):
xbmc.Player.__init__(self)
self.logger = None
def onPlayBackStarted(self, *arg):
global playback_timer
global sleep_done
global pause_timer
# Allow idle sleep to work again
sleep_done = False
addon = xbmcaddon.Addon()
# Deal with endPlayback not being called previously
if self.playing_file: self.runPlaybackEnded("onPlayBackStarted")
self.playing_file = True
t = now()
try:
infoTrace("service.py", "Playing " + self.getPlayingFile())
recordAction("Playing " + self.getPlayingFile())
except:
pass
# Reset the pause time, just in case so the film is not stopped randomly
pause_timer = 0
# Determine the end time if there's a play back limit
d_timer = 0
t_timer = 0
playback_timer = 0
if playback_duration_check: d_timer = t + (playback_duration_minutes * 60)
if playback_time_check: t_timer = parseTimer("Play back timer", "Daily", playback_time, "", "", "", 0)
if not d_timer == 0 and (d_timer < t_timer or t_timer == 0): playback_timer = d_timer
if not t_timer == 0 and (t_timer < d_timer or d_timer == 0): playback_timer = t_timer
if playback_timer: debugTrace("Time is " + str(t) + " playing until " + str(playback_timer) + ". Duration was " + str(playback_duration_minutes) + ", time was " + playback_time)
# If playback ended some time ago, this isn't a playlist
if self.playlist_playing and t - self.playlist_ended > playlist_detection_delay:
debugTrace("Playlist is over")
debugTrace("Ended because time between videos was " + str(t-self.playlist_ended) + " seconds, max is " + str(playlist_detection_delay))
self.resetPlaybackCounts()
if not self.playlist_playing:
# If a playlist isn't active, this is the first video in a playlist (or otherwise)
updateSettings("onPlayBackStarted", True)
self.playlist_playing = True
self.playlist_max = t + (playlist_max_minutes * 60)
self.playlist_count = 1
debugTrace("Detected playback starting")
debugTrace("Max playback time is " + str(playlist_max_minutes))
debugTrace("Max playback videos is " + str(playlist_max_count))
debugTrace("Time is " + str(t) + " max time is " + str(self.playlist_max))
else:
# This is not the first video in a playlist
if playlist_count_check: debugTrace("Count is " + str(self.playlist_count) + ", max is " + str(playlist_max_count) + ", min is " + str(playlist_min_count))
if playlist_time_check: debugTrace("Time is " + str(t) + ", timeout is " + str(self.playlist_max))
if playlist_count_check and self.playlist_count >= playlist_max_count:
xbmc.Player().stop()
infoTrace("service.py", "Stopping playlist after playing " + str(playlist_max_count) + " videos.")
self.resetPlaybackCounts()
elif playlist_time_check and t > self.playlist_max and self.playlist_count >= playlist_min_count:
xbmc.Player().stop()
infoTrace("service.py", "Stopping playlist after reaching maximum time period")
self.resetPlaybackCounts()
if addon.getSetting("auto_sleep") == "true" and t > auto_sleep_start and t < auto_sleep_end:
if getSleep() == SLEEP_OFF:
debugTrace("Setting auto sleep")
setSleepReq("End")
setSleepReqTime(t-SLEEP_DELAY_TIME)
xbmcgui.Dialog().notification("Sleeping at end of video." , "", "", 2000, False)
addAlert()
def onPlayBackStopped(self, *arg):
self.runPlaybackEnded("onPlayBackStopped")
self.resetPlaybackCounts
def onPlayBackPaused(self):
global pause_timer
if pause_duration_minutes > 0: pause_timer = now() + (pause_duration_minutes * 60)
else: pause_timer = 0
debugTrace("Playback paused, pausing limited to " + str(pause_duration_minutes) + " miuntes, sleep is " + getSleep())
def onPlayBackResumed(self):
global pause_timer
pause_timer = 0
def onPlayBackEnded(self, *arg):
self.runPlaybackEnded("onPlayBackEnded")
def resetPlaybackCounts(self):
self.playlist_playing = False
self.playlist_max = 0
self.playlist_count = 0
self.playlist_ended = 0
def runPlaybackEnded(self, caller):
global playback_timer
global sleep_timer
global pause_timer
global enable_idle_time
self.playing_file = False
playback_timer = 0
pause_timer = 0
t = now()
if idle_duration_minutes > 0: enable_idle_time = t + (idle_duration_minutes * 60)
else: enable_idle_time = 0
self.playlist_ended = t
self.playlist_count += 1
debugTrace("Playback ended called from " + caller + ", at " + str(self.playlist_ended) + ", count is " + str(self.playlist_count) + " sleep is " + getSleep())
if getSleep() == SLEEP_END:
addAlert()
sleep_timer = 1
def isStillPlaying(self):
return self.playing_file
if __name__ == '__main__':
infoTrace("service.py", "Starting Zomboided Tools service, version is " + addon.getAddonInfo("version"))
infoTrace("service.py", "Kodi build is " + xbmc.getInfoLabel('System.BuildVersion'))
monitor = KodiMonitor()
player = KodiPlayer()
api = None
# <FIXME> Add nord support
if xbmc.getCondVisibility("System.HasAddon(service.vpn.manager)"):
try:
api = VPNAPI()
debugTrace("Found VPN Manager")
except Exception as e:
errorTrace("service.py", "Couldn't connect to the VPN Mgr API")
errorTrace("service.py", str(e))
api = None
# Initialise some variables we'll be using repeatedly
addon = xbmcaddon.Addon()
allowUpdates(False)
addon.setSetting("boot_time", time.strftime('%Y-%m-%d %H:%M:%S'))
allowUpdates(True)
last_boot = now()
updateSettings("main initialisation", True)
# Initialise a bunch of variables
delay = 10
delay_loop = 6
# Prevent idle sleep for 5 minutes after boot
enable_idle_time = now() + 300
file_timer = 0
last_file_check = 0
action_number_f = 0
addon_timer = 0
last_addon_check = 0
action_number_a = 0
clock_timer = 0
pause_timer = 0
last_clock_check = 0
if addon.getSetting("clock_resync") == "true":
clock_sync = True;
clock_sync_force = True;
else:
clock_sync = False;
last_sleep = SLEEP_OFF
sleep_timer = 0
sleep_notify = 0
notify_mins = "0"
clearSleep()
do_it = False
action_if_playing = False
action = ""
warn = -1
action_number = 0
# Check the keymaps for this add-on are intact
if fixKeymaps():
xbmcgui.Dialog().ok(addon_name, "The keymap had been renamed. This has been reverted to the correct name, but you must restart for the keymap to take effect.")
while not monitor.abortRequested():
t = now()
# This copes with endPlayback not being called properly (for whatever reason)
if player.isStillPlaying() and not player.isPlaying():
player.runPlaybackEnded("main loop")
if playback_timer > 0 and t > playback_timer:
player.stop()
infoTrace("service.py", "Stopping play back. Duration is " + str(playback_duration_minutes) + " minutes, time limit is " + str(playback_time))
# Sleep Checking
if sleep_timer > 0 and not do_it:
if t >= sleep_timer:
sleep_timer = 0
do_it = True
action_number = SLEEP_ACTION
action = addon.getSetting("sleep_action")
warn = int(addon.getSetting("sleep_warn"))
action_if_playing = True
infoTrace("service.py", "Sleep timer has triggered on " + str(t) + ".")
last_sleep = SLEEP_OFF
clearSleep()
# FIXME switch off idle sleep timer here? Who switches it back on?
if sleep_notify > 0 and t > sleep_notify:
sleep_notify = 0
if notify_mins == "1":
xbmcgui.Dialog().notification("Sleeping in 1 minute" , "", "", 5000, False)
else:
xbmcgui.Dialog().notification("Sleeping in " + notify_mins + " minutes" , "", "", 5000, False)
# Idle checking
if not player.isPlaying() and idle_duration_minutes > 0 and not do_it:
if enable_idle_time == 0:
idle_duration_seconds = idle_duration_minutes * 60
if xbmc.getCondVisibility('System.IdleTime(' + str(idle_duration_seconds) + ')'):
# Only allow idle sleep once, then not again until some more user input has happened
if not sleep_done:
infoTrace("service.py", "Sleeping after being idle for " + str(idle_duration_minutes) + " minutes")
addAlert()
sleep_timer = 1
sleep_done = True
else:
# Idle time is less than when we last (tried to) sleep, so reset the flag
sleep_done = False
else:
# Reenable idle time after pausing it following playback finishing or the service starting
if t >= enable_idle_time: enable_idle_time = 0;
# Timer Checking
if action_timer > 0 and t >= action_timer and not do_it:
do_it = True
action_number = str(action_timer_number)
action = addon.getSetting("action_" + action_number)
warn = int(addon.getSetting("action_warn_" + action_number))
action_if_playing = False
if addon.getSetting("action_if_playing_" + action_number) == "true": action_if_playing = True
infoTrace("service.py", "Timer " + str(action_timer) + " has triggered on " + str(t) + " for action #" + action_number + ".")
# Pause checking
if pause_timer > 0 and t >= pause_timer and not do_it:
player.stop()
infoTrace("service.py", "Paused for longer than " + str(pause_duration_minutes) + " minutes, stopping playback")
# File Checking
if not player.isPlaying() and file_timer >= file_check_freq and not do_it:
allowUpdates(False)
action_number_f += 1
if action_number_f > ACTION_COUNT:
action_number_f = 1
action_number = str(action_number_f)
debugTrace("Checking file for action #" + action_number)
if addon.getSetting("action_file_enabled_" + action_number) == "true":
unavailable = False
if addon.getSetting("action_file_unavailable_" + action_number) == "true": unavailable = True
file = addon.getSetting("action_file_" + action_number)
last_file_time = addon.getSetting("file_time_" + action_number)
last_reboot = addon.getSetting("file_reboot_" + action_number)
file_error = False
if not file == "":
if xbmcvfs.exists(file):
try:
stats = xbmcvfs.Stat(file)
file_time = str(stats.st_mtime())
addon.setSetting("file_reboot_" + action_number, "")
debugTrace("Checking file " + file + " " + file_time + " with " + last_file_time)
if last_file_time == "":
addon.setSetting("file_time_" + action_number, file_time)
elif not last_file_time == file_time:
addon.setSetting("file_time_" + action_number, file_time)
do_it = True
infoTrace("service.py", "File " + file + " had time stamp " + last_file_time + " and now has " + file_time + ", triggering action #" + action_number + ".")
except Exception as e:
errorTrace("service.py", "Couldn't get the time stamp of " + file + " for action #" + action_number + ", will try again later.")
errorTrace("service.py", str(e))
file_error = True
else:
infoTrace("service.py", "File " + file + " does not exist for action #" + action_number + ", will try again later.")
file_error = True
# Take action if file unavailable after 2 tries, and never take the action more than once (avoid reboot loops, etc)
if file_error and unavailable:
if last_reboot == "" :
addon.setSetting("file_reboot_" + action_number, "pending")
else :
do_it = True
addon.setSetting("file_reboot_" + action_number, "true")
infoTrace("service.py", "File " + file + " still cannot be found or accessed and is triggering action #" + action_number + ".")
else:
if not last_file_time == "":
addon.setSetting("file_time_" + action_number, "")
if not last_reboot == "":
addon.setSetting("file_reboot_" + action_number, "")
addon = xbmcaddon.Addon()
if do_it:
action = addon.getSetting("action_" + action_number)
warn = int(addon.getSetting("action_warn_" + action_number))
action_if_playing = True
if action_number_f == ACTION_COUNT: file_timer = 0
allowUpdates(True)
# Add-on Checking
if not player.isPlaying() and addon_timer >= addon_check_freq and not do_it:
allowUpdates(False)
action_number_a += 1
if action_number_a > ACTION_COUNT:
action_number_a = 1
action_number = str(action_number_a)
debugTrace("Checking add-on for action # " + action_number)
if addon.getSetting("action_addon_enabled_" + action_number) == "true":
# Get the current list of add-ons and previously detected settings
addons_s = addon.getSetting("action_addon_" + action_number)
addons_l = addons_s.split(",")
last_s = addon.getSetting("addon_name_" + action_number)
last_l = last_s.split(",")
versions_s = addon.getSetting("addon_version_" + action_number)
versions_l = versions_s.split(",")
debugTrace("Addons are " + addons_s + ", previous addons are " + last_s + ", versions are " + versions_s)
# Compare the previous with the versions now
if len(addons_l) > 0 and addons_s == last_s:
if len(versions_l) == len(last_l):
i = 0
for i in range(0, len(last_l)):
try:
command = "System.HasAddon(" + last_l[i] + ")"
if xbmc.getCondVisibility(command):
version = xbmcaddon.Addon(last_l[i]).getAddonInfo("version")
else:
version = " "
except Exception as e:
version = " "
if version == " ":
if not versions_l[i] == version :
errorTrace("service.py", "Add-on " + last_l[i] + ", is not available to check as part of action #" + action_number)
last_s = ""
else:
debugTrace("Add-on " + last_l[i] + ", is still not available to check as part of action #" + action_number)
elif not version == versions_l[i]:
infoTrace("service.py", "Add-on " + last_l[i] + ", has been updated from " + versions_l[i] + " to " + version)
do_it = True
action = addon.getSetting("action_" + action_number)
warn = int(addon.getSetting("action_warn_" + action_number))
action_if_playing = True
# Force new list of versions to be build below
last_s = ""
break
else:
last_s = ""
if last_s == "" or not addons_s == last_s:
# Addons list is different, reset to current versions
addon.setSetting("addon_name_" + action_number, addons_s)
versions = ""
for name in addons_l:
try:
command = "System.HasAddon(" + name + ")"
if xbmc.getCondVisibility(command):
version = xbmcaddon.Addon(name).getAddonInfo("version")
else:
version = " "
except:
version = " "
if versions == "": versions = version
else: versions = versions + "," + version
addon.setSetting("addon_version_" + action_number, versions)
else:
if not addon.getSetting("addon_name_" + action_number) == "":
addon.setSetting("addon_name_" + action_number, "")
addon.setSetting("addon_version_" + action_number, "")
if action_number_a == ACTION_COUNT: addon_timer = 0
allowUpdates(True)
addon = xbmcaddon.Addon()
# Clock checking
if not player.isPlaying() and clock_timer >= clock_check_freq:
prev_dst = addon.getSetting("clock_dst")
clock_t = time.localtime()
current_dst = str(clock_t.tm_isdst)
if (not current_dst == -1 and not prev_dst == current_dst) or clock_sync_force:
if hasInternet("http://google.com"):
if not clock_sync_force: infoTrace("service.py", "Daylist savings time change detected, resyncing the clock")
else: infoTrace("service.py", "Forcing resync of the clock")
addon.setSetting("clock_dst", current_dst)
clock_sync_force = False
syncClock()
addon = xbmcaddon.Addon()
# Don't want to check again for a while, so start the time again regardless of what happened
clock_timer = 0
# Set up sleep timer
sleep_setting = getSleepReq()
if not sleep_setting == "":
if t - getSleepReqTime() < SLEEP_DELAY_TIME:
# This reduces the loop time so that sleep changes are noticed in a reasonable time
addAlert()
else:
forceSleepLock()
infoTrace("service.py", "Setting a sleep timer, " + sleep_setting + ". Previous was " + last_sleep)
last_sleep = sleep_setting
if sleep_setting == SLEEP_OFF or sleep_setting == SLEEP_END:
sleep_timer = 0
sleep_notification = 0
setSleepRemaining("")
else:
if sleep_setting.isdigit():
sleep_timer = t + (int(sleep_setting) * 60)
notify_mins = addon.getSetting("sleep_notify")
sleep_notify = 0
if not (notify_mins == "" or notify_mins == "0"):
sleep_notify = sleep_timer - (int(notify_mins) * 60)
debugTrace("Time now is " + str(t) + ", sleep timer set for " + str(sleep_timer) + ", sleep notify is " + str(sleep_notify))
else:
errorTrace("Sleep timer was bad, found" + sleep_setting)
sleep_timer = 0
setSleepRemaining("")
sleep_setting = SLEEP_OFF
setSleep(sleep_setting)
setSleepReq("")
freeSleepLock()
# Update sleep remaining for sleep cycle display elsewhere
sleep_setting = getSleep()
if not (sleep_setting == SLEEP_OFF or sleep_setting == SLEEP_END):
setSleepRemaining(str((sleep_timer - t)/60))
# Take any outstanding action
if do_it and (not player.isPlaying() or (player.isPlaying() and action_if_playing)):
if action == "Stop Playing" and not player.isPlaying():
if not action_number == SLEEP_ACTION or (action_number == SLEEP_ACTION and not addon.getSetting("sleep_cec_off") == "true"):
# There's nothing to do here...
do_it = False
infoTrace("service.py", action + " unnecessary")
if do_it and warn > 0 and not action == "None":
msg = ""
if action_number == SLEEP_ACTION:
msg = "Going to sleep. "
if not action == "Stop Playing" or (action == "Stop Playing" and player.isPlaying()):
msg = msg + "About to " + action + ". "
msg = msg + "Click cancel to abort. "
if action == "Clear Cache":
msg = msg + "[COLOR red][B]Avoid using any input device until cache clearance is complete.[/B][/COLOR]"
if action == "Run Command":
if action_number == SLEEP_ACTION: c = addon.getSetting("sleep_command")
else: c = addon.getSetting("action_command_" + action_number)
msg = msg + "Command is '[I]" + c + "'[/I]"
dialog = xbmcgui.DialogProgress()
dialog.create(addon_name, msg)
dialog.update(100)
xbmc.sleep(1000)
tick = int(100 / warn)
for i in range(1, 100):
if dialog.iscanceled():
do_it = False
clearSleep()
infoTrace("service.py", action + " aborted by user")
break
percent = 100-(i*tick)
if percent < 0: break
dialog.update(percent)
xbmc.sleep(1000)
dialog.close()
if do_it:
infoTrace("service.py", "Trigger fired for action #" + action_number + ", performing a " + action)
recordAction("Action #" + action_number + " fired, performing a " + action)
if action_number == SLEEP_ACTION and addon.getSetting("sleep_cec_off") == "true":
infoTrace("service.py", "Turning off TV before action " + action)
xbmc.executebuiltin("CECStandby")
if action == "None":
xbmcgui.Dialog().ok(addon_name, "Trigger has fired for action #" + action_number + ", but no action is defined.")
elif action == "Stop Playing":
player.stop()
elif action == "Disconnect VPN":
if api is not None:
result = api.disconnect(False)
else:
xbmcgui.Dialog().ok(addon_name, "Trigger has fired for action #" + action_number + ", but VPN Manager is not available.")
elif action == "Reconnect VPN":
if api is not None:
result = api.reconnect(True)
else:
xbmcgui.Dialog().ok(addon_name, "Trigger has fired for action #" + action_number + ", but VPN Manager is not available.")
elif action == "Run Command":
if action_number == SLEEP_ACTION: c = addon.getSetting("sleep_command")
else: c = addon.getSetting("action_command_" + action_number)
infoTrace("service.py", "Executing command '" + c + "'")
try:
xbmc.executebuiltin(c)
except Exception as e:
xbmcgui.Dialog().ok(addon_name, "Trigger has fired for action #" + action_number + ", but command failed to run. See log for details.")
errorTrace("service.py", "Could not run command '" + c + "' for action #" + action_number + ". Error shown on next line.")
errorTrace("service.py", str(e))
else:
xbmc.executebuiltin(action)
# Clear the last period timer, so periodical timers gets reset to count from today
if not action_number == SLEEP_ACTION:
addon.setSetting("action_period_last_" + action_number, "")
# Get the next timer setting
updateSettings("main after action", True)
do_it = False
action_if_playing = False
# If the settings haven't been updated in a while, force one anyway because of timing windows
if not player.isPlaying() and refresh_timer >= refresh_check_freq:
updateSettings("main refresh timer", True)
# Have a nap before checking timers again
delay_count = 0
for i in range(0, delay_loop):
delay_count += delay
if monitor.waitForAbort(delay):
# Abort was requested while waiting. We should exit
infoTrace("service.py", "Abort received, shutting down service")
break
if activeAlert() or not player.isPlaying(): break
clearAlert()
# Increment the timers if they're active
if t > addon_timer_start and t < addon_timer_end:
if t - last_addon_check > addon_check_freq:
addon_timer = addon_check_freq
else:
addon_timer = addon_timer + delay_count
last_addon_check = t
if t > file_timer_start and t < file_timer_end:
if t - last_file_check > file_check_freq:
file_timer = file_check_freq
else:
file_timer = file_timer + delay_count
last_file_check = t
if (clock_sync and (t > clock_timer_start and t < clock_timer_end)) or clock_sync_force:
if (t - last_clock_check > clock_check_freq) or clock_sync_force:
clock_timer = clock_check_freq
else:
clock_timer = clock_timer + delay_count
last_clock_check = t
refresh_timer = refresh_timer + delay_count