Skip to content

Commit

Permalink
Rename the addon
Browse files Browse the repository at this point in the history
Start using the new API
  • Loading branch information
CaTzil committed Jul 7, 2017
1 parent f692f6e commit e81209f
Show file tree
Hide file tree
Showing 6 changed files with 92 additions and 120 deletions.
6 changes: 3 additions & 3 deletions addon.xml
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><addon id="service.subtitles.subscenter" name="Subscenter.org" version="5.0.2" provider-name="CaTz">
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><addon id="service.subtitles.subscenter" name="Cinemast.org" version="5.0.2" provider-name="CaTz">
<requires>
<import addon="xbmc.python" version="2.14.0"/>
<import addon="script.common.plugin.cache" version="2.5.5"/>
<import addon="script.module.requests" version="2.4.3"/>
</requires>
<extension point="xbmc.subtitle.module" library="service.py"/>
<extension point="xbmc.addon.metadata">
<summary lang="en">Subscenter.org</summary>
<description lang="en">Search and Download subtitles from subscenter.org. Contributors: rabak, Ori Varon, sagiben</description>
<summary lang="en">Cinemast.org</summary>
<description lang="en">Search and Download subtitles from cinemast.org. Contributors: rabak, Ori Varon, sagiben</description>
<source>https://github.com/XBMCil/service.subtitles.subscenter</source>
<language>en</language>
<email> </email>
Expand Down
Binary file modified icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file removed logo.png
Binary file not shown.
155 changes: 76 additions & 79 deletions resources/lib/SUBUtilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,8 @@ def notify(msg_id):
xbmc.executebuiltin((u'Notification(%s,%s)' % (__scriptname__, __language__(msg_id))).encode('utf-8'))


class SubscenterHelper:
BASE_URL = "http://www.subscenter.info/he/"
class SubsHelper:
BASE_URL = "http://www.cinemast.org/he/cinemast/api/"

def __init__(self):
self.urlHandler = URLHandler()
Expand All @@ -130,102 +130,97 @@ def _search(self, item):
results = []

search_string = re.split(r'\s\(\w+\)$', item["tvshow"])[0] if item["tvshow"] else item["title"]

if item["tvshow"]:
cache_key = get_store_key("tv-show_", search_string)
results = store.get(cache_key)
if results:
results = eval(results)

if not results:
query = {"q": search_string.encode("utf-8").lower() + "'"} # hack to prevent redirection in hebrew search
search_result = self.urlHandler.request(self.BASE_URL + "subtitle/search/", query_string=query)
if search_result is None:
user_token = self.get_user_token()

if user_token:
query = {"q": search_string.encode("utf-8"), "user": user_token["user"], "token": user_token["token"]}
if item["tvshow"]:
query["type"] = "series"
query["season"] = item["season"]
query["episode"] = item["episode"]
else:
query["type"] = "movies"
if item["year"]:
query["year_start"] = int(item["year"]) - 1
query["year_end"] = int(item["year"])

search_result = self.urlHandler.request(self.BASE_URL + "search/", query)

if search_result is not None and search_result["result"] == "failed":
# Update cached token
user_token = self.get_user_token(True)
query["token"] = user_token["token"]
search_result = self.urlHandler.request(self.BASE_URL + "search/", query)

if search_result is not None and search_result["result"] == "failed":
notify(32009)
return results

log("Results: %s" % search_result)

if search_result is None or search_result["result"] != "success" or search_result["count"] < 1:
return results # return empty set

urls = re.findall(u'<a href=".*/he/subtitle/(movie|series)/([^/]+)/">(.*) / ([^<]+)</a>', search_result)
years = re.findall(u'<span class="special">[^:]+: </span>(\d{4}).<br />', search_result)
for i, url in enumerate(urls):
year = years[i] if len(years) > i else ''
urls[i] += (year,)
results = self._filter_results(search_result["data"], search_string, item)
log("Filtered: %s" % results)

results = self._filter_results(urls, search_string, item)

if item["tvshow"] and results:
store.set(cache_key, repr(results))
else:
notify(32009)

return results

def _filter_results(self, results, search_string, item):
filtered = []
search_string = regexHelper.sub('', search_string.lower())

h = HTMLParser.HTMLParser()

log("results: %s" % results)

for i, (content_type, slug, heb_name, eng_name, year) in enumerate(results):
eng_name = unicode(eng_name, 'utf-8')
heb_name = unicode(heb_name, 'utf-8')

eng_name = h.unescape(eng_name).replace(' ...', '').lower()
heb_name = h.unescape(heb_name).replace(' ...', '')
for result in results:
eng_name = result["name_en"].strip().lower()
heb_name = result["name_he"].strip()

eng_name = regexHelper.sub(' ', eng_name)
eng_name_tmp = regexHelper.sub('', eng_name)
heb_name_tmp = regexHelper.sub('', heb_name)

