forked from xbmc/repo-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
watchedlist.py
1846 lines (1673 loc) · 94.2 KB
/
watchedlist.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 file contains the class of the addon
Settings for this addon:
w_movies
'true', 'false': save watched state of movies
w_episodes
'true', 'false': save watched state of movies
autostart
delay
delay after startup in minutes: '0', '5', '10', ...
starttype
'0' = No autostart
'1' = One Execution after Kodi start
'2' = Periodic start of the addon
interval
watch_user
progressdialog
verbosity
'0' = All messages (debug)
'1' = Only info / notification
'2' = Only warnings
'3' = Only errors
'4' = No Messages
db_format
'0' = SQLite File
'1' = MYSQL Server
drobox_enabled
extdb
'true', 'false': Use external database file
dbpath
String: Specify path to external database file
dbfilename
dbbackupcount
mysql_server
mysql_port
mysql_db
mysql_user
mysql_pass
"""
import sys
import os
import re
import time
import sqlite3
import base64
import xbmc
import xbmcgui
import xbmcvfs
import mysql.connector
import buggalo
import lib.watchedlist.utils as utils
try:
import dropbox
from dropbox.exceptions import ApiError as DropboxApiError
DROPBOX_APP_KEY = base64.b64decode("YmhkMnY4aGdzbXF3Y2d0").decode('ascii')
DROPBOX_APP_SECRET = base64.b64decode("dDJjZXBvZXZqcXl1Ym5k").decode('ascii')
DROPBOX_ENABLED = True
except BaseException:
DROPBOX_ENABLED = False
if utils.getSetting("dropbox_enabled") == 'true':
utils.showNotification(utils.getString(32708), utils.getString(32720), xbmc.LOGWARNING)
if utils.getSetting('dbbackupcount') != '0':
import zipfile
import datetime
buggalo.EMAIL_CONFIG = {"recipient": base64.b64decode("bXNhaGFkbDYwQGdtYWlsLmNvbQ==").decode('ascii'),
"sender": base64.b64decode("QnVnZ2FsbyA8a29kaXdhdGNoZWRsaXN0QGdtYWlsLmNvbT4=").decode('ascii'),
"server": base64.b64decode("c210cC5nb29nbGVtYWlsLmNvbQ==").decode('ascii'),
"method": "ssl",
"user": base64.b64decode("a29kaXdhdGNoZWRsaXN0QGdtYWlsLmNvbQ==").decode('ascii'),
"pass": base64.b64decode("bWNneHd1and6c3ducW1iaA==").decode('ascii')}
QUERY_MV_INSERT_SQLITE = 'INSERT OR IGNORE INTO movie_watched (idMovieImdb,playCount,lastChange,lastPlayed,title) VALUES (?, ?, ?, ?, ?)'
QUERY_MV_INSERT_MYSQL = 'INSERT IGNORE INTO movie_watched (idMovieImdb,playCount,lastChange,lastPlayed,title) VALUES (%s, %s, FROM_UNIXTIME(%s), FROM_UNIXTIME(%s), %s)'
QUERY_EP_INSERT_SQLITE = 'INSERT OR IGNORE INTO episode_watched (idShow,season,episode,playCount,lastChange,lastPlayed) VALUES (?, ?, ?, ?, ?, ?)'
QUERY_EP_INSERT_MYSQL = 'INSERT IGNORE INTO episode_watched (idShow,season,episode,playCount,lastChange,lastPlayed) VALUES (%s, %s, %s, %s, FROM_UNIXTIME(%s), FROM_UNIXTIME(%s))'
QUERY_MV_UPDATE_SQLITE = 'UPDATE movie_watched SET playCount = ?, lastplayed = ?, lastChange = ? WHERE idMovieImdb LIKE ?'
QUERY_MV_UPDATE_MYSQL = 'UPDATE movie_watched SET playCount = %s, lastplayed = FROM_UNIXTIME(%s), lastChange = FROM_UNIXTIME(%s) WHERE idMovieImdb LIKE %s'
QUERY_EP_UPDATE_SQLITE = 'UPDATE episode_watched SET playCount = ?, lastPlayed = ?, lastChange = ? WHERE idShow LIKE ? AND season LIKE ? AND episode LIKE ?'
QUERY_EP_UPDATE_MYSQL = 'UPDATE episode_watched SET playCount = %s, lastPlayed = FROM_UNIXTIME(%s), lastChange = FROM_UNIXTIME(%s) WHERE idShow LIKE %s AND season LIKE %s AND episode LIKE %s'
# Queries to create tables for movies ("mv"), episodes ("ep") and series ("ss") for sqlite and mysql
QUERY_CREATE_MV_SQLITE = "CREATE TABLE IF NOT EXISTS movie_watched (idMovieImdb INTEGER PRIMARY KEY,playCount INTEGER,lastChange INTEGER,lastPlayed INTEGER,title TEXT)"
QUERY_CREATE_EP_SQLITE = "CREATE TABLE IF NOT EXISTS episode_watched (idShow INTEGER, season INTEGER, episode INTEGER, playCount INTEGER,lastChange INTEGER,lastPlayed INTEGER, PRIMARY KEY (idShow, season, episode))"
QUERY_CREATE_SS_SQLITE = "CREATE TABLE IF NOT EXISTS tvshows (idShow INTEGER, title TEXT, PRIMARY KEY (idShow))"
QUERY_CREATE_MV_MYSQL = ("CREATE TABLE IF NOT EXISTS `movie_watched` ("
"`idMovieImdb` int unsigned NOT NULL,"
"`playCount` tinyint unsigned DEFAULT NULL,"
"`lastChange` timestamp NULL DEFAULT NULL,"
"`lastPlayed` timestamp NULL DEFAULT NULL,"
"`title` text,"
"PRIMARY KEY (`idMovieImdb`)"
") ENGINE=InnoDB DEFAULT CHARSET=utf8;")
QUERY_CREATE_EP_MYSQL = ("CREATE TABLE IF NOT EXISTS `episode_watched` ("
"`idShow` int unsigned NOT NULL DEFAULT '0',"
"`season` smallint unsigned NOT NULL DEFAULT '0',"
"`episode` smallint unsigned NOT NULL DEFAULT '0',"
"`playCount` tinyint unsigned DEFAULT NULL,"
"`lastChange` timestamp NULL DEFAULT NULL,"
"`lastPlayed` timestamp NULL DEFAULT NULL,"
"PRIMARY KEY (`idShow`,`season`,`episode`)"
") ENGINE=InnoDB DEFAULT CHARSET=utf8;")
QUERY_CREATE_SS_MYSQL = ("CREATE TABLE IF NOT EXISTS `tvshows` ("
"`idShow` int unsigned NOT NULL,"
"`title` text,"
"PRIMARY KEY (`idShow`)"
") ENGINE=InnoDB DEFAULT CHARSET=utf8;")
# Queries for clearing data from the tables
QUERY_CLEAR_MV_SQLITE = "DELETE FROM movie_watched;"
QUERY_CLEAR_EP_SQLITE = "DELETE FROM episode_watched;"
# Queries for selecting all table entries
QUERY_SELECT_MV_SQLITE = "SELECT idMovieImdb, lastPlayed, playCount, title, lastChange FROM movie_watched ORDER BY title"
QUERY_SELECT_MV_MYSQL = "SELECT `idMovieImdb`, UNIX_TIMESTAMP(`lastPlayed`), `playCount`, `title`, UNIX_TIMESTAMP(`lastChange`) FROM `movie_watched` ORDER BY `title`"
QUERY_SELECT_EP_SQLITE = "SELECT idShow, season, episode, lastPlayed, playCount, lastChange FROM episode_watched ORDER BY idShow, season, episode"
QUERY_SELECT_EP_MYSQL = "SELECT `idShow`, `season`, `episode`, UNIX_TIMESTAMP(`lastPlayed`), `playCount`, UNIX_TIMESTAMP(`lastChange`) FROM `episode_watched` ORDER BY `idShow`, `season`, `episode`"
# Queries for inserting tv series
QUERY_INSERT_SS_SQLITE = "INSERT OR IGNORE INTO tvshows (idShow,title) VALUES (?, ?)"
QUERY_INSERT_SS_MYSQL = "INSERT IGNORE INTO tvshows (idShow,title) VALUES (%s, %s)"
class WatchedList:
"""
Main class of the add-on
"""
def __init__(self, externalcall=False):
"""
Initialize Class, default values for all class variables
Args:
externalcall: Flag if the class was created for use with another Addon (via the API).
In this case some features will be deactivated for speed purpose
"""
self.watchedmovielist_wl = list([]) # 0imdbnumber, 1empty, 2empty, 3lastPlayed, 4playCount, 5title, 6lastChange
self.watchedepisodelist_wl = list([]) # 0tvdbnumber, 1season, 2episode, 3lastplayed, 4playcount, 5empty, 6lastChange
self.watchedmovielist_xbmc = list([]) # 0imdbnumber, 1empty, 2empty, 3lastPlayed, 4playCount, 5title, 6empty, 7movieid
self.watchedepisodelist_xbmc = list([]) # 0tvdbnumber, 1season, 2episode, 3lastplayed, 4playcount, 5name, 6empty, 7episodeid
self.tvshows = {} # dict: key=xbmcid, value=[tvdbnumber, showname]
self.tvshownames = {} # dict: key=tvdbnumber, value=showname
self.sqlcon_wl = 0
self.sqlcursor_wl = 0
self.sqlcon_db = 0
self.sqlcursor_db = 0
self.db_method = 'file' # either 'file' or 'mysql'
# flag to remember copying the databasefile if requested
self.dbbackupdone = False
self.watch_user_changes_count = 0
# normal access of files or access over the Kodi virtual file system (on unix)
self.dbfileaccess = 'normal'
self.dbpath = ''
self.dbdirectory = ''
self.dropbox_path = None
self.downloaded_dropbox_timestamp = 0
self.dbdirectory_copy = ''
self.dbpath_copy = ''
# monitor for shutdown detection
self.monitor = xbmc.Monitor()
if externalcall:
# No Dropbox for external API calls
self.downloaded_dropbox_timestamp = float('inf')
# No database backup
self.dbbackupdone = True
def __del__(self):
''' Cleanup db when object destroyed '''
self.close_db(3) # changes have to be committed before
def __enter__(self): # for using the class in a with-statement
return self
def __exit__(self, exc_type, exc_value, traceback): # for using the class in a with-statement
self.close_db(3) # changes have to be committed before
def runProgram(self):
"""
entry point for automatic start.
Main function to call other functions
infinite loop for periodic database update
Returns:
return codes:
0 success
2 undefined
3 error/exit
4 planned exit (no error)
"""
try:
# workaround to disable autostart, if requested
if utils.getSetting("autostart") == 'false':
return 0
utils.buggalo_extradata_settings()
utils.footprint()
# wait the delay time after startup
delaytime = int(utils.getSetting("delay")) * 60 # in seconds
utils.log(u'Delay time before execution: %d seconds' % delaytime, xbmc.LOGDEBUG)
utils.showNotification(utils.getString(32101), utils.getString(32004) % int(utils.getSetting("delay")), xbmc.LOGINFO)
if self.monitor.waitForAbort(1 + delaytime): # wait at least one second (zero waiting time waits infinitely)
return 0
# load all databases
if self.sqlcursor_wl == 0 or self.sqlcon_wl == 0:
if self.load_db():
utils.showNotification(utils.getString(32102), utils.getString(32601), xbmc.LOGERROR)
return 3
if not self.tvshownames:
if self.sync_tvshows():
return 2
if not self.watchedmovielist_wl:
if self.get_watched_wl(1):
return 2
if not self.watchedmovielist_xbmc:
if self.get_watched_xbmc(1):
return 2
executioncount = 0
idletime = 0
if utils.getSetting("watch_user") == 'true':
utils.showNotification(utils.getString(32101), utils.getString(32005), xbmc.LOGINFO)
# handle the periodic execution
while int(utils.getSetting("starttype")) > 0 or utils.getSetting("watch_user") == 'true':
starttime = time.time()
# determine sleeptime before next full watched-database update
if utils.getSetting("starttype") == '1' and executioncount == 0: # one execution after startup
sleeptime = 0
elif utils.getSetting("starttype") == '2': # periodic execution
if executioncount == 0: # with periodic execution, one update after startup and then periodic
sleeptime = 0
else:
sleeptime = int(utils.getSetting("interval")) * 3600 # wait interval until next startup in [seconds]
# wait and then update again
utils.log(u'wait %d seconds until next update' % sleeptime)
utils.showNotification(utils.getString(32101), utils.getString(32003) % (sleeptime / 3600), xbmc.LOGINFO)
else: # no autostart, only watch user
sleeptime = 3600 # arbitrary time for infinite loop
# sleep the requested time and watch user changes
while True:
if self.monitor.abortRequested():
return 4
# check if user changes arrived
if utils.getSetting("watch_user") == 'true':
idletime_old = idletime
idletime = xbmc.getGlobalIdleTime() # Kodi idletime in seconds
# check if user could have made changes and process these changes to the wl database
self.watch_user_changes(idletime_old, idletime)
# check if time for update arrived
if time.time() > starttime + sleeptime:
break
if self.monitor.waitForAbort(1):
return 4 # wait 1 second until next check if Kodi terminates and user made changes
# perform full update
if utils.getSetting("starttype") == '1' and executioncount == 0 or utils.getSetting("starttype") == '2':
self.runUpdate(False)
executioncount += 1
# check for exiting program
if int(utils.getSetting("starttype")) < 2 and utils.getSetting("watch_user") == 'false':
return 0 # the program may exit. No purpose for background process
return 0
except SystemExit:
return 4
except BaseException:
buggalo.onExceptionRaised()
def runUpdate(self, manualstart):
"""
entry point for manual start.
this function is called for periodic update for automatic start
perform the update step by step
Args:
manualstart: True if called manually
Returns:
return code:
0 success
2 SystemExit
3 Error opening database
4 Error getting watched state from addon database
5 Error getting watched state from Kodi database
6 Error writing WL Database
7 Error writing Kodi database
8 Error merging dropbox database into local watched list
9 Error merging local database into dropbox
10 Error performing database backup
"""
try:
utils.buggalo_extradata_settings()
# check if player is running before doing the update. Only do this check for automatic start
while xbmc.Player().isPlaying() and not manualstart:
if self.monitor.waitForAbort(60):
return 1 # wait one minute until next check for active playback
if not xbmc.Player().isPlaying():
if self.monitor.waitForAbort(180):
return 1 # wait 3 minutes so the dialogue does not pop up directly after the playback ends
# load the addon-database
if self.sqlcursor_wl == 0 or self.sqlcon_wl == 0:
if self.load_db(True): # True: Manual start
utils.showNotification(utils.getString(32102), utils.getString(32601), xbmc.LOGERROR)
return 3
if self.sync_tvshows():
utils.showNotification(utils.getString(32102), utils.getString(32604), xbmc.LOGERROR)
return 5
# get the watched state from the addon
if self.get_watched_wl(0):
utils.showNotification(utils.getString(32102), utils.getString(32602), xbmc.LOGERROR)
return 4
# get watched state from xbmc
if self.get_watched_xbmc(0):
utils.showNotification(utils.getString(32102), utils.getString(32603), xbmc.LOGERROR)
return 5
if self.sync_tvshows():
utils.showNotification(utils.getString(32102), utils.getString(32604), xbmc.LOGERROR)
return 5
# attempt to merge the database from dropbox
if DROPBOX_ENABLED and utils.getSetting("dropbox_enabled") == 'true' and self.merge_dropbox_local():
utils.showNotification(utils.getString(32102), utils.getString(32607), xbmc.LOGERROR)
# do not abort execution of the whole addon if dropbox fails (e.g. due to network issues)
# return 8
# import from Kodi into addon database
res = self.write_wl_wdata()
if res == 2: # user exit
return 0
elif res == 1: # error
utils.showNotification(utils.getString(32102), utils.getString(32604), xbmc.LOGERROR)
return 6
# export from addon database into Kodi database
res = self.write_xbmc_wdata((utils.getSetting("progressdialog") == 'true'), 2)
if res == 2: # user exit
return 0
elif res == 1: # error
utils.showNotification(utils.getString(32102), utils.getString(32605), xbmc.LOGERROR)
return 7
utils.showNotification(utils.getString(32101), utils.getString(32107), xbmc.LOGINFO)
utils.log(u'runUpdate exited with success', xbmc.LOGDEBUG)
# sync with dropbox
if DROPBOX_ENABLED and utils.getSetting("dropbox_enabled") == 'true':
if self.merge_local_dropbox() == 0:
self.close_db(2) # save the database to file.
self.pushToDropbox()
else:
return 9
# close the watchedlist database. Is only closed locally in case of error
self.close_db(1)
# delete old backup files of the database
# do this at the end for not destroying valuable backup in case something went wrong before
if self.database_backup_delete():
return 10
return 0
except SystemExit:
return 2
except BaseException:
buggalo.onExceptionRaised()
def load_db(self, manualstart=False):
"""Load WL database
Args:
manualstart: True if called manually; only retry opening db once
Returns:
return code:
0 successfully opened database
1 error
2 shutdown (serious error in subfunction)
"""
try:
if int(utils.getSetting("db_format")) != 1:
# SQlite3 database in a file
# load the db path
if utils.getSetting("extdb") == 'false':
# use the default file
self.dbdirectory = xbmcvfs.translatePath(utils.data_dir())
buggalo.addExtraData('dbdirectory', self.dbdirectory)
self.dbpath = os.path.join(self.dbdirectory, "watchedlist.db")
else:
wait_minutes = 1 # retry waittime if db path does not exist/ is offline
while not self.monitor.abortRequested():
# use a user specified file, for example to synchronize multiple clients
self.dbdirectory = xbmcvfs.translatePath(utils.getSetting("dbpath"))
self.dbfileaccess = utils.fileaccessmode(self.dbdirectory)
self.dbpath = os.path.join(self.dbdirectory, utils.getSetting("dbfilename"))
if not xbmcvfs.exists(self.dbdirectory): # do not use os.path.exists to access smb:// paths
if manualstart:
utils.log(u'db path does not exist: %s' % self.dbdirectory, xbmc.LOGWARNING)
return 1 # raise error on manual start if directory not accessible (we do not want to wait in that case)
else:
utils.log(u'db path does not exist, wait %d minutes: %s' % (wait_minutes, self.dbdirectory), xbmc.LOGWARNING)
utils.showNotification(utils.getString(32102), utils.getString(32002) % self.dbdirectory, xbmc.LOGWARNING)
# Wait "wait_minutes" minutes until next check for file path (necessary on network shares, that are offline)
wait_minutes += wait_minutes # increase waittime until next check
if self.monitor.waitForAbort(wait_minutes * 60):
return 2
else:
break # directory exists, continue below
# on unix, smb-shares can not be accessed with sqlite3 --> copy the db with Kodi file system operations and work in mirror directory
buggalo.addExtraData('dbfileaccess', self.dbfileaccess)
buggalo.addExtraData('dbdirectory', self.dbdirectory)
buggalo.addExtraData('dbpath', self.dbpath)
if self.dbfileaccess == 'copy':
self.dbdirectory_copy = self.dbdirectory
self.dbpath_copy = self.dbpath # path to db file as in the settings (but not accessable)
buggalo.addExtraData('dbdirectory_copy', self.dbdirectory_copy)
buggalo.addExtraData('dbpath_copy', self.dbpath_copy)
# work in copy directory in the Kodi profile folder
self.dbdirectory = os.path.join(xbmcvfs.translatePath(utils.data_dir()), 'dbcopy' + os.sep)
if not xbmcvfs.exists(self.dbdirectory): # directory has to end with '/' (os.sep)
xbmcvfs.mkdir(self.dbdirectory)
utils.log(u'created directory %s' % str(self.dbdirectory))
self.dbpath = os.path.join(self.dbdirectory, "watchedlist.db")
if xbmcvfs.exists(self.dbpath_copy):
success = xbmcvfs.copy(self.dbpath_copy, self.dbpath) # copy the external db file to local mirror directory
utils.log(u'copied db file from share: %s -> %s. Success: %d' % (self.dbpath_copy, self.dbpath, success), xbmc.LOGDEBUG)
buggalo.addExtraData('dbdirectory', self.dbdirectory)
buggalo.addExtraData('dbpath', self.dbpath)
# connect to the local wl database. create database if it does not exist
self.sqlcon_wl = sqlite3.connect(self.dbpath)
self.sqlcursor_wl = self.sqlcon_wl.cursor()
else:
# MySQL Database on a server
self.sqlcon_wl = mysql.connector.connect(user=utils.getSetting("mysql_user"), password=utils.getSetting("mysql_pass"), database=utils.getSetting("mysql_db"), host=utils.getSetting("mysql_server"), port=utils.getSetting("mysql_port"))
self.sqlcursor_wl = self.sqlcon_wl.cursor()
# create tables if they don't exist
if int(utils.getSetting("db_format")) != 1: # sqlite file
self.sqlcursor_wl.execute(QUERY_CREATE_MV_SQLITE)
self.sqlcursor_wl.execute(QUERY_CREATE_EP_SQLITE)
self.sqlcursor_wl.execute(QUERY_CREATE_SS_SQLITE)
else: # mysql network database
self.sqlcursor_wl.execute(QUERY_CREATE_MV_MYSQL)
self.sqlcursor_wl.execute(QUERY_CREATE_EP_MYSQL)
self.sqlcursor_wl.execute(QUERY_CREATE_SS_MYSQL)
# check for dropbox
if DROPBOX_ENABLED and utils.getSetting("dropbox_enabled") == 'true':
# Download Dropbox database only once a day to reduce traffic.
if time.time() > self.downloaded_dropbox_timestamp + 3600.0 * 24.0:
if self.pullFromDropbox():
return 1
self.downloaded_dropbox_timestamp = time.time()
# connect to the dropbox wl database.
if self.dropbox_path is not None:
self.sqlcon_db = sqlite3.connect(self.dropbox_path)
self.sqlcursor_db = self.sqlcon_db.cursor()
# create tables in dropbox file, if they don't exist
self.sqlcursor_db.execute(QUERY_CREATE_MV_SQLITE)
self.sqlcursor_db.execute(QUERY_CREATE_EP_SQLITE)
self.sqlcursor_db.execute(QUERY_CREATE_SS_SQLITE)
buggalo.addExtraData('db_connstatus', 'connected')
except sqlite3.Error as err:
try:
errstring = err.args[0] # TODO: Find out, why this does not work some times
except BaseException:
errstring = ''
utils.log(u"Database error while opening %s. '%s'" % (self.dbpath, errstring), xbmc.LOGERROR)
utils.showNotification(utils.getString(32109), errstring, xbmc.LOGERROR)
self.close_db(3)
buggalo.addExtraData('db_connstatus', 'sqlite3 error, closed')
return 1
except mysql.connector.Error as err:
# Catch common mysql errors and show them to guide the user
utils.log(u"Database error while opening mySQL DB %s [%s:%s@%s]. %s" % (utils.getSetting("mysql_db"), utils.getSetting("mysql_user"), utils.getSetting("mysql_pass"), utils.getSetting("mysql_db"), err.msg), xbmc.LOGERROR)
if err.errno == mysql.connector.errorcode.ER_DBACCESS_DENIED_ERROR:
utils.showNotification(utils.getString(32108), utils.getString(32210) % (utils.getSetting("mysql_user"), utils.getSetting("mysql_db")), xbmc.LOGERROR)
elif err.errno == mysql.connector.errorcode.ER_ACCESS_DENIED_ERROR:
utils.showNotification(utils.getString(32108), utils.getString(32208), xbmc.LOGERROR)
elif err.errno == mysql.connector.errorcode.ER_BAD_DB_ERROR:
utils.showNotification(utils.getString(32108), utils.getString(32209) % utils.getSetting("mysql_db"), xbmc.LOGERROR)
else:
utils.showNotification(utils.getString(32108), err.msg, xbmc.LOGERROR)
buggalo.addExtraData('db_connstatus', 'mysql error, closed')
self.close_db(3)
return 1
except SystemExit:
return 1
except BaseException:
utils.log(u"Error while opening %s: %s" % (self.dbpath, sys.exc_info()[2]), xbmc.LOGERROR)
self.close_db(3)
buggalo.addExtraData('dbpath', self.dbpath)
buggalo.addExtraData('db_connstatus', 'error, closed')
buggalo.onExceptionRaised()
return 1
# only commit the changes if no error occured to ensure database persistence
self.sqlcon_wl.commit()
return 0
def close_db(self, flag):
"""Close WL database
Argument:
flag
1 for closing the WatchedList database
2 for closing the DropBox database
3 for closing both
Returns:
return code:
0 successfully closed database
1 error
"""
# close watchedlist db (if it is open)
if self.sqlcon_wl and (flag == 1 or flag == 3):
if self.sqlcon_wl:
self.sqlcon_wl.close()
self.sqlcon_wl = 0
# copy the db file back to the shared directory, if needed
if utils.getSetting("db_format") == '0' and self.dbfileaccess == 'copy':
if xbmcvfs.exists(self.dbpath):
success = xbmcvfs.copy(self.dbpath, self.dbpath_copy)
utils.log(u'copied db file to share: %s -> %s. Success: %d' % (self.dbpath, self.dbpath_copy, success), xbmc.LOGDEBUG)
if not success:
utils.showNotification(utils.getString(32102), utils.getString(32606) % self.dbpath, xbmc.LOGERROR)
return 1
buggalo.addExtraData('db_connstatus', 'closed')
# close dropbox db
if flag == 2 or flag == 3:
if self.sqlcon_db:
self.sqlcon_db.close()
self.sqlcon_db = 0
return 0
def get_watched_xbmc(self, silent):
"""Get Watched States of Kodi Database
Args:
silent: Do not show notifications if True
Returns:
return code:
0 success
1 error
4 planned exit (no error)
"""
try:
############################################
# first tv shows with TheTVDB-ID, then tv episodes
if utils.getSetting("w_episodes") == 'true':
############################################
# get imdb tv-show id from Kodi database
utils.log(u'get_watched_xbmc: Get all TV shows from Kodi database', xbmc.LOGDEBUG)
json_response = utils.executeJSON({
"jsonrpc": "2.0",
"method": "VideoLibrary.GetTVShows",
"params": {
"properties": ["title", "uniqueid"],
"sort": {"order": "ascending", "method": "title"}
},
"id": 1})
if 'result' in json_response and json_response['result'] is not None and 'tvshows' in json_response['result']:
for item in json_response['result']['tvshows']:
if self.monitor.abortRequested():
self.close_db(3)
return 4
tvshowId_xbmc = int(item['tvshowid'])
if not 'uniqueid' in item:
utils.log(u'get_watched_xbmc: tv show "%s" has no field uniqueid in database. tvshowid=%d. Try rescraping.' % (item['title'], tvshowId_xbmc), xbmc.LOGINFO)
continue
try:
tvshowId_tvdb = int(item['uniqueid']['tvdb'])
except BaseException:
utils.log(u'get_watched_xbmc: tv show "%s" has no tvdb-number in database. tvshowid=%d. Unique IDs: %s. Try rescraping.' % (item['title'], tvshowId_xbmc, str(list(item['uniqueid'].keys()))), xbmc.LOGINFO)
if not silent:
utils.showNotification(utils.getString(32101), utils.getString(32297) % (item['title'], tvshowId_xbmc), xbmc.LOGINFO)
tvshowId_tvdb = int(0)
self.tvshows[tvshowId_xbmc] = list([tvshowId_tvdb, item['title']])
if tvshowId_tvdb > 0:
self.tvshownames[tvshowId_tvdb] = item['title']
# Get all watched movies and episodes by unique id from xbmc-database via JSONRPC
self.watchedmovielist_xbmc = list([])
self.watchedepisodelist_xbmc = list([])
for modus in ['movie', 'episode']:
if self.monitor.abortRequested():
self.close_db(3)
return 4
buggalo.addExtraData('modus', modus)
if modus == 'movie' and utils.getSetting("w_movies") != 'true':
continue
if modus == 'episode' and utils.getSetting("w_episodes") != 'true':
continue
utils.log(u'get_watched_xbmc: Get all %ss from Kodi database' % modus, xbmc.LOGDEBUG)
if modus == 'movie':
# use the JSON-RPC to access the xbmc-database.
json_response = utils.executeJSON({
"jsonrpc": "2.0",
"method": "VideoLibrary.GetMovies",
"params": {
"properties": ["title", "year", "lastplayed", "playcount", "uniqueid"],
"sort": {"order": "ascending", "method": "title"}
},
"id": 1
})
else:
json_response = utils.executeJSON({
"jsonrpc": "2.0",
"method": "VideoLibrary.GetEpisodes",
"params": {
"properties": ["tvshowid", "season", "episode", "playcount", "showtitle", "lastplayed", "uniqueid"]
},
"id": 1
})
if modus == 'movie':
searchkey = 'movies'
else:
searchkey = 'episodes'
if 'result' in json_response and json_response['result'] is not None and searchkey in json_response['result']:
# go through all watched movies and save them in the class-variable self.watchedmovielist_xbmc
for item in json_response['result'][searchkey]:
if self.monitor.abortRequested():
break
if not 'uniqueid' in item:
if modus == 'movie':
utils.log(u'get_watched_xbmc: Movie %s has no field uniqueid in database. Try rescraping.' % (item['title']), xbmc.LOGINFO)
else: # episode
utils.log(u'get_watched_xbmc: Episode id %d (show %d, S%02dE%02d) has no field uniqueid in database. Try rescraping.' % (item['episodeid'], item['tvshowid'], item['season'], item['episode']), xbmc.LOGINFO)
continue
if modus == 'movie':
name = item['title'] + ' (' + str(item['year']) + ')'
try:
# check if movie number is in imdb-format (scraper=imdb)
res = re.compile(r'tt(\d+)').findall(item['uniqueid']['imdb'])
imdbId = int(res[0])
except BaseException:
# no imdb-number for this movie in database. Skip
utils.log(u'get_watched_xbmc: Movie %s has no imdb-number in database. movieid=%d. IDs are %s. Try rescraping' % (name, int(item['movieid']), str(list(item['uniqueid'].keys()))), xbmc.LOGINFO)
imdbId = 0
continue
else: # episodes
tvshowId_xbmc = item['tvshowid']
try:
tvshowName_xbmc = item['showtitle']
except BaseException:
# TODO: Something is wrong with the database or the json output since the field tvshowid is missing although requested. Check if this error still occurs and remove try-except
utils.log(u'get_watched_xbmc: TV episode id %d (show %d, S%02dE%02d) has no associated showtitle. Skipping.' % (item['episodeid'], item['tvshowid'], item['season'], item['episode']), xbmc.LOGWARNING)
continue
name = '%s S%02dE%02d' % (tvshowName_xbmc, item['season'], item['episode'])
try:
tvshowId_tvdb = self.tvshows[tvshowId_xbmc][0]
except BaseException:
utils.log(u'get_watched_xbmc: Kodi tv showid %d is not in Kodi-table tvshows. Skipping episode id %d (%s)' % (item['tvshowid'], item['episodeid'], name), xbmc.LOGINFO)
continue
if tvshowId_tvdb == 0:
utils.log(u'get_watched_xbmc: tvshow %d has no tvdb-number. Skipping episode id %d (%s)' % (item['tvshowid'], item['episodeid'], name), xbmc.LOGDEBUG)
continue
lastplayed = utils.sqlDateTimeToTimeStamp(item['lastplayed']) # convert to integer-timestamp
playcount = int(item['playcount'])
# add data to the class-variables
if modus == 'movie':
self.watchedmovielist_xbmc.append(list([imdbId, 0, 0, lastplayed, playcount, name, 0, int(item['movieid'])])) # 0imdbnumber, 1empty, 2empty, 3lastPlayed, 4playCount, 5title, 6empty, 7movieid
else:
self.watchedepisodelist_xbmc.append(list([tvshowId_tvdb, int(item['season']), int(item['episode']), lastplayed, playcount, name, 0, int(item['episodeid'])])) # 0tvdbnumber, 1season, 2episode, 3lastplayed, 4playcount, 5name, 6empty, 7episodeid
if not silent:
utils.showNotification(utils.getString(32101), utils.getString(32299) % (len(self.watchedmovielist_xbmc), len(self.watchedepisodelist_xbmc)), xbmc.LOGINFO)
if self.monitor.abortRequested():
self.close_db(3)
return 4
return 0
except SystemExit:
return 4
except BaseException:
utils.log(u'get_watched_xbmc: error getting the Kodi database : %s' % sys.exc_info()[2], xbmc.LOGERROR)
self.close_db(3)
buggalo.onExceptionRaised()
return 1
def get_watched_wl(self, silent):
"""Get Watched States of WL Database
Args:
silent: Do not show notifications if True
Returns:
return code:
0 successfully got watched states from WL-database
1 unknown error (programming related)
2 shutdown (error in subfunction)
3 error related to opening the database
4 exit requested (no error)
"""
try:
buggalo.addExtraData('self_sqlcursor', self.sqlcursor_wl)
buggalo.addExtraData('self_sqlcon', self.sqlcon_wl)
if self.sqlcursor_wl == 0 or self.sqlcon_wl == 0:
if self.load_db():
return 2
# get watched movies from addon database
self.watchedmovielist_wl = list([])
if utils.getSetting("w_movies") == 'true':
utils.log(u'get_watched_wl: Get watched movies from WL database', xbmc.LOGDEBUG)
if int(utils.getSetting("db_format")) != 1: # SQLite3 File. Timestamp stored as integer
self.sqlcursor_wl.execute(QUERY_SELECT_MV_SQLITE)
else: # mySQL: Create integer timestamp with the request
self.sqlcursor_wl.execute(QUERY_SELECT_MV_MYSQL)
rows = self.sqlcursor_wl.fetchall()
for row in rows:
if self.monitor.abortRequested():
self.close_db(1)
return 4
self.watchedmovielist_wl.append(list([int(row[0]), 0, 0, int(row[1]), int(row[2]), row[3], int(row[4])])) # 0tvdbnumber, 1empty, 2empty, 3lastPlayed, 4playCount, 5title, 6lastChange
# get watched episodes from addon database
self.watchedepisodelist_wl = list([])
if utils.getSetting("w_episodes") == 'true':
utils.log(u'get_watched_wl: Get watched episodes from WL database', xbmc.LOGDEBUG)
if int(utils.getSetting("db_format")) != 1: # SQLite3 File. Timestamp stored as integer
self.sqlcursor_wl.execute(QUERY_SELECT_EP_SQLITE)
else: # mySQL: Create integer timestamp with the request
self.sqlcursor_wl.execute(QUERY_SELECT_EP_MYSQL)
rows = self.sqlcursor_wl.fetchall()
for row in rows:
if self.monitor.abortRequested():
self.close_db(1)
return 4
try:
name = '%s S%02dE%02d' % (self.tvshownames[int(row[0])], int(row[1]), int(row[2]))
except BaseException:
name = 'tvdb-id %d S%02dE%02d' % (int(row[0]), int(row[1]), int(row[2]))
self.watchedepisodelist_wl.append(list([int(row[0]), int(row[1]), int(row[2]), int(row[3]), int(row[4]), name, int(row[5])])) # 0tvdbnumber, 1season, 2episode, 3lastplayed, 4playcount, 5name, 6lastChange
if not silent:
utils.showNotification(utils.getString(32101), utils.getString(32298) % (len(self.watchedmovielist_wl), len(self.watchedepisodelist_wl)), xbmc.LOGINFO)
return 0
except sqlite3.Error as err:
try:
errstring = err.args[0] # TODO: Find out, why this does not work some times
except BaseException:
errstring = ''
utils.log(u'get_watched_wl: SQLite Database error getting the wl database. %s' % errstring, xbmc.LOGERROR)
self.close_db(1)
# error could be that the database is locked (for tv show strings). This is not an error to disturb the other functions
return 3
except mysql.connector.Error as err:
utils.log(u'get_watched_wl: MySQL Database error getting the wl database. %s' % err, xbmc.LOGERROR)
return 3
except SystemExit:
return 4
except BaseException:
utils.log(u'get_watched_wl: Error getting the wl database : %s' % sys.exc_info()[2], xbmc.LOGERROR)
self.close_db(1)
buggalo.onExceptionRaised()
return 1
def sync_tvshows(self):
"""Sync List of TV Shows from Kodi to WL Database
Returns:
return code:
0 successfully synched tv shows
1 database access error
2 database loading error
4 exit requested (no error)
"""
try:
utils.log(u'sync_tvshows: sync tvshows with wl database : %s' % sys.exc_info()[2], xbmc.LOGDEBUG)
if self.sqlcursor_wl == 0 or self.sqlcon_wl == 0:
if self.load_db():
return 2
# write eventually new tv shows to wl database
for xbmcid in self.tvshows:
if self.monitor.abortRequested():
break # all queries will be commited
values = self.tvshows[xbmcid]
if values[0] == 0:
# no imdb-id saved for this tv show. Nothing to process.
continue
if int(utils.getSetting("db_format")) != 1: # sqlite3
self.sqlcursor_wl.execute(QUERY_INSERT_SS_SQLITE, values)
else: # mysql
self.sqlcursor_wl.execute(QUERY_INSERT_SS_MYSQL, values)
self.database_backup()
self.sqlcon_wl.commit()
if self.monitor.abortRequested():
self.close_db(1)
return 4
# get all known tv shows from wl database
self.sqlcursor_wl.execute("SELECT idShow, title FROM tvshows")
rows = self.sqlcursor_wl.fetchall()
for row_i in rows:
if self.monitor.abortRequested():
break
self.tvshownames[int(row_i[0])] = row_i[1]
except sqlite3.Error as err:
try:
errstring = err.args[0] # TODO: Find out, why this does not work some times
except BaseException:
errstring = ''
utils.log(u'sync_tvshows: SQLite Database error accessing the wl database: ''%s''' % errstring, xbmc.LOGERROR)
self.close_db(1)
# error could be that the database is locked (for tv show strings).
return 1
except mysql.connector.Error as err:
utils.log(u"sync_tvshows: MySQL Database error accessing the wl database: ''%s''" % (err), xbmc.LOGERROR)
self.close_db(1)
return 1
except SystemExit:
return 4
except BaseException:
utils.log(u'sync_tvshows: Error getting the wl database: ''%s''' % sys.exc_info()[2], xbmc.LOGERROR)
self.close_db(1)
buggalo.onExceptionRaised()
return 1
if self.monitor.abortRequested():
return 4
return 0
def write_wl_wdata(self):
"""Go through all watched movies from Kodi and check whether they are up to date in the addon database
Returns:
return code:
0 successfully written WL
1 program exception
2 database loading error
4 SystemExit
"""
buggalo.addExtraData('self_sqlcursor', self.sqlcursor_wl)
buggalo.addExtraData('self_sqlcon', self.sqlcon_wl)
if self.sqlcursor_wl == 0 or self.sqlcon_wl == 0:
if self.load_db():
return 2
for modus in ['movie', 'episode']:
buggalo.addExtraData('modus', modus)
if modus == 'movie' and utils.getSetting("w_movies") != 'true':
continue
if modus == 'episode' and utils.getSetting("w_episodes") != 'true':
continue
utils.log(u'write_wl_wdata: Write watched %ss to WL database' % modus, xbmc.LOGDEBUG)
count_insert = 0
count_update = 0
if utils.getSetting("progressdialog") == 'true':
DIALOG_PROGRESS = xbmcgui.DialogProgress()
DIALOG_PROGRESS.create(utils.getString(32101), utils.getString(32105))
if modus == 'movie':
list_length = len(self.watchedmovielist_xbmc)
else:
list_length = len(self.watchedepisodelist_xbmc)
for i in range(list_length):
if self.monitor.abortRequested():
break # this loop can take some time in debug mode and prevents Kodi to exit
if utils.getSetting("progressdialog") == 'true' and DIALOG_PROGRESS.iscanceled():
if modus == 'movie':
strno = 32202
else:
strno = 32203
utils.showNotification(utils.getString(strno), utils.getString(32301) % (count_insert, count_update), xbmc.LOGINFO)
return 2
if modus == 'movie':
row_xbmc = self.watchedmovielist_xbmc[i]
else:
row_xbmc = self.watchedepisodelist_xbmc[i]
if utils.getSetting("progressdialog") == 'true':
DIALOG_PROGRESS.update(int(100 * (i + 1) / list_length), (utils.getString(32105)+"\n"+utils.getString(32610) % (i + 1, list_length, row_xbmc[5])))
try:
res = self._wl_update_media(modus, row_xbmc, 0, 0, 0)
count_insert += res['num_new']
count_update += res['num_update']
except sqlite3.Error as err:
try:
errstring = err.args[0] # TODO: Find out, why this does not work some times
except BaseException:
errstring = ''
utils.log(u'write_wl_wdata: SQLite Database error ''%s'' while updating %s %s' % (errstring, modus, row_xbmc[5]), xbmc.LOGERROR)
# error at this place is the result of duplicate movies, which produces a DUPLICATE PRIMARY KEY ERROR
return 1
except mysql.connector.Error as err:
utils.log(u'write_wl_wdata: MySQL Database error ''%s'' while updating %s %s' % (err, modus, row_xbmc[5]), xbmc.LOGERROR)
self.close_db(1)
return 1 # error while writing. Do not continue with episodes, if movies raised an exception
except SystemExit:
return 4
except BaseException:
utils.log(u'write_wl_wdata: Error while updating %s %s: %s' % (modus, row_xbmc[5], sys.exc_info()[2]), xbmc.LOGERROR)
self.close_db(1)
if utils.getSetting("progressdialog") == 'true':
DIALOG_PROGRESS.close()
buggalo.addExtraData('count_update', count_update)
buggalo.addExtraData('count_insert', count_insert)
buggalo.onExceptionRaised()
return 1
if utils.getSetting("progressdialog") == 'true':
DIALOG_PROGRESS.close()
if self.monitor.abortRequested():
break # break outer loop if exit requested. Do not do any database operations below
# only commit the changes if no error occured to ensure database persistence
if count_insert > 0 or count_update > 0:
self.database_backup()
self.sqlcon_wl.commit()
if modus == 'movie':
strno = [32202, 32301]
else:
strno = [32203, 32301]
utils.showNotification(utils.getString(strno[0]), utils.getString(strno[1]) % (count_insert, count_update), xbmc.LOGINFO)
return 0
def write_xbmc_wdata(self, progressdialogue, notifications):
"""Go through all watched movies/episodes from the wl-database and check,
if the xbmc-database is up to date
Args:
progressdialogue: Show Progress Bar if True
notifications: 0= no, 1=only changed info, 2=all
Returns:
return code:
0 successfully written Kodi database
1 program exception
2 cancel by user interaction
4 SystemExit
"""
for modus in ['movie', 'episode']:
buggalo.addExtraData('modus', modus)
if modus == 'movie' and utils.getSetting("w_movies") != 'true':
continue
if modus == 'episode' and utils.getSetting("w_episodes") != 'true':
continue
utils.log(u'write_xbmc_wdata: Write watched %ss to Kodi database (pd=%d, noti=%d)' % (modus, progressdialogue, notifications), xbmc.LOGDEBUG)
count_update = 0
if progressdialogue:
DIALOG_PROGRESS = xbmcgui.DialogProgress()
DIALOG_PROGRESS.create(utils.getString(32101), utils.getString(32106))
# list to iterate over
if modus == 'movie':
list_length = len(self.watchedmovielist_wl)
else:
list_length = len(self.watchedepisodelist_wl)
# iterate over wl-list
for j in range(list_length):
if self.monitor.abortRequested():
break # this loop can take some time in debug mode and prevents Kodi to exit
if progressdialogue and DIALOG_PROGRESS.iscanceled():
if notifications > 0:
utils.showNotification(utils.getString(32204), utils.getString(32302) % (count_update), xbmc.LOGINFO)
return 2
# get media-specific list items
if modus == 'movie':
row_wl = self.watchedmovielist_wl[j]
else:
row_wl = self.watchedepisodelist_wl[j]
season = row_wl[1]
episode = row_wl[2]
imdbId = row_wl[0]
name = row_wl[5]