forked from Amelandbor/service.subtitles.addic7ed
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.py
280 lines (218 loc) · 9.91 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
# -*- coding: utf-8 -*-
# Based on contents from https://github.com/Diecke/service.subtitles.addicted
# Thanks Diecke!
import os
import sys
import xbmc
import urllib
import urllib2
import xbmcvfs
import xbmcaddon
import xbmcgui
import xbmcplugin
import shutil
import unicodedata
import re
import socket
import string
from BeautifulSoup import BeautifulSoup
__addon__ = xbmcaddon.Addon()
__scriptid__ = __addon__.getAddonInfo('id')
__scriptname__ = __addon__.getAddonInfo('name')
__version__ = __addon__.getAddonInfo('version')
__language__ = __addon__.getLocalizedString
__cwd__ = xbmc.translatePath( __addon__.getAddonInfo('path') ).decode("utf-8")
__profile__ = xbmc.translatePath( __addon__.getAddonInfo('profile') ).decode("utf-8")
__resource__ = xbmc.translatePath( os.path.join( __cwd__, 'resources', 'lib' ) ).decode("utf-8")
__temp__ = xbmc.translatePath( os.path.join( __profile__, 'temp', '') ).decode("utf-8")
sys.path.append (__resource__)
from Addic7edUtilities import log, get_language_info
self_host = "http://www.addic7ed.com"
self_release_pattern = re.compile("Version (.+), ([0-9]+).([0-9])+ MBs")
req_headers = {
'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13',
'Referer': 'http://www.addic7ed.com'}
def get_url(url):
request = urllib2.Request(url, headers=req_headers)
opener = urllib2.build_opener()
response = opener.open(request)
contents = response.read()
return contents
def append_subtitle(item):
listitem = xbmcgui.ListItem(label=item['lang']['name'],
label2=item['filename'],
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')
url = "plugin://%s/?action=download&link=%s&filename=%s" % (__scriptid__,
item['link'],
item['filename'])
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=False)
def query_TvShow(name, season, episode, langs, file_original_path):
name = addic7ize(name).lower().replace(" ", "_")
searchurl = "%s/serie/%s/%s/%s/addic7ed" %(self_host, name, season, episode)
filename_string = "%s.S%.2dE%.2d" %(name.replace("_", ".").title(), int(season), int(episode) )
query(searchurl, langs, file_original_path, filename_string)
def query_Film(name, year, langs, file_original_path):
name = urllib.quote(name.replace(" ", "_"))
searchurl = "%s/film/%s_(%s)-Download" %(self_host,name, str(year))
filename_string = "%s" %(name.replace("_", ".").title() )
query(searchurl, langs, file_original_path, filename_string)
def query(searchurl, langs, file_original_path, filename_string):
sublinks = []
socket.setdefaulttimeout(20)
request = urllib2.Request(searchurl, headers=req_headers)
request.add_header('Pragma', 'no-cache')
page = urllib2.build_opener().open(request)
content = page.read()
content = content.replace("The safer, easier way", "The safer, easier way \" />")
soup = BeautifulSoup(content)
file_name = str(os.path.basename(file_original_path)).split("-")[-1].lower()
for langs_html in soup("td", {"class" : "language"}):
try:
subs = langs_html.findPrevious("td", {"class":"NewsTitle", "colspan" : "3"})
fullLanguage = str(langs_html).split('class="language">')[1].split('<a')[0].replace("\n","")
subteams = self_release_pattern.match(str(subs.contents[1])).groups()[0]
if (str(subteams.replace("WEB-DL-", "").lower()).find(str(file_name))) > -1:
hashed = True
else:
hashed = False
try:
lang = get_language_info(fullLanguage)
except:
lang = ""
statusTD = langs_html.findNext("td")
status = statusTD.find("b").string.strip()
linkTD = statusTD.findNext("td")
link = "%s%s" % (self_host,linkTD.find("a")["href"])
if(subs.findNext("td", {"class":"newsDate", "colspan" : "2"}).findAll('img', {'title': 'Hearing Impaired'})):
HI = True
else:
HI = False
if status == "Completed" and (lang['3let'] in langs) :
sublinks.append({'rating': '0', 'filename': "%s-%s" %(filename_string, subteams ), 'sync': hashed, 'link': link, 'lang': lang, 'hearing_imp': HI})
except:
log(__name__, "ERROR IN BS")
pass
sublinks.sort(key=lambda x: [not x['sync']])
log(__name__, "sub='%s'" % (sublinks))
for s in sublinks:
append_subtitle(s)
def search_manual(searchstr, languages, filename):
xbmc.executebuiltin((u'Notification(%s,%s)' % (__scriptname__ , __language__(24000))).encode('utf-8'))
return False
search_string = prepare_search_string(searchstr)
url = self_host + "/search.php?search=" + search_string + '&Submit=Search'
content, response_url = geturl(url)
if content is not None:
return False
# getallsubs(content, 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
if title and yearval > 1900:
query_Film(title, year, item['3let_language'], filename)
else:
match = re.search(r'\WS(?P<season>\d\d)E(?P<episode>\d\d)', title, flags=re.IGNORECASE)
if match is not None:
tvshow = string.strip(title[:match.start('season')-1])
season = string.lstrip(match.group('season'), '0')
episode = string.lstrip(match.group('episode'), '0')
query_TvShow(tvshow, season, episode, item['3let_language'], filename)
else:
search_manual(filename, item['3let_language'], filename)
def Search(item):
filename = os.path.splitext(os.path.basename(item['file_original_path']))[0]
log(__name__, "Search_addic7ed='%s', filename='%s', addon_version=%s" % (item, filename, __version__))
if item['mansearch']:
search_manual(item['mansearchstr'], item['3let_language'], filename)
elif item['tvshow']:
query_TvShow(item['tvshow'], item['season'], item['episode'], item['3let_language'], filename)
elif item['title'] and item['year']:
query_Film(item['title'], item['year'], item['3let_language'], filename)
else:
search_filename(filename, item['3let_language'])
def download(link):
subtitle_list = []
if xbmcvfs.exists(__temp__):
shutil.rmtree(__temp__)
xbmcvfs.mkdirs(__temp__)
file = os.path.join(__temp__, "addic7ed.srt")
f = get_url(link)
local_file_handle = open(file, "wb")
local_file_handle.write(f)
local_file_handle.close()
subtitle_list.append(file)
if len(subtitle_list) == 0:
if search_string:
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(str):
return unicodedata.normalize(
'NFKD', unicode(unicode(str, 'utf-8'))
).encode('ascii', 'ignore')
# Sometimes search fail because Addic7ed uses URLs that does not match the TheTVDB format.
# This will probably grow to be a hardcoded colleciton over time.
def addic7ize(str):
addic7ize_dict = eval(open(__cwd__ + '/addic7ed_dict.txt').read())
return addic7ize_dict.get(str, str)
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
item['tvshow'] = normalizeString(xbmc.getInfoLabel("VideoPlayer.TVshowtitle")) # Show
item['title'] = normalizeString(xbmc.getInfoLabel("VideoPlayer.OriginalTitle")) # try to get original title
item['file_original_path'] = urllib.unquote(xbmc.Player().getPlayingFile().decode('utf-8')) # Full path
item['3let_language'] = []
if 'searchstring' in params:
item['mansearch'] = True
item['mansearchstr'] = params['searchstring']
for lang in urllib.unquote(params['languages']).decode('utf-8').split(","):
item['3let_language'].append(xbmc.convertLanguage(lang, xbmc.ISO_639_2))
if item['title'] == "":
item['title'] = normalizeString(xbmc.getInfoLabel("VideoPlayer.Title")) # no original title, get just Title
if item['episode'].lower().find("s") > -1: # Check if season is "Special"
item['season'] = "0" #
item['episode'] = item['episode'][-1:]
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':
subs = download(params["link"])
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