if ((content_type == "movie" and not item["tvshow"]) or (content_type == "series" and item["tvshow"])) \
and (search_string.startswith(eng_name_tmp) or
eng_name_tmp.startswith(search_string) or
search_string.startswith(heb_name_tmp) or
heb_name_tmp.startswith(search_string)) \
and (item["tvshow"] or
item["year"] == '' or
year == '' or
(int(year) - 1) <= int(item["year"]) <= (int(year) + 1) or
(int(item["year"]) - 1) <= int(year) <= (int(item["year"]) + 1)):
filtered.append({"type": content_type, "name": eng_name, "slug": slug, "year": year})
log("filtered: %s" % filtered)
heb_name = regexHelper.sub('', heb_name)

if (search_string.startswith(eng_name_tmp) or eng_name_tmp.startswith(search_string) or
search_string.startswith(heb_name) or heb_name.startswith(search_string)) and \
(item["tvshow"] or
item["year"] == '' or
result["year"] == '' or
(int(result["year"]) - 1) <= int(item["year"]) <= (int(result["year"]) + 1) or
(int(item["year"]) - 1) <= int(result["year"]) <= (int(item["year"]) + 1)):
filtered.append({"name": eng_name, "year": result["year"], "subs": result["subtitles"]})
return filtered

def _build_subtitle_list(self, search_results, item):
ret = []
for result in search_results:
total_downloads = 0
counter = 0
url = self.BASE_URL + "cinemast/data/" + result["type"] + "/sb/" + result["slug"]
url += "/" + item["season"] + "/" + item["episode"] + "/" if result["type"] == "series" else "/"
subs_list = self.urlHandler.request(url)
subs_list = result["subs"]

if subs_list is not None:
if not isinstance(subs_list, dict):
subs_list = json.loads(subs_list, encoding="utf-8")
for language in subs_list:
for language in subs_list.keys():
if xbmc.convertLanguage(language, xbmc.ISO_639_2) in item["3let_language"]:
for translator in subs_list[language]:
for quality in subs_list[language][translator]:
for current in subs_list[language][translator][quality]:
current = subs_list[language][translator][quality][current]
counter += 1
title = current["subtitle_version"]
subtitle_rate = self._calc_rating(title, item["file_original_path"])
total_downloads += current["downloaded"]
ret.append(
{'lang_index': item["3let_language"].index(
xbmc.convertLanguage(language, xbmc.ISO_639_2)),
'filename': title,
'link': current["key"],
'language_name': xbmc.convertLanguage(language, xbmc.ENGLISH_NAME),
'language_flag': language,
'id': current["id"],
'rating': current["downloaded"],
'sync': subtitle_rate >= 3.8,
'hearing_imp': current["hearing_impaired"] > 0,
'is_preferred':
xbmc.convertLanguage(language, xbmc.ISO_639_2) == item[
'preferredlanguage']
})
for current in subs_list[language]:
counter += 1
title = current["version"]
subtitle_rate = self._calc_rating(title, item["file_original_path"])
total_downloads += int(current["downloads"])
ret.append(
{'lang_index': item["3let_language"].index(
xbmc.convertLanguage(language, xbmc.ISO_639_2)),
'filename': title,
'link': current["key"],
'language_name': xbmc.convertLanguage(language, xbmc.ENGLISH_NAME),
'language_flag': language,
'id': current["id"],
'rating': current["downloads"],
'sync': subtitle_rate >= 3.8,
'hearing_imp': False,
'is_preferred':
xbmc.convertLanguage(language, xbmc.ISO_639_2) == item[
'preferredlanguage']
})
# Fix the rating
if total_downloads:
for it in ret[-1 * counter:]:
Expand Down Expand Up @@ -258,20 +253,22 @@ def _calc_rating(self, subsfile, file_original_path):

return round(rating, 1)

def download(self, id, language, key, filename, zip_filename):
def download(self, id, language, key, version, zip_filename):
## Cleanup temp dir, we recomend you download/unzip your subs in temp folder and
## pass that to XBMC to copy and activate
if xbmcvfs.exists(__temp__):
shutil.rmtree(__temp__)
xbmcvfs.mkdirs(__temp__)

query = {"v": ''.join(hex(ord(chr))[2:] for chr in filename),
query = {"v": version,
"key": key,
"sub_id": id}

user_token = self.get_user_token()

url = self.BASE_URL + "subtitle/download/" + language + "/"

f = self.urlHandler.request(url, query_string=query)
f = self.urlHandler.request(url, data=user_token, query_string=query)

with open(zip_filename, "wb") as subFile:
subFile.write(f)
Expand Down Expand Up @@ -319,7 +316,7 @@ def __init__(self):
('Pragma', 'no-cache'),
('Cache-Control', 'no-cache'),
('User-Agent',
'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36')]
'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 Kodi/17.2 (KHTML, like Gecko) Chrome/49.0.2526.111 Safari/537.36')]

def request(self, url, data=None, query_string=None, ajax=False, referrer=None, cookie=None):
if data is not None:
Expand Down
6 changes: 6 additions & 0 deletions resources/settings.xml
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<settings>
<category label="32007">
<setting id="Email" type="text" label="32005" default=""/>
<setting id="Password" type="text" option = "hidden" label="32006" default=""/>
<setting type="sep"/>
<setting type="action" label="32008" action="RunScript(service.subtitles.subscenter, 1,action=login)" option="close"/>
</category>
<category label="32002">
<setting type="action" label="32003" action="RunScript(service.subtitles.subscenter, 1,action=clear_store)"/>
</category>
Expand Down
45 changes: 7 additions & 38 deletions service.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,6 @@
import xbmcaddon
import xbmcgui
import xbmcplugin
import json
from requests import post


