This repository has been archived by the owner on Jan 19, 2022. It is now read-only.
forked from manacker/service.subtitles.subscene
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathservice.py
613 lines (516 loc) · 26.2 KB
/
service.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
# -*- coding: utf-8 -*-
import os
import sys
import xbmc
if sys.version_info.major == 3:
import urllib.request, urllib.parse, urllib.error
import html.parser as HTMLParser
else:
import urllib
import urllib2
import HTMLParser
import xbmcvfs
import xbmcaddon
import xbmcgui
import xbmcplugin
import uuid
import unicodedata
import re
import difflib
from operator import itemgetter
__addon__ = xbmcaddon.Addon()
__author__ = __addon__.getAddonInfo('author')
__scriptid__ = __addon__.getAddonInfo('id')
__scriptname__ = __addon__.getAddonInfo('name')
__version__ = __addon__.getAddonInfo('version')
__language__ = __addon__.getLocalizedString
if sys.version_info.major == 3:
__cwd__ = xbmcvfs.translatePath(__addon__.getAddonInfo('path'))
__profile__ = xbmcvfs.translatePath(__addon__.getAddonInfo('profile'))
__resource__ = xbmcvfs.translatePath(os.path.join(__cwd__, 'resources', 'lib'))
__temp__ = xbmcvfs.translatePath(os.path.join(__profile__, 'temp', ''))
else:
__cwd__ = unicode(xbmc.translatePath(__addon__.getAddonInfo('path')), 'utf-8')
__profile__ = unicode(xbmc.translatePath(__addon__.getAddonInfo('profile')), 'utf-8')
__resource__ = unicode(xbmc.translatePath(os.path.join(__cwd__, 'resources', 'lib')), 'utf-8')
__temp__ = unicode(xbmc.translatePath(os.path.join(__profile__, 'temp', '')), 'utf-8')
sys.path.append(__resource__)
from SubsceneUtilities import log, geturl, get_language_codes, subscene_languages, get_episode_pattern
main_url = "https://subscene.com"
aliases = {
"marvels agents of shield" : "Agents of Shield",
"marvels agents of s.h.i.e.l.d" : "Agents of Shield",
"marvels jessica jones": "Jessica Jones",
"dcs legends of tomorrow": "Legends of Tomorrow"
}
# Seasons as strings for searching
seasons = ["Specials", "First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eighth", "Ninth", "Tenth"]
seasons = seasons + ["Eleventh", "Twelfth", "Thirteenth", "Fourteenth", "Fifteenth", "Sixteenth", "Seventeenth",
"Eighteenth", "Nineteenth", "Twentieth"]
seasons = seasons + ["Twenty-first", "Twenty-second", "Twenty-third", "Twenty-fourth", "Twenty-fifth", "Twenty-sixth",
"Twenty-seventh", "Twenty-eighth", "Twenty-ninth"]
search_section_pattern = "<h2 class=\"(?P<section>\w+)\">(?:[^<]+)</h2>\s+<ul>(?P<content>.*?)</ul>"
movie_season_pattern = ("<a href=\"(?P<link>/subtitles/[^\"]*)\">(?P<title>[^<]+)\((?P<year>\d{4})\)</a>\s+"
"</div>\s+<div class=\"subtle count\">\s+(?P<numsubtitles>\d+)")
def rmtree(path):
if sys.version_info.major < 3:
if isinstance(path, unicode):
path = path.encode('utf-8')
dirs, files = xbmcvfs.listdir(path)
for dir in dirs:
rmtree(os.path.join(path, dir))
for file in files:
xbmcvfs.delete(os.path.join(path, file))
xbmcvfs.rmdir(path)
try:
rmtree(__temp__)
except:
pass
xbmcvfs.mkdirs(__temp__)
def find_movie(content, title, year):
found_urls = {}
found_movies = []
h = HTMLParser.HTMLParser()
for secmatches in re.finditer(search_section_pattern, content, re.IGNORECASE | re.DOTALL):
log(__name__, secmatches.group('section'))
for matches in re.finditer(movie_season_pattern, secmatches.group('content'), re.IGNORECASE | re.DOTALL):
if matches.group('link') in found_urls:
if secmatches.group('section') == 'close':
found_movies[found_urls[matches.group('link')]]['is_close'] = True
if secmatches.group('section') == 'exact':
found_movies[found_urls[matches.group('link')]]['is_exact'] = True
continue
found_urls[matches.group('link')] = len(found_movies)
found_title = matches.group('title')
found_title = h.unescape(found_title)
log(__name__, "Found movie on search page: %s (%s)" % (found_title, matches.group('year')))
found_movies.append(
{'t': found_title.lower(),
'y': int(matches.group('year')),
'is_exact': secmatches.group('section') == 'exact',
'is_close': secmatches.group('section') == 'close',
'l': matches.group('link'),
'c': int(matches.group('numsubtitles'))})
year = int(year)
title = title.lower()
# Priority 1: matching title and year
for movie in found_movies:
if movie['t'].find(title) > -1:
if movie['y'] == year:
log(__name__, "Matching movie found on search page: %s (%s)" % (movie['t'], movie['y']))
return movie['l']
# Priority 2: matching title and one off year
for movie in found_movies:
if movie['t'].find(title) > -1:
if movie['y'] == year + 1 or movie['y'] == year - 1:
log(__name__, "Matching movie found on search page (one off year): %s (%s)" % (movie['t'], movie['y']))
return movie['l']
# Priority 3: "Exact" match according to search result page
close_movies = []
for movie in found_movies:
if movie['is_exact']:
log(__name__, "Using 'Exact' match: %s (%s)" % (movie['t'], movie['y']))
return movie['l']
if movie['is_close']:
close_movies.append(movie)
# Priority 4: "Close" match according to search result page
if len(close_movies) > 0:
close_movies = sorted(close_movies, key=itemgetter('c'), reverse=True)
log(__name__, "Using 'Close' match: %s (%s)" % (close_movies[0]['t'], close_movies[0]['y']))
return close_movies[0]['l']
return None
def find_tv_show_season(content, tvshow, season):
url_found = None
found_urls = []
possible_matches = []
all_tvshows = []
h = HTMLParser.HTMLParser()
for matches in re.finditer(movie_season_pattern, content, re.IGNORECASE | re.DOTALL):
found_title = matches.group('title')
found_title = h.unescape(found_title)
if matches.group('link') in found_urls:
continue
log(__name__, "Found tv show season on search page: %s" % found_title)
found_urls.append(matches.group('link'))
s = difflib.SequenceMatcher(None, (found_title + ' ' + matches.group('year')).lower(), tvshow.lower())
all_tvshows.append(matches.groups() + (s.ratio() * int(matches.group('numsubtitles')),))
if found_title.lower().find(tvshow.lower() + " ") > -1:
if found_title.lower().find(season.lower()) > -1:
log(__name__, "Matching tv show season found on search page: %s" % found_title)
possible_matches.append(matches.groups())
if len(possible_matches) > 0:
possible_matches = sorted(possible_matches, key=lambda x: -int(x[3]))
url_found = possible_matches[0][0]
log(__name__, "Selecting matching tv show with most subtitles: %s (%s)" % (
possible_matches[0][1], possible_matches[0][3]))
else:
if len(all_tvshows) > 0:
all_tvshows = sorted(all_tvshows, key=lambda x: -int(x[4]))
url_found = all_tvshows[0][0]
log(__name__, "Selecting tv show with highest fuzzy string score: %s (score: %s subtitles: %s)" % (
all_tvshows[0][1], all_tvshows[0][4], all_tvshows[0][3]))
return url_found
def append_subtitle(item):
title = item['filename']
if 'comment' in item and item['comment'] != '':
title = "%s[CR][COLOR silver][I](%s)[/I][/COLOR]" % (title, item['comment'])
if sys.version_info.major == 3:
listitem = xbmcgui.ListItem(label=item['lang']['name'],
label2=title)
listitem.setArt({'icon': item['rating'], 'thumb': item['lang']['2let']})
else:
listitem = xbmcgui.ListItem(label=item['lang']['name'],
label2=title,
iconImage=item['rating'],
thumbnailImage=item['lang']['2let'])
listitem.setProperty("sync", 'true' if item["sync"] else 'false')
listitem.setProperty("hearing_imp", 'true' if item["hearing_imp"] else 'false')
# below arguments are optional, it can be used to pass any info needed in download function
# anything after "action=download&" will be sent to addon once user clicks listed subtitle to downlaod
url = "plugin://%s/?action=download&link=%s&filename=%s" % (__scriptid__,
item['link'],
item['filename'])
if 'episode' in item:
url += "&episode=%s" % item['episode']
# add it to list, this can be done as many times as needed for all subtitles found
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=False)
def getallsubs(url, allowed_languages, filename="", episode=""):
subtitle_pattern = ("<td class=\"a1\">\s+<a href=\"(?P<link>/subtitles/[^\"]+)\">\s+"
"<span class=\"[^\"]+ (?P<quality>\w+-icon)\">\s+(?P<language>[^\r\n\t]+)\s+</span>\s+"
"<span>\s+(?P<filename>[^\r\n\t]+)\s+</span>\s+"
"</a>\s+</td>\s+"
"<td class=\"[^\"]+\">\s+(?P<numfiles>[^\r\n\t]*)\s+</td>\s+"
"<td class=\"(?P<hiclass>[^\"]+)\">"
"(?:.*?)<td class=\"a6\">\s+<div>\s+(?P<comment>[^\"]+) \s*</div>")
codes = get_language_codes(allowed_languages)
if len(codes) < 1:
if sys.version_info.major == 3:
xbmc.executebuiltin('Notification(%s,%s)' % (__scriptname__, __language__(32004)))
else:
xbmc.executebuiltin((u'Notification(%s,%s)' % (__scriptname__, __language__(32004))).encode('utf-8'))
return
log(__name__, 'LanguageFilter='+','.join(codes))
content, response_url = geturl(url, 'LanguageFilter='+','.join(codes))
if content is None:
return
subtitles = []
h = HTMLParser.HTMLParser()
episode_regex = None
if episode != "":
episode_regex = re.compile(get_episode_pattern(episode), re.IGNORECASE)
log(__name__, "regex: %s" % get_episode_pattern(episode))
for matches in re.finditer(subtitle_pattern, content, re.IGNORECASE | re.DOTALL):
numfiles = 1
if matches.group('numfiles') != "":
numfiles = int(matches.group('numfiles'))
languagefound = matches.group('language')
language_info = subscene_languages[languagefound]
if language_info and language_info['3let'] in allowed_languages:
link = main_url + matches.group('link')
subtitle_name = matches.group('filename').strip()
hearing_imp = (matches.group('hiclass') == "a41")
rating = '0'
if matches.group('quality') == "bad-icon":
continue
if matches.group('quality') == "positive-icon":
rating = '5'
comment = re.sub("[\r\n\t]+", " ", h.unescape(matches.group('comment').strip()))
sync = False
if filename != "" and filename.lower() == subtitle_name.lower():
sync = True
if episode != "":
# log(__name__, "match: "+subtitle_name)
if episode_regex.search(subtitle_name):
subtitles.append({'rating': rating, 'filename': subtitle_name, 'sync': sync, 'link': link,
'lang': language_info, 'hearing_imp': hearing_imp, 'comment': comment})
elif numfiles > 2:
subtitle_name = subtitle_name + ' ' + (__language__(32001) % int(matches.group('numfiles')))
subtitles.append({'rating': rating, 'filename': subtitle_name, 'sync': sync, 'link': link,
'lang': language_info, 'hearing_imp': hearing_imp, 'comment': comment,
'episode': episode})
else:
subtitles.append({'rating': rating, 'filename': subtitle_name, 'sync': sync, 'link': link,
'lang': language_info, 'hearing_imp': hearing_imp, 'comment': comment})
subtitles.sort(key=lambda x: [not x['sync'], not x['lang']['name'] == PreferredSub])
for s in subtitles:
append_subtitle(s)
def prepare_search_string(s):
s = str(s)
s = s.strip()
s = re.sub(r'\s+\(\d\d\d\d\)$', '', s) # remove year from title
return str(s)
def search_movie(title, year, languages, filename):
title = prepare_search_string(title)
log(__name__, "Search movie = %s" % title)
if sys.version_info.major == 3:
url = main_url + "/subtitles/searchbytitle?query="+ urllib.parse.quote_plus(title)
else:
url = main_url + "/subtitles/searchbytitle?query="+ urllib.quote_plus(title)
content, response_url = geturl(url)
if content is not None:
log(__name__, "Multiple movies found, searching for the right one ...")
subspage_url = find_movie(content, title, year)
if subspage_url is not None:
log(__name__, "Movie found in list, getting subs ...")
url = main_url + subspage_url
getallsubs(url, languages, filename)
else:
log(__name__, "Movie not found in list: %s" % title)
if title.lower().find("&") > -1:
title = title.replace("&", "and")
log(__name__, "Trying searching with replacing '&' to 'and': %s" % title)
subspage_url = find_movie(content, title, year)
if subspage_url is not None:
log(__name__, "Movie found in list, getting subs ...")
url = main_url + subspage_url
getallsubs(url, languages, filename)
else:
log(__name__, "Movie not found in list: %s" % title)
def search_tvshow(tvshow, season, episode, languages, filename):
tvshow = prepare_search_string(tvshow)
tvshow_lookup = tvshow.lower().replace("'", "").strip(".")
if tvshow_lookup in aliases:
log(__name__, 'found alias for "%s"' % tvshow_lookup)
tvshow = aliases[tvshow_lookup]
search_string = tvshow + " - " + seasons[int(season)] + " Season"
log(__name__, "Search tvshow = %s" % search_string)
if sys.version_info.major == 3:
url = main_url + "/subtitles/searchbytitle?query=" + urllib.parse.quote_plus(search_string)
else:
url = main_url + "/subtitles/searchbytitle?query=" + urllib.quote_plus(search_string)
content, response_url = geturl(url)
if content is not None:
log(__name__, "Multiple tv show seasons found, searching for the right one ...")
tv_show_seasonurl = find_tv_show_season(content, tvshow, seasons[int(season)])
if tv_show_seasonurl is not None:
log(__name__, "Tv show season found in list, getting subs ...")
url = main_url + tv_show_seasonurl
epstr = "%d:%d" % (int(season), int(episode))
getallsubs(url, languages, filename, epstr)
def search_manual(searchstr, languages, filename):
search_string = prepare_search_string(searchstr)
url = main_url + "/subtitles/searchbytitle?query=" + search_string
getallsubs(url, languages, filename)
def search_filename(filename, languages):
title, year = xbmc.getCleanMovieTitle(filename)
log(__name__, "clean title: \"%s\" (%s)" % (title, year))
try:
yearval = int(year)
except ValueError:
yearval = 0
match = re.search(r'\WS(?P<season>\d\d)E(?P<episode>\d\d)', filename, flags=re.IGNORECASE)
if match is not None:
tvshow = title[:match.start('season') - 1].strip()
season = match.group('season').lstrip('0')
episode = match.group('episode').lstrip('0')
search_tvshow(tvshow, season, episode, languages, filename)
elif title and yearval > 1900:
search_movie(title, year, languages, filename)
else:
search_manual(filename, languages, filename)
def search(item):
filename = os.path.splitext(os.path.basename(item['file_original_path']))[0]
log(__name__, "Search_subscene='%s', filename='%s', addon_version=%s" % (item, filename, __version__))
if item['mansearch']:
search_manual(item['mansearchstr'], item['3let_language'], filename)
elif item['tvshow']:
search_tvshow(item['tvshow'], item['season'], item['episode'], item['3let_language'], filename)
elif item['title'] and item['year']:
search_movie(item['title'], item['year'], item['3let_language'], filename)
elif item['title']:
search_filename(item['title'], item['3let_language'])
else:
search_filename(filename, item['3let_language'])
def download(link, episode=""):
subtitle_list = []
exts = [".srt", ".sub", ".txt", ".smi", ".ssa", ".ass"]
downloadlink_pattern = "...<a href=\"(.+?)\" rel=\"nofollow\" onclick=\"DownloadSubtitle"
uid = uuid.uuid4()
if sys.version_info.major == 3:
tempdir = os.path.join(__temp__, str(uid))
else:
tempdir = os.path.join(__temp__, unicode(uid))
if not xbmcvfs.mkdirs(tempdir):
log(__name__, "Failed to create temp directory " + tempdir)
content, response_url = geturl(link)
content = str(content)
match = re.compile(downloadlink_pattern).findall(content)
if match:
downloadlink = main_url + match[0]
viewstate = 0
previouspage = 0
subtitleid = 0
typeid = "zip"
filmid = 0
if sys.version_info.major == 3:
postparams = urllib.parse.urlencode(
{'__EVENTTARGET': 's$lc$bcr$downloadLink', '__EVENTARGUMENT': '', '__VIEWSTATE': viewstate,
'__PREVIOUSPAGE': previouspage, 'subtitleId': subtitleid, 'typeId': typeid, 'filmId': filmid}).encode()
else:
postparams = urllib.urlencode(
{'__EVENTTARGET': 's$lc$bcr$downloadLink', '__EVENTARGUMENT': '', '__VIEWSTATE': viewstate,
'__PREVIOUSPAGE': previouspage, 'subtitleId': subtitleid, 'typeId': typeid, 'filmId': filmid})
useragent = ("User-Agent=Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.3) "
"Gecko/20100401 Firefox/3.6.3 ( .NET CLR 3.5.30729)")
headers = {'User-Agent': useragent, 'Referer': link}
log(__name__, "Fetching subtitles using url '%s' with referer header '%s' and post parameters '%s'" % (
downloadlink, link, postparams))
if sys.version_info.major == 3:
request = urllib.request.Request(downloadlink, postparams, headers)
response = urllib.request.urlopen(request)
else:
request = urllib2.Request(downloadlink, postparams, headers)
response = urllib2.urlopen(request)
if response.getcode() != 200:
log(__name__, "Failed to download subtitle file")
return subtitle_list
local_tmp_file = os.path.join(tempdir, "subscene.xxx")
packed = False
try:
log(__name__, "Saving subtitles to '%s'" % local_tmp_file)
if sys.version_info.major == 3:
local_file_handle = xbmcvfs.File(local_tmp_file, "w")
local_file_handle.write(bytearray(response.read()))
else:
local_file_handle = xbmcvfs.File(local_tmp_file, "wb")
local_file_handle.write(response.read())
local_file_handle.close()
log(__name__, "Checking archive type")
# Check archive type (rar/zip/else) through the file header (rar=Rar!, zip=PK)
myfile = xbmcvfs.File(local_tmp_file, "rb")
myfile.seek(0,0)
if myfile.read(1) == 'R':
typeid = "rar"
packed = True
log(__name__, "Discovered RAR Archive")
else:
myfile.seek(0,0)
if myfile.read(1) == 'P':
typeid = "zip"
packed = True
log(__name__, "Discovered ZIP Archive")
else:
typeid = "srt"
packed = False
log(__name__, "Discovered a non-archive file")
myfile.close()
local_tmp_file = os.path.join(tempdir, "subscene." + typeid)
xbmcvfs.rename(os.path.join(tempdir, "subscene.xxx"), local_tmp_file)
log(__name__, "Saving to %s" % local_tmp_file)
except:
log(__name__, "Failed to save subtitle to %s" % local_tmp_file)
#NOTE: RAR is not supported natively. The addon vfs.rar or vfs.libarchive is required and needs to be enabled for rar support. However, those addons aren't working in Kodi 19 yet.
if packed:
xbmc.sleep(500)
log(__name__, "Extracting '%s' to '%s'" % (local_tmp_file, tempdir))
if sys.version_info.major == 3:
xbmc.executebuiltin('XBMC.Extract("%s","%s")' % (local_tmp_file, tempdir), True)
else:
xbmc.executebuiltin(('XBMC.Extract("%s","%s")' % (local_tmp_file, tempdir,)).encode('utf-8'), True)
episode_pattern = None
if episode != '':
episode_pattern = re.compile(get_episode_pattern(episode), re.IGNORECASE)
for dir in xbmcvfs.listdir(tempdir)[0]:
for file in xbmcvfs.listdir(os.path.join(tempdir, dir))[1]:
if os.path.splitext(file)[1] in exts:
log(__name__, 'match '+episode+' '+file)
if episode_pattern and not episode_pattern.search(file):
continue
log(__name__, "=== returning subtitle file %s" % file)
subtitle_list.append(os.path.join(tempdir, dir, file))
for file in xbmcvfs.listdir(tempdir)[1]:
if os.path.splitext(file)[1] in exts:
log(__name__, 'match '+episode+' '+file)
if episode_pattern and not episode_pattern.search(file):
continue
log(__name__, "=== returning subtitle file %s" % file)
subtitle_list.append(os.path.join(tempdir, file))
if len(subtitle_list) == 0:
if sys.version_info.major == 3:
if episode:
xbmc.executebuiltin('Notification(%s,%s)' % (__scriptname__, __language__(32002)))
else:
xbmc.executebuiltin('Notification(%s,%s)' % (__scriptname__, __language__(32003)))
else:
if episode:
xbmc.executebuiltin((u'Notification(%s,%s)' % (__scriptname__, __language__(32002))).encode('utf-8'))
else:
xbmc.executebuiltin((u'Notification(%s,%s)' % (__scriptname__, __language__(32003))).encode('utf-8'))
return subtitle_list
def normalizeString(string):
if sys.version_info.major == 3:
return unicodedata.normalize(
'NFKD', string
)
else:
return unicodedata.normalize(
'NFKD', unicode(unicode(string, 'utf-8'))
).encode('ascii', 'ignore')
def get_params():
param = {}
paramstring = sys.argv[2]
if len(paramstring) >= 2:
params = paramstring
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 = pairsofparams[i].split('=')
if (len(splitparams)) == 2:
param[splitparams[0]] = splitparams[1]
return param
params = get_params()
if params['action'] == 'search' or params['action'] == 'manualsearch':
item = {}
item['temp'] = False
item['rar'] = False
item['mansearch'] = False
item['year'] = xbmc.getInfoLabel("VideoPlayer.Year") # Year
item['season'] = str(xbmc.getInfoLabel("VideoPlayer.Season")) # Season
item['episode'] = str(xbmc.getInfoLabel("VideoPlayer.Episode")) # Episode
if item['episode'].lower().find("s") > -1: # Check if season is "Special"
item['season'] = "0" #
item['episode'] = item['episode'][-1:]
item['tvshow'] = normalizeString(xbmc.getInfoLabel("VideoPlayer.TVshowtitle")) # Show
item['title'] = normalizeString(xbmc.getInfoLabel("VideoPlayer.OriginalTitle")) # try to get original title
if item['title'] == "":
item['title'] = normalizeString(xbmc.getInfoLabel("VideoPlayer.Title")) # no original title, get just Title
if 'searchstring' in params:
item['mansearch'] = True
item['mansearchstr'] = params['searchstring']
item['3let_language'] = []
PreferredSub = params.get('preferredlanguage')
if 'languages' in params:
if sys.version_info.major == 3:
for lang in urllib.parse.unquote(params['languages']).split(","):
item['3let_language'].append(xbmc.convertLanguage(lang, xbmc.ISO_639_2))
else:
for lang in urllib.unquote(params['languages']).decode('utf-8').split(","):
item['3let_language'].append(xbmc.convertLanguage(lang, xbmc.ISO_639_2))
if sys.version_info.major == 3:
item['file_original_path'] = urllib.parse.unquote(xbmc.Player().getPlayingFile()) # Full path
else:
item['file_original_path'] = urllib.unquote(xbmc.Player().getPlayingFile().decode('utf-8')) # Full path
if item['file_original_path'].find("http") > -1:
item['temp'] = True
elif item['file_original_path'].find("rar://") > -1:
item['rar'] = True
item['file_original_path'] = os.path.dirname(item['file_original_path'][6:])
elif item['file_original_path'].find("stack://") > -1:
stackPath = item['file_original_path'].split(" , ")
item['file_original_path'] = stackPath[0][8:]
search(item)
elif params['action'] == 'download':
# we pickup all our arguments sent from def Search()
if 'episode' in params:
subs = download(params["link"], params["episode"])
else:
subs = download(params["link"])
# we can return more than one subtitle for multi CD versions, for now we are still working out how to handle that
# in XBMC core
for sub in subs:
listitem = xbmcgui.ListItem(label=sub)
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=sub, listitem=listitem, isFolder=False)
xbmcplugin.endOfDirectory(int(sys.argv[1])) # send end of directory to XBMC