forked from DiMartinoXBMC/plugin.video.torrenter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.py
2104 lines (1795 loc) · 75.6 KB
/
functions.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
# -*- coding: utf-8 -*-
'''
Torrenter v2 plugin for XBMC/Kodi
Copyright (C) 2012-2015 Vadim Skorba v1 - DiMartino v2
https://forums.tvaddons.ag/addon-releases/29224-torrenter-v2.html
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/>.
'''
import urllib2
import re
import socket
import datetime
import time
import sys
import os
import json
import urllib
import xbmcplugin
import xbmcgui
import xbmc
import xbmcaddon
import xbmcvfs
import Localization
try:
from sqlite3 import dbapi2 as sqlite
except:
from pysqlite2 import dbapi2 as sqlite
__settings__ = xbmcaddon.Addon(id='plugin.video.torrenter')
__language__ = __settings__.getLocalizedString
ROOT = __settings__.getAddonInfo('path') # .decode('utf-8').encode(sys.getfilesystemencoding())
userStorageDirectory = __settings__.getSetting("storage")
USERAGENT = "Mozilla/5.0 (Windows NT 6.1; rv:5.0) Gecko/20100101 Firefox/5.0"
__addonpath__ = __settings__.getAddonInfo('path')
icon = os.path.join(__addonpath__, 'icon.png')
__version__ = __settings__.getAddonInfo('version')
__plugin__ = __settings__.getAddonInfo('name') + " v." + __version__
def clearStorage(userStorageDirectory, force = False):
userStorageDirectory = decode(userStorageDirectory)
#log('[clearStorage]: storage '+str(userStorageDirectory) + os.sep)
min_storage_size = __settings__.getSetting("min_storage_size")
storage_size = getDirectorySizeInGB(userStorageDirectory.encode('utf-8'))
if storage_size >= min_storage_size or force:
if xbmcvfs.exists(userStorageDirectory + os.sep) or os.path.exists(userStorageDirectory):
log('[clearStorage]: storage exists')
import shutil
temp = userStorageDirectory.rstrip('Torrenter').rstrip('/\\')
torrents_temp, saved_temp, i = None, None, ''
while not torrents_temp or os.path.exists(torrents_temp) or os.path.exists(saved_temp):
torrents_temp = os.path.join(temp, 'torrents' + str(i)) + os.sep
saved_temp = os.path.join(temp, 'Saved Files' + str(i)) + os.sep
if i=='':
i=0
else:
i += 1
torrents = os.path.join(userStorageDirectory, 'torrents')
saved = os.path.join(userStorageDirectory, 'Saved Files')
torrents_bool, saved_bool = False, False
if os.path.exists(torrents):
shutil.move(torrents, torrents_temp)
torrents_bool = True
if os.path.exists(saved):
shutil.move(saved, saved_temp)
saved_bool = True
shutil.rmtree(userStorageDirectory, ignore_errors=True)
#log(str(xbmcvfs.listdir(userStorageDirectory)))
xbmcvfs.mkdir(userStorageDirectory)
if torrents_bool:
shutil.move(torrents_temp, torrents)
if saved_bool:
shutil.move(saved_temp, saved)
showMessage(Localization.localize('Storage'), Localization.localize('Storage has been cleared'), forced=True)
else:
showMessage(Localization.localize('Storage'), Localization.localize('Does not exists'), forced=True)
log('[clearStorage]: fail storage '+userStorageDirectory + os.sep)
try:
DownloadDB().clear()
except Exception, e:
log('[clearStorage]: DownloadDB().clear() failed. '+str(e))
def sortcomma(dict, json):
for x in dict:
y = dict[x].split(',')
dict[x] = ''
for i in y:
if i not in json:
dict[x] = dict[x] + ',' + i
if len(dict[x]) > 0: dict[x] = dict[x][1:len(dict[x])]
return dict
def md5(string):
try:
from hashlib import md5
except ImportError:
from md5 import md5
hasher = hashlib.md5()
try:
hasher.update(string)
except:
hasher.update(string.encode('utf-8', 'ignore'))
return hasher.hexdigest()
def log(msg):
try:
xbmc.log("### [%s]: %s" % (__plugin__,msg,), level=xbmc.LOGNOTICE )
except UnicodeEncodeError:
xbmc.log("### [%s]: %s" % (__plugin__,msg.encode("utf-8", "ignore"),), level=xbmc.LOGNOTICE )
except:
xbmc.log("### [%s]: %s" % (__plugin__,'ERROR LOG',), level=xbmc.LOGNOTICE )
def debug(msg, forced=False):
if getSettingAsBool('debug') and forced:
level=xbmc.LOGNOTICE
else:
level=xbmc.LOGDEBUG
try:
xbmc.log("### [%s]: %s" % (__plugin__,msg,), level=level )
except UnicodeEncodeError:
xbmc.log("### [%s]: %s" % (__plugin__,msg.encode("utf-8", "ignore"),), level=level )
except:
xbmc.log("### [%s]: %s" % (__plugin__,'ERROR DEBUG',), level=level )
def showMessage(heading, message, times=10000, forced=False):
xbmc.executebuiltin('XBMC.Notification("%s", "%s", %s, "%s")' % (
heading.replace('"', "'"), message.replace('"', "'"), times, icon))
debug(str((heading.replace('"', "'"), message.replace('"', "'"), times, icon)))
def magnet_alert():
showMessage('Ace Stream', Localization.localize('Does not support magnet links!'))
def dates_diff(fdate, ldate):
try:
if ldate == 'today':
x = datetime.datetime.now()
else:
x = datetime.datetime.strptime(ldate, '%d.%m.%Y')
y = datetime.datetime.strptime(fdate, '%d.%m.%Y')
z = x - y
except TypeError:
if ldate == 'today':
x = datetime.datetime.now()
else:
x = datetime.datetime(*(time.strptime(ldate, '%d.%m.%Y')[0:6]))
y = datetime.datetime(*(time.strptime(fdate, '%d.%m.%Y')[0:6]))
z = x - y
return str(z.days)
def today_str():
try:
x = datetime.datetime.now().strftime('%d.%m.%Y')
except TypeError:
x = datetime.datetime(*(time.strptime(datetime.datetime.now().strftime('%d.%m.%Y'), '%d.%m.%Y')[0:6]))
x = datetime.datetime.strftime(x, '%d.%m.%Y')
return str(x)
def get_params():
param = []
paramstring = sys.argv[2]
if len(paramstring) >= 2:
params = sys.argv[2]
cleanedparams = params.replace('?', '')
if (params[len(params) - 1] == '/'):
params = params[0:len(params) - 2]
pairsofparams = cleanedparams.split('&')
param = {}
for i in range(len(pairsofparams)):
splitparams = {}
splitparams = pairsofparams[i].split('=')
if (len(splitparams)) == 2:
param[splitparams[0]] = splitparams[1]
return param
def get_apps(paramstring=None):
if not paramstring: paramstring = sys.argv[2]
if len(paramstring) >= 2:
try:
apps = json.loads(urllib.unquote_plus(paramstring))
except:
cleanapps = str(paramstring).replace('?', '', 1)
apps = json.loads(urllib.unquote_plus(cleanapps))
return apps
def int_xx(intxx):
if intxx and intxx != 'None':
return '%02d' % (int(intxx))
else:
return '00'
def StripName(name, list, replace=' '):
lname = name.lower().split(' ')
name = ''
for n in lname:
if n not in list: name += ' ' + n
return name.strip()
def tempdir():
dirname = xbmc.translatePath('special://temp')
for subdir in ('xbmcup', 'plugin.video.torrenter'):
dirname = os.path.join(dirname, subdir)
if not os.path.exists(dirname):
os.mkdir(dirname)
return dirname
def makeapp(s):
return urllib.quote_plus(json.dumps(s))
def get_url(cookie, url):
headers = {'User-Agent': 'XBMC',
'Content-Type': 'application/x-www-form-urlencoded',
'Cookie': cookie}
try:
conn = urllib2.urlopen(urllib2.Request(url, urllib.urlencode({}), headers))
array = conn.read()
# debug('[get_url]: arr"'+str(array)+'"')
if array == '':
# debug('[get_url][2]: arr=""')
array = True
return array
except urllib2.HTTPError as e:
# debug('[get_url]: HTTPError, e.code='+str(e.code))
if e.code == 401:
debug('[get_url]: Denied! Wrong login or api is broken!')
return
elif e.code in [503]:
debug('[get_url]: Denied, HTTP Error, e.code=' + str(e.code))
return
else:
showMessage('HTTP Error', str(e.code))
debug('[get_url]: HTTP Error, e.code=' + str(e.code))
xbmc.sleep(2000)
return
except:
return False
def post_url_json(cookie, url, post):
headers = {'User-Agent': 'XBMC',
'Connection': 'keep-alive',
'Cookie': cookie}
conn = urllib2.urlopen(urllib2.Request(url, post, headers))
array = conn.read()
conn.close()
return array
def creat_db(dbfilename):
db = sqlite.connect(dbfilename)
cur = db.cursor()
cur.execute('pragma auto_vacuum=1')
cur.execute(
'create table sources(addtime integer, filename varchar(32) PRIMARY KEY, showId integer, seasonId integer, episodeId integer, id integer, stype varchar(32))')
cur.execute('create table cache(addtime integer, url varchar(32))')
cur.execute('create table scan(addtime integer, filename varchar(32) PRIMARY KEY)')
cur.execute('create table watched(addtime integer, rating integer, id varchar(32) PRIMARY KEY)')
db.commit()
cur.close()
db.close()
def invert_bool(var):
if bool(var):
var = False
else:
var = True
return var
def getSettingAsBool(setting):
return __settings__.getSetting(setting).lower() == "true"
def calculate(full):
consts = [(100, 20), (300, 15), (500, 10), (2000, 7), (4000, 5)]
max_const = 150
repl_const = 0
for size, const in consts:
if (size * 1024 * 1024) > full:
repl_const = int(float(const) / 100 * (full / (1024 * 1024))) # MB of first
break
if repl_const == 0:
repl_const = max_const
return repl_const
def getDirList(path, newl=None):
l = []
try:
if not newl: dirs, newl = xbmcvfs.listdir(path)
except:
try:
if not newl: dirs, newl = xbmcvfs.listdir(path.decode('utf-8').encode('cp1251'))
except:
showMessage(__language__(30206), __language__(30280), forced=True)
return l
for fl in newl:
match = re.match('.avi|.mp4|.mkV|.flv|.mov|.vob|.wmv|.ogm|.asx|.mpg|mpeg|.avc|.vp3|.fli|.flc|.m4v',
fl[int(len(fl)) - 4:len(fl)], re.I)
if match:
l.append(fl)
return l
def cutFileNames(l):
from difflib import Differ
d = Differ()
text = sortext(l)
newl = []
for li in l: newl.append(cutStr(li[0:len(li) - 1 - len(li.split('.')[-1])]))
l = newl
text1 = cutStr(text[0][0:len(text[0]) - 1 - len(text[0].split('.')[-1])])
text2 = cutStr(text[1][0:len(text[1]) - 1 - len(text[1].split('.')[-1])])
sep_file = " "
result = list(d.compare(text1.split(sep_file), text2.split(sep_file)))
debug('[cutFileNames] ' + unicode(result))
start = ''
end = ''
for res in result:
if str(res).startswith('-') or str(res).startswith('+') or str(res).startswith('.?'):
break
start = start + str(res).strip() + sep_file
result.reverse()
for res in result:
if str(res).startswith('-') or str(res).startswith('+') or str(res).startswith('?'):
break
end = sep_file + str(res).strip() + end
newl = l
l = []
debug('[cutFileNames] [start] ' + start)
debug('[cutFileNames] [end] ' + end)
for fl in newl:
if cutStr(fl[0:len(start)]) == cutStr(start): fl = fl[len(start):]
if cutStr(fl[len(fl) - len(end):]) == cutStr(end): fl = fl[0:len(fl) - len(end)]
try:
isinstance(int(fl.split(sep_file)[0]), int)
fl = fl.split(sep_file)[0]
except:
pass
l.append(fl)
debug('[cutFileNames] [sorted l] ' + unicode(sorted(l, key=lambda x: x)))
return l
def cutStr(s):
return s.replace('.', ' ').replace('_', ' ').replace('[', ' ').replace(']', ' ').lower().strip()
def sortext(filelist):
result = {}
for name in filelist:
ext = name.split('.')[-1]
try:
result[ext] = result[ext] + 1
except:
result[ext] = 1
lol = result.iteritems()
lol = sorted(lol, key=lambda x: x[1])
debug('[sortext]: lol:' + str(lol))
popext = lol[-1][0]
result, i = [], 0
for name in filelist:
if name.split('.')[-1] == popext:
result.append(name)
i = i + 1
result = sweetpair(result)
debug('[sortext]: result:' + str(result))
return result
def cutFolder(contentList, tdir=None):
dirList, contentListNew = [], []
if len(contentList) > 1:
common_folder = contentList[0][0]
debug('[cutFolder]: common_folder '+common_folder)
if '\\' in common_folder:
common_folder = common_folder.split('\\')[0]
elif '/' in common_folder:
common_folder = common_folder.split('/')[0]
common = True
for item in contentList:
if common_folder not in item[0]:
common = False
break
for item in contentList:
dir = None
if common:
item[0] = item[0][len(common_folder) + 1:]
#debug('[cutFolder]: item[0] '+item[0])
if '\\' in item[0]:
dir = item[0].split('\\')[0]
elif '/' in item[0]:
dir = item[0].split('/')[0]
elif not tdir:
contentListNew.append(item)
if tdir and ensure_str(dir) == ensure_str(tdir):
tupleContent = list(item)
tupleContent[0] = item[0][len(dir) + 1:]
contentListNew.append(list(tupleContent))
if not tdir and dir and dir not in dirList:
dirList.append(dir)
debug('[cutFolder]: dirList, contentListNew '+str(dirList)+str(contentListNew))
return dirList, contentListNew
else:
debug('[cutFolder]: dirList, contentList '+str(dirList)+str(contentList))
return dirList, contentList
def sweetpair(l):
from difflib import SequenceMatcher
s = SequenceMatcher()
ratio = []
for i in range(0, len(l)): ratio.append(0)
for i in range(0, len(l)):
for p in range(0, len(l)):
s.set_seqs(l[i], l[p])
ratio[i] = ratio[i] + s.quick_ratio()
id1, id2 = 0, 0
for i in range(0, len(l)):
if ratio[id1] <= ratio[i] and i != id2 or id2 == id1 and ratio[id1] == ratio[i]:
id2 = id1
id1 = i
# debug('1 - %d %d' % (id1, id2))
elif (ratio[id2] <= ratio[i] or id1 == id2) and i != id1:
id2 = i
# debug('2 - %d %d' % (id1, id2))
debug('[sweetpair]: id1 ' + l[id1] + ':' + str(ratio[id1]))
debug('[sweetpair]: id2 ' + l[id2] + ':' + str(ratio[id2]))
return [l[id1], l[id2]]
def FileNamesPrepare(filename):
my_season = None
my_episode = None
try:
if int(filename):
my_episode = int(filename)
debug('[FileNamesPrepare] ' + str([my_season, my_episode, filename]))
return [my_season, my_episode, filename]
except:
pass
urls = ['s(\d+)e(\d+)', '(\d+)[x|-](\d+)', 'E(\d+)', 'Ep(\d+)', '\((\d+)\)']
for file in urls:
match = re.compile(file, re.DOTALL | re.I | re.IGNORECASE).findall(filename)
if match:
try:
my_episode = int(match[1])
my_season = int(match[0])
except:
try:
my_episode = int(match[0])
except:
try:
my_episode = int(match[0][1])
my_season = int(match[0][0])
except:
try:
my_episode = int(match[0][0])
except:
break
if my_season and my_season > 100: my_season = None
if my_episode and my_episode > 365: my_episode = None
debug('[FileNamesPrepare] ' + str([my_season, my_episode, filename]))
return [my_season, my_episode, filename]
def filename2match(filename, no_date=False):
results = {'label': filename}
urls = ['(.+|.?)s(\d+)e(\d+)', '(.+|.?)s(\d+)\.e(\d+)', '(.+|.?) [\[|\(](\d+)[x|-](\d+)[\]|\)]',
'(.+|.?) (\d+)[x|-](\d+)'] # same in service
for file in urls:
match = re.compile(file, re.I | re.IGNORECASE).findall(filename)
# print str(results)
if match:
results['showtitle'], results['season'], results['episode'] = match[0]
results['showtitle'] = results['showtitle'].replace('.', ' ').replace('_', ' ').strip().replace(
'The Daily Show', 'The Daily Show With Jon Stewart')
results['season'], results['episode'] = int(results['season']), int(results['episode'])
# debug('[filename2match] '+str(results))
return results
if no_date: return
urls = ['(.+)(\d{4})\.(\d{2,4})\.(\d{2,4})', '(.+)(\d{4}) (\d{2}) (\d{2})'] # same in service
for file in urls:
match = re.compile(file, re.I | re.IGNORECASE).findall(filename)
if match:
results['showtitle'] = match[0][0].replace('.', ' ').strip().replace('The Daily Show',
'The Daily Show With Jon Stewart')
results['date'] = '%s.%s.%s' % (match[0][3], match[0][2], match[0][1])
debug('[filename2match] ' + str(results))
return results
def TextBB(string, action=None, color=None):
if action == 'b':
string = '[B]' + string + '[/B]'
return string
def jstr(s):
if not s:
s = 'null'
elif not unicode(s).isnumeric():
s = '"%s"' % (s)
return str(s)
def view_style(func):
styles = {}
num_skin = 0
view_style = int(__settings__.getSetting("skin_optimization"))
if view_style in [3, 2, 6]:
styles['searchOption'] = styles['History'] = styles['List'] = 'info'
styles['drawContent'] = styles['drawtrackerList'] = styles['drawcontentList'] = 'info'
styles['sectionMenu'] = styles['Seasons'] = 'list'
styles['uTorrentBrowser'] = styles['torrentPlayer'] = styles['openTorrent'] = 'wide'
styles['showFilesList'] = styles['DownloadStatus'] = 'wide'
elif view_style in [1, 4, 5]:
styles['searchOption'] = 'info'
styles['drawContent'] = styles['torrentPlayer'] = styles['openTorrent'] = styles['drawtrackerList'] = 'info'
styles['uTorrentBrowser'] = styles['History'] = styles['DownloadStatus'] = 'wide'
styles['showFilesList'] = styles['sectionMenu'] = 'wide'
styles['List'] = styles['drawcontentList'] = 'info3'
if view_style == 1:
styles['uTorrentBrowser'] = styles['torrentPlayer'] = 'wide'
styles['openTorrent'] = styles['History'] = styles['DownloadStatus'] = 'wide'
styles['sectionMenu'] = 'icons'
elif view_style == 5:
styles['uTorrentBrowser'] = styles['torrentPlayer'] = 'wide'
styles['openTorrent'] = styles['History'] = styles['DownloadStatus'] = 'wide'
styles['drawtrackerList'] = styles['drawContent'] = styles['List'] = styles['sectionMenu'] = 'icons'
styles['searchOption'] = 'info'
if view_style in [1, 3, 4, 5]:
num_skin = 0
elif view_style == 2:
num_skin = 1
elif view_style == 6:
num_skin = 2
style = styles.get(func)
# debug('[view_style]: lock '+str(style))
lockView(style, num_skin)
def lockView(viewId='info', num_skin=0):
xbmcplugin.setContent(int(sys.argv[1]), 'movies')
skinOptimizations = (
{'list': 50, 'info': 50, 'wide': 51, 'icons': 500, 'info3': 515, }, # Confluence
{'list': 50, 'info': 51, 'wide': 52, 'icons': 53, }, # Transperency!
{'list': 55, 'info': 55, 'wide': 55, 'icons': 55, 'info3': 55, }, # Aeon Nox
)
try:
xbmc.executebuiltin("Container.SetViewMode(%s)" % str(skinOptimizations[num_skin][viewId]))
except:
return
'''
<include>PosterWrapView2_Fanart</include> <!-- view id = 508 -->
<include>MediaListView3</include> <!-- view id = 503 -->
<include>MediaListView2</include> <!-- view id = 504 -->
<include>MediaListView4</include> <!-- view id = 515 -->
<include>WideIconView</include> <!-- view id = 505 -->
<include>MusicVideoInfoListView</include> <!-- view id = 511 -->
<include>AddonInfoListView1</include> <!-- view id = 550 -->
<include>AddonInfoThumbView1</include> <!-- view id = 551 -->
<include>LiveTVView1</include> <!-- view id = 560 -->
'''
def torrent_dir():
from resources.utorrent.net import Download
socket.setdefaulttimeout(3)
list = Download().list()
ret = 0
if list and len(list) > 0:
dirs = ["Keyboard"]
for dl in list:
if dl['dir'] not in dirs:
dirs.append(dl['dir'])
basename = os.path.dirname(dl['dir'])
if basename not in dirs:
dirs.append(basename)
else:
dirs.remove(basename)
dirs.insert(1, basename)
dialog = xbmcgui.Dialog()
ret = dialog.select(Localization.localize('Manual Torrent-client Path Edit'), dirs)
else:
ret = 0
if ret == 0:
KB = xbmc.Keyboard()
KB.setHeading(Localization.localize('Manual Torrent-client Path Edit'))
KB.setDefault(__settings__.getSetting("torrent_dir"))
KB.doModal()
if (KB.isConfirmed()):
__settings__.setSetting("torrent_dir", KB.getText())
elif ret > 0:
__settings__.setSetting("torrent_dir", dirs[ret])
def saveCheckPoint():
__settings__.setSetting("checkpoint", str(sys.argv[2]))
def gotoCheckPoint():
xbmc.executebuiltin(
'XBMC.ActivateWindow(Videos,plugin://plugin.video.myshows/%s)' % (__settings__.getSetting("checkpoint")))
def smbtopath(path):
x = path.split('@')
if len(x) > 1:
path = x[1]
else:
path = path.replace('smb://', '')
debug('[smbtopath]:' + '\\\\' + path.replace('/', '\\'))
return '\\\\' + path.replace('/', '\\')
def PrepareFilename(filename):
badsymb = [':', '"', '\\', '/', '\'', '!', ['&', 'and'], '*', '?', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ',
' ', ' ']
for b in badsymb:
if not isinstance(b, list):
filename = filename.replace(b, ' ')
else:
filename = filename.replace(b[0], b[1])
return filename.rstrip('. ')
def PrepareSearch(filename):
titles = [filename]
rstr = '. -'
badsymb = [':', '"', r'\\', '/', r'\'', '!', '&', '*', '_', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ']
for b in badsymb:
filename = filename.replace(b, ' ')
filename = re.sub("\([^)]*\)([^(]*)", "\\1", filename)
filename = re.sub("\[[^\]]*\]([^\[]*)", "\\1", filename)
filename = filename.strip().rstrip(rstr)
if titles[0] != filename and filename != '': titles.insert(0, filename)
title_array = [(u'(.+?)(Cезон|cезон|Сезон|сезон|Season|season|СЕЗОН|SEASON)', titles[0], 0),
(u'(.+?)[sS](\d{1,2})', titles[0].replace('.', ' '), 0),
]
for regex, title, i in title_array:
recomp = re.compile(regex)
match = recomp.findall(title)
if match:
titles.insert(0, match[0][i].rstrip(rstr))
return titles
def isRemoteTorr():
localhost = ['127.0.0.1', '0.0.0.0', 'localhost']
if __settings__.getSetting("torrent") == '0':
if __settings__.getSetting("torrent_utorrent_host") not in localhost:
debug('[isRemoteTorr]: uTorrent is Remote!')
return True
elif __settings__.getSetting("torrent") == '1':
if __settings__.getSetting("torrent_transmission_host") not in localhost:
debug('[isRemoteTorr]: Transmission is Remote!')
return True
def changeDBTitle(showId):
from utilities import xbmcJsonRequest
shows = xbmcJsonRequest(
{'jsonrpc': '2.0', 'method': 'VideoLibrary.GetTVShows', 'params': {'properties': ['title']}, 'id': 0})
if not shows:
debug('[changeDBTitle]: XBMC JSON Result was empty.')
return
if 'tvshows' in shows:
shows = shows['tvshows']
debug("[changeDBTitle]: XBMC JSON Result: '%s'" % str(shows))
else:
debug("[changeDBTitle]: Key 'tvshows' not found")
return
if len(shows) > 0:
newtitle = id2title(showId, None, True)[0].decode('utf-8', 'ignore')
dialog = xbmcgui.Dialog()
dialog_items, dialog_ids = [__language__(30205)], [-1]
shows = sorted(shows, key=lambda x: x['tvshowid'], reverse=True)
for show in shows:
dialog_ids.append(show['tvshowid'])
dialog_items.append(show['title'])
ret = dialog.select(newtitle, dialog_items)
if ret > 0:
ok = dialog.yesno(__language__(30322), __language__(30534),
__language__(30535) % (dialog_items[ret], newtitle))
if ok:
result = xbmcJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.SetTVShowDetails',
'params': {'tvshowid': int(dialog_ids[ret]), 'title': unicode(newtitle)},
'id': 1})
if result in [newtitle, 'OK']:
showMessage(__language__(30208), __language__(30536) % (newtitle), forced=True)
else:
debug("[changeDBTitle]: XBMC JSON Result: '%s'" % str(result))
return
class TimeOut():
def __init__(self):
self.scan = CacheDB('web_timeout')
self.gone_online = CacheDB('go_online')
self.get = self.scan.get()
self.online = 30
self.offline = 1
def go_offline(self, manual=False):
gone_online = self.gone_online.get()
if gone_online:
gone_online = int(gone_online)
else:
gone_online = 0
if not manual:
if gone_online and gone_online + self.online >= int(round(time.time())):
debug('[TimeOut]: too soon to go back offline! %d s' % (
(gone_online + self.online * 4) - int(round(time.time()))))
return
if self.timeout() == self.online:
debug('[TimeOut]: Gone offline! %d s' % ((gone_online + self.online * 4) - int(round(time.time()))))
showMessage(__language__(30520), __language__(30545) % (self.offline))
if self.get: self.scan.delete()
self.scan.add()
def go_online(self):
if self.get:
self.scan.delete()
debug('[TimeOut]: Gone online!')
showMessage(__language__(30521), __language__(30545) % (self.online))
if self.gone_online.get():
self.gone_online.delete()
self.gone_online.add()
def timeout(self):
if self.get and int(time.time()) - self.get < refresh_period * 3600:
to = self.offline
else:
to = self.online
# debug('[TimeOut]: '+str(to))
return to
class ListDB:
def __init__(self, version=1.0):
self.dbname = 'list' + '.db3'
dirname = xbmc.translatePath('special://temp')
self.dbfilename = os.path.join(dirname, 'xbmcup',
__settings__.getAddonInfo('id').replace('plugin://', '').replace('/', ''),
self.dbname)
self.version = version
if not xbmcvfs.exists(self.dbfilename):
self.creat_db()
def creat_db(self):
self._connect()
self.cur.execute('pragma auto_vacuum=1')
self.cur.execute('create table db_ver(version real)')
# self.cur.execute('create table list(addtime integer PRIMARY KEY, title varchar(32), originaltitle varchar(32)'
# ', year integer, category varchar(32), subcategory varchar(32))')
self.cur.execute('create table list(addtime integer PRIMARY KEY, info varchar(32))')
self.cur.execute('insert into db_ver(version) values(?)', (self.version,))
self.db.commit()
self._close()
def get(self, addtime):
self._connect()
self.cur.execute('select info from list where addtime="' + addtime + '"')
x = self.cur.fetchone()
self._close()
return x[0] if x else None
def get_all(self):
self._connect()
# self.cur.execute('select addtime,title,originaltitle,year,category,subcategory from list')
self.cur.execute('select addtime,info from list')
x = self.cur.fetchall()
self._close()
return x if x else None
def add(self, url):
self._connect()
self.cur.execute('insert into list(addtime,info)'
' values(?,?)', (int(time.time()), url))
self.db.commit()
self._close()
def delete(self, addtime):
self._connect()
self.cur.execute('delete from list where addtime="' + addtime + '"')
self.db.commit()
self._close()
def _connect(self):
self.db = sqlite.connect(self.dbfilename)
self.cur = self.db.cursor()
def _close(self):
self.cur.close()
self.db.close()
class HistoryDB:
def __init__(self, version=1.1):
self.name = 'history.db3'
self.version = version
def get_all(self):
self._connect()
self.cur.execute('select addtime,string,fav from history order by addtime DESC')
x = self.cur.fetchall()
self._close()
return x if x else None
def get(self, url):
self._connect()
self.cur.execute('select string from history where string="' + url + '"')
x = self.cur.fetchone()
self._close()
return x[0] if x else None
def get_providers(self, addtime):
self._connect()
self.cur.execute('select providers from history where addtime="' + addtime + '"')
x = self.cur.fetchone()
self._close()
# print 'get_providers: '+str(x[0].split(',') if x and x[0]!='' else None)
return x[0].split(',') if x and x[0] != '' else None
def set_providers(self, addtime, providers):
self._connect()
if isinstance(providers, dict):
temp = []
for i in providers.keys():
if providers.get(i):
temp.append(i)
providers = temp
str_p = ','.join(providers)
self.cur.execute('UPDATE history SET providers = "' + str_p + '" where addtime=' + addtime)
self.db.commit()
self._close()
def change_providers(self, addtime, searcher):
self._connect()
providers = self.get_providers(addtime)
keys = Searchers().dic().keys()
if providers and len(providers) > 0:
if searcher in providers:
providers.remove(searcher)
else:
providers.append(searcher)
for i in providers:
if i not in keys:
providers.remove(i)
self.set_providers(addtime, providers)
self.db.commit()
self._close()
def add(self, url):
self._connect()
self.cur.execute('select fav from history where string="' + url + '"')
x = self.cur.fetchone()
if x: x = int(x[0])
fav = True if x else False
if not fav:
self.cur.execute('delete from history where string="' + decode(url) + '"')
self.cur.execute('insert into history(addtime,string,fav,providers)'
' values(?,?,?,?)', (int(time.time()), decode(url), 0, ""))
self.db.commit()
self._close()
def update(self, addtime, fav):
self._connect()
self.cur.execute('UPDATE history SET fav = ' + str(fav) + ' where addtime=' + addtime)
self.db.commit()
self._close()
def fav(self, addtime):
self.update(addtime, fav=1)
def unfav(self, addtime):
self.update(addtime, fav=0)
def delete(self, addtime):
self._connect()
self.cur.execute('delete from history where addtime="' + addtime + '"')
self.db.commit()
self._close()
def clear(self):
self._connect()
self.cur.execute('delete from history where fav=0')
self.db.commit()
self._close()
def _connect(self):
dirname = xbmc.translatePath('special://temp')
for subdir in ('xbmcup', 'plugin.video.torrenter'):
dirname = os.path.join(dirname, subdir)
if not xbmcvfs.exists(dirname):
xbmcvfs.mkdir(dirname)
self.filename = os.path.join(dirname, self.name)
first = False
if not xbmcvfs.exists(self.filename):
first = True
self.db = sqlite.connect(self.filename, check_same_thread=False)
if not first:
self.cur = self.db.cursor()
try:
self.cur.execute('select version from db_ver')
row = self.cur.fetchone()
if not row or float(row[0]) != self.version:
self.cur.execute('drop table history')
self.cur.execute('drop table if exists db_ver')
first = True
self.db.commit()
self.cur.close()
except:
self.cur.execute('drop table history')
first = True
self.db.commit()
self.cur.close()