__addon__ = xbmcaddon.Addon()
__author__ = __addon__.getAddonInfo('author')
Expand All @@ -26,19 +23,19 @@

sys.path.append(__resource__)

from SUBUtilities import SubscenterHelper, log, normalizeString, clear_store, parse_rls_title, clean_title
from SUBUtilities import SubsHelper, log, normalizeString, clear_store, parse_rls_title, clean_title


def search(item):
helper = SubscenterHelper()
helper = SubsHelper()
subtitles_list = helper.get_subtitle_list(item)
if subtitles_list:
for it in subtitles_list:
listitem = xbmcgui.ListItem(label=it["language_name"],
label2=it["filename"],
iconImage=it["rating"],
thumbnailImage=it["language_flag"]
)
)
if it["sync"]:
listitem.setProperty("sync", "true")
else:
Expand All @@ -60,7 +57,7 @@ def download(id, language, key, filename):

zip_filename = os.path.join(__temp__, "subs.zip")

helper = SubscenterHelper()
helper = SubsHelper()
helper.download(id, language, key, filename, zip_filename)

for file in xbmcvfs.listdir(__temp__)[1]:
Expand Down Expand Up @@ -93,34 +90,9 @@ def get_params(string=""):

return param

def mirror_sub(id, filename, sub_file):
try:
playerid_query = '{"jsonrpc": "2.0", "method": "Player.GetActivePlayers", "id": 1}'
playerid = json.loads(xbmc.executeJSONRPC(playerid_query))['result'][0]['playerid']
imdb_id_query = '{"jsonrpc": "2.0", "method": "Player.GetItem", "params": {"playerid": ' + str(playerid) + ', "properties": ["imdbnumber"]}, "id": 1}'
imdb_id = json.loads(xbmc.executeJSONRPC (imdb_id_query))['result']['item']['imdbnumber']
except:
imdb_id = 0

values = {}
values['id'] = id
values['versioname'] = filename
values['source'] = 'subscenter'
values['year'] = xbmc.getInfoLabel("VideoPlayer.Year")
values['season'] = str(xbmc.getInfoLabel("VideoPlayer.Season"))
values['episode'] = str(xbmc.getInfoLabel("VideoPlayer.Episode"))
values['imdb'] = str(imdb_id)
values['tvshow'] = normalizeString(xbmc.getInfoLabel("VideoPlayer.TVshowtitle"))
values['title'] = normalizeString(xbmc.getInfoLabel("VideoPlayer.OriginalTitle"))
values['file_original_path'] = urllib.unquote(unicode(xbmc.Player().getPlayingFile(), 'utf-8'))
url = 'http://api.wizdom.xyz/upload.php'
try:
post(url, files={'sub': open(sub_file, 'rb')}, data=values)
except:
pass

def takeTitleFromFocusedItem():
labelType = xbmc.getInfoLabel("ListItem.DBTYPE") #movie/tvshow/season/episode
labelType = xbmc.getInfoLabel("ListItem.DBTYPE") # movie/tvshow/season/episode
labelMovieTitle = xbmc.getInfoLabel("ListItem.OriginalTitle")
labelYear = xbmc.getInfoLabel("ListItem.Year")
labelTVShowTitle = xbmc.getInfoLabel("ListItem.TVShowTitle")
Expand Down Expand Up @@ -148,7 +120,7 @@ def takeTitleFromFocusedItem():
params['searchstring'] = urllib.unquote(params['searchstring'])

item = {}

if xbmc.Player().isPlaying():
item['temp'] = False
item['rar'] = False
Expand All @@ -175,7 +147,6 @@ def takeTitleFromFocusedItem():
item['preferredlanguage'] = unicode(urllib.unquote(params.get('preferredlanguage', '')), 'utf-8')
item['preferredlanguage'] = xbmc.convertLanguage(item['preferredlanguage'], xbmc.ISO_639_2)


if item['title'] == "":
log("VideoPlayer.OriginalTitle not found")
item['title'] = normalizeString(xbmc.getInfoLabel("VideoPlayer.Title")) # no original title, get just Title
Expand Down Expand Up @@ -218,8 +189,6 @@ def takeTitleFromFocusedItem():
subs = download(params["id"], params["language"], params["link"], params["filename"])
## 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:
if params["language"] == 'he' and xbmc.Player().isPlaying():
mirror_sub(params["id"], params["filename"], sub)
listitem = xbmcgui.ListItem(label=sub)
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=sub, listitem=listitem, isFolder=False)

Expand All @@ -228,7 +197,7 @@ def takeTitleFromFocusedItem():

elif params['action'] == 'login':
clear_store(False)
helper = SubscenterHelper()
helper = SubsHelper()
helper.login(True)
__addon__.openSettings()

Expand Down

0 comments on commit e81209f

Please sign in to comment.