diff --git a/channels/altadefinizionecommunity.py b/channels/altadefinizionecommunity.py index 8cf2019f..09682770 100644 --- a/channels/altadefinizionecommunity.py +++ b/channels/altadefinizionecommunity.py @@ -130,6 +130,7 @@ def registerOrLogin(): @support.scrape def peliculas(item): json = {} + # debug=True if item.contentType == 'undefined': # tmdbEnabled = False @@ -149,7 +150,7 @@ def peliculas(item): else: json = support.httptools.downloadpage(item.url, headers=headers, cloudscraper=True).json data = "\n".join(json['data']) - patron = r'wrapFilm">\s*\s*(?P[0-9]{4})\s*]+>(?P[^<]+)\s*(?P[^<]+).*?]+>){1,2}\s*

(?P[^<[]+)(?:\[(?P<lang>[sSuUbBiItTaA-]+))?' + patron = r'wrapFilm">\s*<a href="(?P<url>[^"]+)">\s*<span class="year">(?P<year>[0-9]{4})</span>\s*<span[^>]+>(?P<rating>[^<]+)</span>\s*<span class="qual">(?P<quality>[^<]+)(?:[^>]+>){2}\s*<img src="(?P<thumbnail>[^"]+)(?:[^>]+>){1,6}\s*<h3>(?P<title>[^<[]+)(?:\[(?P<lang>[sSuUbBiItTaA-]+))?' # paginazione logger.debug('JSON FIND',jsontools.load(json)) diff --git a/channels/animealtadefinizione.json b/channels/animealtadefinizione.json index f9a1945a..86170bac 100644 --- a/channels/animealtadefinizione.json +++ b/channels/animealtadefinizione.json @@ -5,7 +5,7 @@ "language": ["ita", "sub-ita"], "thumbnail": "animealtadefinizione.png", "banner": "animealtadefinizione.png", - "categories": ["anime", "sub-ita"], + "categories": ["anime", "sub"], "default_off": ["include_in_newest"], "settings": [ { diff --git a/channels/animeuniverse.json b/channels/animeuniverse.json index 0fa509cc..b242753f 100644 --- a/channels/animeuniverse.json +++ b/channels/animeuniverse.json @@ -5,7 +5,7 @@ "language": ["ita", "sub-ita"], "thumbnail": "animeuniverse.png", "banner": "animeuniverse.png", - "categories": ["anime", "sub-ita"], + "categories": ["anime", "sub"], "default_off": ["include_in_newest"], "settings": [ { diff --git a/channels/cineblog01.py b/channels/cineblog01.py index 8ea2edc0..4944438a 100644 --- a/channels/cineblog01.py +++ b/channels/cineblog01.py @@ -76,7 +76,8 @@ def newest(categoria): def search(item, text): - logger.info("search", text) + + logger.info("search", item, text) if item.contentType == 'tvshow': item.url = host + '/serietv' else: item.url = host try: @@ -160,19 +161,21 @@ def episodios(item): return locals() data = support.match(item.url, headers=headers).data - itemlist = listed(item, data) + # itemlist = listed(item, data) + itemlist = [] if not item.itemlist: itemlist.extend(folder(item, data) if 'TUTTE LE' in data or 'TUTTA LA' in data else []) itemDict = {'ITA':{}, 'Sub-ITA':{}} seasons = [] - + # support.dbg() for it in itemlist: if it.contentSeason and it.contentSeason not in seasons: seasons.append(it.contentSeason) itemDict['ITA'][it.contentSeason] = [] itemDict['Sub-ITA'][it.contentSeason] = [] if it.contentSeason: + if not it.contentLanguage: it.contentLanguage = 'ITA' itemDict[it.contentLanguage][it.contentSeason].append(it) diff --git a/channels/guardaserieclick.json b/channels/guardaserieclick.json index 79c3620d..a850b5de 100644 --- a/channels/guardaserieclick.json +++ b/channels/guardaserieclick.json @@ -2,7 +2,7 @@ "id": "guardaserieclick", "name": "GuardaSerie.click", "active": true, - "language": ["ita", "sub"], + "language": ["ita", "sub-ita"], "thumbnail": "guardaserieclick.png", "bannermenu": "guardaserieclick.png", "categories": ["tvshow", "anime"], diff --git a/channels/raiplay.py b/channels/raiplay.py index 4434d907..ee456506 100644 --- a/channels/raiplay.py +++ b/channels/raiplay.py @@ -258,7 +258,7 @@ def getUrl(url): def addinfo(items, item): def itInfo(key, item): - logger.debug(jsontools.dump(key)) + # logger.debug(jsontools.dump(key)) item.forcethumb = True if key.get('titolo', ''): key = requests.get(getUrl(key['path_id'])).json()['program_info'] diff --git a/channels/streamingcommunity.py b/channels/streamingcommunity.py index 6e193154..1d57470d 100644 --- a/channels/streamingcommunity.py +++ b/channels/streamingcommunity.py @@ -210,14 +210,14 @@ def findvideos(item): token = calculateToken() - # def videourls(res): - # newurl = '{}/{}{}'.format(url, res, token) - # if requests.head(newurl, headers=headers).status_code == 200: - # video_urls.append({'type':'m3u8', 'res':res, 'url':newurl}) + def videourls(res): + newurl = '{}/{}{}'.format(url, res, token) + if requests.head(newurl, headers=headers).status_code == 200: + video_urls.append({'type':'m3u8', 'res':res, 'url':newurl}) - # with futures.ThreadPoolExecutor() as executor: - # for res in ['480p', '720p', '1080p']: - # executor.submit(videourls, res) + with futures.ThreadPoolExecutor() as executor: + for res in ['480p', '720p', '1080p']: + executor.submit(videourls, res) if not video_urls: video_urls = [{'type':'m3u8', 'url':url + token}] itemlist = [item.clone(title = channeltools.get_channel_parameters(item.channel)['title'], server='directo', video_urls=video_urls, thumbnail=channeltools.get_channel_parameters(item.channel)["thumbnail"], forcethumb=True)] diff --git a/channels/vvvvid.json b/channels/vvvvid.json index 98681f9d..de10b326 100644 --- a/channels/vvvvid.json +++ b/channels/vvvvid.json @@ -2,7 +2,7 @@ "id": "vvvvid", "name": "VVVVID", "active": true, - "language": ["ita","sub"], + "language": ["ita","sub-ita"], "thumbnail": "vvvvid.png", "banner": "vvvvid.png", "categories": ["anime","tvshow","movie","sub"], diff --git a/channelselector.py b/channelselector.py index 8be8675b..20a98b82 100644 --- a/channelselector.py +++ b/channelselector.py @@ -26,7 +26,7 @@ def getmainlist(view="thumb_"): if addon.getSetting('enable_search_menu') == "true": itemlist.append(Item(title=config.get_localized_string(30103), channel="search", path='special', action="mainlist", thumbnail=thumb("search"), category=config.get_localized_string(30119), viewmode="list", - context = [{"title": config.get_localized_string(60412), "action": "setting_channel_new", "channel": "search"}, + context = [{"title": config.get_localized_string(60412), "action": "channels_selections", "channel": "search"}, {"title": config.get_localized_string(70286), "channel": "shortcuts", "action": "SettingOnPosition", "category":5 , "setting":1}])) if addon.getSetting('enable_onair_menu') == "true": diff --git a/core/servertools.py b/core/servertools.py index c049f060..e957b11e 100644 --- a/core/servertools.py +++ b/core/servertools.py @@ -717,9 +717,12 @@ def sort_servers(servers_list): sorted_list.append(element) # We order according to priority - if priority == 0: sorted_list.sort(key=lambda element: (element['index_language'], -element['index_quality'] if inverted else element['index_quality'] , element['videoitem'].server)) - elif priority == 1: sorted_list.sort(key=lambda element: (element['index_language'], element['index_server'], -element['index_quality'] if inverted else element['index_quality'])) # Servers and Qualities - elif priority == 2: sorted_list.sort(key=lambda element: (element['index_language'], -element['index_quality'] if inverted else element['index_quality'], element['index_server'])) # Qualities and Servers + if priority == 0: + sorted_list.sort(key=lambda element: (element['index_language'], -element['index_quality'] if inverted else element['index_quality'] , element['videoitem'].server)) + elif priority == 1: + sorted_list.sort(key=lambda element: (element['index_language'], element['index_server'], -element['index_quality'] if inverted else element['index_quality'])) # Servers and Qualities + elif priority == 2: + sorted_list.sort(key=lambda element: (element['index_language'], -element['index_quality'] if inverted else element['index_quality'], element['index_server'])) # Qualities and Servers return [v['videoitem'] for v in sorted_list if v] diff --git a/core/support.py b/core/support.py index ccbc5671..40abaf5d 100755 --- a/core/support.py +++ b/core/support.py @@ -106,7 +106,6 @@ class scrape: self.function = self.func.__name__ if not 'actLike' in self.args else self.args['actLike'] # self.args - self.item = self.args['item'] self.action = self.args.get('action', 'findvideos') self.search = self.args.get('search', '') self.lang = self.args.get('deflang', '') @@ -143,40 +142,40 @@ class scrape: self.downloadEnabled = False self.seasonPagination = False + item = self.args['item'] # variable - self.pag = self.item.page if self.item.page else 1 + self.pag = item.page if item.page else 1 self.itemlist = [] self.matches = [] self.seasons = [] - self.itemParams = Item() self.known_keys = ['url', 'title', 'title2', 'season', 'episode', 'episode2', 'thumb', 'quality', 'year', 'plot', 'duration', 'genere', 'rating', 'type', 'lang', 'size', 'seed'] # run scrape - self._scrape() + self._scrape(item) return self.itemlist - def _scrape(self): + def _scrape(self, item): - if self.item.itemlist: + if item.itemlist: scrapingTime = time() self.itemlist = itemlistdb() - self.seasons = self.item.allSeasons + self.seasons = item.allSeasons else: for n in range(2): logger.debug('PATRON= ', self.patron) if not self.data: - page = httptools.downloadpage(self.item.url, headers=self.headers, ignore_response_code=True) - self.item.url = page.url # might be a redirect + page = httptools.downloadpage(item.url, headers=self.headers, ignore_response_code=True) + item.url = page.url # might be a redirect self.data = page.data self.data = html_uniform(self.data) scrapingTime = time() if self.patronBlock: - if self.debugBlock: regexDbg(self.item, self.patronBlock, self.headers, self.data) + if self.debugBlock: regexDbg(item, self.patronBlock, self.headers, self.data) blocks = scrapertools.find_multiple_matches_groups(self.data, self.patronBlock) - for bl in blocks:self._scrapeBlock(bl) + for bl in blocks:self._scrapeBlock(item, bl) elif self.patron: - self._scrapeBlock(self.data) + self._scrapeBlock(item, self.data) if 'itemlistHook' in self.args: try: @@ -190,9 +189,9 @@ class scrape: ch = self.func.__module__.split('.')[-1] try: host = config.get_channel_url(self.func.__globals__['findhost'], ch, True) - parse = list(urlparse.urlparse(self.item.url)) + parse = list(urlparse.urlparse(item.url)) parse[1] = scrapertools.get_domain_from_url(host) - self.item.url = urlparse.urlunparse(parse) + item.url = urlparse.urlunparse(parse) except: raise logger.ChannelScraperException self.data = None @@ -203,16 +202,16 @@ class scrape: if not self.data: from platformcode.logger import WebErrorException - raise WebErrorException(urlparse.urlparse(self.item.url)[1], self.item.channel) + raise WebErrorException(urlparse.urlparse(item.url)[1], item.channel) - if self.group and self.item.grouped or self.args.get('groupExplode'): + if self.group and item.grouped or self.args.get('groupExplode'): import copy nextargs = copy.copy(self.args) @scrape def newFunc(): return nextargs - nextargs['item'] = nextPage(self.itemlist, self.item, self.function, data=self.data, patron=self.patronNext, patron_total_pages=self.patronTotalPages) + nextargs['item'] = nextPage(self.itemlist, item, self.function, data=self.data, patron=self.patronNext, patron_total_pages=self.patronTotalPages) nextargs['group'] = False if nextargs['item']: nextargs['groupExplode'] = True @@ -226,7 +225,7 @@ class scrape: if not self.group and not self.args.get('groupExplode') and ((self.pagination and len(self.matches) <= self.pag * self.pagination) or not self.pagination): # next page with pagination if self.patronNext and inspect.stack()[1][3] not in ['newest'] and len(inspect.stack()) > 2 and inspect.stack()[2][3] not in ['get_channel_results']: - nextPage(self.itemlist, self.item, self.function, data=self.data, patron=self.patronNext, patron_total_pages=self.patronTotalPages) + nextPage(self.itemlist, item, self.function, data=self.data, patron=self.patronNext, patron_total_pages=self.patronTotalPages) if self.numerationEnabled and inspect.stack()[1][3] not in ['find_episodes']: from platformcode import autorenumber @@ -242,19 +241,19 @@ class scrape: if inspect.stack()[1][3] not in ['add_tvshow', 'get_episodes', 'update', 'find_episodes']: if len(self.seasons) > 1 and self.seasonPagination: - self.itemlist = season_pagination(self.itemlist, self.item, self.seasons, self.function) + self.itemlist = season_pagination(self.itemlist, item, self.seasons, self.function) elif self.pagination: - self.itemlist = pagination(self.itemlist, self.item, self.function) + self.itemlist = pagination(self.itemlist, item, self.function) if self.action != 'play' and 'patronMenu' not in self.args and 'patronGenreMenu' not in self.args and self.tmdbEnabled and inspect.stack()[1][3] not in ['add_tvshow'] and self.function not in ['episodios', 'mainlist'] or (self.function in ['episodios'] and config.get_setting('episode_info')): # and function != 'episodios' and item.contentType in ['movie', 'tvshow', 'episode', 'undefined'] tmdb.set_infoLabels_itemlist(self.itemlist, seekTmdb=True) if inspect.stack()[1][3] not in ['find_episodes', 'add_tvshow']: - if self.videlibraryEnabled and (self.item.infoLabels["title"] or self.item.fulltitle): + if self.videlibraryEnabled and (item.infoLabels["title"] or item.fulltitle): # item.fulltitle = item.infoLabels["title"] - videolibrary(self.itemlist, self.item, function=self.function) + videolibrary(self.itemlist, item, function=self.function) if self.downloadEnabled and self.function == 'episodios' or self.function == 'findvideos': - download(self.itemlist, self.item, function=self.function) + download(self.itemlist, item, function=self.function) if 'patronGenreMenu' in self.args and self.itemlist: self.itemlist = thumb(self.itemlist, mode='genre') @@ -273,69 +272,69 @@ class scrape: trakt_tools.trakt_check(self.itemlist) logger.debug('scraping time: ', time()-scrapingTime) - def _scrapeBlock(self, block): + def _scrapeBlock(self, item, block): itemlist = [] contents = [] if type(block) == dict: - if 'season' in block and block['season']: self.item.season = block['season'] - if 'lang' in block: self.item.contentLanguage = scrapeLang(block, self.item.contentLanguage) - if 'quality' in block and block['quality']: self.item.quality = block['quality'].strip() + if 'season' in block and block['season']: item.season = block['season'] + if 'lang' in block: item.contentLanguage = scrapeLang(block, item.contentLanguage) + if 'quality' in block and block['quality']: item.quality = block['quality'].strip() block = block['block'] if self.debug: - regexDbg(self.item, self.patron, self.headers, block) + regexDbg(item, self.patron, self.headers, block) matches = scrapertools.find_multiple_matches_groups(block, self.patron) logger.debug('MATCHES =', matches) for match in matches: - self.scraped = {} + self.itemParams = Item() for k, v in match.items(): if v and k in ['url', 'thumb'] and 'http' not in v: domain = '' if v.startswith('//'): - domain = scrapertools.find_single_match(self.item.url, 'https?:') + domain = scrapertools.find_single_match(item.url, 'https?:') elif v.startswith('/'): - domain = scrapertools.find_single_match(self.item.url, 'https?://[a-z0-9.-]+') + domain = scrapertools.find_single_match(item.url, 'https?://[a-z0-9.-]+') v = domain + v self.itemParams.__setattr__(k, v.strip() if type(v) == str else v) self.itemParams.title = cleantitle(self.itemParams.title) - if self.group and self.itemParams.title in contents and not self.item.grouped: # same title and grouping enabled + if self.group and self.itemParams.title in contents and not item.grouped: # same title and grouping enabled continue - if self.item.grouped and self.itemParams.title != self.item.fulltitle: # inside a group different tvshow should not be included + if item.grouped and self.itemParams.title != item.fulltitle: # inside a group different tvshow should not be included continue contents.append(self.itemParams.title) - self.itemParams.title2 = cleantitle(self.itemParams.title2) if not self.group or self.item.grouped else '' + self.itemParams.title2 = cleantitle(self.itemParams.title2) if not self.group or item.grouped else '' self.itemParams.quality = self.itemParams.quality self.itemParams.plot = cleantitle(self.itemParams.plot) - self.itemParams.language = scrapeLang(self.scraped, self.lang) + self.itemParams.language = scrapeLang(self.itemParams, self.lang) - self.set_infolabels() + self.set_infolabels(item) if self.sceneTitle: self.set_sceneTitle() - if not self.group or self.item.grouped: - self.set_episodes() + if not self.group or item.grouped: + self.set_episodes(item) if self.itemParams.episode2: self.itemParams.second_episode = scrapertools.find_single_match(self.itemParams.episode2, r'(\d+)').split('x') if self.itemParams.season: self.itemParams.infoLabels['season'] = int(self.itemParams.season) if self.itemParams.episode: self.itemParams.infoLabels['episode'] = int(self.itemParams.episode) - it = self.set_item(match) + it = self.set_item(item, match) if it: itemlist.append(it) self.itemlist.extend(itemlist) self.matches.extend(matches) - def set_infolabels(self): - if self.item.infoLabels["title"] == self.itemParams.title: - infolabels = self.item.infoLabels + def set_infolabels(self, item): + if item.infoLabels["title"] == self.itemParams.title: + infolabels = item.infoLabels else: if self.function == 'episodios': - infolabels = self.item.infoLabels + infolabels = item.infoLabels else: infolabels = {} if self.itemParams.year: @@ -377,31 +376,31 @@ class scrape: self.itemParams.infoLabels['year'] = parsedTitle.get('year', '') if parsedTitle.get('episode') and parsedTitle.get('season'): if type(parsedTitle.get('season')) == list: - self.itemParams.season = parsedTitle.get('season')[0] + self.itemParams.season = str(parsedTitle.get('season')[0]) elif parsedTitle.get('season'): - self.itemParams.season = parsedTitle.get('season') + self.itemParams.season = str(parsedTitle.get('season')) if type(parsedTitle.get('episode')) == list: - self.itemParams.episode = parsedTitle.get('episode')[0] - self.itemParams.second_episode = parsedTitle.get('episode')[1:] + self.itemParams.episode = str(parsedTitle.get('episode')[0]) + self.itemParams.second_episode = str(parsedTitle.get('episode')[1:]) else: self.itemParams.infoLabels['episode'] = parsedTitle.get('episode') elif parsedTitle.get('season') and type(parsedTitle.get('season')) == list: self.itemParams.extraInfo = '{}: {}-{}'.format(config.get_localized_string(30140), parsedTitle.get('season')[0], parsedTitle.get('season')[-1]) elif parsedTitle.get('season'): - self.itemParams.season = parsedTitle.get('season') + self.itemParams.season = str(parsedTitle.get('season')) if parsedTitle.get('episode_title'): self.itemParams.extraInfo += parsedTitle.get('episode_title') except: import traceback logger.error(traceback.format_exc()) - def set_episodes(self): + def set_episodes(self, item): ep = unifyEp(self.itemParams.episode) if self.itemParams.episode else '' se = self.itemParams.season if self.itemParams.season.isdigit() else '' if ep and se: - self.itemParams.season = int(se) + self.itemParams.season = se if 'x' in ep: ep_list = ep.split('x') self.itemParams.episode = ep_list[0] @@ -409,12 +408,12 @@ class scrape: else: self.itemParams.episode = ep - elif self.item.season: - self.itemParams.season = int(self.item.season) + elif item.season: + self.itemParams.season = item.season if ep: self.itemParams.episode = int(scrapertools.find_single_match(self.itemParams.episode, r'(\d+)')) - elif self.item.contentType == 'tvshow' and (self.itemParams.episode == '' and self.itemParams.season == '' and self.itemParams.season == ''): - self.item.news = 'season_completed' + elif item.contentType == 'tvshow' and (self.itemParams.episode == '' and self.itemParams.season == '' and self.itemParams.season == ''): + item.news = 'season_completed' else: try: @@ -430,7 +429,7 @@ class scrape: logger.debug('invalid episode: ' + self.itemParams.episode) pass - def set_item(self, match): + def set_item(self, item, match): AC = '' CT = '' if self.typeContentDict: @@ -438,7 +437,7 @@ class scrape: if str(self.itemParams.type).lower() in variants: CT = name break - else: CT = self.item.contentType + else: CT = item.contentType if self.typeActionDict: for name, variants in self.typeActionDict.items(): if str(self.itemParams.type).lower() in variants: @@ -447,7 +446,7 @@ class scrape: else: AC = self.action if (not self.itemParams.title or self.itemParams.title not in self.blacklist) and (self.search.lower() in self.itemParams.title.lower()): - it = self.item.clone(title=self.itemParams.title, + it = item.clone(title=self.itemParams.title, fulltitle=self.itemParams.title, show=self.itemParams.title, infoLabels=self.itemParams.infoLabels, @@ -464,16 +463,16 @@ class scrape: if self.function == 'episodios': it.fulltitle = it.show = self.itemParams.title if self.itemParams.quality: it.quality = self.itemParams.quality if self.itemParams.language: it.contentLanguage = self.itemParams.language - if self.item.prevthumb: it.thumbnail = self.item.prevthumb + if item.prevthumb: it.thumbnail = item.prevthumb elif self.itemParams.thumb: it.thumbnail = self.itemParams.thumb - it.contentType = 'episode' if self.function == 'episodios' else CT if CT else self.item.contentType + it.contentType = 'episode' if self.function == 'episodios' else CT if CT else item.contentType if it.contentType not in ['movie'] and self.function != 'episodios' or it.contentType in ['undefined']: it.contentSerieName = self.itemParams.title if self.function == 'peliculas': it.contentTitle= self.itemParams.title it.contentSeason= self.itemParams.infoLabels.get('season', ''), it.contentEpisodeNumber= self.itemParams.infoLabels.get('episode', ''), if self.itemParams.title2: it.title2 = self.itemParams.title2 - if self.itemParams.episode and self.group and not self.item.grouped: + if self.itemParams.episode and self.group and not item.grouped: it.action = self.function elif AC: it.action = AC @@ -481,7 +480,7 @@ class scrape: it.action=self.action if it.action == 'findvideos': - it.window = True if self.item.window_type == 0 or (config.get_setting("window_type") == 0) else False + it.window = True if item.window_type == 0 or (config.get_setting("window_type") == 0) else False if it.window: it.folder = False for lg in list(set(match.keys()).difference(self.known_keys)): @@ -531,10 +530,11 @@ def scrapeLang(scraped, lang): # altrimenti dopo un sub-ita mette tutti quelli a seguire in sub-ita # e credo sia utile per filtertools language = '' + lang = scraped.get('lang') if type(scraped) == dict else scraped.lang - if scraped.get('lang'): - if 'ita' in scraped['lang'].lower(): language = 'ITA' - if 'sub' in scraped['lang'].lower(): language = 'Sub-' + language + if lang: + if 'ita' in lang.lower(): language = 'ITA' + if 'sub' in lang.lower(): language = 'Sub-' + language if not language: language = lang # if language: longtitle += typo(language, '_ [] color kod') @@ -1005,6 +1005,7 @@ def server(item, data='', itemlist=[], headers='', AutoPlay=True, CheckLinks=Tru videoitem.server = videoitem.server.lower() if videoitem.video_urls or srv_param.get('active', False): + logger.debug(item) quality = videoitem.quality if videoitem.quality else item.quality if item.quality else '' # videoitem = item.clone(url=videoitem.url, serverName=videoitem.serverName, server=videoitem.server, action='play') videoitem.contentLanguage = videoitem.contentLanguage if videoitem.contentLanguage else item.contentLanguage if item.contentLanguage else 'ITA' @@ -1022,6 +1023,7 @@ def server(item, data='', itemlist=[], headers='', AutoPlay=True, CheckLinks=Tru videoitem.action = "play" videoitem.videolibrary_id = item.videolibrary_id videoitem.from_library = item.from_library + videoitem.fanart = item.fanart if item.contentType == 'movie' else item.thumbnail return videoitem # non threaded for webpdb diff --git a/core/tmdb.py b/core/tmdb.py index 4a7dd7ef..7beac2c5 100644 --- a/core/tmdb.py +++ b/core/tmdb.py @@ -1082,7 +1082,7 @@ class Tmdb(object): if total_results > 0 or self.cast: if self.cast: - results = result[self.cast] + results = result['self.cast'] total_results = len(results) else: results = result["results"] @@ -1685,7 +1685,7 @@ class Tmdb(object): elif k == 'vote_count': ret_infoLabels['votes'] = v - elif k == 'poster_path': + elif k in ['poster_path', 'profile_path']: ret_infoLabels['thumbnail'] = 'https://image.tmdb.org/t/p/original' + v elif k == 'backdrop_path': diff --git a/core/trakt_tools.py b/core/trakt_tools.py index bf00588a..7734799d 100644 --- a/core/trakt_tools.py +++ b/core/trakt_tools.py @@ -120,9 +120,9 @@ def token_trakt(item): itemlist = [] if token: - itemlist.append(item.clone(config.get_localized_string(60256), action="")) + itemlist.append(item.clone(title=config.get_localized_string(60256), action="")) else: - itemlist.append(item.clone(config.get_localized_string(60260), action="")) + itemlist.append(item.clone(title=config.get_localized_string(60260), action="")) return itemlist diff --git a/platformcode/config.py b/platformcode/config.py index 4a229955..aad32626 100644 --- a/platformcode/config.py +++ b/platformcode/config.py @@ -305,6 +305,11 @@ def get_localized_category(categ): return categories[categ] if categ in categories else categ +def get_localized_language(lang): + languages = {'ita': 'ITA', 'sub-ita': 'Sub-ITA'} + return languages[lang] if lang in languages else lang + + def get_videolibrary_config_path(): value = get_setting("videolibrarypath") diff --git a/platformcode/dbconverter.py b/platformcode/dbconverter.py index a6d3bb22..7bd5ceaa 100644 --- a/platformcode/dbconverter.py +++ b/platformcode/dbconverter.py @@ -7,7 +7,7 @@ from platformcode.xbmc_videolibrary import execute_sql_kodi, get_data, get_file_ from time import time, strftime, localtime import sqlite3 -conn = sqlite3.connect(get_file_db()) +# conn = sqlite3.connect(get_file_db()) date = strftime('%Y-%m-%d %H:%M:%S', localtime(float(time()))) def save_all(): @@ -23,7 +23,7 @@ def save_all(): item = tvshow['item'] item.no_reload = True add_video(item) - conn.close() + # conn.close() reload() @@ -50,6 +50,8 @@ def reload(): def add_video(item): + global conn + conn = sqlite3.connect(get_file_db()) progress = platformtools.dialog_progress_bg('Sincronizzazione Libreria', item.title) progress.update(0) if item.contentType == 'movie': @@ -61,6 +63,7 @@ def add_video(item): addTvShow(item=item) logger.debug('TOTAL TIME:', time() - start) videolibrarydb.close() + conn.close() progress.close() @@ -223,7 +226,7 @@ class addMovie(object): get_data(payload) else: xbmc.executebuiltin('ReloadSkin()') - conn.close() + # conn.close() def get_id(self): Type = 'id' + self.item.contentType.replace('tv', '').capitalize() @@ -433,7 +436,9 @@ class addMovie(object): params = [] art_urls = [] _id = get_id('art_id', 'art') - art_urls = [[u[0], u[1], u[2]] for u in execute_sql_kodi('select media_id, media_type, type from art', conn=conn)[1]] + arts = execute_sql_kodi('select media_id, media_type, type from art', conn=conn)[1] + if arts: + art_urls = [[u[0], u[1], u[2]] for u in arts] for art in self.art: if [art ['media_id'], art['media_type'], art['type']] not in art_urls: params.append((_id, art['media_id'], art['media_type'], art['type'], art['url'])) @@ -490,7 +495,7 @@ class addTvShow(object): get_data(payload) else: xbmc.executebuiltin('ReloadSkin()') - conn.close() + # conn.close() def get_idShow(self): sql = 'select idShow from tvshow_view where uniqueid_value = {} and uniqueid_type = "kod"'.format(self.info['tmdb_id']) @@ -867,7 +872,9 @@ class addTvShow(object): params = [] art_urls = [] _id = get_id('art_id', 'art') - art_urls = [[u[0], u[1], u[2]] for u in execute_sql_kodi('select media_id, media_type, type from art', conn=conn)[1]] + arts = execute_sql_kodi('select media_id, media_type, type from art', conn=conn)[1] + if arts: + art_urls = [[u[0], u[1], u[2]] for u in arts] for art in self.art: if [art['media_id'], art['media_type'], art['type']] not in art_urls: params.append((_id, art['media_id'], art['media_type'], art['type'], art['url'])) diff --git a/platformcode/infoplus.py b/platformcode/infoplus.py index b49508fa..b964199f 100644 --- a/platformcode/infoplus.py +++ b/platformcode/infoplus.py @@ -146,7 +146,7 @@ class InfoPlus(xbmcgui.WindowXML): back(self) elif action in [UP, DOWN, LEFT, RIGHT] and focus not in [LIST, CAST, RECOMANDED, TRAILERS, FANARTS, SEARCH, BACK, CLOSE]: self.setFocusId(LIST) - if focus > 0: + if focus > 0 and focus not in [SEARCH, BACK, CLOSE]: self.item.setFocus = focus self.item.focus[focus] = self.getControl(focus).getSelectedPosition() @@ -155,13 +155,13 @@ class InfoPlus(xbmcgui.WindowXML): global info_list if control in [SEARCH]: - from specials.globalsearch import Search + from specials.globalsearch import new_search if self.item.contentType == 'episode': - self.item.mode = 'tvshow' + self.item.contentType = 'tvshow' self.item.text = self.item.contentSerieName - else: - self.item.mode = self.item.contentType - Search(self.item) + self.item.mode = 'all' + self.item.type = self.item.contentType + new_search(self.item) elif control in [CLOSE]: self.close() @@ -281,7 +281,7 @@ class CastWindow(xbmcgui.WindowXML): place = info.get('place_of_birth') self.castitem = xbmcgui.ListItem(info.get('name')) birth = born + (' - ' + dead if dead else '') + (' [B]•[/B] ' + place if place else '') - self.castitem.setArt({'poster':self.item.poster}) + self.castitem.setArt({'poster':self.item.poster if self.item.poster else self.item.infoLabels.get('thumbnail', '')}) self.castitem.setProperties({'birth':birth, 'plot':biography}) def onInit(self): diff --git a/platformcode/launcher.py b/platformcode/launcher.py index 657a44f9..ed546144 100644 --- a/platformcode/launcher.py +++ b/platformcode/launcher.py @@ -3,6 +3,7 @@ # XBMC Launcher (xbmc / kodi) # ------------------------------------------------------------ +import platformcode from specials import videolibrary import sys, os @@ -112,7 +113,8 @@ def run(item=None): elif item.channel == "infoplus": from platformcode import infoplus - return infoplus.start(item) + action = getattr(infoplus, item.action) + return action(item) elif item.channel == "backup": from platformcode import backup diff --git a/platformcode/platformtools.py b/platformcode/platformtools.py index 61ef1ef1..065a3d37 100644 --- a/platformcode/platformtools.py +++ b/platformcode/platformtools.py @@ -365,18 +365,18 @@ def render_items(itemlist, parent_item): icon_image = "DefaultFolder.png" if item.folder else "DefaultVideo.png" - title = item.title + title = item.title if item.title else item.contentTitle episode = '' if title[:1] not in ['[', '•']: - if item.contentTitle: title = item.contentTitle - elif item.contentSerieName: title = item.contentSerieName + # if item.contentTitle: title = item.contentTitle + # elif item.contentSerieName: title = item.contentSerieName if type(item.contentSeason) == int and type(item.contentEpisodeNumber) == int and not item.onlyep: episode = '{}x{:02d}'.format(item.contentSeason, item.contentEpisodeNumber) elif type(item.contentEpisodeNumber) == int: episode = '{:02d}'.format(item.contentEpisodeNumber) if episode and item.episode2: - if len(item.episode2) < 4: episode = '{}-{}'.format(episode, '-'.join('{:02d}'.format(e) for e in item.episode2)) + if len(item.episode2) < 4: episode = '{}-{}'.format(episode, '-'.join('{:02d}'.format(int(e)) for e in item.episode2)) else: episode = '{} -> {:02d}'.format(episode, item.episode2[-1]) if episode: title = '{}. {}'.format(episode, title) if item.title2: title = '{} - {}'.format(title, item.title2) @@ -481,23 +481,24 @@ def render_items(itemlist, parent_item): def viewmodeMonitor(): - try: - currentModeName = xbmc.getInfoLabel('Container.Viewmode') - win = xbmcgui.Window(xbmcgui.getCurrentWindowId()) - currentMode = int(win.getFocusId()) - if currentModeName and 'plugin.video.kod' in xbmc.getInfoLabel('Container.FolderPath') and currentMode < 1000 and currentMode >= 50: # inside addon and in itemlist view - content, Type = getCurrentView() - if content: - defaultMode = int(config.get_setting('view_mode_%s' % content).split(',')[-1]) - if currentMode != defaultMode: - logger.debug('viewmode changed: ' + currentModeName + '-' + str(currentMode) + ' - content: ' + content) - config.set_setting('view_mode_%s' % content, currentModeName + ', ' + str(currentMode)) - dialog_notification(config.get_localized_string(70153), - config.get_localized_string(70187) % (content, currentModeName), - sound=False) - except: - import traceback - logger.error(traceback.print_exc()) + if get_window() == 'WINDOW_VIDEO_NAV': + try: + currentModeName = xbmc.getInfoLabel('Container.Viewmode') + win = xbmcgui.Window(xbmcgui.getCurrentWindowId()) + currentMode = int(win.getFocusId()) + if currentModeName and 'plugin.video.kod' in xbmc.getInfoLabel('Container.FolderPath') and currentMode < 1000 and currentMode >= 50: # inside addon and in itemlist view + content, Type = getCurrentView() + if content: + defaultMode = int(config.get_setting('view_mode_%s' % content).split(',')[-1]) + if currentMode != defaultMode: + logger.debug('viewmode changed: ' + currentModeName + '-' + str(currentMode) + ' - content: ' + content) + config.set_setting('view_mode_%s' % content, currentModeName + ', ' + str(currentMode)) + dialog_notification(config.get_localized_string(70153), + config.get_localized_string(70187) % (content, currentModeName), + sound=False) + except: + import traceback + logger.error(traceback.print_exc()) def getCurrentView(item=None, parent_item=None): @@ -1884,7 +1885,7 @@ def serverwindow(item, itemlist): title = self.item.contentTitle it.setProperties({'name': title, 'channel': videoitem.ch_name, 'color': color if color else 'FF0082C2'}) - it.setArt({'poster':self.item.contentThumbnail, 'thumb':videoitem.thumbnail, 'fanart':item.fanart}) + it.setArt({'poster':self.item.contentThumbnail if self.item.contentThumbnail else self.item.thumbnail, 'thumb':videoitem.thumbnail, 'fanart':videoitem.fanart}) self.servers.append(it) self.doModal() return self.selection diff --git a/platformcode/xbmc_videolibrary.py b/platformcode/xbmc_videolibrary.py index 886092fe..08cddd76 100644 --- a/platformcode/xbmc_videolibrary.py +++ b/platformcode/xbmc_videolibrary.py @@ -32,6 +32,7 @@ def mark_auto_as_watched(item): sync = False next_episode = None show_server = True + mark_time = 100 percentage = float(config.get_setting("watched_setting")) / 100 time_from_end = config.get_setting('next_ep_seconds') @@ -47,9 +48,9 @@ def mark_auto_as_watched(item): while not xbmc.Monitor().abortRequested(): if not platformtools.is_playing(): break try: actual_time = xbmc.Player().getTime() - except: pass + except: actual_time = 0 try: total_time = xbmc.Player().getTotalTime() - except: pass + except: total_time = 0 if item.played_time and xbmcgui.getCurrentWindowId() == 12005: xbmc.Player().seekTime(item.played_time) item.played_time = 0 # Fix for Slow Devices @@ -262,7 +263,6 @@ def mark_content_as_watched_on_kodi(item, value=1): logger.debug() if item.contentType == 'movie': - conn = sqlite3.connect(get_file_db()) path = '%{}%'.format(item.strm_path.split('\\')[0].split('/')[0] if item.strm_path else item.base_name) sql = 'select idMovie from movie_view where strPath like "{}"'.format(path) @@ -270,7 +270,15 @@ def mark_content_as_watched_on_kodi(item, value=1): if r: payload = {"jsonrpc": "2.0", "method": "VideoLibrary.SetMovieDetails", "params": {"movieid": r[0][0], "playcount": value}, "id": 1} data = get_data(payload) + elif item.contentType == 'episode': + from core.support import dbg;dbg() + path = '%{}'.format(item.strm_path.replace('\\','%').replace('/', '%')) + sql = 'select idEpisode from episode_view where c18 like "{}"'.format(path) + n, r = execute_sql_kodi(sql) + if r: + payload = {"jsonrpc": "2.0", "method": "VideoLibrary.SetEpisodeDetails", "params": {"episodeid": r[0][0], "playcount": value}, "id": 1} + data = get_data(payload) else: nun_records, records = execute_sql_kodi('SELECT idShow FROM tvshow_view WHERE uniqueid_value LIKE "{}"'.format(item.videolibrary_id)) # delete TV show @@ -286,7 +294,7 @@ def mark_content_as_watched_on_kodi(item, value=1): payload = {"jsonrpc": "2.0", "method": "VideoLibrary.RemoveTVShow", "id": 1, "params": {"tvshowid": tvshowid}} data = get_data(payload) - from platformcode.dbconverter import add_video;add_video(item) + from platformcode.dbconverter import add_video;add_video(item) def set_watched_on_kod(data): diff --git a/resources/skins/Default/720p/GlobalSearch.xml b/resources/skins/Default/720p/GlobalSearch.xml index dcf2fc84..766277b7 100644 --- a/resources/skins/Default/720p/GlobalSearch.xml +++ b/resources/skins/Default/720p/GlobalSearch.xml @@ -12,7 +12,6 @@ <control type='group' id="2"/> <control type='group' id="3"/> <control type='group' id="4"/> - <control type='group' id="5"/> <control type="image"> <!-- BACKGROUND --> <description>Window Background</description> @@ -38,6 +37,7 @@ <height>100%</height> <aspectratio>scale</aspectratio> <texture colordiffuse="FF555555">$INFO[Container(102).ListItem.Art(fanart)]</texture> + <visible>!String.IsEmpty(Container(102).ListItem.Art(fanart))</visible> </control> @@ -154,6 +154,18 @@ <control type='group'> <description>Video Info</description> <visible>Integer.IsGreater(Container(102).NumItems, 0)</visible> + <animation type="Visible" reversible="false"> + <effect type="slide" delay="160" start="100,0" end="0,0" time="200" /> + <effect type="fade" delay="160" start="0" end="100" time="200" /> + </animation> + <animation type="Hidden" reversible="false"> + <effect type="slide" start="0,0" end="100,0" time="200" /> + <effect type="fade" start="100" end="0" time="200" /> + </animation> + <animation type="WindowClose" reversible="false"> + <effect type="slide" start="0,0" end="100,0" time="200" /> + <effect type="fade" start="100" end="0" time="200" /> + </animation> <top>80</top> <height>120</height> <width>840</width> @@ -254,6 +266,11 @@ </control> <control type="fixedlist" id="102"> + <animation effect="slide" start="0,100" time="200" condition="Integer.IsGreater(Container(102).NumItems, 0)">Conditional</animation> + <animation effect="fade" start="0" time="200" condition="Integer.IsGreater(Container(102).NumItems, 0)">Conditional</animation> + <animation effect="slide" end="0,100" time="200">WindowClose</animation> + <animation effect="fade" time="100">WindowClose</animation> + <description>Search Results list</description> <bottom>70</bottom> <left>0</left> @@ -285,6 +302,7 @@ <texture>$INFO[ListItem.Property(channelthumb)]</texture> <bordersize>10</bordersize> <aspectratio>scale</aspectratio> + <visible>!String.IsEmpty(ListItem.Property(verified))</visible> </control> <control type="image"> <description>Item Poster</description> @@ -478,6 +496,15 @@ <control type="image"> <description>Poster</description> + <visible>Control.IsVisible(2)</visible> + <animation type="Visible" reversible="false"> + <effect type="slide" delay="160" start="-100,0" end="0,0" time="200" /> + <effect type="fade" delay="160" start="0" end="100" time="200" /> + </animation> + <animation type="Hidden" reversible="false"> + <effect type="slide" start="0,0" end="-100,0" time="200" /> + <effect type="fade" start="100" end="" time="200" /> + </animation> <top>0</top> <left>0</left> <width>480</width> @@ -487,6 +514,15 @@ <control type="textbox"> <description>Main Title</description> + <visible>Control.IsVisible(2)</visible> + <animation type="Visible" reversible="false"> + <effect type="slide" delay="160" start="100,0" end="0,0" time="200" /> + <effect type="fade" delay="160" start="0" end="100" time="200" /> + </animation> + <animation type="Hidden" reversible="false"> + <effect type="slide" start="0,0" end="100,0" time="200" /> + <effect type="fade" start="100" end="0" time="200" /> + </animation> <left>520</left> <top>40</top> <width>1150</width> @@ -501,6 +537,15 @@ <control type="list" id="200"> <!-- Episodes List --> <description>Episodes List</description> + <visible>Control.IsVisible(2)</visible> + <animation type="Visible" reversible="false"> + <effect type="slide" delay="160" start="100,0" end="0,0" time="200" /> + <effect type="fade" delay="160" start="0" end="100" time="200" /> + </animation> + <animation type="Hidden" reversible="false"> + <effect type="slide" start="0,0" end="100,0" time="200" /> + <effect type="fade" start="100" end="0" time="200" /> + </animation> <top>110</top> <left>520</left> <width>700</width> @@ -555,6 +600,15 @@ <visible>Control.IsVisible(3)</visible> <control type="image"> + <visible>Control.IsVisible(3)</visible> + <animation type="Visible" reversible="false"> + <effect type="slide" delay="160" start="-100,0" end="0,0" time="200" /> + <effect type="fade" delay="160" start="0" end="100" time="200" /> + </animation> + <animation type="Hidden" reversible="false"> + <effect type="slide" start="0,0" end="-100,0" time="200" /> + <effect type="fade" start="100" end="" time="200" /> + </animation> <description>Poster</description> <top>0</top> <left>0</left> @@ -564,6 +618,16 @@ </control> <control type="textbox"> + <visible>Control.IsVisible(3)</visible> + <animation type="Visible" reversible="false"> + <effect type="slide" delay="160" start="100,0" end="0,0" time="200" /> + <effect type="fade" delay="160" start="0" end="100" time="200" /> + </animation> + <animation type="Hidden" reversible="false"> + <effect type="slide" start="0,0" end="100,0" time="200" /> + <effect type="fade" start="100" end="0" time="200" /> + </animation> + <visible>Control.IsVisible(3)</visible> <description>Main Title</description> <left>520</left> <top>40</top> @@ -578,6 +642,15 @@ </control> <control type="list" id="300"> <!-- Servers List --> + <visible>Control.IsVisible(3)</visible> + <animation type="Visible" reversible="false"> + <effect type="slide" delay="160" start="100,0" end="0,0" time="200" /> + <effect type="fade" delay="160" start="0" end="100" time="200" /> + </animation> + <animation type="Hidden" reversible="false"> + <effect type="slide" start="0,0" end="100,0" time="200" /> + <effect type="fade" start="100" end="0" time="200" /> + </animation> <description>Servers List</description> <bottom>40</bottom> <left>520</left> @@ -596,58 +669,31 @@ <texture>$INFO[ListItem.Art(poster)]</texture> <aspectratio>scale</aspectratio> </control> - <control type="group"> - <visible>ListItem.Property(quality)</visible> - <control type="image"> - <description>Servers Quality</description> - <top>35</top> - <left>150</left> - <width>60</width> - <height>60</height> - <texture>$INFO[ListItem.Property(quality)]</texture> - <aspectratio>scale</aspectratio> - </control> - <control type="textbox"> - <description>Server Title</description> - <left>220</left> - <top>35</top> - <width>450</width> - <height>60</height> - <font>font13</font> - <textcolor>FFFFFFFF</textcolor> - <shadowcolor>00000000</shadowcolor> - <align>left</align> - <aligny>center</aligny> - <label>[B][COLOR FFAAAAAA]$INFO[ListItem.Property(servername)][/COLOR][/B]</label> - </control> - </control> <control type="textbox"> - <visible>!ListItem.Property(quality)</visible> <description>Server Title</description> <left>150</left> - <top>35</top> + <top>30</top> <width>450</width> - <height>60</height> + <height>30</height> <font>font13</font> <textcolor>FFFFFFFF</textcolor> <shadowcolor>00000000</shadowcolor> <align>left</align> <aligny>center</aligny> - <label>[B][COLOR FFAAAAAA]$INFO[ListItem.Property(servername)][/COLOR][/B]</label> + <label>[B]$INFO[ListItem.Label][/B]</label> </control> <control type="textbox"> - <description>No Server Title</description> + <description>Channel</description> <left>150</left> - <top>35</top> + <top>60</top> <width>450</width> - <height>60</height> + <height>30</height> <font>font13</font> <textcolor>FFFFFFFF</textcolor> <shadowcolor>00000000</shadowcolor> <align>left</align> <aligny>center</aligny> - <label>$INFO[ListItem.Label]</label> - <visible>!ListItem.Property(servername)</visible> + <label>[B][COLOR FFAAAAAA]$INFO[ListItem.Property(channel)][/COLOR][/B]</label> </control> </itemlayout> <focusedlayout height="140" width="700"> @@ -664,10 +710,8 @@ <left>0</left> <width>130</width> <height>130</height> - <visible>Control.HasFocus(300)</visible> <texture colordiffuse="$INFO[ListItem.Property(color)]">white.png</texture> <aspectratio>scale</aspectratio> - <visible>ListItem.Property(servername)</visible> </control> <control type="image"> <description>Servers Icon</description> @@ -678,58 +722,31 @@ <texture>$INFO[ListItem.Art(poster)]</texture> <aspectratio>scale</aspectratio> </control> - <control type="group"> - <visible>ListItem.Property(quality)</visible> - <control type="image"> - <description>Servers Quality</description> - <top>35</top> - <left>150</left> - <width>60</width> - <height>60</height> - <texture>$INFO[ListItem.Property(quality)]</texture> - <aspectratio>scale</aspectratio> - </control> - <control type="textbox"> - <description>Server Title</description> - <left>220</left> - <top>35</top> - <width>450</width> - <height>60</height> - <font>font13</font> - <textcolor>FFFFFFFF</textcolor> - <shadowcolor>00000000</shadowcolor> - <align>left</align> - <aligny>center</aligny> - <label>[B][COLOR FFAAAAAA]$INFO[ListItem.Property(servername)][/COLOR][/B]</label> - </control> - </control> <control type="textbox"> - <visible>!ListItem.Property(quality)</visible> <description>Server Title</description> <left>150</left> - <top>35</top> + <top>30</top> <width>450</width> - <height>60</height> + <height>30</height> <font>font13</font> <textcolor>FFFFFFFF</textcolor> <shadowcolor>00000000</shadowcolor> <align>left</align> <aligny>center</aligny> - <label>[B][COLOR FFAAAAAA]$INFO[ListItem.Property(servername)][/COLOR][/B]</label> + <label>[B]$INFO[ListItem.Label][/B]</label> </control> <control type="textbox"> - <description>No Server Title</description> + <description>Channel</description> <left>150</left> - <top>35</top> + <top>60</top> <width>450</width> - <height>60</height> + <height>30</height> <font>font13</font> <textcolor>FFFFFFFF</textcolor> <shadowcolor>00000000</shadowcolor> <align>left</align> <aligny>center</aligny> - <label>$INFO[ListItem.Label]</label> - <visible>!ListItem.Property(servername)</visible> + <label>[B][COLOR FFAAAAAA]$INFO[ListItem.Property(channel)][/COLOR][/B]</label> </control> </focusedlayout> </control> <!-- END Servers List --> @@ -781,60 +798,52 @@ <visible>Control.IsVisible(4)</visible> </control> - <control type="textbox"> - <description>Load Channels</description> - <top>300</top> - <left>0</left> - <width>100%</width> - <height>40</height> - <font>font13</font> - <textcolor>FFFFFFFF</textcolor> - <shadowcolor>00000000</shadowcolor> - <align>center</align> - <aligny>center</aligny> - <label>[UPPERCASE]$ADDON[plugin.video.kod 60519][/UPPERCASE]</label> - <visible>Control.IsVisible(5)</visible> - </control> - - <control type="button" id="502"> - <description>Menu</description> - <top>30</top> - <right>110</right> - <height>40</height> - <width>40</width> - <onleft>504</onleft> - <onright>503</onright> - <texturefocus colordiffuse="FFFFFFFF">menu.png</texturefocus> - <texturenofocus colordiffuse="80FFFFFF">menu.png</texturenofocus> - <visible>Integer.IsGreater(Container(101).NumItems, 0)</visible> - </control> - - <control type="button" id="503"> - <description>Back</description> - <top>30</top> - <right>70</right> - <height>40</height> - <width>40</width> - <onleft>502</onleft> - <onright>504</onright> - <texturefocus colordiffuse="FFFFFFFF">left.png</texturefocus> - <texturenofocus colordiffuse="80FFFFFF">left.png</texturenofocus> - </control> - - <control type="button" id="504"> - <description>Close</description> + <control type="group"> + <description>Buttons Group</description> <top>30</top> <right>30</right> + <width>150</width> <height>40</height> - <width>40</width> - <onleft>503</onleft> - <onright>502</onright> - <texturefocus colordiffuse="FFFFFFFF">close.png</texturefocus> - <texturenofocus colordiffuse="80FFFFFF">close.png</texturenofocus> + <control type="button" id="502"> + <description>Menu</description> + <top>0</top> + <right>80</right> + <height>40</height> + <width>40</width> + <onleft>504</onleft> + <onright>503</onright> + <texturefocus colordiffuse="FFFFFFFF">menu.png</texturefocus> + <texturenofocus colordiffuse="80FFFFFF">menu.png</texturenofocus> + <visible>Integer.IsGreater(Container(101).NumItems, 0)</visible> + </control> + + <control type="button" id="503"> + <description>Back</description> + <top>0</top> + <right>40</right> + <height>40</height> + <width>40</width> + <onleft>502</onleft> + <onright>504</onright> + <texturefocus colordiffuse="FFFFFFFF">left.png</texturefocus> + <texturenofocus colordiffuse="80FFFFFF">left.png</texturenofocus> + </control> + + <control type="button" id="504"> + <description>Close</description> + <top>0</top> + <right>0</right> + <height>40</height> + <width>40</width> + <onleft>503</onleft> + <onright>502</onright> + <texturefocus colordiffuse="FFFFFFFF">close.png</texturefocus> + <texturenofocus colordiffuse="80FFFFFF">close.png</texturenofocus> + </control> </control> <control type="textbox" id="505"> - <description>Load Channels</description> + <description>Quality Tag</description> <top>670</top> <right>20</right> <width>200</width> diff --git a/resources/skins/Default/720p/InfoPlus.xml b/resources/skins/Default/720p/InfoPlus.xml index 2f7d4536..7001417e 100644 --- a/resources/skins/Default/720p/InfoPlus.xml +++ b/resources/skins/Default/720p/InfoPlus.xml @@ -399,18 +399,18 @@ <control type='label'> <description>Name</description> <top>20</top> - <right>50</right> + <right>15</right> <width>40</width> <height>30</height> <font>font13</font> <scroll>true</scroll> - <textcolor>ffFFFFFF</textcolor> + <textcolor>Container(102).ListItem.Property(color)</textcolor> <shadowcolor>00000000</shadowcolor> <label>[B]$INFO[Container(102).ListItem.Rating][/B]</label> <align>right</align> <aligny>center</aligny> </control> - <control type='image'> + <!-- <control type='image'> <description>Rating Circle</description> <top>20</top> <right>15</right> @@ -418,7 +418,7 @@ <height>30</height> <texture colordiffuse='$INFO[Container(102).ListItem.Property(color)]'>Circular/$INFO[Container(102).ListItem.Property(rating)].png</texture> <aspectratio aligny='center'>keep</aspectratio> - </control> + </control> --> <control type='textbox'> <description>Plot</description> <top>60</top> diff --git a/resources/skins/Default/720p/Servers.xml b/resources/skins/Default/720p/Servers.xml index 2b5793b2..28cc2383 100644 --- a/resources/skins/Default/720p/Servers.xml +++ b/resources/skins/Default/720p/Servers.xml @@ -38,7 +38,7 @@ <effect type="slide" delay="160" start="-100,0" end="0,0" time="200" /> <effect type="fade" delay="160" start="0" end="100" time="200" /> </animation> - <animation type="WindowOpen" reversible="false"> + <animation type="WindowClose" reversible="false"> <effect type="slide" delay="160" start="0,0" end="-100,0" time="200" /> <effect type="fade" delay="160" start="100" end="0" time="200" /> </animation> @@ -68,7 +68,7 @@ <effect type="slide" delay="160" start="100,0" end="0,0" time="200" /> <effect type="fade" delay="160" start="0" end="100" time="200" /> </animation> - <animation type="WindowOpen" reversible="false"> + <animation type="WindowClose" reversible="false"> <effect type="slide" delay="160" start="0,0" end="100,0" time="200" /> <effect type="fade" delay="160" start="100" end="0" time="200" /> </animation> diff --git a/servers/streamtape.py b/servers/streamtape.py index 779fe0a0..fc412553 100644 --- a/servers/streamtape.py +++ b/servers/streamtape.py @@ -29,7 +29,7 @@ def test_video_exists(page_url): def get_video_url(page_url, premium=False, user="", password="", video_password=""): logger.debug("url=" + page_url) video_urls = [] - find_url = match(data, patron=r'innerHTML = ([^;]+)').match + find_url = match(data, patron=r'innerHTML = ([^;]+)').matches[-1] possible_url = js2py.eval_js(find_url) url = "https:" + possible_url url = httptools.downloadpage(url, follow_redirects=False, only_headers=True).headers.get("location", "") diff --git a/service.py b/service.py index 4445e30e..c3e2867e 100644 --- a/service.py +++ b/service.py @@ -92,7 +92,7 @@ class AddonMonitor(xbmc.Monitor): if wait > 0: xbmc.sleep(wait) if not config.get_setting("update", "videolibrary") == 2: - run_threaded(check_for_update, (False,)) + run_threaded(check_for_update, []) self.scheduleVideolibrary() super(AddonMonitor, self).__init__() @@ -181,8 +181,9 @@ class AddonMonitor(xbmc.Monitor): logger.debug('scheduled videolibrary at ' + str(self.update_hour).zfill(2) + ':00') def scheduleScreenOnJobs(self): + # pass schedule.every().second.do(platformtools.viewmodeMonitor).tag('screenOn') - schedule.every().second.do(torrent.elementum_monitor).tag('screenOn') + # schedule.every().second.do(torrent.elementum_monitor).tag('screenOn') def onDPMSActivated(self): logger.debug('DPMS activated, un-scheduling screen-on jobs') diff --git a/specials/classicsearch.py b/specials/classicsearch.py new file mode 100644 index 00000000..b3bca021 --- /dev/null +++ b/specials/classicsearch.py @@ -0,0 +1,602 @@ +# -*- coding: utf-8 -*- +# -*- Channel New Search -*- +# -*- Created for Alfa-addon -*- +# -*- By the Alfa Develop Group -*- + +from __future__ import division +from builtins import range +from core import support +from past.utils import old_div +#from builtins import str +import sys +PY3 = False +if sys.version_info[0] >= 3: PY3 = True; unicode = str; unichr = chr; long = int + +import time, channelselector + +if PY3: + from concurrent import futures +else: + from concurrent_py2 import futures +from core.item import Item +from core import tmdb, scrapertools, channeltools, filetools +from platformcode import logger, config, platformtools, unify +from core.support import typo, thumb +from specials.search import channel_selections, set_context, save_search + +info_language = ["de", "en", "es", "fr", "it", "pt"] # from videolibrary.json +def_lang = info_language[config.get_setting("info_language", "videolibrary")] + + +def new_search(item): + logger.debug() + + temp_search_file = config.get_temp_file('temp-search') + if filetools.isfile(temp_search_file): + filetools.remove(temp_search_file) + + itemlist = [] + if config.get_setting('last_search'): + last_search = channeltools.get_channel_setting('Last_searched', 'search', '') + else: + last_search = '' + + if item.search_text: + searched_text = item.search_text + else: + searched_text = platformtools.dialog_input(default=last_search, heading='') + + save_search(searched_text) + if not searched_text: + return + + channeltools.set_channel_setting('Last_searched', searched_text, 'search') + searched_text = searched_text.replace("+", " ") + + if item.mode == 'person': + item.searched_text = searched_text + return actor_list(item) + + if item.mode != 'all': + tmdb_info = tmdb.Tmdb(searched_text=searched_text, search_type=item.mode.replace('show', '')) + results = tmdb_info.results + for result in results: + result = tmdb_info.get_infoLabels(result, origen=result) + if item.mode == 'movie': + title = result['title'] + else: + title = result['name'] + item.mode = 'tvshow' + + thumbnail = result.get('thumbnail', '') + fanart = result.get('fanart', '') + + new_item = Item(channel=item.channel, + action='channel_search', + title=title, + text=searched_text, + thumbnail=thumbnail, + fanart=fanart, + mode=item.mode, + contentType=item.mode, + infoLabels=result) + + if item.mode == 'movie': + new_item.contentTitle = result['title'] + else: + new_item.contentSerieName = result['name'] + + itemlist.append(new_item) + + if item.mode == 'all' or not itemlist: + return channel_search(Item(channel=item.channel, + title=searched_text, + text=searched_text, + mode='all', + infoLabels={})) + + return itemlist + + +def channel_search(item): + logger.debug(item) + + start = time.time() + searching = list() + searching_titles = list() + results = list() + valid = list() + ch_list = dict() + mode = item.mode + + if item.infoLabels['tvshowtitle']: + item.text = item.infoLabels['tvshowtitle'].split(' - ')[0] + item.title = item.text + elif item.infoLabels['title']: + item.text = item.infoLabels['title'].split(' - ')[0] + item.title = item.text + + temp_search_file = config.get_temp_file('temp-search') + if filetools.isfile(temp_search_file): + itemlist = [] + f = filetools.read(temp_search_file) + if f.startswith(item.text): + for it in f.split(','): + if it and it != item.text: + itemlist.append(Item().fromurl(it)) + return itemlist + else: + filetools.remove(temp_search_file) + + searched_id = item.infoLabels['tmdb_id'] + + channel_list, channel_titles = get_channels(item) + + searching += channel_list + searching_titles += channel_titles + cnt = 0 + progress = platformtools.dialog_progress(config.get_localized_string(30993) % item.title, config.get_localized_string(70744) % len(channel_list) + '\n' + ', '.join(searching_titles)) + config.set_setting('tmdb_active', False) + search_action_list = [] + module_dict = {} + for ch in channel_list: + try: + module = __import__('channels.%s' % ch, fromlist=["channels.%s" % ch]) + mainlist = getattr(module, 'mainlist')(Item(channel=ch, global_search=True)) + + module_dict[ch] = module + search_action_list.extend([elem for elem in mainlist if + elem.action == "search" and (mode == 'all' or elem.contentType in [mode, 'undefined'])]) + if progress.iscanceled(): + return [] + except: + import traceback + logger.error('error importing/getting search items of ' + ch) + logger.error(traceback.format_exc()) + + total_search_actions = len(search_action_list) + with futures.ThreadPoolExecutor(max_workers=set_workers()) as executor: + c_results = [] + for search_action in search_action_list: + c_results.append(executor.submit(get_channel_results, item, module_dict, search_action)) + if progress.iscanceled(): + break + + for res in futures.as_completed(c_results): + search_action = res.result()[0] + channel = search_action.channel + if res.result()[1]: + if channel not in ch_list: + ch_list[channel] = [] + ch_list[channel].extend(res.result()[1]) + if res.result()[2]: + valid.extend(res.result()[2]) + + if progress.iscanceled(): + break + + search_action_list.remove(search_action) + # if no action of this channel remains + for it in search_action_list: + if it.channel == channel: + break + else: + cnt += 1 + searching_titles.remove(searching_titles[searching.index(channel)]) + searching.remove(channel) + progress.update(old_div(((total_search_actions - len(search_action_list)) * 100), total_search_actions), config.get_localized_string(70744) % str(len(channel_list) - cnt) + '\n' + ', '.join(searching_titles)) + + progress.close() + + cnt = 0 + progress = platformtools.dialog_progress(config.get_localized_string(30993) % item.title, config.get_localized_string(60295) + '\n' + config.get_localized_string(60293)) + + config.set_setting('tmdb_active', True) + # res_count = 0 + for key, value in ch_list.items(): + ch_name = channel_titles[channel_list.index(key)] + grouped = list() + cnt += 1 + progress.update(old_div((cnt * 100), len(ch_list)), config.get_localized_string(60295)) + + for it in value: + if it.channel == item.channel: + it.channel = key + if it in valid: + continue + if mode == 'all' or (it.contentType and mode == it.contentType): + if config.get_setting('result_mode') != 0: + if config.get_localized_string(30992) not in it.title: + it.title += typo(ch_name,'_ [] color kod bold') + results.append(it) + else: + grouped.append(it) + elif (mode == 'movie' and it.contentTitle) or (mode == 'tvshow' and (it.contentSerieName or it.show)): + grouped.append(it) + else: + continue + + if not grouped: + continue + # to_temp[key] = grouped + if config.get_setting('result_mode') == 0: + if not config.get_setting('unify'): + title = typo(ch_name,'bold') + typo(str(len(grouped)), '_ [] color kod bold') + else: + title = typo('%s %s' % (len(grouped), config.get_localized_string(70695)), 'bold') + # res_count += len(grouped) + plot='' + + for it in grouped: + plot += it.title +'\n' + ch_thumb = channeltools.get_channel_parameters(key)['thumbnail'] + results.append(Item(channel=item.channel, title=title, + action='get_from_temp', thumbnail=ch_thumb, itemlist=[ris.tourl() for ris in grouped], plot=plot, page=1)) + + progress.close() + # "All Together" and movie mode -> search servers + if config.get_setting('result_mode') == 1 and mode == 'movie': + progress = platformtools.dialog_progress(config.get_localized_string(30993) % item.title, config.get_localized_string(60683)) + valid_servers = [] + with futures.ThreadPoolExecutor(max_workers=set_workers()) as executor: + c_results = [executor.submit(get_servers, v, module_dict) for v in valid] + completed = 0 + + for res in futures.as_completed(c_results): + if progress.iscanceled(): + break + if res.result(): + completed += 1 + valid_servers.extend(res.result()) + progress.update(old_div(completed * 100, len(valid))) + valid = valid_servers + progress.close() + + # send_to_temp(to_temp) + + results = sorted(results, key=lambda it: it.title) + results_statistic = config.get_localized_string(59972) % (item.title, time.time() - start) + if mode == 'all': + results.insert(0, Item(title=typo(results_statistic, 'color kod bold'), thumbnail=thumb('search'))) + else: + if not valid: + valid.append(Item(title=config.get_localized_string(60347), thumbnail=thumb('nofolder'))) + + valid.insert(0, Item(title=typo(results_statistic, 'color kod bold'), thumbnail=thumb('search'))) + results.insert(0, Item(title=typo(config.get_localized_string(30025), 'color kod bold'), thumbnail=thumb('search'))) + # logger.debug(results_statistic) + + itlist = valid + results + writelist = item.text + for it in itlist: + writelist += ',' + it.tourl() + filetools.write(temp_search_file, writelist) + + return itlist + + +def get_channel_results(item, module_dict, search_action): + ch = search_action.channel + results = list() + valid = list() + module = module_dict[ch] + searched_id = item.infoLabels['tmdb_id'] + + try: + results.extend(module.search(search_action, item.text)) + if len(results) == 1: + if not results[0].action or config.get_localized_string(70006).lower() in results[0].title.lower(): + results.clear() + if item.mode != 'all': + for elem in results: + if not elem.infoLabels.get('year', ""): + elem.infoLabels['year'] = '-' + tmdb.set_infoLabels_item(elem) + if elem.infoLabels['tmdb_id'] == searched_id: + elem.from_channel = ch + if not config.get_setting('unify'): + elem.title += ' [%s]' % ch + valid.append(elem) + + # if len(results) < 0 and len(results) < max_results and item.mode != 'all': + # + # if len(results) == 1: + # if not results[0].action or config.get_localized_string(30992).lower() in results[0].title.lower(): + # return [ch, []] + # + # results = get_info(results) + + return [search_action, results, valid] + except: + return [search_action, results, valid] + + +def get_servers(item, module_dict): + item.global_search = True + ch = item.channel + results = list() + module = module_dict[ch] + try: + results = getattr(module, item.action)(item) + except: + import traceback + logger.error(traceback.format_exc()) + return [r.clone(title=r.title + typo(item.channel, '_ [] color kod')) for r in results if r.action == 'play'] + + +def get_info(itemlist): + logger.debug() + tmdb.set_infoLabels_itemlist(itemlist, True, forced=True) + + return itemlist + + +def get_channels(item): + logger.debug() + + channels_list = list() + title_list = list() + all_channels = channelselector.filterchannels('all') + + for ch in all_channels: + channel = ch.channel + ch_param = channeltools.get_channel_parameters(channel) + if not ch_param.get("active", False): + continue + list_cat = ch_param.get("categories", []) + + if not ch_param.get("include_in_global_search", False): + continue + + if 'anime' in list_cat: + n = list_cat.index('anime') + list_cat[n] = 'tvshow' + + if item.mode == 'all' or (item.mode in list_cat): + if config.get_setting("include_in_global_search", channel) and ch_param.get("active", False): + channels_list.append(channel) + title_list.append(ch_param.get('title', channel)) + + return channels_list, title_list + + +def settings(item): + return platformtools.show_channel_settings(caption=config.get_localized_string(59993)) + + +def set_workers(): + workers = config.get_setting('thread_number') if config.get_setting('thread_number') > 0 else None + return workers + + + + + +def genres_menu(item): + itemlist = [] + mode = item.mode.replace('show', '') + + genres = tmdb.get_dic_genres(mode) + for key, value in list(genres[mode].items()): + discovery = {'url': 'discover/%s' % mode, 'with_genres': key, + 'language': def_lang, 'page': '1'} + + itemlist.append(Item(channel=item.channel, title=typo(value, 'bold'), page=1, + action='discover_list', discovery=discovery, + mode=item.mode)) + from core import support + support.thumb(itemlist, mode='genre') + return sorted(itemlist, key=lambda it: it.title) + + +def years_menu(item): + import datetime + itemlist = [] + + mode = item.mode.replace('show', '') + + par_year = 'primary_release_year' + thumb = thumb('movie_year') + + if mode != 'movie': + par_year = 'first_air_date_year' + thumb = thumb('tvshow_year') + + c_year = datetime.datetime.now().year + 1 + l_year = c_year - 31 + + for year in range(l_year, c_year): + discovery = {'url': 'discover/%s' % mode, 'page': '1', + '%s' % par_year: '%s' % year, + 'sort_by': 'popularity.desc', 'language': def_lang} + + itemlist.append(Item(channel=item.channel, title=typo(str(year), 'bold'), action='discover_list', + discovery=discovery, mode=item.mode, year_=str(year), thumbnail=thumb)) + itemlist.reverse() + itemlist.append(Item(channel=item.channel, title=typo(config.get_localized_string(70745),'color kod bold'), url='', + action="year_cus", mode=item.mode, par_year=par_year)) + + return itemlist + + +def year_cus(item): + mode = item.mode.replace('show', '') + + heading = config.get_localized_string(70042) + year = platformtools.dialog_numeric(0, heading, default="") + item.discovery = {'url': 'discover/%s' % mode, 'page': '1', + '%s' % item.par_year: '%s' % year, + 'sort_by': 'popularity.desc', 'language': def_lang} + item.action = "discover_list" + if year and len(year) == 4: + return discover_list(item) + + +def actor_list(item): + itemlist = [] + + dict_ = {'url': 'search/person', 'language': def_lang, 'query': item.searched_text, 'page': item.page} + + prof = {'Acting': 'Actor', 'Directing': 'Director', 'Production': 'Productor'} + plot = '' + item.search_type = 'person' + + tmdb_inf = tmdb.discovery(item, dict_=dict_) + results = tmdb_inf.results + + if not results: + return results + + for elem in results: + name = elem.get('name', '') + if not name: + continue + + rol = elem.get('known_for_department', '') + rol = prof.get(rol, rol) + # genero = elem.get('gender', 0) + # if genero == 1 and rol in prof: + # rol += 'a' + # rol = rol.replace('Actora', 'Actriz') + + know_for = elem.get('known_for', '') + cast_id = elem.get('id', '') + if know_for: + t_k = know_for[0].get('title', '') + if t_k: + plot = '%s in %s' % (rol, t_k) + + thumbnail = 'https://image.tmdb.org/t/p/original%s' % elem.get('profile_path', '') + title = typo(name,'bold')+typo(rol,'_ [] color kod bold') + + discovery = {'url': 'person/%s/combined_credits' % cast_id, 'page': '1', + 'sort_by': 'primary_release_date.desc', 'language': def_lang} + + itemlist.append(Item(channel=item.channel, title=title, action='discover_list', cast_='cast', + discovery=discovery, thumbnail=thumbnail, plot=plot, page=1)) + + if len(results) > 19: + next_ = item.page + 1 + itemlist.append(Item(channel=item.channel, title=typo(config.get_localized_string(30992),'bold color kod'), action='actor_list', + page=next_, thumbnail=thumbnail, + searched_text=item.searched_text)) + return itemlist + + +def discover_list(item): + import datetime + itemlist = [] + + year = 0 + tmdb_inf = tmdb.discovery(item, dict_=item.discovery, cast=item.cast_) + result = tmdb_inf.results + tvshow = False + + for elem in result: + elem = tmdb_inf.get_infoLabels(elem, origen=elem) + if 'title' in elem: + title = unify.normalize(elem['title']).capitalize() + else: + title = unify.normalize(elem['name']).capitalize() + tvshow = True + elem['tmdb_id'] = elem['id'] + + mode = item.mode or elem['mediatype'] + thumbnail = elem.get('thumbnail', '') + fanart = elem.get('fanart', '') + + if item.cast_: + release = elem.get('release_date', '0000') or elem.get('first_air_date', '0000') + year = scrapertools.find_single_match(release, r'(\d{4})') + + if not item.cast_ or (item.cast_ and (int(year) <= int(datetime.datetime.today().year))): + if config.get_setting('new_search'): + new_item = Item(channel='globalsearch', title=typo(title, 'bold'), infoLabels=elem, + action='Search', text=title, + thumbnail=thumbnail, fanart=fanart, + context='', mode='search', type = mode, contentType=mode, + release_date=year, folder = False) + else: + new_item = Item(channel='search', title=typo(title, 'bold'), infoLabels=elem, + action='channel_search', text=title, + thumbnail=thumbnail, fanart=fanart, + context='', mode=mode, contentType=mode, + release_date=year) + + if tvshow: + new_item.contentSerieName = title + else: + new_item.contentTitle = title + + itemlist.append(new_item) + + itemlist = set_context(itemlist) + + if item.cast_: + itemlist.sort(key=lambda it: int(it.release_date), reverse=True) + return itemlist + + elif len(result) > 19 and item.discovery: + item.discovery['page'] = str(int(item.discovery['page']) + 1) + itemlist.append(Item(channel=item.channel, action='discover_list', nextPage=True, + title=typo(config.get_localized_string(30992), 'color kod bold'), + list_type=item.list_type, discovery=item.discovery, thumbnail=thumb(), page=item.discovery['page'])) + elif len(result) > 19: + next_page = str(int(item.page) + 1) + + itemlist.append(Item(channel=item.channel, action='discover_list', nextPage=True, + title=typo(config.get_localized_string(30992), 'color kod bold'), + list_type=item.list_type, search_type=item.search_type, mode=item.mode, page=next_page, thumbnail=thumb())) + + return itemlist + + +def from_context(item): + logger.debug() + + select = channel_selections(item) + + if not select: + return + + if 'infoLabels' in item and 'mediatype' in item.infoLabels: + item.mode = item.infoLabels['mediatype'] + else: + return + + if config.get_setting('new_search'): + from specials import globalsearch + if item.infoLabels['tmdb_id']: + item.type = item.mode + item.mode = 'search' + return globalsearch.Search(item) + + if 'list_type' not in item: + if 'wanted' in item: + item.title = item.wanted + return channel_search(item) + + return discover_list(item) + + +def get_from_temp(item): + logger.debug() + + n = 30 + nTotal = len(item.itemlist) + nextp = n * item.page + prevp = n * (item.page - 1) + + results = [Item().fromurl(elem) for elem in item.itemlist[prevp:nextp]] + + if nextp < nTotal: + results.append(Item(channel='search', title=typo(config.get_localized_string(30992), 'bold color kod'), + action='get_from_temp', itemlist=item.itemlist, page=item.page + 1, nextPage=True)) + + tmdb.set_infoLabels_itemlist(results, True) + for elem in results: + if not elem.infoLabels.get('year', ""): + elem.infoLabels['year'] = '-' + tmdb.set_infoLabels_item(elem, True) + + return results diff --git a/specials/globalsearch.py b/specials/globalsearch.py index 7b51e087..d9ecd67d 100644 --- a/specials/globalsearch.py +++ b/specials/globalsearch.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +from logging import Logger import threading from core import jsontools, support @@ -30,7 +31,7 @@ def set_workers(): workers = config.get_setting('thread_number') if config.get_setting('thread_number') > 0 else None return workers -def Search(*args): +def new_search(*args): xbmc.executebuiltin('Dialog.Close(all)') w = SearchWindow('GlobalSearch.xml', config.get_runtime_path()) w.start(*args) @@ -54,7 +55,6 @@ SEARCH = 1 EPISODES = 2 SERVERS = 3 NORESULTS = 4 -LOADING = 5 # Search MAINTITLE = 100 @@ -79,7 +79,6 @@ class SearchWindow(xbmcgui.WindowXML): self.exit = False self.item = item - self.type = self.item.mode self.channels = [] self.persons = [] self.episodes = [] @@ -95,7 +94,7 @@ class SearchWindow(xbmcgui.WindowXML): self.search_threads = [] self.reload = False - if not thActions: + if not thActions and not self.searchActions: self.thActions = Thread(target=self.getActionsThread) self.thActions.start() else: @@ -126,15 +125,15 @@ class SearchWindow(xbmcgui.WindowXML): def getActionsThread(self): logger.debug() self.channelsList = self.get_channels() + for channel in self.channelsList: logger.debug(channel) try: module = __import__('channels.%s' % channel, fromlist=["channels.%s" % channel]) mainlist = getattr(module, 'mainlist')(Item(channel=channel, global_search=True)) - action = [elem for elem in mainlist if elem.action == "search" and ( - self.item.mode in ['all', 'person'] or elem.contentType in [self.item.mode, 'undefined'])] + actions = [elem for elem in mainlist if elem.action == "search" and (self.item.mode in ['all', 'person'] or elem.contentType in [self.item.mode, 'undefined'])] self.moduleDict[channel] = module - self.searchActions += action + self.searchActions.append(actions) except: import traceback logger.error('error importing/getting search items of ' + channel) @@ -147,19 +146,20 @@ class SearchWindow(xbmcgui.WindowXML): # wait and return as getActionsThread load lastLen = len(self.searchActions) - while self.thActions.is_alive(): - while len(self.searchActions) == lastLen: - if not self.thActions.is_alive(): - return - time.sleep(0.1) - yield self.searchActions[lastLen-1] - lastLen = len(self.searchActions) + if self.thActions: + while self.thActions.is_alive(): + while len(self.searchActions) == lastLen: + if not self.thActions.is_alive(): + return + time.sleep(0.1) + yield self.searchActions[lastLen-1] + lastLen = len(self.searchActions) def select(self): logger.debug() self.PROGRESS.setVisible(False) self.items = [] - if self.item.mode == 'person_': + if self.item.mode == 'filmography': tmdb_info = tmdb.discovery(self.item, dict_=self.item.discovery) results = tmdb_info.results.get('cast',[]) else: @@ -255,12 +255,12 @@ class SearchWindow(xbmcgui.WindowXML): discovery = {'url': 'person/%s/combined_credits' % cast_id, 'page': '1', 'sort_by': 'primary_release_date.desc', 'language': def_lang} self.persons.append(discovery) - new_item = Item(channel='search', + new_item = Item(channel='globalsearch', action=True, title=name, thumbnail=thumb, plot= plot, - mode='search') + mode='search_filmography') it = xbmcgui.ListItem(name) platformtools.set_infolabels(it, new_item) @@ -306,7 +306,7 @@ class SearchWindow(xbmcgui.WindowXML): n = list_cat.index('anime') list_cat[n] = 'tvshow' - if self.item.mode in ['all', 'person'] or self.item.mode in list_cat or self.item.type in list_cat: + if self.item.mode in ['all', 'person'] or self.item.mode in list_cat: if config.get_setting("include_in_global_search", channel) and ch_param.get("active", False): channels_list.append(channel) @@ -315,7 +315,7 @@ class SearchWindow(xbmcgui.WindowXML): return channels_list def timer(self): - while self.searchActions or self.thActions.is_alive(): + while self.searchActions or (self.thActions and self.thActions.is_alive()): if self.exit: return try: percent = (float(self.count) / len(self.searchActions)) * 100 @@ -323,28 +323,27 @@ class SearchWindow(xbmcgui.WindowXML): percent = 0 self.PROGRESS.setPercent(percent) self.MAINTITLE.setText('{} | {}/{} [{}"]'.format(self.mainTitle,self.count, len(self.searchActions), int(time.time() - self.time))) - # self.COUNT.setText('%s/%s [%s"]' % (self.count, len(self.searchActions), int(time.time() - self.time))) + if percent == 100: + if len(self.channels) == 1: + self.setFocusId(RESULTS) + elif not self.results: + self.PROGRESS.setVisible(False) + self.NORESULTS.setVisible(True) + self.setFocusId(CLOSE) self.channels = [] self.moduleDict = {} self.searchActions = [] - # if no results - total = 0 - for num in self.results.values(): - total += num - if not total: - self.PROGRESS.setVisible(False) - self.NORESULTS.setVisible(True) - self.setFocusId(CLOSE) time.sleep(1) def search(self): logger.debug() self.count = 0 - self.LOADING.setVisible(True) Thread(target=self.timer).start() + # for searchAction in self.getActions(): + # self.search_threads.append(self.get_channel_results(searchAction)) try: with futures.ThreadPoolExecutor(max_workers=set_workers()) as executor: for searchAction in self.getActions(): @@ -357,10 +356,13 @@ class SearchWindow(xbmcgui.WindowXML): def get_channel_results(self, searchAction): def channel_search(text): - logger.debug('Search on channel:', channel) + results = [] valid = [] other = [] - results = self.moduleDict[channel].search(searchAction, text) + + for a in searchAction: + logger.debug('Search on channel:', a.channel) + results.extend(self.moduleDict[a.channel].search(a, text)) if len(results) == 1: if not results[0].action or results[0].nextPage: results = [] @@ -368,7 +370,7 @@ class SearchWindow(xbmcgui.WindowXML): if self.item.mode != 'all': for elem in results: if elem.infoLabels.get('tmdb_id') == self.item.infoLabels.get('tmdb_id'): - elem.from_channel = channel + elem.from_channel = elem.channel elem.verified = 1 valid.append(elem) else: @@ -376,11 +378,11 @@ class SearchWindow(xbmcgui.WindowXML): return results, valid, other logger.debug() - channel = searchAction.channel results = [] valid = [] other = [] + try: results, valid, other = channel_search(self.item.text) @@ -388,12 +390,12 @@ class SearchWindow(xbmcgui.WindowXML): # to add year to search text for better filtering if self.item.contentType == 'movie' and not valid and other and other[-1].nextPage \ and self.item.infoLabels['year']: - logger.debug('retring adding year on channel ' + channel) + logger.debug('retring adding year on channel ') dummy, valid, dummy = channel_search(self.item.text + " " + str(self.item.infoLabels['year'])) # some channels may use original title if self.item.mode != 'all' and not valid and self.item.infoLabels.get('originaltitle'): - logger.debug('retring with original title on channel ' + channel) + logger.debug('retring with original title on channel ') dummy, valid, dummy = channel_search(self.item.infoLabels.get('originaltitle')) except: import traceback @@ -401,10 +403,11 @@ class SearchWindow(xbmcgui.WindowXML): if self.exit: return + update_lock.acquire() self.count += 1 - logger.debug('Results:', channel, results, valid, other) - self.update(channel, valid, other if other else results) + + self.update(valid, other if other else results) update_lock.release() def makeItem(self, item): @@ -429,16 +432,19 @@ class SearchWindow(xbmcgui.WindowXML): it.setProperties({'rating': str(int(info.get('rating',10) * 10)), 'color': color, 'item': item.tourl(), 'verified': item.verified, 'channel':channelParams['title'], 'channelthumb': channelParams['thumbnail'], 'sub':'true' if 'sub' in item.contentLanguage.lower() else ''}) if item.server: + servername = servertools.get_server_parameters(item.server.lower()).get('name', item.server) + if item. quality: servername ='{} [{}]'.format(servername, item.quality) + it.setLabel(servername) color = scrapertools.find_single_match(item.alive, r'(FF[^\]]+)') it.setArt({'poster': config.get_online_server_thumb(item.server)}) - it.setProperties({'channel': channeltools.get_channel_parameters(item.channel).get('title', ''), - 'servername': servertools.get_server_parameters(item.server.lower()).get('name', item.server), + + it.setProperties({'quality':'[{}]'.format(item.quality) if item.quality else '', + 'channel': channeltools.get_channel_parameters(item.channel).get('title', ''), 'color': color if color else 'FF0082C2'}) return it - def update(self, channel, valid, results): - self.LOADING.setVisible(False) + def update(self, valid, results): if self.exit: return @@ -452,7 +458,6 @@ class SearchWindow(xbmcgui.WindowXML): pos = self.CHANNELS.getSelectedPosition() self.CHANNELS.addItems(self.channels) self.CHANNELS.selectItem(pos) - self.setFocusId(RESULTS) if valid and self.CHANNELS.size(): item = self.CHANNELS.getListItem(0) @@ -475,27 +480,18 @@ class SearchWindow(xbmcgui.WindowXML): if results: resultsList = '' - channelParams = channeltools.get_channel_parameters(channel) + channelParams = channeltools.get_channel_parameters(results[0].channel) name = channelParams['title'] - if name not in self.results: - item = xbmcgui.ListItem(name) - item.setArt({'poster':channelParams['thumbnail']}) - item.setProperties({'position': '0', - 'results': str(len(results)) - }) - for result in results: - resultsList += result.tourl() + '|' - item.setProperty('items',resultsList) - self.results[name] = len(self.results) - self.channels.append(item) - else: - item = self.CHANNELS.getListItem(self.results[name]) - resultsList = item.getProperty('items') - for result in results: - resultsList += result.tourl() + '|' - item.setProperty('items',resultsList) - logger.log(self.channels[int(self.results[name])]) - self.channels[int(self.results[name])].setProperty('results', str(len(resultsList.split('|')) - 1)) + item = xbmcgui.ListItem(name) + item.setArt({'poster':channelParams['thumbnail']}) + item.setProperties({'position': '0', + 'results': str(len(results)) + }) + for result in results: + resultsList += result.tourl() + '|' + item.setProperties({'items': resultsList, 'results': str(len(resultsList.split('|')) - 1)}) + self.results[name] = len(self.results) + self.channels.append(item) pos = self.CHANNELS.getSelectedPosition() self.CHANNELS.reset() self.CHANNELS.addItems(self.channels) @@ -511,6 +507,9 @@ class SearchWindow(xbmcgui.WindowXML): self.RESULTS.addItems(items) def onInit(self): + self.NORESULTS = self.getControl(NORESULTS) + self.NORESULTS.setVisible(False) + self.time = time.time() self.mainTitle = config.get_localized_string(30993).replace('...', '') % '"%s"' % self.item.text @@ -526,25 +525,18 @@ class SearchWindow(xbmcgui.WindowXML): self.EPISODESLIST = self.getControl(EPISODESLIST) self.SERVERS = self.getControl(SERVERS) self.SERVERLIST = self.getControl(SERVERLIST) - self.NORESULTS = self.getControl(NORESULTS) - self.NORESULTS.setVisible(False) - self.LOADING = self.getControl(LOADING) - self.LOADING.setVisible(False) - self.Focus(self.focus) - if self.type: - self.type = None - if self.item.mode in ['all', 'search']: - if self.item.type: - self.item.mode = self.item.type - self.item.text = scrapertools.title_unify(self.item.text) - self.thread = Thread(target=self.search) - self.thread.start() - elif self.item.mode in ['movie', 'tvshow', 'person_']: - self.select() - elif self.item.mode in ['person']: - self.actors() + if self.item.mode.split('_')[0] in ['all', 'search']: + if 'search' in self.item.mode: + self.item.mode = self.item.mode.split('_')[-1] + self.item.text = scrapertools.title_unify(self.item.text) + self.thread = Thread(target=self.search) + self.thread.start() + elif self.item.mode in ['movie', 'tvshow', 'filmography']: + self.select() + elif self.item.mode in ['person']: + self.actors() def Focus(self, focusid): if focusid in [SEARCH]: @@ -608,7 +600,7 @@ class SearchWindow(xbmcgui.WindowXML): elif action in [EXIT]: self.Close() - reload() + # reload() close_action = True xbmc.sleep(500) @@ -635,7 +627,7 @@ class SearchWindow(xbmcgui.WindowXML): elif control_id in [CLOSE]: self.Close() - reload() + # reload() close_action = True elif control_id in [MENU]: @@ -651,7 +643,7 @@ class SearchWindow(xbmcgui.WindowXML): self.actors() elif search == 'persons': item = self.item.clone(mode='person_', discovery=self.persons[pos]) - Search(item, self.moduleDict, self.searchActions, self.thActions) + new_search(item, self.moduleDict, self.searchActions) if close_action: self.close() else: @@ -659,7 +651,7 @@ class SearchWindow(xbmcgui.WindowXML): if self.item.mode == 'movie': item.contentTitle = self.RESULTS.getSelectedItem().getLabel() else: item.contentSerieName = self.RESULTS.getSelectedItem().getLabel() - Search(item, self.moduleDict, self.searchActions, self.thActions) + new_search(item, self.moduleDict, self.searchActions) if close_action: self.close() @@ -695,54 +687,16 @@ class SearchWindow(xbmcgui.WindowXML): if config.get_setting('checklinks') and not config.get_setting('autoplay'): self.itemsResult = servertools.check_list_links(self.itemsResult, config.get_setting('checklinks_number')) - servers = self.itemsResult if self.itemsResult else [] - self.itemsResult = [] - uhd = [] - fhd = [] - hd = [] - sd = [] - unknown = [] - other = [] - for i, item in enumerate(servers): - if item.server: - it = self.makeItem(item) - it.setProperty('index', str(i)) - if item.quality.lower() in ['4k', '2160p', '2160', '4k2160p', '4k2160', '4k 2160p', '4k 2160', '2k']: - it.setProperty('quality', 'uhd.png') - uhd.append(it) - elif item.quality.lower() in ['fullhd', 'fullhd 1080', 'fullhd 1080p', 'full hd', 'full hd 1080', 'full hd 1080p', 'hd1080', 'hd1080p', 'hd 1080', 'hd 1080p', '1080', '1080p']: - it.setProperty('quality', 'Fhd.png') - fhd.append(it) - elif item.quality.lower() in ['hd', 'hd720', 'hd720p', 'hd 720', 'hd 720p', '720', '720p', 'hdtv']: - it.setProperty('quality', 'hd.png') - hd.append(it) - elif item.quality.lower() in ['sd', '480p', '480', '360p', '360', '240p', '240']: - it.setProperty('quality', 'sd.png') - sd.append(it) - else: - it.setProperty('quality', '') - unknown.append(it) - elif not item.action: - self.getControl(QUALITYTAG).setText(item.fulltitle) - else: - it = self.makeItem(item) - other.append(it) - logger.debug(it) + for s in self.itemsResult: logger.debug(s) + servers = [self.makeItem(s) for s in self.itemsResult if s.server] - uhd.sort(key=lambda it: it.getProperty('index')) - fhd.sort(key=lambda it: it.getProperty('index')) - hd.sort(key=lambda it: it.getProperty('index')) - sd.sort(key=lambda it: it.getProperty('index')) - unknown.sort(key=lambda it: it.getProperty('index')) - - serverlist = uhd + fhd + hd + sd + unknown + other - if not serverlist: - serverlist = [xbmcgui.ListItem(config.get_localized_string(60347))] - serverlist[0].setArt({'poster': support.thumb('nofolder')}) + if not servers: + servers = [xbmcgui.ListItem(config.get_localized_string(60347))] + servers[0].setArt({'poster': support.thumb('nofolder')}) self.Focus(SERVERS) self.SERVERLIST.reset() - self.SERVERLIST.addItems(serverlist) + self.SERVERLIST.addItems(servers) self.setFocusId(SERVERLIST) if config.get_setting('autoplay'): @@ -772,10 +726,12 @@ class SearchWindow(xbmcgui.WindowXML): platformtools.dialog_busy(False) + elif control_id in [SERVERLIST]: server = Item().fromurl(self.getControl(control_id).getSelectedItem().getProperty('item')) return self.play(server) + def Back(self): self.getControl(QUALITYTAG).setText('') if self.SERVERS.isVisible(): diff --git a/specials/search.py b/specials/search.py index 8aa267f0..6db08e96 100644 --- a/specials/search.py +++ b/specials/search.py @@ -1,81 +1,180 @@ # -*- coding: utf-8 -*- -# -*- Channel New Search -*- -# -*- Created for Alfa-addon -*- -# -*- By the Alfa Develop Group -*- +# ------------------------------------------------------------ +# Search Entry Point +# ------------------------------------------------------------ -from __future__ import division -from builtins import range -from core import support -from past.utils import old_div -#from builtins import str -import sys -PY3 = False -if sys.version_info[0] >= 3: PY3 = True; unicode = str; unichr = chr; long = int - -import time, channelselector - -if PY3: - from concurrent import futures -else: - from concurrent_py2 import futures -from core.item import Item -from core import tmdb, scrapertools, channeltools, filetools, jsontools, servertools -from platformcode import logger, config, platformtools, unify -from core.support import typo, thumb -import xbmcgui import xbmc -from threading import Thread -from core.support import dbg - -info_language = ["de", "en", "es", "fr", "it", "pt"] # from videolibrary.json -def_lang = info_language[config.get_setting("info_language", "videolibrary")] - +from core.item import Item +from core.support import typo, thumb +from platformcode import logger, config, platformtools def mainlist(item): logger.debug() - + action = 'new_search' + channel = 'classicsearch' + folder = True if platformtools.get_window() not in ('WINDOW_SETTINGS_MENU', 'WINDOW_SETTINGS_INTERFACE', 'WINDOW_SKIN_SETTINGS')\ and xbmc.getInfoLabel('System.CurrentWindow') in ('Home', '') and config.get_setting('new_search'): - itemlist = [Item(channel='globalsearch', title=config.get_localized_string(70276), action='Search', mode='all', folder=False), - Item(channel='globalsearch', title=config.get_localized_string(70741) % config.get_localized_string(30122), action='Search', mode='movie', folder=False), - Item(channel='globalsearch', title=config.get_localized_string(70741) % config.get_localized_string(30123), action='Search', mode='tvshow', folder=False), - Item(channel='globalsearch', title=config.get_localized_string(70741) % config.get_localized_string(70314), action='Search', page=1, mode='person', folder=False)] - else: - itemlist = [Item(channel=item.channel, title=config.get_localized_string(70276), action='new_search', mode='all'), - Item(channel=item.channel, title=config.get_localized_string(70741) % config.get_localized_string(30122), action='new_search', mode='movie'), - Item(channel=item.channel, title=config.get_localized_string(70741) % config.get_localized_string(30123), action='new_search', mode='tvshow'), - Item(channel=item.channel, title=config.get_localized_string(70741) % config.get_localized_string(70314), action='new_search', page=1, mode='person')] + channel = 'globalsearch' + folder = False - itemlist += [Item(channel=item.channel, title=config.get_localized_string(59995), action='saved_search', thumbnail=thumb('search')), + itemlist = [Item(channel=channel, title=config.get_localized_string(70276), action=action, mode='all', folder=folder), + Item(channel=channel, title=config.get_localized_string(70741) % config.get_localized_string(30122), action=action, mode='movie', folder=folder), + Item(channel=channel, title=config.get_localized_string(70741) % config.get_localized_string(30123), action=action, mode='tvshow', folder=folder), + Item(channel=channel, title=config.get_localized_string(70741) % config.get_localized_string(70314), action=action, page=1, mode='person', folder=folder), + + Item(channel=item.channel, title=config.get_localized_string(59995), action='saved_search', thumbnail=thumb('search')), Item(channel=item.channel, title=config.get_localized_string(60420), action='sub_menu', thumbnail=thumb('search')), Item(channel="tvmoviedb", title=config.get_localized_string(70274), action="mainlist", thumbnail=thumb('search')), - Item(channel=item.channel, title=typo(config.get_localized_string(59994) + '{config}', 'color kod bold'), action='setting_channel_new', folder=False), - Item(channel='shortcuts', title=typo(config.get_localized_string(70286), 'color kod bold'), action='SettingOnPosition', category=5, setting=1, folder=False)] + Item(channel=item.channel, title=typo(config.get_localized_string(59994), 'bold'), action='channel_selections', folder=False), + Item(channel='shortcuts', title=typo(config.get_localized_string(70286), 'bold'), action='SettingOnPosition', category=5, setting=1, folder=False)] - itemlist = set_context(itemlist) thumb(itemlist) return itemlist def sub_menu(item): logger.debug() - - itemlist = [Item(channel=item.channel, action='genres_menu', title=config.get_localized_string(70306), mode='movie'), - Item(channel=item.channel, action='years_menu', title=config.get_localized_string(70742), mode='movie'), - Item(channel=item.channel, action='discover_list', title=config.get_localized_string(70307), search_type='list', list_type='movie/popular', mode='movie'), - Item(channel=item.channel, action='discover_list', title=config.get_localized_string(70308), search_type='list', list_type='movie/top_rated', mode='movie'), - Item(channel=item.channel, action='discover_list', title=config.get_localized_string(70309), search_type='list', list_type='movie/now_playing', mode='movie'), - Item(channel=item.channel, action='genres_menu', title=config.get_localized_string(70310), mode='tvshow'), - Item(channel=item.channel, action='years_menu', title=config.get_localized_string(70743), mode='tvshow'), - Item(channel=item.channel, action='discover_list', title=config.get_localized_string(70311), search_type='list', list_type='tv/popular', mode='tvshow'), - Item(channel=item.channel, action='discover_list', title=config.get_localized_string(70312), search_type='list', list_type='tv/on_air', mode='tvshow'), - Item(channel=item.channel, action='discover_list', title=config.get_localized_string(70313), search_type='list', list_type='tv/top_rated', mode='tvshow')] + channel = 'classicsearch' + itemlist = [Item(channel=channel, action='genres_menu', title=config.get_localized_string(70306), mode='movie'), + Item(channel=channel, action='years_menu', title=config.get_localized_string(70742), mode='movie'), + Item(channel=channel, action='discover_list', title=config.get_localized_string(70307), search_type='list', list_type='movie/popular', mode='movie'), + Item(channel=channel, action='discover_list', title=config.get_localized_string(70308), search_type='list', list_type='movie/top_rated', mode='movie'), + Item(channel=channel, action='discover_list', title=config.get_localized_string(70309), search_type='list', list_type='movie/now_playing', mode='movie'), + Item(channel=channel, action='genres_menu', title=config.get_localized_string(70310), mode='tvshow'), + Item(channel=channel, action='years_menu', title=config.get_localized_string(70743), mode='tvshow'), + Item(channel=channel, action='discover_list', title=config.get_localized_string(70311), search_type='list', list_type='tv/popular', mode='tvshow'), + Item(channel=channel, action='discover_list', title=config.get_localized_string(70312), search_type='list', list_type='tv/on_air', mode='tvshow'), + Item(channel=channel, action='discover_list', title=config.get_localized_string(70313), search_type='list', list_type='tv/top_rated', mode='tvshow')] itemlist = set_context(itemlist) - support.thumb(itemlist) + thumb(itemlist) return itemlist +def set_context(itemlist): + logger.debug() + channel = 'classicsearch' + for elem in itemlist: + elem.context = [{"title": config.get_localized_string(60412), + "action": "channel_selections", + "channel": channel}, + {"title": config.get_localized_string(60415), + "action": "settings", + "channel": channel}, + {"title": config.get_localized_string(60416), + "action": "clear_saved_searches", + "channel": channel}] + return itemlist + + +def channel_selections(item): + import xbmcgui, channelselector + from core import channeltools + + # Load list of options (active user channels that allow global search) + channel_list = [] + ids = [] + lang_list = [] + cat_list = [] + channels_list = channelselector.filterchannels('all') + for channel in channels_list: + if channel.action == '': + continue + + channel_parameters = channeltools.get_channel_parameters(channel.channel) + + # Do not include if "include_in_global_search" does not exist in the channel configuration + if not channel_parameters['include_in_global_search']: + continue + label_cat = ', '.join(config.get_localized_category(c) for c in channel_parameters['categories']) + label_lang = ', '.join(config.get_localized_language(l) for l in channel_parameters['language']) + label = '{} [{}]'.format(label_cat, label_lang) + + it = xbmcgui.ListItem(channel.title, label) + it.setArt({'thumb': channel.thumbnail, 'fanart': channel.fanart}) + channel_list.append(it) + ids.append(channel.channel) + lang_list.append(channel_parameters['language']) + cat_list.append(channel_parameters['categories']) + + # Pre-select dialog + preselections = [ + config.get_localized_string(70570), + config.get_localized_string(70571), + config.get_localized_string(70572), + config.get_localized_string(70573), + ] + preselections_values = ['skip', 'actual', 'all', 'none'] + + categories = ['movie', 'tvshow', 'documentary', 'anime', 'sub', 'live', 'torrent'] + for c in categories: + preselections.append(config.get_localized_string(70577) + config.get_localized_category(c)) + preselections_values.append(c) + + if item.action == 'setting_channel': # Configure channels included in search + del preselections[0] + del preselections_values[0] + + ret = platformtools.dialog_select(config.get_localized_string(59994), preselections) + if ret == -1: + return False # order cancel + if preselections_values[ret] == 'skip': + return True # continue unmodified + elif preselections_values[ret] == 'none': + preselect = [] + elif preselections_values[ret] == 'all': + preselect = list(range(len(ids))) + elif preselections_values[ret] == 'actual': + preselect = [] + for i, channel in enumerate(ids): + channel_status = config.get_setting('include_in_global_search', channel) + if channel_status: + preselect.append(i) + else: + preselect = [] + for i, ctgs in enumerate(cat_list): + if preselections_values[ret] in ctgs: + preselect.append(i) + + # Selection Dialog + ret = platformtools.dialog_multiselect(config.get_localized_string(59994), channel_list, preselect=preselect, useDetails=True) + + if ret == None: return False # order cancel + selected = [ids[i] for i in ret] + + # Save changes to search channels + for channel in ids: + channel_status = config.get_setting('include_in_global_search', channel) + + if channel_status and channel not in selected: + config.set_setting('include_in_global_search', False, channel) + elif not channel_status and channel in selected: + config.set_setting('include_in_global_search', True, channel) + + return True + +def save_search(text): + if text: + saved_searches_limit = config.get_setting("saved_searches_limit") + + current_saved_searches_list = config.get_setting("saved_searches_list", "search") + if current_saved_searches_list is None: + saved_searches_list = [] + else: + saved_searches_list = list(current_saved_searches_list) + + if text in saved_searches_list: + saved_searches_list.remove(text) + + saved_searches_list.insert(0, text) + + config.set_setting("saved_searches_list", saved_searches_list[:saved_searches_limit], "search") + +def clear_saved_searches(item): + config.set_setting("saved_searches_list", list(), "search") + platformtools.dialog_ok(config.get_localized_string(60423), config.get_localized_string(60424)) + def saved_search(item): logger.debug() @@ -103,731 +202,6 @@ def saved_search(item): itemlist = set_context(itemlist) return itemlist - -def new_search(item): - logger.debug() - - temp_search_file = config.get_temp_file('temp-search') - if filetools.isfile(temp_search_file): - filetools.remove(temp_search_file) - - itemlist = [] - if config.get_setting('last_search'): - last_search = channeltools.get_channel_setting('Last_searched', 'search', '') - else: - last_search = '' - - if item.search_text: - searched_text = item.search_text - else: - searched_text = platformtools.dialog_input(default=last_search, heading='') - - save_search(searched_text) - if not searched_text: - return - - channeltools.set_channel_setting('Last_searched', searched_text, 'search') - searched_text = searched_text.replace("+", " ") - - if item.mode == 'person': - item.searched_text = searched_text - return actor_list(item) - - if item.mode != 'all': - tmdb_info = tmdb.Tmdb(searched_text=searched_text, search_type=item.mode.replace('show', '')) - results = tmdb_info.results - for result in results: - result = tmdb_info.get_infoLabels(result, origen=result) - if item.mode == 'movie': - title = result['title'] - else: - title = result['name'] - item.mode = 'tvshow' - - thumbnail = result.get('thumbnail', '') - fanart = result.get('fanart', '') - - new_item = Item(channel=item.channel, - action='channel_search', - title=title, - text=searched_text, - thumbnail=thumbnail, - fanart=fanart, - mode=item.mode, - contentType=item.mode, - infoLabels=result) - - if item.mode == 'movie': - new_item.contentTitle = result['title'] - else: - new_item.contentSerieName = result['name'] - - itemlist.append(new_item) - - if item.mode == 'all' or not itemlist: - return channel_search(Item(channel=item.channel, - title=searched_text, - text=searched_text, - mode='all', - infoLabels={})) - - return itemlist - - -def channel_search(item): - logger.debug(item) - - start = time.time() - searching = list() - searching_titles = list() - results = list() - valid = list() - ch_list = dict() - mode = item.mode - - if item.infoLabels['tvshowtitle']: - item.text = item.infoLabels['tvshowtitle'].split(' - ')[0] - item.title = item.text - elif item.infoLabels['title']: - item.text = item.infoLabels['title'].split(' - ')[0] - item.title = item.text - - temp_search_file = config.get_temp_file('temp-search') - if filetools.isfile(temp_search_file): - itemlist = [] - f = filetools.read(temp_search_file) - if f.startswith(item.text): - for it in f.split(','): - if it and it != item.text: - itemlist.append(Item().fromurl(it)) - return itemlist - else: - filetools.remove(temp_search_file) - - searched_id = item.infoLabels['tmdb_id'] - - channel_list, channel_titles = get_channels(item) - - searching += channel_list - searching_titles += channel_titles - cnt = 0 - progress = platformtools.dialog_progress(config.get_localized_string(30993) % item.title, config.get_localized_string(70744) % len(channel_list) + '\n' + ', '.join(searching_titles)) - config.set_setting('tmdb_active', False) - search_action_list = [] - module_dict = {} - for ch in channel_list: - try: - module = __import__('channels.%s' % ch, fromlist=["channels.%s" % ch]) - mainlist = getattr(module, 'mainlist')(Item(channel=ch, global_search=True)) - - module_dict[ch] = module - search_action_list.extend([elem for elem in mainlist if - elem.action == "search" and (mode == 'all' or elem.contentType in [mode, 'undefined'])]) - if progress.iscanceled(): - return [] - except: - import traceback - logger.error('error importing/getting search items of ' + ch) - logger.error(traceback.format_exc()) - - total_search_actions = len(search_action_list) - with futures.ThreadPoolExecutor(max_workers=set_workers()) as executor: - c_results = [] - for search_action in search_action_list: - c_results.append(executor.submit(get_channel_results, item, module_dict, search_action)) - if progress.iscanceled(): - break - - for res in futures.as_completed(c_results): - search_action = res.result()[0] - channel = search_action.channel - if res.result()[1]: - if channel not in ch_list: - ch_list[channel] = [] - ch_list[channel].extend(res.result()[1]) - if res.result()[2]: - valid.extend(res.result()[2]) - - if progress.iscanceled(): - break - - search_action_list.remove(search_action) - # if no action of this channel remains - for it in search_action_list: - if it.channel == channel: - break - else: - cnt += 1 - searching_titles.remove(searching_titles[searching.index(channel)]) - searching.remove(channel) - progress.update(old_div(((total_search_actions - len(search_action_list)) * 100), total_search_actions), config.get_localized_string(70744) % str(len(channel_list) - cnt) + '\n' + ', '.join(searching_titles)) - - progress.close() - - cnt = 0 - progress = platformtools.dialog_progress(config.get_localized_string(30993) % item.title, config.get_localized_string(60295) + '\n' + config.get_localized_string(60293)) - - config.set_setting('tmdb_active', True) - # res_count = 0 - for key, value in ch_list.items(): - ch_name = channel_titles[channel_list.index(key)] - grouped = list() - cnt += 1 - progress.update(old_div((cnt * 100), len(ch_list)), config.get_localized_string(60295)) - - for it in value: - if it.channel == item.channel: - it.channel = key - if it in valid: - continue - if mode == 'all' or (it.contentType and mode == it.contentType): - if config.get_setting('result_mode') != 0: - if config.get_localized_string(30992) not in it.title: - it.title += typo(ch_name,'_ [] color kod bold') - results.append(it) - else: - grouped.append(it) - elif (mode == 'movie' and it.contentTitle) or (mode == 'tvshow' and (it.contentSerieName or it.show)): - grouped.append(it) - else: - continue - - if not grouped: - continue - # to_temp[key] = grouped - if config.get_setting('result_mode') == 0: - if not config.get_setting('unify'): - title = typo(ch_name,'bold') + typo(str(len(grouped)), '_ [] color kod bold') - else: - title = typo('%s %s' % (len(grouped), config.get_localized_string(70695)), 'bold') - # res_count += len(grouped) - plot='' - - for it in grouped: - plot += it.title +'\n' - ch_thumb = channeltools.get_channel_parameters(key)['thumbnail'] - results.append(Item(channel='search', title=title, - action='get_from_temp', thumbnail=ch_thumb, itemlist=[ris.tourl() for ris in grouped], plot=plot, page=1)) - - progress.close() - # "All Together" and movie mode -> search servers - if config.get_setting('result_mode') == 1 and mode == 'movie': - progress = platformtools.dialog_progress(config.get_localized_string(30993) % item.title, config.get_localized_string(60683)) - valid_servers = [] - with futures.ThreadPoolExecutor(max_workers=set_workers()) as executor: - c_results = [executor.submit(get_servers, v, module_dict) for v in valid] - completed = 0 - - for res in futures.as_completed(c_results): - if progress.iscanceled(): - break - if res.result(): - completed += 1 - valid_servers.extend(res.result()) - progress.update(old_div(completed * 100, len(valid))) - valid = valid_servers - progress.close() - - # send_to_temp(to_temp) - - results = sorted(results, key=lambda it: it.title) - results_statistic = config.get_localized_string(59972) % (item.title, time.time() - start) - if mode == 'all': - results.insert(0, Item(title=typo(results_statistic, 'color kod bold'), thumbnail=thumb('search'))) - else: - if not valid: - valid.append(Item(title=config.get_localized_string(60347), thumbnail=thumb('nofolder'))) - - valid.insert(0, Item(title=typo(results_statistic, 'color kod bold'), thumbnail=thumb('search'))) - results.insert(0, Item(title=typo(config.get_localized_string(30025), 'color kod bold'), thumbnail=thumb('search'))) - # logger.debug(results_statistic) - - itlist = valid + results - writelist = item.text - for it in itlist: - writelist += ',' + it.tourl() - filetools.write(temp_search_file, writelist) - - return itlist - - -def get_channel_results(item, module_dict, search_action): - ch = search_action.channel - results = list() - valid = list() - module = module_dict[ch] - searched_id = item.infoLabels['tmdb_id'] - - try: - results.extend(module.search(search_action, item.text)) - if len(results) == 1: - if not results[0].action or config.get_localized_string(70006).lower() in results[0].title.lower(): - results.clear() - if item.mode != 'all': - for elem in results: - if not elem.infoLabels.get('year', ""): - elem.infoLabels['year'] = '-' - tmdb.set_infoLabels_item(elem) - if elem.infoLabels['tmdb_id'] == searched_id: - elem.from_channel = ch - if not config.get_setting('unify'): - elem.title += ' [%s]' % ch - valid.append(elem) - - # if len(results) < 0 and len(results) < max_results and item.mode != 'all': - # - # if len(results) == 1: - # if not results[0].action or config.get_localized_string(30992).lower() in results[0].title.lower(): - # return [ch, []] - # - # results = get_info(results) - - return [search_action, results, valid] - except: - return [search_action, results, valid] - - -def get_servers(item, module_dict): - item.global_search = True - ch = item.channel - results = list() - module = module_dict[ch] - try: - results = getattr(module, item.action)(item) - except: - import traceback - logger.error(traceback.format_exc()) - return [r.clone(title=r.title + typo(item.channel, '_ [] color kod')) for r in results if r.action == 'play'] - - -def get_info(itemlist): - logger.debug() - tmdb.set_infoLabels_itemlist(itemlist, True, forced=True) - - return itemlist - - -def get_channels(item): - logger.debug() - - channels_list = list() - title_list = list() - all_channels = channelselector.filterchannels('all') - - for ch in all_channels: - channel = ch.channel - ch_param = channeltools.get_channel_parameters(channel) - if not ch_param.get("active", False): - continue - list_cat = ch_param.get("categories", []) - - if not ch_param.get("include_in_global_search", False): - continue - - if 'anime' in list_cat: - n = list_cat.index('anime') - list_cat[n] = 'tvshow' - - if item.mode == 'all' or (item.mode in list_cat): - if config.get_setting("include_in_global_search", channel) and ch_param.get("active", False): - channels_list.append(channel) - title_list.append(ch_param.get('title', channel)) - - return channels_list, title_list - - -def settings(item): - return platformtools.show_channel_settings(caption=config.get_localized_string(59993)) - - -def set_workers(): - workers = config.get_setting('thread_number') if config.get_setting('thread_number') > 0 else None - return workers - - -def setting_channel_new(item): - import xbmcgui - - # Load list of options (active user channels that allow global search) - lista = [] - ids = [] - lista_lang = [] - lista_ctgs = [] - channels_list = channelselector.filterchannels('all') - for channel in channels_list: - if channel.action == '': - continue - - channel_parameters = channeltools.get_channel_parameters(channel.channel) - - # Do not include if "include_in_global_search" does not exist in the channel configuration - if not channel_parameters['include_in_global_search']: - continue - - lbl = '%s' % channel_parameters['language'] - lbl += ' %s' % ', '.join(config.get_localized_category(categ) for categ in channel_parameters['categories']) - - it = xbmcgui.ListItem(channel.title, lbl) - it.setArt({'thumb': channel.thumbnail, 'fanart': channel.fanart}) - lista.append(it) - ids.append(channel.channel) - lista_lang.append(channel_parameters['language']) - lista_ctgs.append(channel_parameters['categories']) - - # Pre-select dialog - preselecciones = [ - config.get_localized_string(70570), - config.get_localized_string(70571), - # 'Modificar partiendo de Recomendados', - # 'Modificar partiendo de Frecuentes', - config.get_localized_string(70572), - config.get_localized_string(70573), - # 'Modificar partiendo de Castellano', - # 'Modificar partiendo de Latino' - ] - # presel_values = ['skip', 'actual', 'recom', 'freq', 'all', 'none', 'cast', 'lat'] - presel_values = ['skip', 'actual', 'all', 'none'] - - categs = ['movie', 'tvshow', 'documentary', 'anime', 'sub', 'live', 'torrent'] - for c in categs: - preselecciones.append(config.get_localized_string(70577) + config.get_localized_category(c)) - presel_values.append(c) - - if item.action == 'setting_channel': # Configuración de los canales incluídos en la búsqueda - del preselecciones[0] - del presel_values[0] - # else: # Call from "search on other channels" (you can skip the selection and go directly to the search) - - ret = platformtools.dialog_select(config.get_localized_string(59994), preselecciones) - if ret == -1: - return False # order cancel - if presel_values[ret] == 'skip': - return True # continue unmodified - elif presel_values[ret] == 'none': - preselect = [] - elif presel_values[ret] == 'all': - preselect = list(range(len(ids))) - elif presel_values[ret] in ['cast', 'lat']: - preselect = [] - for i, lg in enumerate(lista_lang): - if presel_values[ret] in lg or '*' in lg: - preselect.append(i) - elif presel_values[ret] == 'actual': - preselect = [] - for i, canal in enumerate(ids): - channel_status = config.get_setting('include_in_global_search', canal) - if channel_status: - preselect.append(i) - - elif presel_values[ret] == 'recom': - preselect = [] - for i, canal in enumerate(ids): - _not, set_canal_list = channeltools.get_channel_controls_settings(canal) - if set_canal_list.get('include_in_global_search', False): - preselect.append(i) - - elif presel_values[ret] == 'freq': - preselect = [] - for i, canal in enumerate(ids): - frequency = channeltools.get_channel_setting('frequency', canal, 0) - if frequency > 0: - preselect.append(i) - else: - preselect = [] - for i, ctgs in enumerate(lista_ctgs): - if presel_values[ret] in ctgs: - preselect.append(i) - - # Dialog to select - ret = platformtools.dialog_multiselect(config.get_localized_string(59994), lista, preselect=preselect, useDetails=True) - - if ret == None: return False # order cancel - seleccionados = [ids[i] for i in ret] - - # Save changes to search channels - for canal in ids: - channel_status = config.get_setting('include_in_global_search', canal) - # if not channel_status: - # channel_status = True - - if channel_status and canal not in seleccionados: - config.set_setting('include_in_global_search', False, canal) - elif not channel_status and canal in seleccionados: - config.set_setting('include_in_global_search', True, canal) - - return True - - -def genres_menu(item): - itemlist = [] - mode = item.mode.replace('show', '') - - genres = tmdb.get_dic_genres(mode) - for key, value in list(genres[mode].items()): - discovery = {'url': 'discover/%s' % mode, 'with_genres': key, - 'language': def_lang, 'page': '1'} - - itemlist.append(Item(channel=item.channel, title=typo(value, 'bold'), page=1, - action='discover_list', discovery=discovery, - mode=item.mode)) - from core import support - support.thumb(itemlist, mode='genre') - return sorted(itemlist, key=lambda it: it.title) - - -def years_menu(item): - import datetime - itemlist = [] - - mode = item.mode.replace('show', '') - - par_year = 'primary_release_year' - thumb = thumb('movie_year') - - if mode != 'movie': - par_year = 'first_air_date_year' - thumb = thumb('tvshow_year') - - c_year = datetime.datetime.now().year + 1 - l_year = c_year - 31 - - for year in range(l_year, c_year): - discovery = {'url': 'discover/%s' % mode, 'page': '1', - '%s' % par_year: '%s' % year, - 'sort_by': 'popularity.desc', 'language': def_lang} - - itemlist.append(Item(channel=item.channel, title=typo(str(year), 'bold'), action='discover_list', - discovery=discovery, mode=item.mode, year_=str(year), thumbnail=thumb)) - itemlist.reverse() - itemlist.append(Item(channel=item.channel, title=typo(config.get_localized_string(70745),'color kod bold'), url='', - action="year_cus", mode=item.mode, par_year=par_year)) - - return itemlist - - -def year_cus(item): - mode = item.mode.replace('show', '') - - heading = config.get_localized_string(70042) - year = platformtools.dialog_numeric(0, heading, default="") - item.discovery = {'url': 'discover/%s' % mode, 'page': '1', - '%s' % item.par_year: '%s' % year, - 'sort_by': 'popularity.desc', 'language': def_lang} - item.action = "discover_list" - if year and len(year) == 4: - return discover_list(item) - - -def actor_list(item): - itemlist = [] - - dict_ = {'url': 'search/person', 'language': def_lang, 'query': item.searched_text, 'page': item.page} - - prof = {'Acting': 'Actor', 'Directing': 'Director', 'Production': 'Productor'} - plot = '' - item.search_type = 'person' - - tmdb_inf = tmdb.discovery(item, dict_=dict_) - results = tmdb_inf.results - - if not results: - return results - - for elem in results: - name = elem.get('name', '') - if not name: - continue - - rol = elem.get('known_for_department', '') - rol = prof.get(rol, rol) - # genero = elem.get('gender', 0) - # if genero == 1 and rol in prof: - # rol += 'a' - # rol = rol.replace('Actora', 'Actriz') - - know_for = elem.get('known_for', '') - cast_id = elem.get('id', '') - if know_for: - t_k = know_for[0].get('title', '') - if t_k: - plot = '%s in %s' % (rol, t_k) - - thumbnail = 'https://image.tmdb.org/t/p/original%s' % elem.get('profile_path', '') - title = typo(name,'bold')+typo(rol,'_ [] color kod bold') - - discovery = {'url': 'person/%s/combined_credits' % cast_id, 'page': '1', - 'sort_by': 'primary_release_date.desc', 'language': def_lang} - - itemlist.append(Item(channel=item.channel, title=title, action='discover_list', cast_='cast', - discovery=discovery, thumbnail=thumbnail, plot=plot, page=1)) - - if len(results) > 19: - next_ = item.page + 1 - itemlist.append(Item(channel=item.channel, title=typo(config.get_localized_string(30992),'bold color kod'), action='actor_list', - page=next_, thumbnail=thumbnail, - searched_text=item.searched_text)) - return itemlist - - -def discover_list(item): - import datetime - itemlist = [] - - year = 0 - tmdb_inf = tmdb.discovery(item, dict_=item.discovery, cast=item.cast_) - result = tmdb_inf.results - tvshow = False - - for elem in result: - elem = tmdb_inf.get_infoLabels(elem, origen=elem) - if 'title' in elem: - title = unify.normalize(elem['title']).capitalize() - else: - title = unify.normalize(elem['name']).capitalize() - tvshow = True - elem['tmdb_id'] = elem['id'] - - mode = item.mode or elem['mediatype'] - thumbnail = elem.get('thumbnail', '') - fanart = elem.get('fanart', '') - - if item.cast_: - release = elem.get('release_date', '0000') or elem.get('first_air_date', '0000') - year = scrapertools.find_single_match(release, r'(\d{4})') - - if not item.cast_ or (item.cast_ and (int(year) <= int(datetime.datetime.today().year))): - if config.get_setting('new_search'): - new_item = Item(channel='globalsearch', title=typo(title, 'bold'), infoLabels=elem, - action='Search', text=title, - thumbnail=thumbnail, fanart=fanart, - context='', mode='search', type = mode, contentType=mode, - release_date=year, folder = False) - else: - new_item = Item(channel='search', title=typo(title, 'bold'), infoLabels=elem, - action='channel_search', text=title, - thumbnail=thumbnail, fanart=fanart, - context='', mode=mode, contentType=mode, - release_date=year) - - if tvshow: - new_item.contentSerieName = title - else: - new_item.contentTitle = title - - itemlist.append(new_item) - - itemlist = set_context(itemlist) - - if item.cast_: - itemlist.sort(key=lambda it: int(it.release_date), reverse=True) - return itemlist - - elif len(result) > 19 and item.discovery: - item.discovery['page'] = str(int(item.discovery['page']) + 1) - itemlist.append(Item(channel=item.channel, action='discover_list', nextPage=True, - title=typo(config.get_localized_string(30992), 'color kod bold'), - list_type=item.list_type, discovery=item.discovery, thumbnail=thumb(), page=item.discovery['page'])) - elif len(result) > 19: - next_page = str(int(item.page) + 1) - - itemlist.append(Item(channel=item.channel, action='discover_list', nextPage=True, - title=typo(config.get_localized_string(30992), 'color kod bold'), - list_type=item.list_type, search_type=item.search_type, mode=item.mode, page=next_page, thumbnail=thumb())) - - return itemlist - - -def from_context(item): - logger.debug() - - select = setting_channel_new(item) - - if not select: - return - - if 'infoLabels' in item and 'mediatype' in item.infoLabels: - item.mode = item.infoLabels['mediatype'] - else: - return - - if config.get_setting('new_search'): - from specials import globalsearch - if item.infoLabels['tmdb_id']: - item.type = item.mode - item.mode = 'search' - return globalsearch.Search(item) - - if 'list_type' not in item: - if 'wanted' in item: - item.title = item.wanted - return channel_search(item) - - return discover_list(item) - - -def set_context(itemlist): - logger.debug() - - for elem in itemlist: - elem.context = [{"title": config.get_localized_string(60412), - "action": "setting_channel_new", - "channel": "search"}, - {"title": config.get_localized_string(60415), - "action": "settings", - "channel": "search"}, - {"title": config.get_localized_string(60416), - "action": "clear_saved_searches", - "channel": "search"}] - - return itemlist - - -def get_from_temp(item): - logger.debug() - - n = 30 - nTotal = len(item.itemlist) - nextp = n * item.page - prevp = n * (item.page - 1) - - results = [Item().fromurl(elem) for elem in item.itemlist[prevp:nextp]] - - if nextp < nTotal: - results.append(Item(channel='search', title=typo(config.get_localized_string(30992), 'bold color kod'), - action='get_from_temp', itemlist=item.itemlist, page=item.page + 1, nextPage=True)) - - tmdb.set_infoLabels_itemlist(results, True) - for elem in results: - if not elem.infoLabels.get('year', ""): - elem.infoLabels['year'] = '-' - tmdb.set_infoLabels_item(elem, True) - - return results - - -def save_search(text): - if text: - saved_searches_limit = config.get_setting("saved_searches_limit") - - current_saved_searches_list = config.get_setting("saved_searches_list", "search") - if current_saved_searches_list is None: - saved_searches_list = [] - else: - saved_searches_list = list(current_saved_searches_list) - - if text in saved_searches_list: - saved_searches_list.remove(text) - - saved_searches_list.insert(0, text) - - config.set_setting("saved_searches_list", saved_searches_list[:saved_searches_limit], "search") - - -def clear_saved_searches(item): - config.set_setting("saved_searches_list", list(), "search") - platformtools.dialog_ok(config.get_localized_string(60423), config.get_localized_string(60424)) - - def get_saved_searches(): current_saved_searches_list = config.get_setting("saved_searches_list", "search") if current_saved_searches_list is None: @@ -835,4 +209,4 @@ def get_saved_searches(): else: saved_searches_list = list(current_saved_searches_list) - return saved_searches_list + return saved_searches_list \ No newline at end of file diff --git a/specials/tvmoviedb.json b/specials/tvmoviedb.json index 81c365c6..fb083887 100644 --- a/specials/tvmoviedb.json +++ b/specials/tvmoviedb.json @@ -30,7 +30,7 @@ ] }, { - "id": "tmdb_alternativo", + "id": "tmdbfallback", "type": "list", "label": "@70426", "default": 6, diff --git a/specials/tvmoviedb.py b/specials/tvmoviedb.py index 13c070cc..1c40343b 100644 --- a/specials/tvmoviedb.py +++ b/specials/tvmoviedb.py @@ -1,2982 +1,84 @@ # -*- coding: utf-8 -*- +from platformcode.platformtools import calcResolution +from core.item import Item import re from core import filetools, jsontools, trakt_tools -from core import support +from core import support, tmdb from core.tmdb import Tmdb from core.scrapertools import htmlclean, decodeHtmlentities -from core.support import thumb, typo, match, Item -from platformcode import config, platformtools -from platformcode import logger +from core.support import thumb, typo, match, dbg +from platformcode import config, logger -info_language = ["de", "en", "es", "fr", "it", "pt"] # from videolibrary.json -def_lang = info_language[config.get_setting("info_language", "videolibrary")] -langs = ['auto', 'de', 'fr', 'pt', 'it', 'es-MX', 'ca', 'en', 'es'] -langt = langs[config.get_setting('tmdb', "tvmoviedb")] -if langt == 'auto': langt = def_lang -langt_alt = langs[config.get_setting('tmdb_alternativo', "tvmoviedb")] -# langs = ['auto', 'co', 'cl', 'ar', 'mx', 'en', 'es'] -# langf = langs[config.get_setting('filmaff', "tvmoviedb")] -# if langf == 'auto': langf = 'en' -langs = ['auto', 'de-de', 'fr-fr', 'pt-pt', 'it-it', 'es-MX', 'ca-es', 'en', 'es'] -langi = langs[config.get_setting('imdb', "tvmoviedb")] -if langi == 'auto': langi = def_lang +langs = Item(tmdb=[tmdb.def_lang, 'de', 'fr', 'pt', 'it', 'es-MX', 'ca', 'en', 'es'], + imdb=[tmdb.def_lang, 'de-de', 'fr-fr', 'pt-pt', 'it-it', 'es-MX', 'ca-es', 'en', 'es']) +lang = Item(tmdb=langs.tmdb[config.get_setting('tmdb', 'tvmoviedb')], + tmdbfallback= langs.tmdb[config.get_setting('tmdbfallback', 'tvmoviedb')], + imdb=langs.imdb[config.get_setting('imdb', 'tvmoviedb')]) -adult_mal = config.get_setting('adult_mal', "tvmoviedb") -mal_ck = "MzE1MDQ2cGQ5N2llYTY4Z2xwbGVzZjFzbTY=" -images_predef = "https://raw.githubusercontent.com/master-1970/resources/master/images/genres/" -default_fan = filetools.join(config.get_runtime_path(), "fanart.jpg") + +mal_adult = config.get_setting('adult_mal', 'tvmoviedb') +mal_key = 'MzE1MDQ2cGQ5N2llYTY4Z2xwbGVzZjFzbTY=' +# fanart = filetools.join(config.get_runtime_path(), re 'fanart.jpg') def mainlist(item): logger.debug() - itemlist = [ - # TMDB - # item.clone(title=typo(config.get_localized_string(70021), 'bold'), action=""), - item.clone(title=config.get_localized_string(70021) % (config.get_localized_string(30122), 'TMDB'), action="tmdb", args="movie"), - item.clone(title=config.get_localized_string(70021) % (config.get_localized_string(30123), 'TMDB'), action="tmdb", args="tv"), - # Filmaffinity - # itemlist.append(item.clone(title=typo(config.get_localized_string(70024), 'bold'), action="")) - # itemlist.append(item.clone(title=config.get_localized_string(70022), action="filmaf", args="movie", thumbnail=thumb('search_movie'))) - # itemlist.append(item.clone(title=config.get_localized_string(70023), action="filmaf", args="tv", thumbnail=thumb('search_tvshow'))) - # IMDB - # item.clone(title=typo(config.get_localized_string(70025), 'bold'), action=""), - item.clone(title=config.get_localized_string(70021) % (config.get_localized_string(30122), 'IMDB'), action="imdb", args="movie", url='&title_type=feature,tv_movie'), - item.clone(title=config.get_localized_string(70021) % (config.get_localized_string(30123), 'IMDB'), action="imdb", args="tv", url='&title_type=tv_series,tv_special,mini_series'), - item.clone(title=config.get_localized_string(70415), action="trakt", thumbnail="http://i.imgur.com/5sQjjuk.png"), - item.clone(title=config.get_localized_string(70026), action="mal", thumbnail="http://i.imgur.com/RhsYWmd.png"), - item.clone(title=typo(config.get_localized_string(70027), 'color kod'), action="configuracion", folder=False) - ] + itemlist = [item.clone(title='TMDB', action='tmdb_menu'), + item.clone(title='IMDB', action='imdb_menu')] + # itemlist = [item.clone(title=config.get_localized_string(70021) % (config.get_localized_string(30122), 'TMDB'), action='tmdb_menu', args='movie'), + # item.clone(title=config.get_localized_string(70021) % (config.get_localized_string(30123), 'TMDB'), action='tmdb_menu', args='tv'), + # item.clone(title=config.get_localized_string(70021) % (config.get_localized_string(30122), 'IMDB'), action='imdb', args='movie', url='&title_type=feature,tv_movie'), + # item.clone(title=config.get_localized_string(70021) % (config.get_localized_string(30123), 'IMDB'), action='imdb', args='tv', url='&title_type=tv_series,tv_special,mini_series')] support.thumb(itemlist) + itemlist += [item.clone(title=config.get_localized_string(70415), action='trakt', thumbnail=support.thumb('trakt')), + item.clone(title=config.get_localized_string(70026), action='mal', thumbnail=support.thumb('mal')), + item.clone(title=typo(config.get_localized_string(70027), 'bold'), action='configuracion', folder=False, thumbnail=support.thumb('setting'))] return itemlist -def configuracion(item): - ret = platformtools.show_channel_settings() - platformtools.itemlist_refresh() - return ret -def search_star(item): - logger.debug() +def tmdb_menu(item): + if not item.args: + return [item.clone(title=config.get_localized_string(70741) % config.get_localized_string(30122), args='movie'), + item.clone(title=config.get_localized_string(70741) % config.get_localized_string(30123), args='tv')] - itemlist = [] - item.type='movie' - itemlist.extend(search_(item)) - item.type='tvshow' - itemlist.extend(search_(item)) - return itemlist + item.contentType = item.args.replace('tv', 'tvshow') -def search_(item): - text = platformtools.dialog_input(heading=item.title) - if text: - if "imdb" in item.url: - item.url = item.url.format(text.replace(" ", "+")) - item.action = "list_imdb" - return list_imdb(item) - # if "filmaffinity" in item.url: - # item.url += text.replace(" ", "+") - # item.action = "list_fa" - # return list_fa(item) - if "myanimelist" in item.url: - item.url += text.replace(" ", "%20") - item.url += "&type=0&score=0&status=0&p=0&r=0&sm=0&sd=0&sy=0&em=0&ed=0&ey=0&c[0]=a&c[1]=b&c[2]=c&c[3]=d&c[4]=f&gx=0" - item.action = "searching_mal" - return searching_mal(item) + itemlist = [item.clone(title=config.get_localized_string(70028), action='peliculas', args=item.args + '/popular'), + item.clone(title=config.get_localized_string(70029), action='peliculas', args=item.args + '/top_rated'), + item.clone(title=config.get_localized_string(50001), action='peliculas', args=item.args + '/now_playing' if item.args == 'movie' else '/on_the_air'), + item.clone(title=config.get_localized_string(70032), action='indices_tmdb'), + item.clone(title=config.get_localized_string(70042), action='indices_tmdb')] - item.search['query'] = text - item.action = "list_tmdb" - - if item.star == True: - types = ['movie','tv'] - itemlist = [] - for type in types: - item.contentType = type - item.search['type']=type - itemlist.extend(list_tmdb(item)) - return itemlist - else: - return list_tmdb(item) + if item.args == 'movie': + itemlist.extend([item.clone(title=config.get_localized_string(70033), action='peliculas', args='person/popular'), + item.clone(title=config.get_localized_string(70034), action='list_tmdb', args=item.args + '/upcoming')]) -def searcing(item): - logger.debug() + itemlist.extend([item.clone(title=config.get_localized_string(70035) % config.get_localized_string(60244 if item.args == 'movie' else 60245).lower(), action='search_', search={'url': 'search/%s' % item.args, 'language': lang.tmdb, 'page': 1}), + item.clone(title=config.get_localized_string(70036), action='search_', search={'url': 'search/person', 'language': lang.tmdb, 'page': 1})]) - new_item = Item(title=item.contentTitle, text=item.contentTitle.replace("+", " "), mode=item.contentType, infoLabels=item.infoLabels) + if item.args == 'movie': itemlist.append(item.clone(title=config.get_localized_string(70037), action='search_', search={'url': 'search/person', 'language': lang.tmdb, 'page': 1}, crew=True)) - from specials import search - return search.channel_search(new_item) - - -def tmdb(item): - item.contentType = item.args.replace("tv", "tvshow") - - itemlist = [] - - itemlist.append(item.clone(title=config.get_localized_string(70028), action="list_tmdb", search={'url': item.args + "/popular", 'language': langt, 'page': 1})) - itemlist.append(item.clone(title=config.get_localized_string(70029), action="list_tmdb", search={'url': item.args + "/top_rated", 'language': langt, 'page': 1})) - - if item.args == "movie": itemlist.append(item.clone(title=config.get_localized_string(70030), action="list_tmdb", search={'url': item.args + "/now_playing", 'language': langt, 'page': 1})) - else: itemlist.append(item.clone(title=config.get_localized_string(70031), action="list_tmdb", search={'url': item.args + "/on_air", 'language': langt, 'page': 1})) - - itemlist.append(item.clone(title=config.get_localized_string(70032), action="indices_tmdb")) - itemlist.append(item.clone(title=config.get_localized_string(70042), action="indices_tmdb")) - - if item.args == "movie": - itemlist.append(item.clone(title=config.get_localized_string(70033), action="list_tmdb", search={'url': 'person/popular', 'language': langt, 'page': 1})) - itemlist.append(item.clone(title=config.get_localized_string(70034), action="list_tmdb", search={'url': item.args + "/upcoming", 'language': langt, 'page': 1})) - - if config.get_platform() != "plex": - title = item.contentType.replace("movie", config.get_localized_string(70283)).replace("tvshow", "serie") - itemlist.append(item.clone(title=config.get_localized_string(70035) % title, action="search_", search={'url': 'search/%s' % item.args, 'language': langt, 'page': 1})) - - itemlist.append(item.clone(title=config.get_localized_string(70036), action="search_", search={'url': 'search/person', 'language': langt, 'page': 1})) - if item.args == "movie": itemlist.append(item.clone(title=config.get_localized_string(70037), action="search_", search={'url': "search/person", 'language': langt, 'page': 1}, crew=True)) - - itemlist.append(item.clone(title=typo(config.get_localized_string(70038),'color kod'), action="filter", )) - itemlist.append(item.clone(title=typo(config.get_localized_string(70039),'color kod'), action="filter", )) + itemlist.extend([item.clone(title=typo(config.get_localized_string(70038),'bold'), action='filter', ), + item.clone(title=typo(config.get_localized_string(70039),'bold'), action='filter', )]) return thumb(itemlist) - -def imdb(item): - item.contentType = item.args.replace("tv", "tvshow") - +def peliculas(item): itemlist = [] - itemlist.append(item.clone(title=config.get_localized_string(70028), action="list_imdb")) - itemlist.append(item.clone(title=config.get_localized_string(70029), action="list_imdb", url=item.url + "&num_votes=25000,&sort=user_rating,desc")) - if item.args == "movie": - itemlist.append(item.clone(title=config.get_localized_string(70030), action="list_imdb", url="http://www.imdb.com/showtimes/location?ref_=inth_ov_sh_sm")) - itemlist.append(item.clone(title=config.get_localized_string(70032), action="indices_imdb")) - itemlist.append(item.clone(title=config.get_localized_string(70042), action="indices_imdb")) + _search = {'url': item.args, 'language': lang.tmdb, 'page': item.page if item.page else 1} + obj = tmdb.discovery(item, _search) - if item.args == "movie": - itemlist.append(item.clone(title=config.get_localized_string(70033), action="list_imdb", url="http://www.imdb.com/search/name?gender=male,female&ref_=nv_cel_m_3")) - itemlist.append(item.clone(title=config.get_localized_string(70034), action="list_imdb", url="http://www.imdb.com/movies-coming-soon/?ref_=shlc_cs")) - - if config.get_platform() != "plex": - itemlist.append(item.clone(title=config.get_localized_string(30980), action="search_", url="http://www.imdb.com/search/title?title={}" + item.url)) - itemlist.append(item.clone(title=config.get_localized_string(70036), action="search_", url="http://www.imdb.com/search/name?name={}")) - - itemlist.append(item.clone(title=typo(config.get_localized_string(70038),'color kod'), action="filter_imdb", )) - - return thumb(itemlist) - - -# def filmaf(item): -# item.contentType = item.args.replace("tv", "tvshow") -# login, message = login_fa() -# if def_lang == 'it': langf = 'us' - -# itemlist = [] -# if item.args == "movie": -# itemlist.append(item.clone(title=config.get_localized_string(70040), action="list_fa", args="top", url="http://m.filmaffinity.com/%s/topgen.php?genre=&country=&fromyear=&toyear=¬vse=1&nodoc=1" % langf)) -# itemlist.append(item.clone(title=config.get_localized_string(70030), action="list_fa", url="http://m.filmaffinity.com/%s/rdcat.php?id=new_th_%s" % (langf, langf))) -# itemlist.append(item.clone(title=config.get_localized_string(70032), action="indices_fa", url="http://m.filmaffinity.com/%s/topgen.php" % langf)) -# else: -# itemlist.append(item.clone(title=config.get_localized_string(70040), action="list_fa", args="top", url="http://m.filmaffinity.com/%s/topgen.php?genre=TV_SE&country=&fromyear=&toyear=&nodoc" % langf)) -# itemlist.append(item.clone(title="Series de actualidad", action="list_fa", url="http://m.filmaffinity.com/%s/category.php?id=current_tv" % langf)) - -# itemlist.append(item.clone(title=config.get_localized_string(70042), action="indices_fa")) - -# if item.args == "movie": -# itemlist.append(item.clone(title=config.get_localized_string(70043), action="list_fa", args="estrenos", url="http://m.filmaffinity.com/%s/rdcat.php?id=upc_th_%s" % (langf, langf))) -# itemlist.append(item.clone(title=config.get_localized_string(70044), action="indices_fa", args="sagas", url="http://www.filmaffinity.com/%s/movie-groups-all.php" % langf)) - -# itemlist.append(item.clone(title=config.get_localized_string(70045), action="indices_fa", url='http://m.filmaffinity.com/%s/topics.php' % langf, )) - -# if config.get_platform() != "plex": -# itemlist.append(item.clone(title=config.get_localized_string(70046), action="search_", url="http://m.filmaffinity.com/%s/search.php?stype=title&stext=" % langf)) -# itemlist.append(item.clone(title=config.get_localized_string(70036), action="search_", url="http://m.filmaffinity.com/%s/search.php?stype=cast&stext=" % langf)) -# itemlist.append(item.clone(title=config.get_localized_string(70047), action="search_", url="http://m.filmaffinity.com/%s/search.php?stype=director&stext=" % langf)) - -# itemlist.append(item.clone(title=config.get_localized_string(70038), action="filter_fa", args="top")) -# itemlist.append(item.clone(title=config.get_localized_string(70048), action="cuenta_fa", )) - -# return thumb(itemlist) - - -def trakt(item): - itemlist = [] - token_auth = config.get_setting("token_trakt", "trakt") - page = "?page=1&limit=20&extended=full" - if not item.args: - item.args = "movie" - # itemlist.append(item.clone(title=typo(config.get_localized_string(70416), 'bold'), action="")) - itemlist.append(item.clone(title=typo(config.get_localized_string(30122), 'bold') + typo(config.get_localized_string(70049),'[] _'), action="acciones_trakt", url="movies/popular%s" % page)) - itemlist.append(item.clone(title=typo(config.get_localized_string(30122), 'bold') + typo(config.get_localized_string(70050),'[] _'), action="acciones_trakt", url="movies/trending%s" % page)) - itemlist.append(item.clone(title=typo(config.get_localized_string(30122), 'bold') + typo(config.get_localized_string(70053),'[] _'), action="acciones_trakt", url="movies/watched/all%s" % page)) - itemlist.append(item.clone(title=typo(config.get_localized_string(30122), 'bold') + typo(config.get_localized_string(70051),'[] _'), action="acciones_trakt", url="movies/anticipated%s" % page)) - if token_auth: itemlist.append(item.clone(title=typo(config.get_localized_string(30122), 'bold') + typo(config.get_localized_string(70052),'[] _'), action="acciones_trakt",url="recommendations/movies?limit=100&extended=full", pagina=0)) - # itemlist.append(item.clone(title=typo(config.get_localized_string(70417), 'bold'), action="",)) - item.args = "show" - itemlist.append(item.clone(title=typo(config.get_localized_string(30123), 'bold') + typo(config.get_localized_string(70049),'[] _'), action="acciones_trakt", url="shows/popular%s" % page)) - itemlist.append(item.clone(title=typo(config.get_localized_string(30123), 'bold') + typo(config.get_localized_string(70050),'[] _'), action="acciones_trakt", url="shows/trending%s" % page)) - itemlist.append(item.clone(title=typo(config.get_localized_string(30123), 'bold') + typo(config.get_localized_string(70053),'[] _'), action="acciones_trakt", url="shows/watched/all%s" % page)) - itemlist.append(item.clone(title=typo(config.get_localized_string(30123), 'bold') + typo(config.get_localized_string(70051),'[] _'), action="acciones_trakt", url="shows/anticipated%s" % page)) - if token_auth: itemlist.append(item.clone(title=typo(config.get_localized_string(30123), 'bold') + typo(config.get_localized_string(70052),'[] _'), action="acciones_trakt", url="recommendations/shows?limit=100&extended=full", pagina=0)) - itemlist.append(item.clone(title=typo(config.get_localized_string(70048), 'color kod'), args="cuenta")) - else: - item.args = "movie" - # A saved token is checked and the authentication process is executed - if not token_auth: - folder = (config.get_platform() == "plex") - itemlist.append(item.clone(title=config.get_localized_string(70054), action="auth_trakt", folder=folder)) + for result in obj.results: + if 'person' in item.args: + it = item.clone(action='showCast', channel='infoplus', folder=False) + it.id = result.get('id') else: - - itemlist.append(item.clone(title=typo(config.get_localized_string(30122),'bold') + typo(config.get_localized_string(70055),'_ []'), action="acciones_trakt", url="users/me/watchlist/movies%s" % page, order="added", how="desc")) - itemlist.append(item.clone(title=typo(config.get_localized_string(30122),'bold') + typo(config.get_localized_string(70056),'_ []'), action="acciones_trakt", url="users/me/watched/movies%s" % page, order="added", how="desc")) - itemlist.append(item.clone(title=typo(config.get_localized_string(30122),'bold') + typo(config.get_localized_string(70068),'_ []'), action="acciones_trakt", url="users/me/collection/movies%s" % page, order="added", how="desc")) - - itemlist.append(item.clone(title=typo(config.get_localized_string(30123),'bold') + typo(config.get_localized_string(70055),'_ []'), action="acciones_trakt", url="users/me/watchlist/shows%s" % page, args="show", order="added", how="desc")) - itemlist.append(item.clone(title=typo(config.get_localized_string(30123),'bold') + typo(config.get_localized_string(70056),'_ []'), action="acciones_trakt", url="users/me/watched/shows%s" % page, args="show", order="added", how="desc")) - itemlist.append(item.clone(title=typo(config.get_localized_string(30123),'bold') + typo(config.get_localized_string(70068),'_ []'), action="acciones_trakt", url="users/me/collection/shows%s" % page, args="show", order="added", how="desc")) - - itemlist.append(item.clone(title=typo(config.get_localized_string(70057),'color kod bold'), action="acciones_trakt", url="users/me/lists", )) - + it = item.clone(action='start', channel='infoplus', folder=False) + it.infoLabels = obj.get_infoLabels(it.infoLabels, origen=result) + for k in ['title', 'thumbnail', 'fanart']: + it.__setattr__(k, it.infoLabels.get(k)) + itemlist.append(it) return itemlist - - -def mal(item): - itemlist = [] - login, message, user = login_mal() - if login: - item.login = True - - itemlist.append(item.clone(title=config.get_localized_string(70058), url="https://myanimelist.net/topanime.php?type=tv&limit=0", action="top_mal", contentType="tvshow", args="tv")) - itemlist.append(item.clone(title=config.get_localized_string(70059), url="https://myanimelist.net/topanime.php?type=movie&limit=0", action="top_mal", contentType="movie", args="movie")) - itemlist.append(item.clone(title=config.get_localized_string(70061), url="https://myanimelist.net/topanime.php?type=ova&limit=0", action="top_mal", contentType="tvshow", args="tv", Type="ova")) - itemlist.append(item.clone(title=config.get_localized_string(70028), url="https://myanimelist.net/topanime.php?type=bypopularity&limit=0", action="top_mal")) - itemlist.append(item.clone(title=config.get_localized_string(70060), url="https://myanimelist.net/topanime.php?type=upcoming&limit=0", action="top_mal")) - itemlist.append(item.clone(title=config.get_localized_string(70062), url="", action="indices_mal")) - itemlist.append(item.clone(title=config.get_localized_string(70063), url="", action="indices_mal")) - if config.get_platform() != "plex": - itemlist.append(item.clone(title=config.get_localized_string(70064), url="https://myanimelist.net/anime.php?q=", action="search_")) - itemlist.append(item.clone(title=typo(config.get_localized_string(70038), 'color kod'), action="filter_mal")) - - itemlist.append(item.clone(title=typo(config.get_localized_string(70057), 'color kod'), action="cuenta_mal")) - - return itemlist - - -##-------------------- SECTION TMDB ------------------------## -def list_tmdb(item): - # Main listings of the Tmdb category (Most popular, Most viewed, etc ...) - itemlist = [] - item.fanart = default_fan - if not item.pagina: - item.pagina = 1 - - # List of actors - if 'nm' in item.infoLabels['imdb_id']: - try: - ob_tmdb = Tmdb(discover=item.search, search_type=item.args, search_language=langt) - id_cast = ob_tmdb.result["person_results"][0]["id"] - if item.contentType == "movie": item.search = {'url': 'discover/movie', 'with_cast': id_cast, 'page': item.pagina, 'sort_by': 'primary_release_date.desc', 'language': langt} - else:item.search = {'url': 'person/%s/tv_credits' % id_cast, 'language': langt} - ob_tmdb = Tmdb(discover=item.search, search_type=item.args, search_language=langt) - except: - pass - else: - ob_tmdb = Tmdb(discover=item.search, search_type=item.args, search_language=langt) - - # Sagas and collections - if "collection" in item.search["url"]: - try: - for parte in ob_tmdb.result["parts"]: - new_item = item.clone(action="details") - new_item.infoLabels = ob_tmdb.get_infoLabels(new_item.infoLabels, origen=parte) - if new_item.infoLabels['thumbnail']: new_item.thumbnail = new_item.infoLabels['thumbnail'] - if new_item.infoLabels['fanart']: new_item.fanart = new_item.infoLabels['fanart'] - - if new_item.infoLabels['year']: new_item.title = typo(new_item.contentTitle, 'bold') + ' (%s)' % new_item.infoLabels['year'] + typo(str(new_item.infoLabels['rating']).replace("0.0", ""), '_ color kod') - else: new_item.title = typo(new_item.contentTitle, 'bold') + ' (%s)' % new_item.infoLabels['year'] + typo(str(new_item.infoLabels['rating']).replace("0.0", ""), '_ color kod') - itemlist.append(new_item) - itemlist.sort(key=lambda item: item.infoLabels["year"]) - except: - pass - else: - try: - orden = False - # If you do a search for actors or directors, those results are argscted - if "cast" in ob_tmdb.result and not item.crew: - ob_tmdb.results = ob_tmdb.result["cast"] - orden = True - elif "crew" in ob_tmdb.result and item.crew: - ob_tmdb.results = ob_tmdb.result["crew"] - orden = True - for i in range(0, len(ob_tmdb.results)): - new_item = item.clone(action="details", url='', infoLabels={'mediatype': item.contentType}) - new_item.infoLabels = ob_tmdb.get_infoLabels(new_item.infoLabels, origen=ob_tmdb.results[i]) - # If there is no synopsis in the chosen language, search in the alternative - if not new_item.infoLabels["plot"] and not 'person' in item.search["url"]: - ob_tmdb2 = Tmdb(id_Tmdb=new_item.infoLabels["tmdb_id"], search_type=item.args, search_language=langt_alt) - new_item.infoLabels["plot"] = ob_tmdb2.get_plot() - if new_item.infoLabels['thumbnail']: - new_item.thumbnail = new_item.infoLabels['thumbnail'] - elif new_item.infoLabels['profile_path']: - new_item.thumbnail = 'https://image.tmdb.org/t/p/original' + new_item.infoLabels['profile_path'] - new_item.infoLabels['profile_path'] = '' - new_item.plot = new_item.infoLabels["biography"] - if not item.search.get('with_cast', '') and not item.search.get('with_crew', ''): - if item.contentType == "movie": - new_item.action = "list_tmdb" - cast = 'with_cast' - if item.crew: - cast = 'with_crew' - new_item.search = {'url': 'discover/movie', cast: new_item.infoLabels['tmdb_id'], 'sort_by': 'primary_release_date.desc', 'language': langt, 'page': item.pagina} - else: - new_item.action = "list_tmdb" - new_item.search = {'url': 'person/%s/tv_credits' % new_item.infoLabels['tmdb_id'], 'language': langt} - - elif not new_item.infoLabels['thumbnail'] and not new_item.infoLabels['profile_path']: - new_item.thumbnail = '' - - if new_item.infoLabels['fanart']: new_item.fanart = new_item.infoLabels['fanart'] - - if not 'person' in item.search["url"] or 'tv_credits' in item.search["url"]: - new_item.title = typo(new_item.contentTitle,'bold') - if new_item.infoLabels['year']: new_item.title += typo(new_item.infoLabels['year'],'_ () bold') - if new_item.infoLabels['rating'] != '0.0': new_item.title += typo(new_item.infoLabels['rating'],'_ [] color kod bold') - else: - # If it is a search for people, a film for which it is known is included in the title and fanart - known_for = ob_tmdb.results[i].get("known_for") - # type=item.type - if known_for: - from random import randint - random = randint(0, len(known_for) - 1) - new_item.title = typo(new_item.contentTitle, 'bold') + typo(known_for[random].get("title", known_for[random].get("name")), '_ () color kod') - - if known_for[random]["backdrop_path"]: - new_item.fanart = 'https://image.tmdb.org/t/p/original' + known_for[random]["backdrop_path"] - else: - new_item.title = new_item.contentTitle - itemlist.append(new_item) - except: - import traceback - logger.error(traceback.format_exc()) - - if orden: - itemlist.sort(key=lambda item: item.infoLabels["year"], reverse=True) - if "page" in item.search and ob_tmdb.total_pages > item.search["page"]: - item.search["page"] += 1 - itemlist.append(item.clone(title=typo(config.get_localized_string(30992), 'color kod bold'), pagina=item.pagina + 1, thumbnail=thumb())) - - return itemlist - - -def details(item): - itemlist = [] - images = {} - data = "" - # If it comes from imdb section - if not item.infoLabels["tmdb_id"]: - headers = [['Accept-Language', langi]] - data = match("http://www.imdb.com/title/" + item.infoLabels['imdb_id'], headers=headers).data - - # Imdb images - pics = match(data, patron=r'showAllVidsAndPics.*?href=".*?(tt\d+)').match - if pics: images["imdb"] = {'url': 'http://www.imdb.com/_json/title/%s/mediaviewer' % pics} - - ob_tmdb = Tmdb(external_id=item.infoLabels["imdb_id"], external_source="imdb_id", search_type=item.args, search_language=langt) - item.infoLabels["tmdb_id"] = ob_tmdb.get_id() - - ob_tmdb = Tmdb(id_Tmdb=item.infoLabels["tmdb_id"], search_type=item.args, search_language=langt) - - try: - item.infoLabels = ob_tmdb.get_infoLabels(item.infoLabels) - # If there is no synopsis in the chosen language, search in the alternative - if not item.infoLabels["plot"]: item.infoLabels["plot"] = ob_tmdb.get_sinopsis(idioma_alternativo=langt_alt) - except: - pass - if not item.fanart and item.infoLabels['fanart']: - item.fanart = item.infoLabels['fanart'] - if item.infoLabels['thumbnail']: - item.thumbnail = item.infoLabels['thumbnail'] - - # Synopsis, votes from imdb - if data: - plot = match(data, patron='class="inline canwrap" itemprop="description">(.*?)</div>').match - plot = re.sub(r'(?i)<em[^>]+>|\n|\s{2}', ' ', htmlclean(plot)).strip() - if plot and (item.infoLabels['plot'] and item.infoLabels['plot'] != plot): item.infoLabels['plot'] += " (TMDB)\n" + plot + " (IMDB)" - elif plot and not item.infoLabels['plot']: item.infoLabels['plot'] = plot - - rating = match(data, patron=r'itemprop="ratingValue">([^<]+)<').match - if rating: item.infoLabels['rating'] = float(rating.replace(",", ".")) - - votos = match(data, patron=r'itemprop="ratingCount">([^<]+)<').match - if votos: item.infoLabels['votes'] = votos - - if item.infoLabels['tagline']: item.plot= typo(item.infoLabels['tagline'],'bold') + '\n' + item.plot - - title = item.contentType.replace("movie", config.get_localized_string(70283)).replace("tvshow", "serie") - # from core.support import dbg;dbg() - if not item.contentTitle: item.contentTitle = item.title.split('(')[0].strip() - # Search by titles chosen language and / or original version and Spanish - if config.get_setting('new_search'): - itemlist.append(item.clone(channel='globalsearch', action="Search", title=config.get_localized_string(70069) % (title, item.contentTitle), search_text=item.contentTitle, text=item.contentTitle, mode='search', type=item.contentType, folder=False)) - if item.infoLabels['originaltitle'] and item.contentTitle != item.infoLabels['originaltitle']: - itemlist.append(item.clone(channel='globalsearch', action="Search", search_text=item.infoLabels['originaltitle'], title=config.get_localized_string(70070) % item.infoLabels['originaltitle'], mode='search', type=item.contentType, folder=False)) - else: - itemlist.append(item.clone(channel='search', action="new_search", title=config.get_localized_string(70069) % (title, item.contentTitle), search_text=item.contentTitle, text=item.contentTitle, mode=item.contentType)) - if item.infoLabels['originaltitle'] and item.contentTitle != item.infoLabels['originaltitle']: - itemlist.append(item.clone(channel='search', action="search", search_text=item.infoLabels['originaltitle'], title=config.get_localized_string(70070) % item.infoLabels['originaltitle'], mode=item.contentType)) - - # if langt != "es" and langt != "en" and item.infoLabels["tmdb_id"]: - # tmdb_lang = Tmdb(id_Tmdb=item.infoLabels["tmdb_id"], search_type=item.args, search_language=def_lang) - # if tmdb_lang.result.get("title") and tmdb_lang.result["title"] != item.contentTitle and tmdb_lang.result["title"] != item.infoLabels['originaltitle']: - # tmdb_lang = tmdb_lang.result["title"] - # itemlist.append(item.clone(channel='search', action="search", title=config.get_localized_string(70066) % tmdb_lang, contentTitle=tmdb_lang, mode=item.contentType)) - - # In case of series, option of info by seasons - if item.contentType == "tvshow" and item.infoLabels['tmdb_id'] and "number_of_seasons" in item.infoLabels: - itemlist.append(item.clone(action="info_seasons", title=config.get_localized_string(70067) % item.infoLabels["number_of_seasons"])) - # Option to watch the cast and browse their movies / series - if item.infoLabels['tmdb_id']: - itemlist.append(item.clone(action="distribution", title=config.get_localized_string(70071), infoLabels={'tmdb_id': item.infoLabels['tmdb_id'], 'mediatype': item.contentType})) - - if config.is_xbmc(): - item.contextual = True - itemlist.append(item.clone(channel="trailertools", action="buscartrailer", title=config.get_localized_string(60359))) - - try: - images['tmdb'] = ob_tmdb.result["images"] - itemlist.append(item.clone(action="imagenes", title=config.get_localized_string(70316), images=images, args="menu")) - except: - pass - - try: - if item.contentType == "movie" and item.infoLabels["year"] < 2014: - post_url = "https://theost.com/search/custom/?key=%s&year=%s&country=0&genre=0" % ( - item.infoLabels['originaltitle'].replace(" ", "+"), item.infoLabels["year"]) - url = "https://nl.hideproxy.me/includes/process.php?action=update" - post = "u=%s&proxy_formdata_server=nl&allowCookies=1&encodeURL=1&encodePage=0&stripObjects=0&stripJS=0&go=" % urllib.quote( - post_url) - while True: - response = httptools.downloadpage(url, post=post, follow_redirects=False) - if response.headers.get("location"): - url = response.headers["location"] - post = "" - else: - data_music = response.data - break - - url_album = scrapertools.find_single_match(data_music, 'album(?:|s) on request.*?href="([^"]+)"') - if url_album: - url_album = "https://nl.hideproxy.me" + url_album - itemlist.append(item.clone(action="musica_movie", title=config.get_localized_string(70317), url=url_album)) - except: - pass - - token_auth = config.get_setting("token_trakt", "trakt") - if token_auth: - itemlist.append(item.clone(title=config.get_localized_string(70318), action="menu_trakt")) - - # itemlist.append(item.clone(title="", action="")) - # It is part of a collection - try: - if ob_tmdb.result.get("belongs_to_collection"): - new_item = item.clone(search='', infoLabels={'mediatype': item.contentType}) - saga = ob_tmdb.result["belongs_to_collection"] - new_item.infoLabels["tmdb_id"] = saga["id"] - if saga["poster_path"]: - new_item.thumbnail = 'https://image.tmdb.org/t/p/original' + saga["poster_path"] - if saga["backdrop_path"]: - new_item.fanart = 'https://image.tmdb.org/t/p/original' + saga["backdrop_path"] - new_item.search = {'url': 'collection/%s' % saga['id'], 'language': langt} - itemlist.append(new_item.clone(title=config.get_localized_string(70327) % saga["name"], action="list_tmdb")) - except: - pass - - # Similar Movies / Series and Recommendations - if item.infoLabels['tmdb_id']: - item.args = item.contentType.replace('tvshow', 'tv') - title = title.replace("película", config.get_localized_string(70137)).replace("serie", config.get_localized_string(30123)) - itemlist.append(item.clone(title=config.get_localized_string(70328) % title, action="list_tmdb", search={'url': '%s/%s/similar' % (item.args, item.infoLabels['tmdb_id']), 'language': langt, 'page': 1}, infoLabels={'mediatype': item.contentType})) - itemlist.append(item.clone(title=config.get_localized_string(70315), action="list_tmdb", search={'url': '%s/%s/recommendations' % (item.args, item.infoLabels['tmdb_id']), 'language': langt, 'page': 1})) - - return itemlist - - -def distribution(item): - # Actors and film crew for a movie / series - itemlist = [] - item.args=item.contentType.replace('tvshow','tv') - item.search = {'url': '%s/%s/credits' % (item.args, item.infoLabels['tmdb_id'])} - ob_tmdb = Tmdb(discover=item.search, search_type=item.args, search_language=langt) - - try: - cast = ob_tmdb.result["cast"] - if cast: - itemlist.append(item.clone(title=config.get_localized_string(70314), action="", )) - for actor in cast: - new_item = item.clone(action="list_tmdb", fanart=default_fan) - new_item.title = " " + actor["name"] + " as " + actor["character"] - if actor["profile_path"]: - new_item.thumbnail = 'https://image.tmdb.org/t/p/original' + actor["profile_path"] - if item.contentType == "movie": - new_item.search = {'url': 'discover/movie', 'with_cast': actor['id'], - 'language': langt, 'page': 1, - 'sort_by': 'primary_release_date.desc'} - else: - new_item.search = {'url': 'person/%s/tv_credits' % actor['id'], 'language': langt} - itemlist.append(new_item) - except: - pass - - try: - crew = ob_tmdb.result["crew"] - if crew: - itemlist.append(item.clone(title=config.get_localized_string(70319), action="", )) - for c in crew: - new_item = item.clone(action="list_tmdb", fanart=default_fan) - new_item.title = " " + c["job"] + ": " + c["name"] - if c["profile_path"]: - new_item.thumbnail = 'https://image.tmdb.org/t/p/original' + c["profile_path"] - if item.contentType == "movie": - new_item.search = {'url': 'discover/movie', 'with_crew': c['id'], 'page': 1,'sort_by': 'primary_release_date.desc'} - else: - new_item.search = {'url': 'person/%s/tv_credits' % c['id'], 'language': langt} - new_item.crew = True - itemlist.append(new_item) - except: - pass - - return itemlist - - -def info_seasons(item): - # Season and episode info - itemlist = [] - ob_tmdb = Tmdb(id_Tmdb=item.infoLabels["tmdb_id"], search_type="tv", search_language=langt) - logger.info(item.infoLabels) - - for temp in range(int(item.infoLabels["number_of_seasons"]), 0, -1): - temporada = ob_tmdb.get_temporada(temp) - if temporada: - new_item = item.clone(action="", mediatype="season") - new_item.infoLabels['title'] = temporada['name'] - new_item.infoLabels['season'] = temp - if temporada['overview']: - new_item.infoLabels['plot'] = temporada['overview'] - if temporada['air_date']: - date = temporada['air_date'].split('-') - new_item.infoLabels['aired'] = date[2] + "/" + date[1] + "/" + date[0] - new_item.infoLabels['year'] = date[0] - if temporada['poster_path']: - new_item.infoLabels['poster_path'] = 'https://image.tmdb.org/t/p/original' + temporada['poster_path'] - new_item.thumbnail = new_item.infoLabels['poster_path'] - new_item.title = config.get_localized_string(60027) % temp - itemlist.append(new_item) - - for epi in range(1, len(temporada["episodes"])): - episodio = ob_tmdb.get_episodio(temp, epi) - if episodio: - new_item = item.clone(action="", mediatype="episode") - new_item.infoLabels['season'] = temp - new_item.infoLabels['episode'] = epi - new_item.infoLabels['title'] = episodio['episodio_titulo'] - if episodio['episodio_sinopsis']: - new_item.infoLabels['plot'] = episodio['episodio_sinopsis'] - if episodio['episodio_imagen']: - new_item.infoLabels['poster_path'] = episodio['episodio_imagen'] - new_item.thumbnail = new_item.infoLabels['poster_path'] - if episodio['episodio_air_date']: - new_item.infoLabels['aired'] = episodio['episodio_air_date'] - new_item.infoLabels['year'] = episodio['episodio_air_date'].rsplit("/", 1)[1] - if episodio['episodio_vote_average']: - new_item.infoLabels['rating'] = episodio['episodio_vote_average'] - new_item.infoLabels['votes'] = episodio['episodio_vote_count'] - new_item.title = " %sx%s - %s" % (temp, epi, new_item.infoLabels['title']) - itemlist.append(new_item) - - return itemlist - - -def indices_tmdb(item): - # Indices by gender and year - itemlist = [] - from datetime import datetime - if config.get_localized_string(70032) in item.title: - thumbnail = {} - url = ('http://api.themoviedb.org/3/genre/%s/list?api_key=a1ab8b8669da03637a4b98fa39c39228&language=%s' % (item.args, langt)) - genres_list = {} - try: - for l in jsontools.load(match(url, cookies=False).data)["genres"]: - genres_list[str(l["id"])] = l["name"] - if "es" in langt: thumbnail[str(l["id"])] = "%s1/%s.jpg" % (images_predef, l["name"].lower().replace("ó", "o").replace("í", "i").replace(" ", "%20").replace("Aventuras", "Aventura").replace("ú", "u")) - else: thumbnail[str(l["id"])] = "%s2/%s.jpg" % (images_predef, l["name"]) - except: - pass - - fecha = datetime.now().strftime('%Y-%m-%d') - sort_by = 'release_date.desc' - param_year = 'release_date.lte' - if item.contentType == 'tvshow': - sort_by = 'first_air_date.desc' - param_year = 'air_date.lte' - for key, value in genres_list.items(): - search = {'url': 'discover/%s' % item.args, 'with_genres': key, 'sort_by': sort_by, param_year: fecha,'language': langt, 'page': 1} - new_item = item.clone(title=value, thumbnail=thumbnail[key], action="list_tmdb", search=search) - itemlist.append(new_item) - - itemlist.sort(key=lambda item: item.title) - thumb(itemlist) - else: - year = datetime.now().year + 3 - for i in range(year, 1899, -1): - if item.contentType == 'tvshow': - param_year = 'first_air_date_year' - else: - param_year = 'primary_release_year' - search = {'url': 'discover/%s' % item.args, param_year: i, 'language': langt, 'page': 1} - itemlist.append(item.clone(title=str(i), action='list_tmdb', search=search)) - - return itemlist - - -def filter(item): - logger.debug() - - from datetime import datetime - list_controls = [] - valores = {} - - dict_values = None - - list_controls.append({'id': 'years', 'label': config.get_localized_string(60232), 'enabled': True, 'type': 'list', 'default': -1, 'visible': True}) - list_controls[0]['lvalues'] = [] - valores['years'] = [] - year = datetime.now().year + 1 - for i in range(1900, year + 1): - list_controls[0]['lvalues'].append(str(i)) - valores['years'].append(str(i)) - list_controls[0]['lvalues'].append(config.get_localized_string(70450)) - valores['years'].append('') - - if config.get_localized_string(70038) in item.title: - # Se utilizan los valores por defecto/guardados - saved_values = config.get_setting("default_filter_" + item.args, item.channel) - if saved_values: - dict_values = saved_values - url = ('http://api.themoviedb.org/3/genre/%s/list?api_key=f7f51775877e0bb6703520952b3c7840&language=%s' % (item.args, langt)) - try: - lista = jsontools.load(httptools.downloadpage(url, cookies=False).data)["genres"] - if lista: - list_controls.append({'id': 'labelgenre', 'enabled': True, 'type': 'label', 'default': None, 'label': config.get_localized_string(70451), 'visible': True}) - for l in lista: - list_controls.append({'id': 'genre' + str(l["id"]), 'label': l["name"], 'enabled': True, 'type': 'bool', 'default': False, 'visible': True}) - except: - pass - - list_controls.append({'id': 'orden', 'label': config.get_localized_string(70455), 'enabled': True, 'type': 'list', 'default': -1, 'visible': True}) - orden = [config.get_localized_string(70456), config.get_localized_string(70457), config.get_localized_string(70458), config.get_localized_string(70459), config.get_localized_string(70460), config.get_localized_string(70461)] - if item.args == "movie": - orden.extend([config.get_localized_string(70462), config.get_localized_string(70463)]) - orden_tmdb = ['popularity.desc', 'popularity.asc', 'release_date.desc', 'release_date.asc', 'vote_average.desc', 'vote_average.asc', 'original_title.asc', 'original_title.desc'] - valores['orden'] = [] - list_controls[-1]['lvalues'] = [] - for i, tipo_orden in enumerate(orden): - list_controls[-1]['lvalues'].insert(0, tipo_orden) - valores['orden'].insert(0, orden_tmdb[i]) - - list_controls.append({'id': 'espacio', 'label': '', 'enabled': False, 'type': 'label', 'default': None, 'visible': True}) - list_controls.append({'id': 'save', 'label': config.get_localized_string(70464), 'enabled': True, 'type': 'bool', 'default': False, 'visible': True}) - else: - list_controls.append({'id': 'keyword', 'label': config.get_localized_string(70465), 'enabled': True, 'type': 'text', 'default': '', 'visible': True}) - - item.valores = valores - return platformtools.show_channel_settings(list_controls=list_controls, dict_values=dict_values, caption=config.get_localized_string(70320), item=item, callback='filtered') - - -def filtered(item, values): - values_copy = values.copy() - # Save the filter to be the one loaded by default - if "save" in values and values["save"]: - values_copy.pop("save") - config.set_setting("default_filter_" + item.args, values_copy, item.channel) - - year = item.valores["years"][values["years"]] - if config.get_localized_string(70038) in item.title: - orden = item.valores["orden"][values["orden"]] - if item.args == "tv": orden = orden.replace('release_date', 'first_air_date') - - genre_ids = [] - for v in values: - if "genre" in v: - if values[v]: genre_ids.append(v.replace('genre', '')) - genre_ids = ",".join(genre_ids) - - if config.get_localized_string(70465).lower() in item.title.lower(): item.search = {'url': 'search/%s' % item.args, 'year': year, 'query': values["keyword"], 'language': langt, 'page': 1} - elif item.args == "movie": item.search = {'url': 'discover/%s' % item.args, 'sort_by': orden, 'primary_release_year': year, 'with_genres': genre_ids, 'vote_count.gte': '10', 'language': langt, 'page': 1} - else: item.search = {'url': 'discover/%s' % item.args, 'sort_by': orden, 'first_air_date_year': year, 'with_genres': genre_ids, 'vote_count.gte': '10', 'language': langt, 'page': 1} - - item.action = "list_tmdb" - return list_tmdb(item) - - -def musica_movie(item): - logger.debug() - itemlist = [] - data = match(item).data - matches = match(data, patron=r'<td class="left">([^<]+)<br><small>([^<]+)</small>.*?<td>(\d+:\d+).*?<p id="([^"]+)"').matches - for title, artist, duration, id_p in matches: - title = typo(title, 'bold') + typo(artist, '_ () bold') + typo(duration, '_ [] color kod bold') - url = match(data, patron=r"AudioPlayer.embed\('%s'.*?soundFile: '([^']+)'" % id_p).match - itemlist.append(Item(channel=item.channel, action="play", server="directo", url=url, title=title, thumbnail=item.thumbnail, fanart=item.fanart, )) - return itemlist - - -##-------------------- SECTION IMDB ------------------------## -def list_imdb(item): - # Main method for imdb sections - itemlist = [] - - headers = [['Accept-Language', langi]] - if "www.imdb.com" in item.url: - # data = httptools.downloadpage(item.url, headers=headers, replace_headers=True).data - data = match(item.url, headers=headers).data - else: - url = 'http://www.imdb.com/search/title?' + item.url - # data = httptools.downloadpage(url, headers=headers, replace_headers=True).data - data = match(url, headers=headers).data - logger.debug(data) - - # data = re.sub(r"\n|\r|\t| ", "", data) - # data = re.sub(r"\s{2}", " ", data) - - # List of actors - if 'search/name' in item.url: - patron = r'src="([^"]+)"[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+><a href="/name/(nm\d+)[^>]+>\s*([^<]+)[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>\s([^<]+)[^>]+>[^>]+>[^>]+>\s*([^<]+)<' - matches = match(data, patron=patron).matches - for thumbnail, imdb_id, title, movie, info in matches: - new_item = item.clone(action='list_tmdb') - try: - if "@" in thumbnail: - thumbnail = thumbnail.rsplit('@', 1)[0] - thumbnail += "@._UX482.jpg" - elif "._V1_" in thumbnail: - thumbnail = thumbnail.rsplit('._V1_', 1)[0] - thumbnail += "._V1_UX482.jpg" - except: - pass - new_item.thumbnail = thumbnail - - info = info.strip() - if info: new_item.infoLabels['plot'] = htmlclean(info) - new_item.title = typo(title.strip(), 'bold') + typo(movie.strip(),'_ () color kod bold') - new_item.infoLabels['imdb_id'] = imdb_id - new_item.search = {'url': 'find/%s' % imdb_id, 'external_source': 'imdb_id', 'language': langt} - itemlist.append(new_item) - else: - patron = r'(?:<div class="image">|<div class="lister-item-image).*?(?:loadlate="([^"]+)"|src="([^"]+)").*?href=".*?/(tt\d+)[^>]+>([^<]+)</a>(.*?)(?:"text-muted|"outline)[^>]+>\s*([^<]+)<' - matches = match(data, patron=patron).matches - for thumbnail, thumb2, imdb_id, title, info, plot in matches: - - new_item = item.clone(action='details') - new_item.title = typo(title.strip(),'bold') - if not thumbnail: thumbnail = thumb2 - try: - if "@" in thumbnail: - thumbnail = thumbnail.rsplit('@', 1)[0] - thumbnail += "@._UX482.jpg" - elif "._V1_" in thumbnail: - thumbnail = thumbnail.rsplit('._V1_', 1)[0] - thumbnail += "._V1_UX482.jpg" - except: - pass - new_item.thumbnail = thumbnail - - new_item.infoLabels['plot'] = htmlclean(plot.strip()) - - genres = match(info, patron=r'genre">([^<]+)<').matches - if genres: new_item.infoLabels["genre"] = ", ".join(genres) - duration = match(info, patron=r'(\d+) min').match - if duration: new_item.infoLabels['duration'] = int(duration) * 60 - - new_item.infoLabels['year'] = match(new_item.title, patron=r'\((\d{4})').match - if not new_item.infoLabels['year']: - new_item.infoLabels['year'] = match(info, patron=r'year.*?\((\d{4})').match - if new_item.infoLabels['year']: new_item.title += typo(new_item.infoLabels['year'], '_ () bold') - - rating = match(info, patron=r'(?:rating|Metascore).*?<strong>([^<]*)</strong>').match.replace(",", ".") - if rating: - if not "." in rating: - try: rating = float(rating) / 10 - except: rating = None - if rating: - new_item.title += typo(str(rating), '_ [] color kod') - new_item.infoLabels['rating'] = float(rating) - new_item.infoLabels['imdb_id'] = imdb_id - itemlist.append(new_item) - - match_data = match(data, patron=r'<option selected="selected"[^>]+>\s*([A-Za-z]+)[^\d]+(\d+)\s*</option').match - if match_data: - itemlist.insert(0, Item(title=typo('%s %s' % match_data, '_ bold color kod'), thumbnail=thumb('year'))) - - next_page = match(data, patron=r'<a href="([^"]+)"[^>]*>Next').match - if next_page: - next_page = 'http://www.imdb.com' + next_page - itemlist.append(item.clone(title=typo(config.get_localized_string(30992), 'color kod bold'), url=next_page, thumbnail=thumb())) - - return itemlist - - -def filter_imdb(item): - logger.debug() - - from datetime import datetime - list_controls = [] - valores = {} - - dict_values = None - # Default / saved values ​​are used - saved_values = config.get_setting("default_filter_imdb_" + item.args, item.channel) - if saved_values: dict_values = saved_values - - list_controls = [{'id': 'title', 'label': config.get_localized_string(70505), 'enabled': True, 'type': 'text', 'default': '', 'visible': True}, - {'id': 'yearsdesde', 'label': config.get_localized_string(70452), 'enabled': True, 'type': 'list', 'default': -1, 'visible': True}, - {'id': 'yearshasta', 'label': config.get_localized_string(70453), 'enabled': True, 'type': 'list', 'default': -1, 'visible': True}] - - list_controls[1]['lvalues'] = [] - list_controls[2]['lvalues'] = [] - valores['years'] = [] - year = datetime.now().year + 1 - - for i in range(1900, year + 1): - list_controls[1]['lvalues'].append(str(i)) - list_controls[2]['lvalues'].append(str(i)) - valores['years'].append(str(i)) - list_controls[1]['lvalues'].append(config.get_localized_string(70450)) - list_controls[2]['lvalues'].append(config.get_localized_string(70450)) - valores['years'].append('') - - try: - genres_translate = {'Action': config.get_localized_string(70394), 'Adventure': config.get_localized_string(60267), 'Animation': config.get_localized_string(60268), 'Biography': config.get_localized_string(70403), - 'Comedy': config.get_localized_string(60270), 'Crime': config.get_localized_string(60271), 'Documentary': config.get_localized_string(70396), 'Family': config.get_localized_string(70399), - 'Fantasy': config.get_localized_string(60274), 'Film-Noir': config.get_localized_string(70400), 'Game-Show': config.get_localized_string(70401), - 'History': config.get_localized_string(70405), 'Horror': config.get_localized_string(70013), 'Music': config.get_localized_string(70404), 'Mistery': config.get_localized_string(70402), - 'News': config.get_localized_string(60279), 'Reality-TV': config.get_localized_string(70406), 'Sci-Fi': config.get_localized_string(70397), 'Sport': config.get_localized_string(70395), - 'Talk-Show': config.get_localized_string(70398), 'War': config.get_localized_string(70407)} - - data = match("http://www.imdb.com/search/title", cookies=False).data - # bloque = scrapertools.find_single_match(data, '<h3>Genres</h3>(.*?)</table>') - matches = match(data, patronBlock=r'<h3>Genres</h3>(.*?)</table>', patron=r' value="([^"]+)"\s*>\s*<label.*?>([^<]+)<').matches - if matches: - list_controls.append({'id': 'espacio', 'label': '', 'enabled': False, 'type': 'label', 'default': None, 'visible': True}) - list_controls.append({'id': 'labelgenre', 'enabled': True, 'type': 'label', 'visible': True, 'label': config.get_localized_string(70451),}) - lista = [] - for value, title in matches: - logger.debug('TITOLO:',title, genres_translate.get(title, title)) - title = genres_translate.get(title, title) - lista.append([value, title]) - lista.sort(key=lambda lista: lista[1]) - for value, title in lista: - list_controls.append({'id': 'genre' + value, 'label': title, 'enabled': True, 'type': 'bool', 'default': False, 'visible': True}) - except: - pass - - list_controls.append({'id': 'espacio', 'label': '', 'enabled': False, 'type': 'label', 'default': None, 'visible': True}) - try: - # bloque = scrapertools.find_single_match(data, '<h3>Countries</h3>(.*?)Less-Common') - matches = scrapertools.find_multiple_matches(data, paronBlock=r'<h3>Countries</h3>(.*?)Less-Common', patron=r' value="([^"]+)"\s*>([^<]+)<').matches - if matches: - list_controls.append({'id': 'pais', 'label': config.get_localized_string(70466), 'enabled': True, 'type': 'list', 'default': -1, 'visible': True}) - list_controls[-1]['lvalues'] = [] - list_controls[-1]['lvalues'].append(config.get_localized_string(70450)) - valores['pais'] = [] - valores['pais'].append('') - for valor, titulo in matches: - list_controls[-1]['lvalues'].insert(0, titulo) - valores['pais'].insert(0, valor) - - except: - pass - - list_controls.append({'id': 'orden', 'label': config.get_localized_string(70455), 'enabled': True, 'type': 'list', 'default': -1, 'visible': True}) - orden = [config.get_localized_string(70456), config.get_localized_string(70457), config.get_localized_string(70458), config.get_localized_string(70459), config.get_localized_string(70460), config.get_localized_string(70461), - config.get_localized_string(70462), config.get_localized_string(70463)] - - orden_imdb = ['moviemeter,asc', 'moviemeter,desc', 'year,desc', 'year,asc', 'user_rating,desc', 'user_rating,asc', 'alpha,asc', 'alpha,desc'] - valores['orden'] = [] - list_controls[-1]['lvalues'] = [] - for i, tipo_orden in enumerate(orden): - list_controls[-1]['lvalues'].insert(0, tipo_orden) - valores['orden'].insert(0, orden_imdb[i]) - - list_controls.append({'id': 'save', 'label': config.get_localized_string(70464), 'enabled': True, 'type': 'bool', 'default': False, 'visible': True}) - - item.valores = valores - return platformtools.show_channel_settings(list_controls=list_controls, dict_values=dict_values, caption=config.get_localized_string(70320), item=item, callback='filtered_imdb') - - -def filtered_imdb(item, values): - values_copy = values.copy() - # Save the filter to be the one loaded by default - if "save" in values and values["save"]: - values_copy.pop("save") - config.set_setting("default_filter_imdb_" + item.args, values_copy, item.channel) - - yeard = item.valores["years"][values["yearsdesde"]] - yearh = item.valores["years"][values["yearshasta"]] - orden = item.valores["orden"][values["orden"]] - # pais = item.valores["pais"][values["pais"]] - - genre_ids = [] - for v in values: - if "genre" in v: - if values[v]: - genre_ids.append(v.replace('genre', '')) - genre_ids = ",".join(genre_ids) - try: - votos = int(values["votos"]) - except: - votos = "" - - item.url = 'http://www.imdb.com/search/title?num_votes=%s,&genres=%s&release_date=%s,%s&sort=%s&title=%s&title_type=' % (str(votos), genre_ids, yeard, yearh, orden, values["title"]) - if item.contentType == "movie": item.url += "feature,tv_movie" - else: item.url += "tv_series,tv_special,mini_series" - - item.action = "list_imdb" - return list_imdb(item) - - -def indices_imdb(item): - # Imdb indices by year and gender - itemlist = [] - from datetime import datetime - if config.get_localized_string(70032) in item.title: - genres_translate = {'Action': config.get_localized_string(70394), 'Adventure': config.get_localized_string(60267), 'Animation': config.get_localized_string(60268), 'Biography': config.get_localized_string(70403), 'Thriller': config.get_localized_string(70410), - 'Comedy': config.get_localized_string(60270), 'Crime': config.get_localized_string(60271), 'Documentary': config.get_localized_string(70396), 'Family': config.get_localized_string(70399), 'Romance': config.get_localized_string(70409), - 'Fantasy': config.get_localized_string(60274), 'Film-Noir': config.get_localized_string(70400), 'Game-Show': config.get_localized_string(70401), 'Drama': config.get_localized_string(70412), 'Western': config.get_localized_string(70411), - 'History': config.get_localized_string(70405), 'Horror': config.get_localized_string(70013), 'Music': config.get_localized_string(70404), 'Musical': config.get_localized_string(70408),'Mystery': config.get_localized_string(70402), - 'News': config.get_localized_string(60279), 'Reality-TV': config.get_localized_string(70406), 'Sci-Fi': config.get_localized_string(70397), 'Sport': config.get_localized_string(70395), - 'Talk-Show': config.get_localized_string(70398), 'War': config.get_localized_string(70407)} - data = match("http://www.imdb.com/search/title", cookies=False).data - # bloque = scrapertools.find_single_match(data, '<h3>Genres</h3>(.*?)</table>') - matches = match(data, patronBlock=r'<h3>Genres</h3>(.*?)</table>', patron=r' value="([^"]+)"\s*>\s*<label.*?>([^<]+)<').matches - if matches: - for value, title in matches: - title = genres_translate.get(title, title) - thumbnail = "%s2/%s.jpg" % (images_predef, title) - itemlist.append(item.clone(title=title, action='list_imdb', thumbnail=thumbnail, url='http://www.imdb.com/search/title?genres=%s%s' % (value, item.url))) - itemlist = thumb(itemlist) - itemlist.sort(key=lambda item: item.title) - else: - year = datetime.now().year + 3 - for i in range(year, 1899, -1): - itemlist.append(item.clone(title=str(i), action='list_imdb', url='http://www.imdb.com/search/title?release_date=%s,%s%s' % (i, i, item.url))) - - return itemlist - - -##-------------------- FILMAFFINITY SECTION ------------------------## -# def list_fa(item): -# # Filmaffinity main listing method -# itemlist = [] - -# # Listings with pagination per post -# if item.args == "top": -# if item.page_fa: -# post = "from=%s" % item.page_fa -# data = httptools.downloadpage(item.url, post=post).data -# if item.total > item.page_fa: -# item.page_fa += 30 -# else: -# item.page_fa = "" -# else: -# item.page_fa = 30 -# data = httptools.downloadpage(item.url).data -# item.total = int(scrapertools.find_single_match(data, 'tmResCount\s*=\s*(\d+)')) -# if item.total <= item.page_fa: -# item.page_fa = "" - -# else: -# data = httptools.downloadpage(item.url).data -# data = re.sub(r"\n|\r|\t| ", "", data) -# data = re.sub(r"\s{2}", " ", data) - -# votaciones = [] -# # If it is the premiere section, change the structure of the scraper - -# if item.args == "estrenos": -# patron = r'fa-calendar-alt">[^>]+>([^<]+)<(.*?)(?:id="main-wrapper-rdcat|class="np-cat-wrapper")' -# bloks = scrapertools.find_multiple_matches(data, patron) -# for title, block in bloks: -# itemlist.append(item.clone(title=title, action='', )) - -# patron = r'href="([^"]+)" title="([^"]+)"><img.*?src="([^"]+)[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>\s*(\d+)[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>([^<]+)[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>\s*(\d+)[^>]+>[^>]+>[^>]+>[^>]+>([^<]+)[^>]+>[^>]+>([^<]+)' -# matches = match(block, patron=patron).matches -# # matches = scrapertools.find_multiple_matches(bloque, patron) -# for url, title, thumb, duration, rating, year, genre, plot in matches: -# title = title.strip() -# new_item = item.clone(action="details_fa", contentType="movie", args="movie", contentTitle=title) -# if not url.startswith("http://m.filmaffinity"): new_item.url = "http://m.filmaffinity.com" + url -# else: new_item.url = url - -# new_item.thumbnail = thumb.replace("msmall", "large") -# if not new_item.thumbnail.startswith("http"): new_item.thumbnail = "http://m.filmaffinity.com" + new_item.thumbnail - -# new_item.title = typo(title,'bold') + typo(rating,'_ [] color kod bold') -# new_item.infoLabels['duration'] = int(duration) * 60 -# new_item.infoLabels['rating'] = float(rating.replace(",", ".")) -# new_item.infoLabels['year'] = year -# new_item.infoLabels['genres'] = [genre] -# itemlist.append(new_item) -# else: -# patron = '(?:<a class="list-group-item[^"]*" href="([^"]+)">|<a href="([^"]+)" class="list-group-item[^"]*">)' \ -# '.*?(?:data-src="([^"]+)"|src="((?!/images/empty.gif)[^"]+)").*?' \ -# '<div class="mc-title.*?>([^<]+)<small>\((\d+)\)</small>.*?(?:<div class="avgrat-box in-block ">' \ -# '([^<]+)</div>\s*<small class="ratcount-box">(.*?)\s*<|</li>)' -# matches = scrapertools.find_multiple_matches(data, patron) -# for url, url2, thumb, thumb2, title, year, rating, votos in matches: -# title = title.strip() -# new_item = item.clone(action="details_fa", args="movie") -# if not url: -# url = url2 -# if not url.startswith("http://m.filmaffinity"): -# new_item.url = "http://m.filmaffinity.com" + url -# else: -# new_item.url = url - -# if not thumb: -# thumb = thumb2 -# new_item.thumbnail = thumb.replace("msmall", "large") -# if not new_item.thumbnail.startswith("http"): -# new_item.thumbnail = "http://m.filmaffinity.com" + new_item.thumbnail - -# new_item.title = title.replace("(Serie de TV)", "").replace("(TV)", "") + " (%s) %s" \ -# % (year, rating) -# new_item.contentTitle = re.sub(r'(?i)\(serie de tv\)|\(tv\)|\(c\)', '', title) -# if re.search(r'(?i)serie de tv|\(tv\)', title): -# new_item.contentType = "tvshow" -# new_item.args = "tv" -# new_item.infoLabels["tvshowtitle"] = new_item.contentTitle - -# new_item.infoLabels['year'] = year -# votaciones.append([rating, votos]) -# if rating: -# new_item.infoLabels['rating'] = float(rating.replace(",", ".")) -# new_item.infoLabels['votes'] = votos -# itemlist.append(new_item) - -# if len(itemlist) < 31: -# from core import tmdb -# tmdb.set_infoLabels_itemlist(itemlist, True) -# for i, it in enumerate(itemlist): -# try: -# it.infoLabels['votes'] = votaciones[i][1] -# it.infoLabels['rating'] = float(votaciones[i][0].replace(",", ".")) -# except: -# pass - -# next_page = scrapertools.find_single_match(data, 'aria-label="Next" href="([^"]+)"') -# if next_page: -# if not next_page.startswith("http://m.filmaffinity"): -# next_page = "http://m.filmaffinity.com" + next_page - -# itemlist.append(Item(channel=item.channel, action=item.action, title=config.get_localized_string(70065), url=next_page, -# args=item.args)) -# elif item.page_fa: -# itemlist.append(item.clone(title=config.get_localized_string(70065), )) -# return itemlist - - -# def indices_fa(item): -# # Indexes by gender, year, themes and sagas / collections -# itemlist = [] -# # dbg() -# if item.url: -# data = match(item).data -# # data = httptools.downloadpage(item.url).data -# # data = re.sub(r"\n|\r|\t| ", "", data) -# # data = re.sub(r"\s{2}", " ", data) -# if "sagas" in item.args: -# matches = match(data, patron=r'<li class="fa-shadow"><a href="([^"]+)">[^>]+>([^<]+)<.*?src="([^"]+)".*?"count-movies">([^<]+)<').matches -# # patron = '<li class="fa-shadow">.*?href="([^"]+)".*?group-name">([^<]+)<.*?src="([^"]+)".*?"count-movies">([^<]+)<' -# # matches = scrapertools.find_multiple_matches(data, patron) -# for url, title, thumbnail, info in matches: -# new_item = item.clone(action="list_fa") -# if not url.startswith("http://www.filmaffinity"): new_item.url = "http://m.filmaffinity.com" + url -# else: new_item.url = url.replace("www.filmaffinity.com", "m.filmaffinity.com") - -# new_item.thumbnail = thumbnail.replace("mmed", "large") -# new_item.title = typo(title.strip(),'bold') + typo(info, '_ []') -# itemlist.append(new_item) - -# next_page = match(data, patron = r'<a href="([^"]+)">>>').match# scrapertools.find_single_match(data, '<a href="([^"]+)">>>') -# if next_page: -# if not next_page.startswith("http://www.filmaffinity.com"): next_page = "http://www.filmaffinity.com" + next_page -# itemlist.append(Item(channel=item.channel, action=item.action, title=typo(config.get_localized_string(30992), 'color kod bold'), url=next_page, args=item.args)) -# elif config.get_localized_string(70032) in item.title: -# bloque = scrapertools.find_single_match(data, '="genre">.*?</option>(.*?)</select>') -# matches = scrapertools.find_multiple_matches(bloque, '<option value="([^"]+)">([^<]+)</option>') -# for valor, titulo in matches: -# if valor == "TV_SE": -# continue -# new_item = item.clone(title=titulo, action="list_fa", args="top") -# new_item.url = "http://m.filmaffinity.com/%s/topgen.php?genre=%s&country=&fromyear=&toyear=&nodoc=1" % (langf, valor) -# if item.contentType == "movie": -# new_item.url += "¬vse=1" -# # generos = ['1/accion.jpg', '1/animacion.jpg', '1/aventura.jpg', '1/guerra.jpg', '1/ciencia%20ficcion.jpg', -# # '2/Film-Noir.jpg', '1/comedia.jpg', '0/Unknown.png', '1/documental.jpg', '1/drama.jpg', -# # '1/fantasia.jpg', '2/Kids.jpg', '2/Suspense.jpg', '1/musical.jpg', '1/romance.jpg', -# # '1/terror.jpg', '1/thriler.jpg', '1/western.jpg'] -# # if langf != "en": -# # try: -# # new_item.thumbnail = "%s/%s" % (images_predef, generos[len(itemlist)]) -# # except: -# # new_item.thumbnail = "%s1/%s.jpg" % (images_predef, titulo.lower()) -# # else: -# # new_item.thumbnail = "%s2/%s.jpg" % (images_predef, titulo) -# itemlist.append(new_item) -# elif "Temas" in item.title: -# bloques = scrapertools.find_multiple_matches(data, '<div class="panel-heading" id="topic_([^"]+)".*?' -# '<div class="list-group">(.*?)</div>') -# for letra, bloque in bloques: -# patron = 'href="([^"]+)">([^<]+)<.*?"badge">(\d+)</span>' -# matches = scrapertools.find_multiple_matches(bloque, patron) -# args = len(matches) + 1 -# action = "" -# folder = True -# if config.is_xbmc(): -# action = "move" -# folder = False -# itemlist.append(item.clone(title=letra, action=action, args=args, folder=folder)) -# for url, titulo, numero in matches: -# new_item = item.clone(action="temas_fa") -# topic_id = scrapertools.find_single_match(url, r"topic=(\d+)") -# new_item.url = "http://www.filmaffinity.com/%s/%s&attr=all" % ( -# langf, url.replace("&nodoc", "").replace("¬vse", "")) -# new_item.title = titulo + " (%s)" % numero -# itemlist.append(new_item) -# itemlist = thumb(itemlist) -# else: -# from datetime import datetime -# year = datetime.now().year -# for i in range(year, 1899, -1): -# new_item = item.clone(title=str(i), action="list_fa", args="top") -# genre = '' -# if item.contentType == "tvshow": genre = 'TV_SE' -# new_item.url = "http://m.filmaffinity.com/%s/topgen.php?genre=%s&country=&fromyear=%s&toyear=%s&nodoc=1" % (langf, genre, i, i) -# if item.contentType == "movie": new_item.url += "¬vse=1" -# itemlist.append(new_item) - -# return itemlist - - -# def temas_fa(item): -# # Movies and series by themes -# itemlist = [] - -# data = httptools.downloadpage(item.url).data -# data = re.sub(r"\n|\r|\t| ", "", data) -# data = re.sub(r"\s{2}", " ", data) -# item.infoLabels['plot'] = scrapertools.find_single_match(data, '<p class="description">([^<]+)</p>') - -# patron = '<div class="mc-poster">\s*<a href=".*?(\d+)\.html".*?src="([^"]+)".*?' \ -# 'href.*?>([^<]+)</a>\s*\((\d+)\)' -# matches = scrapertools.find_multiple_matches(data, patron) -# for url, thumb, title, year in matches: -# title = title.strip() -# new_item = item.clone(action="details_fa", contentType="movie", args="movie", ) -# new_item.url = "http://m.filmaffinity.com/%s/movie.php?id=%s" % (langf, url) -# new_item.thumbnail = thumb.replace("msmall", "large") -# if not new_item.thumbnail.startswith("http"): -# new_item.thumbnail = "http://www.filmaffinity.com" + new_item.thumbnail -# new_item.infoLabels["year"] = year -# new_item.title = title + " (%s)" % year -# if re.search(r'(?i)serie de tv|\(tv\)', title): -# new_item.contentType = "tvshow" -# new_item.args = "tv" -# new_item.contentTitle = re.sub(r'(?i)\(serie de tv\)|\(tv\)|\(c\)', '', title) -# itemlist.append(new_item) - -# next_page = scrapertools.find_single_match(data, '<a href="([^"]+)">>>') -# if next_page: -# if not next_page.startswith("http://www.filmaffinity.com"): -# next_page = "http://www.filmaffinity.com/%s/%s" % (langf, next_page) -# itemlist.append(Item(channel=item.channel, action=item.action, title=config.get_localized_string(70065), url=next_page)) - -# return itemlist - - -# def details_fa(item): -# itemlist = [] -# item.plot = "" -# rating = item.infoLabels['rating'] -# votos = item.infoLabels['votes'] - -# data = httptools.downloadpage(item.url).data -# data = re.sub(r"\n|\r|\t| ", "", data) -# data = re.sub(r"\s{2}", " ", data) - -# # The original title is argscted for possible searches in later tmdb -# orig_title = scrapertools.find_single_match(data, 'itemprop="datePublished">.*?<dd>([^<]+)</dd>').strip() -# if item.contentType == "movie": -# item.infoLabels['originaltitle'] = re.sub(r"(?i)\(TV Series\)|\(S\)|\(TV\)", "", orig_title) -# else: -# item.infoLabels['tvshowtitle'] = re.sub(r"(?i)\(TV Series\)|\(S\)|\(TV\)", "", orig_title) -# item_tmdb = item.clone() - -# if item.contentType == "movie": -# ob_tmdb = Tmdb(text_buscado=item_tmdb.contentTitle, year=item_tmdb.infoLabels['year'], search_type=item_tmdb.args, -# search_language=langt) -# if not ob_tmdb.result: -# ob_tmdb = Tmdb(text_buscado=item_tmdb.infoLabels['originaltitle'], year=item_tmdb.infoLabels['year'], -# search_type=item_tmdb.args, search_language=langt) -# else: -# ob_tmdb = Tmdb(text_buscado=item_tmdb.contentTitle, search_type=item_tmdb.args, search_language=langt) -# if not ob_tmdb.result: -# ob_tmdb = Tmdb(text_buscado=item_tmdb.infoLabels['tvshowtitle'], search_type=item_tmdb.args, -# search_language=langt) - -# if ob_tmdb.result: -# ob_tmdb = Tmdb(id_Tmdb=ob_tmdb.get_id(), search_type=item_tmdb.args, search_language=langt) -# item.infoLabels = ob_tmdb.get_infoLabels(item.infoLabels) - -# # If there is no synopsis in the chosen language, search in the alternative -# if not item.infoLabels["plot"]: -# item.infoLabels["plot"] = ob_tmdb.get_sinopsis(idioma_alternativo=langt_alt) - -# # The filmaffinity plot is concatenated to the tmdb plot if any -# plot = scrapertools.find_single_match(data, '<dd itemprop="description">(.*?)</dd>') -# plot = plot.replace("<br><br />", "\n") -# plot = scrapertools.decodeHtmlentities(plot).replace(" (FILMAFFINITY)", "") -# if plot and (item.infoLabels['plot'] and item.infoLabels['plot'] != plot): -# item.infoLabels['plot'] += " (TMDB)\n" + plot + " (FILMAFFINITY)" -# elif plot and not item.infoLabels['plot']: -# item.infoLabels['plot'] = plot - -# # It is searched and filled with the filmaffinity info to differentiate it from tmdb -# if not item.infoLabels['duration']: -# duration = scrapertools.find_single_match(data, '<dd itemprop="duration">(\d+)') -# if duration: -# item.infoLabels['duration'] = int(duration) * 60 - -# if not item.infoLabels['genre']: -# generos = scrapertools.find_multiple_matches(data, 'class="g-t-item">(.*?)</a>') -# genres = [] -# for g in generos: -# genres.append(scrapertools.htmlclean(g.strip())) -# item.infoLabels['genre'] = ", ".join(genres) - -# if not rating: -# rating = scrapertools.find_single_match(data, 'itemprop="ratingValue".*?>([^<]+)<') -# if rating: -# rating = float(rating.replace(",", ".")) -# elif ob_tmdb.result: -# rating = float(ob_tmdb.result.get('vote_average', 0)) -# item.infoLabels['rating'] = rating - -# if not votos: -# votos = scrapertools.find_single_match(data, 'itemprop="ratingCount".*?>([^<]+)<') -# if votos == "0" and ob_tmdb.result: -# votos = ob_tmdb.result.get('vote_count', '') -# item.infoLabels['votes'] = votos - -# if item.infoLabels['fanart']: -# item.fanart = item.infoLabels['fanart'] -# else: -# item.fanart = scrapertools.find_single_match(data, 'Imagen Principal.*?src: "([^"]+)"') -# if item.infoLabels['thumbnail']: -# item.thumbnail = item.infoLabels['thumbnail'] - -# if item.infoLabels['tagline']: -# itemlist.append(item.clone(title="--- %s ---" % item.infoLabels['tagline'], action="")) - -# title = item.contentType.replace("movie", config.get_localized_string(70283)).replace("tvshow", "serie") -# itemlist.append(item.clone(action="searching", title=config.get_localized_string(70069) % (title, item.contentTitle))) -# if item.infoLabels['originaltitle'] and item.contentTitle != item.infoLabels['originaltitle']: -# itemlist.append(item.clone(action="searching", contentTitle=item.infoLabels['originaltitle'], -# title=config.get_localized_string(70070) % item.infoLabels['originaltitle'])) - -# if langt != "es" and langt != "en" and item.infoLabels["tmdb_id"]: -# tmdb_lang = Tmdb(id_Tmdb=item.infoLabels["tmdb_id"], search_type=item.args, search_language=def_lang) -# if tmdb_lang.result.get("title") and tmdb_lang.result["title"] != item.contentTitle: -# tmdb_lang = tmdb_lang.result["title"] -# itemlist.append(item.clone(action="searching", title=config.get_localized_string(70066) % tmdb_lang, -# contentTitle=tmdb_lang)) - -# if item.contentType == "tvshow" and ob_tmdb.result: -# itemlist.append(item.clone(action="info_seasons", -# title=config.get_localized_string(70067) % item.infoLabels["number_of_seasons"])) -# if ob_tmdb.result: -# itemlist.append(item.clone(action="distribution", title=config.get_localized_string(70071), -# infoLabels={'tmdb_id': item.infoLabels['tmdb_id'], -# 'mediatype': item.contentType})) - -# if config.is_xbmc(): -# item.contextual = True -# trailer_url = scrapertools.find_single_match(data, -# '<a href="(?:http://m.filmaffinity.com|)/%s/movieTrailer\.php\?id=(\d+)"' % langf) -# if trailer_url: -# trailer_url = "http://www.filmaffinity.com/%s/evideos.php?movie_id=%s" % (langf, trailer_url) -# itemlist.append(item.clone(channel="trailertools", action="buscartrailer", title=config.get_localized_string(30162), -# filmaffinity=trailer_url)) - -# url_img = scrapertools.find_single_match(data, -# 'href="(?:http://m.filmaffinity.com|)(/%s/movieposters[^"]+)">' % langf) -# images = {} -# if ob_tmdb.result and ob_tmdb.result.get("images"): -# images['tmdb'] = ob_tmdb.result["images"] -# if url_img: -# images['filmaffinity'] = {} -# if images: -# itemlist.append(item.clone(action="imagenes", title=config.get_localized_string(70316), images=images, -# url=url_img, args="menu")) -# try: -# if item.contentType == "movie" and item.infoLabels["year"] < 2014: -# post_url = "https://theost.com/search/custom/?key=%s&year=%s&country=0&genre=0" % ( -# item.infoLabels['originaltitle'].replace(" ", "+"), item.infoLabels["year"]) -# url = "https://nl.hideproxy.me/includes/process.php?action=update" -# post = "u=%s&proxy_formdata_server=nl&allowCookies=1&encodeURL=1&encodePage=0&stripObjects=0&stripJS=0&go=" % urllib.quote( -# post_url) -# while True: -# response = httptools.downloadpage(url, post=post, follow_redirects=False) -# if response.headers.get("location"): -# url = response.headers["location"] -# post = "" -# else: -# data_music = response.data -# break - -# url_album = scrapertools.find_single_match(data_music, 'album(?:s|) on request.*?href="([^"]+)"') -# if url_album: -# url_album = "https://nl.hideproxy.me" + url_album -# itemlist.append( -# item.clone(action="musica_movie", title=config.get_localized_string(70317), url=url_album, -# )) -# except: -# pass - -# token_auth = config.get_setting("token_trakt", "trakt") -# if token_auth and ob_tmdb.result: -# itemlist.append(item.clone(title=config.get_localized_string(70323), action="menu_trakt")) -# # Actions if account is configured in FA (Vote and add / remove in lists) -# mivoto = scrapertools.find_single_match(data, 'bg-my-rating.*?>\s*(\d+)') -# itk = scrapertools.find_single_match(data, 'data-itk="([^"]+)"') -# folder = not config.is_xbmc() -# if mivoto: -# item.infoLabels["userrating"] = int(mivoto) -# new_item = item.clone(action="votar_fa", title=config.get_localized_string(70324) % mivoto, -# itk=itk, voto=int(mivoto), folder=folder) -# new_item.infoLabels["duration"] = "" -# itemlist.append(new_item) -# else: -# if itk: -# new_item = item.clone(action="votar_fa", title=config.get_localized_string(70325) % title, itk=itk, accion="votar", -# folder=folder) -# new_item.infoLabels["duration"] = "" -# itemlist.append(new_item) - -# if itk: -# itk = scrapertools.find_single_match(data, 'var itk="([^"]+)"') -# new_item = item.clone(action="acciones_fa", accion="lista_movie", itk=itk, -# title=config.get_localized_string(70326)) -# new_item.infoLabels["duration"] = "" -# itemlist.append(new_item) - -# # If you belong to a saga / collection -# if ob_tmdb.result: -# itemlist.append(item.clone(title="", action="", infoLabels={})) -# if ob_tmdb.result.get("belongs_to_collection"): -# new_item = item.clone(action="list_tmdb", ) -# saga = ob_tmdb.result["belongs_to_collection"] -# new_item.infoLabels["tmdb_id"] = saga["id"] -# if saga["poster_path"]: -# new_item.thumbnail = 'https://image.tmdb.org/t/p/original' + saga["poster_path"] -# if saga["backdrop_path"]: -# new_item.fanart = 'https://image.tmdb.org/t/p/original' + saga["backdrop_path"] -# new_item.search = {'url': 'collection/%s' % saga['id'], 'language': langt} -# new_item.title = config.get_localized_string(70327) % saga["name"] -# itemlist.append(new_item) - -# itemlist.append(item.clone(title=config.get_localized_string(70328) % title.capitalize(), action="list_tmdb", -# search={'url': '%s/%s/similar' % (item.args, item.infoLabels['tmdb_id']), -# 'language': langt, 'page': 1}, -# )) -# itemlist.append( -# item.clone(title=config.get_localized_string(70315), action="list_tmdb", -# search={'url': '%s/%s/recommendations' % (item.args, item.infoLabels['tmdb_id']), -# 'language': langt, 'page': 1}, )) - -# return itemlist - - -# def filter_fa(item): -# logger.debug() - -# from datetime import datetime -# list_controls = [] -# valores = {} - -# dict_values = None -# # Default / saved values ​​are used -# saved_values = config.get_setting("default_filter_filmaf_" + item.args, item.channel) -# if saved_values: -# dict_values = saved_values - -# list_controls.append({'id': 'yearsdesde', 'label': config.get_localized_string(70452), 'enabled': True, -# 'type': 'list', 'default': -1, 'visible': True}) -# list_controls.append({'id': 'yearshasta', 'label': config.get_localized_string(70453), 'enabled': True, -# 'type': 'list', 'default': -1, 'visible': True}) -# list_controls[0]['lvalues'] = [] -# list_controls[1]['lvalues'] = [] -# valores['years'] = [] -# year = datetime.now().year -# for i in range(1900, year + 1): -# list_controls[0]['lvalues'].append(str(i)) -# list_controls[1]['lvalues'].append(str(i)) -# valores['years'].append(str(i)) -# list_controls[0]['lvalues'].append(config.get_localized_string(70450)) -# list_controls[1]['lvalues'].append(config.get_localized_string(70450)) -# valores['years'].append('') - -# data = httptools.downloadpage("http://m.filmaffinity.com/%s/topgen.php" % langf).data -# data = re.sub(r"\n|\r|\t| ", "", data) -# data = re.sub(r"\s{2}", " ", data) -# if item.contentType == "movie": -# try: -# bloque = scrapertools.find_single_match(data, 'name="genre">.*?</option>(.*?)</select>') -# matches = scrapertools.find_multiple_matches(bloque, '<option value="([^"]+)">([^<]+)</option>') -# if matches: -# list_controls.append({'id': 'genero', 'label': config.get_localized_string(70467), 'enabled': True, -# 'type': 'list', 'default': -1, 'visible': True}) -# list_controls[2]['lvalues'] = [] -# list_controls[2]['lvalues'].append("Todos") -# valores['genero'] = [] -# valores['genero'].append('') -# for valor, titulo in matches: -# if valor == "TV_SE": -# continue -# list_controls[2]['lvalues'].insert(0, titulo) -# valores['genero'].insert(0, valor) - -# except: -# pass - -# try: -# bloque = scrapertools.find_single_match(data, 'name="country">.*?</option>(.*?)</select>') -# matches = scrapertools.find_multiple_matches(bloque, '<option value="([^"]+)"\s*>([^<]+)</option>') -# if matches: -# list_controls.append({'id': 'pais', 'label': config.get_localized_string(70466), 'enabled': True, -# 'type': 'list', 'default': -1, 'visible': True}) -# list_controls[-1]['lvalues'] = [] -# list_controls[-1]['lvalues'].append('Todos') -# valores['pais'] = [] -# valores['pais'].append('') -# for valor, titulo in matches: -# list_controls[-1]['lvalues'].insert(0, titulo) -# valores['pais'].insert(0, valor) -# except: -# pass - -# list_controls.append({'id': 'espacio', 'label': '', 'enabled': False, -# 'type': 'label', 'default': None, 'visible': True}) -# list_controls.append({'id': 'save', 'label': config.get_localized_string(70464), 'enabled': True, -# 'type': 'bool', 'default': False, 'visible': True}) - -# item.valores = valores -# return platformtools.show_channel_settings(list_controls=list_controls, dict_values=dict_values, -# caption=config.get_localized_string(70320), item=item, callback='filtered_fa') - - -# def filtered_fa(item, values): -# values_copy = values.copy() -# # Save the filter to be the one loaded by default -# if "save" in values and values["save"]: -# values_copy.pop("save") -# config.set_setting("default_filter_filmaf_" + item.args, values_copy, item.channel) - -# yeard = item.valores["years"][values["yearsdesde"]] -# yearh = item.valores["years"][values["yearshasta"]] -# pais = item.valores["pais"][values["pais"]] -# if item.contentType == "movie": -# genero = item.valores["genero"][values["genero"]] -# else: -# genero = "TV_SE" - -# item.url = 'http://m.filmaffinity.com/%s/topgen.php?genre=%s&country=%s&fromyear=%s&toyear=%s&nodoc=1' \ -# % (langf, genero, pais, yeard, yearh) -# if item.contentType == "movie": -# item.url += "¬vse=1" -# item.action = "list_fa" - -# return list_fa(item) - - -# def login_fa(): -# logger.debug() - -# try: -# user = config.get_setting("usuariofa", "tvmoviedb") -# password = config.get_setting("passfa", "tvmoviedb") -# userid = config.get_setting("userid", "tvmoviedb") -# if user == "" or password == "": -# return False, config.get_localized_string(70329) -# data = httptools.downloadpage("http://m.filmaffinity.com/%s" % langf).data -# if "modal-menu-user" in data and userid: -# return True, "" - -# post = "postback=1&rp=&username=%s&password=%s&rememberme=on" % (user, password) -# data = httptools.downloadpage("https://m.filmaffinity.com/%s/account.ajax.php?action=login" % langf, post=post).data - -# if "Invalid username" in data: -# logger.error("Error en el login") -# return False, config.get_localized_string(70330) -# else: -# post = "name=user-menu&url=http://m.filmaffinity.com/%s/main.php" % langf -# data = httptools.downloadpage("http://m.filmaffinity.com/%s/tpl.ajax.php?action=getTemplate" % langf, -# post=post).data -# userid = scrapertools.find_single_match(data, 'id-user=(\d+)') -# if userid: -# config.set_setting("userid", userid, "tvmoviedb") -# logger.debug("Login correcto") -# return True, "" -# except: -# import traceback -# logger.error(traceback.format_exc()) -# return False, config.get_localized_string(70331) - - -# def cuenta_fa(item): -# # Filmaffinity account menu -# itemlist = [] -# login, message = login_fa() -# if not login: -# itemlist.append(item.clone(action="", title=message, )) -# else: -# userid = config.get_setting("userid", "tvmoviedb") -# itemlist.append(item.clone(action="acciones_fa", title=config.get_localized_string(70332), accion="votos", -# url="http://m.filmaffinity.com/%s/user_ratings.php?id-user=%s" % (langf, userid))) -# itemlist.append(item.clone(action="acciones_fa", title=config.get_localized_string(70057), accion="listas", -# url="http://m.filmaffinity.com/%s/mylists.php" % langf)) - -# return itemlist - - -# def acciones_fa(item): -# # Actions account filmaffinity, vote, view lists or add / remove from list -# itemlist = [] - -# if item.accion == "votos" or item.accion == "lista": -# data = httptools.downloadpage(item.url).data -# data = re.sub(r"\n|\r|\t| ", "", data) -# data = re.sub(r"\s{2}", " ", data) -# bloques = scrapertools.find_multiple_matches(data, -# 'list-group-item(?:[^>]+>\s*<a| rip)(.*?</div>)\s*</div>\s*<div') -# for bloque in bloques: -# patron = 'href="([^"]+)".*?data-src="([^"]+)".*?mc-title.*?>([^<]+)' \ -# '<small>\((\d+)\)</small>.*?(?:<div class="avgrat-box in-block ">' \ -# '([^<]+)</div>\s*<small class="ratcount-box">(.*?)\s*<|</li>).*?' -# matches = scrapertools.find_multiple_matches(bloque, patron) -# mivoto = scrapertools.find_single_match(bloque, 'bg-my-rating[^>]+>(?:\s*<strong>|)([^<]+)<') -# for url, thumb, title, year, rating, votos in matches: -# new_item = item.clone(action="details_fa", ) -# if not url.startswith("http://m.filmaffinity"): -# new_item.url = "http://m.filmaffinity.com" + url -# else: -# new_item.url = url - -# new_item.infoLabels["year"] = year -# rating = rating.replace(",", ".") -# new_item.infoLabels["rating"] = float(rating) -# new_item.infoLabels["votes"] = votos.replace(".", "") -# if mivoto.isdigit(): -# new_item.infoLabels["userrating"] = int(mivoto) -# new_item.thumbnail = thumb.replace("msmall", "large") -# if not new_item.thumbnail.startswith("http"): -# new_item.thumbnail = "http://m.filmaffinity.com" + new_item.thumbnail - -# if re.search(r'(?i)serie de tv|\(tv\)', title): -# new_item.contentType = "tvshow" -# new_item.args = "tv" -# new_item.title = title.strip() + " (%s) %s/]%s" % ( -# year, rating, mivoto) -# new_item.contentTitle = title.strip() -# itemlist.append(new_item) -# elif item.accion == "listas": -# orderby = config.get_setting("orderfa", "tvmoviedb") -# data = httptools.downloadpage(item.url).data -# data = re.sub(r"\n|\r|\t| ", "", data) -# data = re.sub(r"\s{2}", " ", data) -# patron = 'list-group-item rip.*?href="([^"]+)".*?<strong>([^<]+)</strong>.*?<em>([^<]+)</em>' \ -# '.*?(?:<div class="ls-imgs">(.*?)</a>|</a>)' -# matches = scrapertools.find_multiple_matches(data, patron) -# for url, title, content, imgs in matches: -# new_item = item.clone(accion="lista", ) -# if not url.startswith("http://m.filmaffinity.com"): -# new_item.url = "http://m.filmaffinity.com%s&orderby=%s" % (url, orderby) -# else: -# new_item.url = "%s&orderby=%s" % (url, orderby) -# new_item.title = title + " (%s)" % (content) -# if imgs: -# imagenes = scrapertools.find_multiple_matches(imgs, 'data-src="([^"]+)"') -# from random import randint -# random = randint(0, len(imagenes) - 1) -# new_item.thumbnail = imagenes[random].replace("msmall", "large") -# itemlist.append(new_item) -# elif item.accion == "lista_movie": -# movieid = item.url.rsplit("=", 1)[1] -# url = "http://m.filmaffinity.com/%s/edtmovielists.php?movie_id=%s" % (langf, movieid) -# data = httptools.downloadpage(url).data -# patron = 'data-list-id="([^"]+)"(.*?)<div class="in-block list-name"><strong>([^<]+)<' -# matches = scrapertools.find_multiple_matches(data, patron) -# for listid, chequeo, title in matches: -# new_item = item.clone(folder=not config.is_xbmc()) -# new_item.infoLabels["duration"] = "" -# new_item.listid = listid -# if "checked" in chequeo: -# new_item.title = "[COLOR %s]%s[/COLOR] %s" % ("green", u"\u0474".encode('utf-8'), title) -# new_item.accion = "removeMovieFromList" -# else: -# new_item.title = "%s %s" % ( u"\u04FE".encode('utf-8'), title) -# new_item.accion = "addMovieToList" -# itemlist.append(new_item) -# new_item = item.clone(action="newlist", title=config.get_localized_string(70333), ) -# new_item.infoLabels["duration"] = "" -# itemlist.append(new_item) -# else: -# url = "http://filmaffinity.com/%s/movieslist.ajax.php" % langf -# movieid = item.url.rsplit("=", 1)[1] -# post = "action=%s&listId=%s&movieId=%s&itk=%s" % (item.accion, item.listid, movieid, item.itk) -# data = jsontools.load(httptools.downloadpage(url, post=post).data) -# if not item.folder: -# import xbmc -# return xbmc.executebuiltin("Container.Refresh") -# else: -# if data["result"] == 0: -# title = config.get_localized_string(70334) -# else: -# title = config.get_localized_string(70335) -# itemlist.append(item.clone(action="", title=title)) - -# return itemlist - - -# def votar_fa(item): -# # Window to select the vote -# logger.debug() - -# list_controls = [] -# valores = {} -# dict_values = None -# if item.voto: -# dict_values = {'voto': item.voto} -# list_controls.append({'id': 'voto', 'label': config.get_localized_string(70468), 'enabled': True, -# 'type': 'list', 'default': 0, 'visible': True}) -# list_controls[0]['lvalues'] = ['No vista'] -# valores['voto'] = ["-1"] -# for i in range(1, 11): -# list_controls[0]['lvalues'].append(str(i)) -# valores['voto'].append(i) - -# item.valores = valores -# return platformtools.show_channel_settings(list_controls=list_controls, dict_values=dict_values, -# caption=config.get_localized_string(70336) % item.contentTitle, item=item, -# callback='callback_voto') - - -# def callback_voto(item, values): -# item.voto = item.valores["voto"][values["voto"]] -# item.action = "acciones_fa" -# movieid = item.url.rsplit("=", 1)[1] -# post = "id=%s&rating=%s&itk=%s&action=rate" % (movieid, item.voto, item.itk) -# data = jsontools.load(httptools.downloadpage("http://filmaffinity.com/%s/ratingajax.php" % langf, post=post).data) - -# if not item.folder: -# import xbmc -# return xbmc.executebuiltin("Container.Refresh") -# else: -# if data["result"] == 0: -# title = config.get_localized_string(70337) -# else: -# title = config.get_localized_string(70335) -# itemlist.append(item.clone(action="", title=title)) -# return itemlist - - -# def newlist(item): -# # Creation of new list in filmaffinity -# itemlist = [] -# if item.accion == "lista": -# location = httptools.downloadpage(item.url, only_headers=True).headers["location"] -# data = httptools.downloadpage("http://m.filmaffinity.com" + location).data -# itemlist.append(item.clone(action="", title=config.get_localized_string(70338))) -# else: -# url = "http://m.filmaffinity.com/%s/addlist.php?rp=%s" % (langf, item.url) -# data = httptools.downloadpage(url).data -# data = re.sub(r"\n|\r|\t| |\s{2}", "", data) - -# patron = 'data-list-id="[^"]+" href="([^"]+)"><[^>]+><div class="col-xs-10">' \ -# '([^<]+)</div><div[^>]+><div type="button" class="btn btn-primary">' -# matches = scrapertools.find_multiple_matches(data, patron) -# for scrapedurl, title in matches: -# scrapedurl = "http://m.filmaffinity.com" + scrapedurl -# itemlist.append(item.clone(title=title, url=scrapedurl, accion="lista")) - -# return itemlist - - -##-------------------- IMAGE LISTINGS ------------------------## -def imagenes(item): - itemlist = [] - - - if item.args == "menu": - item.folder = not config.is_xbmc() - if "tmdb" in item.images: - itemlist.append(item.clone(title="Tmdb", args="")) - itemlist.append(item.clone(title="Fanart.Tv", args="")) - if "imdb" in item.images: - itemlist.append(item.clone(title="Imdb", args="")) - # if "filmaffinity" in item.images: - # itemlist.append(item.clone(title="Filmaffinity", args="")) - if "myanimelist" in item.images: - images = match(item.url + "/pics", cookies=False, patron=R'<div class="picSurround"><a href="([^"]+)" title="([^"]+)"').matches - if images: - for thumb, title in images: - item.images["myanimelist"].append([thumb, title]) - itemlist.append(item.clone(title="MyAnimeList", args="")) - - return itemlist - - if "Fanart" in item.title: - try: - item, resultado = fanartv(item) - except: - resultado = None - - if not resultado: - itemlist.append(item.clone(title=config.get_localized_string(70338), action="")) - return itemlist - # elif "Filmaffinity" in item.title: - # try: - # url = "http://m.filmaffinity.com" + item.url - # data = httptools.downloadpage(url).data - # matches = scrapertools.find_multiple_matches(data, 'data-src="([^"]+)" alt="[^-]+\s*([^"]+)"') - # if matches: - # item.images["filmaffinity"] = matches - # else: - # item.images.pop("filmaffinity", None) - # except: - # itemlist.append(item.clone(title=config.get_localized_string(70339), action="")) - # return itemlist - elif "Imdb" in item.title: - try: - from core import httptools - data = jsontools.load(httptools.downloadpage(item.images["imdb"]["url"], cookies=False).data) - item.images["imdb"].pop("url") - if data.get("allImages"): - item.images["imdb"] = data["allImages"] - else: - item.images.pop("imdb", None) - except: - itemlist.append(item.clone(title=config.get_localized_string(70339), action="")) - return itemlist - - if item.images: - from platformcode import infoplus - for key, value in item.images.items(): - if key == "tmdb" and "Tmdb" in item.title: - if item.folder: - for Type, child in value.iteritems(): - for i, imagen in enumerate(child): - thumb = 'https://image.tmdb.org/t/p/w500' + imagen["file_path"] - fanart = 'https://image.tmdb.org/t/p/original' + imagen["file_path"] - title = " %s %s [%sx%s]" % (Type.capitalize(), i + 1, imagen["width"], imagen["height"]) - itemlist.append(Item(channel=item.channel, action="", thumbnail=thumb, fanart=fanart, - title=title, infoLabels=item.infoLabels)) - else: - imagesWindow = infoplus.ImagesWindow(tmdb=value).doModal() - - elif key == "fanart.tv": - if item.folder: - for Type, child in value.iteritems(): - for i, imagen in enumerate(child): - thumb = imagen["url"].replace("/fanart/", "/preview/") - fanart = imagen["url"] - title = " %s %s [%s]" % (Type.capitalize(), i + 1, imagen["lang"]) - itemlist.append(Item(channel=item.channel, action="", thumbnail=thumb, fanart=fanart, - title=title, infoLabels=item.infoLabels)) - else: - imagesWindow = infoplus.ImagesWindow(fanartv=value).doModal() - - # elif key == "filmaffinity" and "Filmaffinity" in item.title: - # if item.folder: - # for thumb, title in value: - # thumb = thumb.replace("-s200", "-large") - # itemlist.append(Item(channel=item.channel, action="", thumbnail=thumb, fanart=thumb, - # title=title, infoLabels=item.infoLabels)) - # else: - # imagesWindow = infoplus.images(fa=value).doModal() - - elif key == "imdb" and "Imdb" in item.title: - if item.folder: - for imagen in value: - thumb = imagen["msrc"] - fanart = imagen["src"] - title = imagen["altText"] - itemlist.append( - Item(channel=item.channel, action="", thumbnail=thumb, fanart=fanart, title=title, - infoLabels=item.infoLabels)) - else: - imagesWindow = infoplus.ImagesWindow(imdb=value).doModal() - - elif key == "myanimelist" and "MyAnimeList" in item.title: - if item.folder: - for imagen, title in value: - itemlist.append( - Item(channel=item.channel, action="", thumbnail=imagen, fanart=imagen, title=title, - infoLabels=item.infoLabels)) - else: - imagesWindow = infoplus.ImagesWindow(mal=value).doModal() - - return itemlist - - -def fanartv(item): - headers = [['Content-Type', 'application/json']] - id_search = item.infoLabels['tmdb_id'] - if item.contentType == "tvshow" and id_search: - search = {'url': 'tv/%s/external_ids' % item.infoLabels['tmdb_id'], 'language': langt} - ob_tmdb = Tmdb(discover=search, search_language=langt) - id_search = ob_tmdb.result.get("tvdb_id") - - resultado = False - if id_search: - if item.contentType == "movie": - url = "http://webservice.fanart.tv/v3/movies/%s?api_key=cab16e262d72fea6a6843d679aa10300" \ - % item.infoLabels['tmdb_id'] - else: - url = "http://webservice.fanart.tv/v3/tv/%s?api_key=cab16e262d72fea6a6843d679aa10300" % id_search - #data = jsontools.load(httptools.downloadpage(url, headers=headers, replace_headers=True).data) - data = jsontools.load(match(url, headers=headers).data) - if data and not "error message" in data: - item.images['fanart.tv'] = {} - for key, value in data.items(): - if key not in ["name", "tmdb_id", "imdb_id", "thetvdb_id"]: - item.images['fanart.tv'][key] = value - resultado = True - - return item, resultado - - -##-------------------- SECTION TRAKT.TV ------------------------## -def auth_trakt(item): - return trakt_tools.auth_trakt() - - -def menu_trakt(item): - # Menu with trakt account actions (views, watchlist, collection) - itemlist = [] - token_auth = config.get_setting("token_trakt", "trakt") - Type = item.args.replace("tv", "show") + "s" - title = item.contentType.replace("movie", config.get_localized_string(70283)).replace("tvshow", config.get_localized_string(30123)) - try: - result = acciones_trakt(item.clone(url="sync/watched/%s" % Type)) - post = {Type: [{"ids": {"tmdb": item.infoLabels["tmdb_id"]}}]} - if '"tmdb":%s' % item.infoLabels["tmdb_id"] in result: itemlist.append(item.clone(title=config.get_localized_string(70341) % title, action="acciones_trakt", url="sync/history/remove", post=post)) - else: itemlist.append(item.clone(title=config.get_localized_string(70342) % title, action="acciones_trakt", url="sync/history", post=post)) - except: - pass - - try: - result = acciones_trakt(item.clone(url="sync/watchlist/%s" % Type)) - post = {Type: [{"ids": {"tmdb": item.infoLabels["tmdb_id"]}}]} - if '"tmdb":%s' % item.infoLabels["tmdb_id"] in result: itemlist.append(item.clone(title=config.get_localized_string(70343) % title, action="acciones_trakt", url="sync/watchlist/remove", post=post)) - else: itemlist.append(item.clone(title=config.get_localized_string(70344) % title, action="acciones_trakt", url="sync/watchlist", post=post)) - except: - pass - - try: - result = acciones_trakt(item.clone(url="sync/collection/%s" % Type)) - post = {Type: [{"ids": {"tmdb": item.infoLabels["tmdb_id"]}}]} - if '"tmdb":%s' % item.infoLabels["tmdb_id"] in result: itemlist.append(item.clone(title=config.get_localized_string(70345) % title, action="acciones_trakt", url="sync/collection/remove", post=post)) - else: itemlist.append(item.clone(title=config.get_localized_string(70346) % title, action="acciones_trakt", url="sync/collection", post=post)) - except: - pass - - return itemlist - - -def acciones_trakt(item): - from core import httptools - token_auth = config.get_setting("token_trakt", "trakt") - itemlist = [] - item.contentType = item.args.replace("show", "tvshow") - client_id = "502bd1660b833c1ae69828163c0848e84e9850061e5529f30930e7356cae73b1" - headers = [['Content-Type', 'application/json'], ['trakt-api-key', client_id], ['trakt-api-version', '2']] - if token_auth: headers.append(['Authorization', "Bearer %s" % token_auth]) - - post = None - if item.post: post = jsontools.dump(item.post) - - url = "http://api.trakt.tv/%s" % item.url - data = httptools.downloadpage(url, post=post, headers=headers) - if data.code == "401": - trakt_tools.token_trakt(item.clone(args="renew")) - token_auth = config.get_setting("token_trakt", "trakt") - headers[3][1] = "Bearer %s" % token_auth - data = httptools.downloadpage(url, post=post, headers=headers) - - data = data.data - if data and "sync" in item.url: - if not item.post: - return data - else: - data = jsontools.load(data) - if "not_found" in data: return platformtools.dialog_notification("Trakt", config.get_localized_string(70347)) - else: return platformtools.dialog_notification("Trakt", config.get_localized_string(70348)) - elif data and "recommendations" in item.url: - data = jsontools.load(data) - ratings = [] - try: - for i, entry in enumerate(data): - logger.debug('ENTRY:',entry) - if i <= item.pagina: continue - # try: entry = entry[item.args] - # except: pass - new_item = item.clone(action="details") - new_item.title = typo(entry["title"], 'bold') + typo(entry["year"],'_ () bold') - new_item.infoLabels["tmdb_id"] = entry["ids"]["tmdb"] - try: ratings.append(entry["rating"]) - except: ratings.append(0.0) - itemlist.append(new_item) - if i == item.pagina + 20: - itemlist.append(item.clone(title=config.get_localized_string(70065), pagina=item.pagina + 20)) - break - - from core import tmdb - tmdb.set_infoLabels_itemlist(itemlist[:-1], True) - for i, new_item in enumerate(itemlist[:-1]): - if new_item.infoLabels["title"]: new_item.title = typo(new_item.infoLabels["title"] + " (%s)" % new_item.infoLabels["year"], 'bold') - if ratings[i]: new_item.title += typo("Trakt: %.2f | Tmdb: %.2f" % (ratings[i], new_item.infoLabels["rating"]), '_ [] color kod') - except: - pass - - elif data and not item.url.endswith("lists"): - data = jsontools.load(data) - if data and "page=1" in item.url and item.order: - valores = {'rank': config.get_localized_string(70003), 'added': config.get_localized_string(70469), 'title': config.get_localized_string(60320), 'released': config.get_localized_string(70470), - 'runtime': config.get_localized_string(70471), 'popularity': config.get_localized_string(70472), 'percentage': config.get_localized_string(70473), - 'votes': config.get_localized_string(70474), 'asc': config.get_localized_string(70475), 'desc': config.get_localized_string(70476)} - orden = valores[item.order] + " " + valores[item.how] - ratings = [] - try: - for entry in data: - # try: entry = entry[item.args] - # except: pass - new_item = item.clone(action="details") - if 'show' in entry and 'show' in item.args: - entry = entry['show'] - new_item.args = 'show' - new_item.contentType = 'tvshow' - elif 'movie' in entry and 'movie' in item.args: - entry = entry['movie'] - new_item.args = 'movie' - new_item.contentType = 'movie' - elif 'show' in item.args: - new_item.args = 'show' - new_item.contentType = 'tvshow' - else: - new_item.args = 'movie' - new_item.contentType = 'movie' - new_item.title = entry["title"] + " (%s)" % entry["year"] - new_item.infoLabels["tmdb_id"] = entry["ids"]["tmdb"] - try: ratings.append(entry["rating"]) - except: ratings.append("") - itemlist.append(new_item) - - from core import tmdb - if "page=1" in item.url and item.order: - tmdb.set_infoLabels_itemlist(itemlist[1:], True) - for i, new_item in enumerate(itemlist[1:]): - if new_item.infoLabels["title"]: new_item.title = typo(new_item.infoLabels["title"] + ' ' + new_item.infoLabels["year"], 'bold') - if ratings[i]: new_item.title += typo("Trakt: %.2f | Tmdb: %.2f" % (ratings[i], new_item.infoLabels["rating"]), '_ [] color kod') - else: - tmdb.set_infoLabels_itemlist(itemlist, True) - for i, new_item in enumerate(itemlist): - if new_item.infoLabels["title"]: new_item.title = typo(new_item.infoLabels["title"] + " (%s)" % new_item.infoLabels["year"], 'bold') - if ratings[i]: new_item.title += typo("Trakt: %.2f | Tmdb: %.2f" % (ratings[i], new_item.infoLabels["rating"]), '_ [] color kod') - except: - import traceback - logger.error(traceback.format_exc()) - - if "page" in item.url and len(itemlist) == 20: - page = match(item.url, patron=r'page=(\d+)').match - page_new = int(page) + 1 - url = item.url.replace("page=" + page, "page=" + str(page_new)) - itemlist.append(item.clone(title=typo(config.get_localized_string(30992), 'color kod bold'), url=url, thumbnail=thumb())) - else: - data = jsontools.load(data) - for entry in data: - new_item = item.clone() - new_item.title = typo(entry["name"],'bold') + typo(str(entry["item_count"]),'color kod bold _ []') - new_item.infoLabels["plot"] = entry.get("description") - new_item.url = "users/me/lists/%s/items/?page=1&limit=20&extended=full" % entry["ids"]["trakt"] - new_item.order = entry.get("sort_by") - new_item.how = entry.get("sort_how") - itemlist.append(new_item) - - return itemlist - - -def order_list(item): - logger.debug() - - list_controls = [] - valores1 = ['rating', 'added', 'title', 'released', 'runtime', 'popularity', 'percentage', 'votes'] - valores2 = ['asc', 'desc'] - - dict_values = {'orderby': valores1.index(item.order), 'orderhow': valores2.index(item.how)} - - list_controls.append({'id': 'orderby', 'label': config.get_localized_string(70455), 'enabled': True, - 'type': 'list', 'default': 0, 'visible': True}) - list_controls.append({'id': 'orderhow', 'label': 'De forma:', 'enabled': True, - 'type': 'list', 'default': 0, 'visible': True}) - list_controls[0]['lvalues'] = ['rank', 'added', 'title', 'released', 'runtime', 'popularity', 'percentage', 'votes'] - list_controls[1]['lvalues'] = ['asc', 'desc'] - return platformtools.show_channel_settings(list_controls=list_controls, dict_values=dict_values, caption=config.get_localized_string(70320), item=item, callback='order_trakt') - - -def order_trakt(item, values): - valores1 = ['rank', 'added', 'title', 'released', 'runtime', 'popularity', 'percentage', 'votes'] - valores2 = ['asc', 'desc'] - orderby = valores1[values["orderby"]] - item.order = orderby - orderhow = valores2[values["orderhow"]] - item.how = orderhow - - item.action = "acciones_trakt" - - return acciones_trakt(item) - - -##-------------------- MYANIMELIST SECTION ------------------------## -def top_mal(item): - # For the main menus of movie tops / series / ova - itemlist = [] - # data = httptools.downloadpage(item.url, cookies=False).data - # data = re.sub(r"\n|\r|\t| ", "", data) - # data = re.sub(r"\s{2}", " ", data) - - patron = r'<td class="title al va-t word-break">\s*<a.*?href="([^"]+)"[^>]+>\s*<img.*?src="([^"]+).*?<div class="di-ib clearfix">.*?href.*?>([^<]+)<.*?<div class="information di-ib mt4">(.*?)<br>.*?(\d{4}|-).*?<span class="text.*?>(.*?)</span>' - matches = match(item, patron=patron) - for url, thumbnail, title, info, year, rating in matches.matches: - new_item = item.clone(action="details_mal", url=url) - info = info.strip() - new_item.thumbnail = thumbnail.replace("r/50x70/", "") + "l.jpg" - year = year.replace("-", "") - if year: - new_item.infoLabels["year"] = year - new_item.title = typo(title.strip(), 'bold') - if not year in title and year: - new_item.title += typo(year,'_ () bold') - if rating != "N/A": - new_item.infoLabels["rating"] = float(rating) - new_item.title += typo(rating, '_ [] color kod bold') - # if not item.args: - info = info.replace("(1 eps)", "").replace("TV ", "") - if "Movie" in info or "Special" in info: - new_item.contentType = "movie" - new_item.args = "movie" - else: - new_item.contentType = "tvshow" - new_item.args = "tv" - new_item.show = title.strip() - if '(' in info: - new_item.title += ' (' + info.split("(", 1)[1] - new_item.contentTitle = title.strip() - itemlist.append(new_item) - - next_page = match(matches.data, patron=r'limit=(\d+)" class="link-blue-box next">').match - if next_page: - next_page = item.url.rsplit("=", 1)[0] + "=%s" % next_page - itemlist.append(item.clone(title=typo(config.get_localized_string(30992), 'color kod bold'), url=next_page, thumbnail=thumb())) - - return itemlist - - -def details_mal(item): - itemlist = [] - - cookie_session = get_cookie_value() - header_mal = {'Cookie': '%s search_sort_anime=score; search_view=tile; is_logged_in=1' % cookie_session} - data = match(item.url, headers=header_mal, cookies=False).data - - item.contentTitle = item.contentTitle.replace("(TV)", "").replace("(Movie)", "") - item.fanart = default_fan - item.infoLabels["plot"] = "" - - title_mal = item.contentTitle - if not item.args: - args = match(data, patron=r'Type:</span>.*?>([^<]+)</a>').match.lower() - item.type = args - if args == "movie" or args == "special": - item.args = "movie" - item.contentType = "movie" - else: - item.args = "tv" - item.contentType = "tvshow" - - if item.infoLabels['rating'] != "0.0": - rating = item.infoLabels['rating'] - else: - rating = match(data, patron=r'<span itemprop="ratingValue">(\d.\d+)</span>').match - - if not item.infoLabels["year"]: - item.infoLabels["year"] = match(data, patron=r'>Aired:</span>.*?(\d{4})').match - - eng_title = match(data, patron=r'English:</span> ([^<]+)</div>').match.strip() - item_tmdb = item.clone() - - if item.contentType == "movie": - ob_tmdb = Tmdb(text_buscado=item_tmdb.contentTitle, year=item_tmdb.infoLabels['year'], search_type=item_tmdb.args, search_language=langt) - if not ob_tmdb.result and eng_title: - ob_tmdb = Tmdb(text_buscado=eng_title, year=item_tmdb.infoLabels['year'], search_type=item_tmdb.args, search_language=langt) - if not ob_tmdb.result and ("Special (" in item.title or item.type == "special"): - item_tmdb.args = "tv" - search = {'url': 'search/tv', 'language': langt, 'query': item_tmdb.contentTitle, 'first_air_date': item_tmdb.infoLabels["year"]} - ob_tmdb = Tmdb(discover=search, search_type=item_tmdb.args, search_language=langt) - else: - search = {'url': 'search/tv', 'language': langt, 'query': eng_title, 'first_air_date': item_tmdb.infoLabels["year"]} - ob_tmdb = Tmdb(discover=search, search_type=item_tmdb.args, search_language=langt) - if not ob_tmdb.result and eng_title: - search['query'] = eng_title - ob_tmdb = Tmdb(discover=search, search_type=item_tmdb.args, search_language=langt) - if not ob_tmdb.result and ("OVA (" in item.title or item.type == "ova"): - item_tmdb.args = "movie" - ob_tmdb = Tmdb(text_buscado=item_tmdb.contentTitle, search_type=item_tmdb.args, search_language=langt, year=item_tmdb.infoLabels['year']) - - if ob_tmdb.result: - ob_tmdb = Tmdb(id_Tmdb=ob_tmdb.get_id(), search_type=item_tmdb.args, search_language=langt) - item.infoLabels = ob_tmdb.get_infoLabels(item.infoLabels) - - # Myanimelist synopsis is concatenated with that of tmdb if any - plot = match(data, patron=r'<span itemprop="description">(.*?)</span>').match - plot = plot.replace("<br />", "\n").replace("<i>", "[I]").replace("</i>", "[/I]") - plot = decodeHtmlentities(plot) - if plot and (item.infoLabels['plot'] and item.infoLabels['plot'] != plot): item.infoLabels['plot'] += " (TMDB)\n\n" + plot + " (MYANIMELIST)" - elif plot and not item.infoLabels['plot']: item.infoLabels['plot'] = plot - - if not item.infoLabels['duration']: - try: - horas, min1, min2 = match(data, patron=r'Duration:</span>\s*(?:(\d+) hr\. (\d+) min|(\d+) min)').match - if horas: horas = int(horas) * 360 - else: horas = 0 - if not min1: min1 = min2 - item.infoLabels['duration'] = horas + (int(min1) * 60) - except: - pass - - # Myanimelist info overwrites tmdb info - generos = match(data, patron=r'Genres:</span>(.*?)</div>').match - if generos: item.infoLabels['genre'] = htmlclean(generos) - - item.infoLabels['rating'] = float(rating) if rating in item.infoLabels else 0 - votos = match(data, patron=r'<span itemprop="ratingCount">([^<]+)<').match - item.infoLabels['votes'] = votos.replace(",", "") - - if item.infoLabels['fanart']: item.fanart = item.infoLabels['fanart'] - if item.infoLabels['thumbnail']: item.thumbnail = item.infoLabels['thumbnail'] - if not item.thumbnail: item.thumbnail = match(data, patron=r'/pics">.*?<img src="([^"]+)"').match.replace(".jpg", "l.jpg") - if config.get_setting('new_search'): - itemlist.append(item.clone(action="Search", channel='globalsearch', title=config.get_localized_string(70350) % title_mal, text=title_mal, mode=item.args.replace("tv", "tvshow"), contentType=item.args.replace("tv", "tvshow"), thumbnail=thumb('search'), folder=False)) - if item.infoLabels["title"] and title_mal != item.infoLabels["title"]: - itemlist.append(item.clone(action="Search", channel='globalsearch', search_text=item.infoLabels["title"], title=config.get_localized_string(70351) % item.infoLabels["title"], mode=item.args.replace("tv", "tvshow"), contentType=item.args.replace("tv", "tvshow"), thumbnail=thumb('search'), folder=False)) - - if eng_title and item.contentTitle != eng_title and title_mal != eng_title: - itemlist.append(item.clone(action="Search", channel='globalsearch', search_text=eng_title, title=config.get_localized_string(70352) % eng_title, mode=item.args.replace("tv", "tvshow"), contentType=item.args.replace("tv", "tvshow"), thumbnail=thumb('search'), folder=False)) - else: - itemlist.append(item.clone(action="new_search", channel='search', title=config.get_localized_string(70350) % title_mal, search_text=title_mal, args=item.args.replace("tv", "anime"), thumbnail=thumb('search'))) - if item.infoLabels["title"] and title_mal != item.infoLabels["title"]: - itemlist.append(item.clone(action="new_search", channel='search', search_text=item.infoLabels["title"], title=config.get_localized_string(70351) % item.infoLabels["title"], thumbnail=thumb('search'))) - - if eng_title and item.contentTitle != eng_title and title_mal != eng_title: - itemlist.append(item.clone(action="new_search", channel='search', search_text=eng_title, title=config.get_localized_string(70352) % eng_title, thumbnail=thumb('search'))) - - if item_tmdb.args == "tv" and ob_tmdb.result and "number_of_seasons" in item.infoLabels: - itemlist.append(item.clone(action="info_seasons", title=config.get_localized_string(70067) % item.infoLabels["number_of_seasons"], thumbnail=thumb('info'))) - - itemlist.append(item.clone(action="videos_mal", title=config.get_localized_string(70353), url=item.url + "/video", thumbnail=thumb('trailer'))) - - # Option to see the info of characters and voiceovers / filming equipment - if not "No characters or voice actors" in data and not "No staff for this anime" in data: - itemlist.append(item.clone(action="staff_mal", title=config.get_localized_string(70354), url=item.url + "/characters", thumbnail=thumb('star'))) - if config.is_xbmc(): - item.contextual = True - itemlist.append(item.clone(channel="trailertools", action="buscartrailer", title=config.get_localized_string(30162), thumbnail=thumb('trailer'))) - - images = {} - if ob_tmdb.result and ob_tmdb.result.get("images"): - images['tmdb'] = ob_tmdb.result["images"] - images['myanimelist'] = [] - itemlist.append(item.clone(action="imagenes", title=config.get_localized_string(70316), images=images, args="menu", thumbnail=thumb('image'))) - - try: - title_search = re.sub(r'[^0-9A-z]+', ' ', title_mal) - post = "searching=%s&button=Search" % urllib.quote(title_search) - data_music = httptools.downloadpage("http://www.freeanimemusic.org/song_search.php", post=post).data - if not "NO MATCHES IN YOUR SEARCH" in data_music: - itemlist.append(item.clone(action="musica_anime", title=config.get_localized_string(70317), post=post, thumbnail=thumb('music'))) - except: - pass - - score = match(data, patron=r'id="myinfo_score".*?selected" value="(\d+)"').match - if score != "0": - score = "Valued:%s" % (score) - else: - score = "Vote" - if item.login and "Add to My List</span>" in data and config.is_xbmc(): - itemlist.append(item.clone(title=config.get_localized_string(70321) % score, action="menu_mal", contentTitle=title_mal)) - elif item.login and config.is_xbmc(): - status = {'1': config.get_localized_string(70479), '2': config.get_localized_string(70480), '3': config.get_localized_string(70384), '4': config.get_localized_string(70385), '6': config.get_localized_string(70481)} - estado = match(data, patron=r'myinfo_updateInfo".*?option selected="selected" value="(\d+)"').match - try: - estado = status[estado] - itemlist.append(item.clone(title=config.get_localized_string(70322) % (estado, score), action="menu_mal", contentTitle=title_mal)) - except: - pass - - token_auth = config.get_setting("token_trakt", "trakt") - if token_auth and ob_tmdb.result: - itemlist.append(item.clone(title=config.get_localized_string(70323), action="menu_trakt", thumbnail=thumb('setting'))) - - # Prequels, sequels and alternative series are listed - prequel = match(data, patron=r'Prequel:</td>(.*?)</td>').match - if prequel: - matches = match(prequel, patron=r'href="([^"]+)">(.*?)</a>').matches - for url, title in matches: - new_item = item.clone(args="") - new_item.title = config.get_localized_string(70355) % title - new_item.contentTitle = title - new_item.url = "https://myanimelist.net" + url if not url.startswith('http') else url - new_item.thumbnail = thumb('back') - itemlist.append(new_item) - - sequel = match(data, patron=r'Sequel:</td>(.*?)</td>').match - if sequel: - matches = match(sequel, patron=r'href="([^"]+)">(.*?)</a>').matches - for url, title in matches: - new_item = item.clone(args="") - new_item.title = config.get_localized_string(70356) % title - new_item.contentTitle = title - new_item.url = "https://myanimelist.net" + url if not url.startswith('http') else url - new_item.thumbnail = thumb('next') - itemlist.append(new_item) - - alt_version = match(data, patron=r'Alternative version:</td>(.*?)</td>').match - if alt_version: - matches = match(alt_version, patron=r'href="([^"]+)">(.*?)</a>').matches - for url, title in matches: - new_item = item.clone(args="") - new_item.title = config.get_localized_string(70357) % title - new_item.contentTitle = title - new_item.url = "https://myanimelist.net" + url if not url.startswith('http') else url - new_item.thumbnail = thumb('alternative') - itemlist.append(new_item) - - if ob_tmdb.result: - # itemlist.append(item.clone(title="", action="", infoLabels={})) - if ob_tmdb.result.get("belongs_to_collection"): - new_item = item.clone(action="list_tmdb", ) - saga = ob_tmdb.result["belongs_to_collection"] - new_item.infoLabels["tmdb_id"] = saga["id"] - if saga["poster_path"]: - new_item.thumbnail = 'https://image.tmdb.org/t/p/original' + saga["poster_path"] - if saga["backdrop_path"]: - new_item.fanart = 'https://image.tmdb.org/t/p/original' + saga["backdrop_path"] - new_item.search = {'url': 'collection/%s' % saga['id'], 'language': langt} - new_item.title = config.get_localized_string(70327) % saga["name"] - itemlist.append(new_item) - - itemlist.append(item.clone(title=config.get_localized_string(70358), action="list_tmdb", search={'url': '%s/%s/recommendations' % (item.args, item.infoLabels['tmdb_id']), 'language': langt, 'page': 1}, thumbnail=thumb('popular'))) - - # Myanimelist recommendations and info search on anidb (fansubs in Spanish) - itemlist.append(item.clone(title=config.get_localized_string(70359), action="reco_mal", thumbnail=thumb('popular'))) - anidb_link = match(data, patron=r'<a href="(http://anidb.info/perl-bin/animedb.pl\?show=anime&aid=\d+)').match - if anidb_link: - anidb_link = anidb_link.replace("&", "&") + "&showallag=1#grouplist" - info_anidb(item, itemlist, anidb_link) - - return itemlist - - -def videos_mal(item): - # Method for crunchyroll and trailer / promotional episodes - itemlist = [] - - data = match(item.url, cookies=False).data - - if not "No episode video" in data and not "http://www.hulu.com/" in data: - patron = r'<a class="video-list di-ib po-r" href="([^"]+)".*?data-src="([^"]+)".*?<span class="title">([^<]+)<(.*?)<span class="episode-title" title="([^"]+)"' - matches = match(data, patron=patron).matches - for url, thumb, epi, info, title in matches: - if "icon-pay" in info and "icon-banned-youtube" in thumb: - continue - url = "https://myanimelist.net" + url if not url.startswith('http') else url - new_item = item.clone(url=url, thumbnail=thumb, action="play", ) - new_item.title = epi + " - " + title.strip() - if "icon-pay" in info: - new_item.title += " (Crunchyroll Premium)" - itemlist.append(new_item) - - next_page = match(data, patron=r'<a href="([^"]+)" class="link-blue-box">More').match - if next_page: itemlist.append(item.clone(title=config.get_localized_string(70361), url=next_page, )) - if itemlist: itemlist.insert(0, item.clone(title=config.get_localized_string(70362), action="", )) - - patron = r'<a class="iframe.*?href="(https://www.youtube.*?)\?.*?data-src="([^"]+)".*?<span class="title">([^<]+)<' - matches = match(data, patron=patron).matches - if matches: - itemlist.append(item.clone(title=config.get_localized_string(70363), action="", )) - for url, thumb, title in matches: - url = url.replace("embed/", "watch?v=") - itemlist.append(item.clone(title=title, url=url, server="youtube", action="play", thumbnail=thumb, )) - - return itemlist - - -def reco_mal(item): - # Myanimelist recommendations - itemlist = [] - - # patronBlock = r'<div class="anime-slide-block" id="anime_recommendation"(.*?)</ul></div>' - patron = r'<div class="picSurround"><a href="([^"]+)"[^>]+><img src="[^"]+" data-src="([^"]+)"[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>([^<\(]+)(?:\([^<]+)?<[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>([^<]+)' - matches = match(item.url + "/userrecs", cookies=False, patron=patron).matches - for url, thumb, title, plot in matches: - new_item = item.clone(action="details_mal", fanart=default_fan, title=title, contentType="", args="", contentTitle=title) - new_item.infoLabels["plot"] = htmlclean(plot) - new_item.url = "https://myanimelist.net" + url if not url.startswith('http') else url - new_item.thumbnail = thumb.replace("r/50x70/", "").replace(".jpg", "l.jpg") - itemlist.append(new_item) - return itemlist - - -def indices_mal(item): - # Seasonal and gender indices - itemlist = [] - url_base = "" - if config.get_localized_string(30140) in item.title: - matches = match("https://myanimelist.net/anime/season/archive", cookies=False, patron=r'<td>\s*<a href="([^"]+)">\s*(.*?)\s*</a>').matches - for url, title in matches: - year = title.rsplit(" ", 1)[1] - thumbnail = item.thumbnail - if int(year) >= 1968: - thumbnail = url_base + year - title = title.replace("Winter", config.get_localized_string(70364)).replace("Spring", config.get_localized_string(70365)).replace("Summer", config.get_localized_string(70366)).replace("Fall", config.get_localized_string(70367)) - itemlist.append(Item(channel=item.channel, action="season_mal", title=typo(title, 'bold'), url=url, thumbnail=thumbnail, info=True, fanart=thumbnail)) - else: - patronBlock = r'Genres</div>(.*?)View More</a>' - patron = r'<a href="([^"]+)" class="genre-name-link">(.*?)</a>' - matches = match("https://myanimelist.net/anime.php", cookies=False, patronBlock=patronBlock, patron=patron).matches - for url, title in matches: - genero = title.split(" (", 1)[0] - logger.debug(url_base, genero) - thumbnail = url_base + genero.lower().replace(" ", "%20") - if genero in ["Hentai", "Yaoi", "Yuri"] and not adult_mal: - continue - if not url.startswith('http'): url = "https://myanimelist.net" + url - itemlist.append(Item(channel=item.channel, action="season_mal", title=typo(title, 'bold'), url=url, thumbnail=thumbnail, fanart=thumbnail)) - - return thumb(itemlist, mode='genre') - - -def season_mal(item): - # Scraper for anime seasons - itemlist = [] - - cookie_session = get_cookie_value() - header_mal = {'Cookie': '%s search_sort_anime=score; search_view=tile; is_logged_in=1' % cookie_session} - data = match(item.url, headers=header_mal, cookies=False).data - if item.info: - blocks = match(data, patron=r'<div class="anime-header">([^<]+)</div>(.*?)</div>\s*</div></div></div>').matches - for head_title, block in blocks: - head_title = head_title.replace("(New)", config.get_localized_string(70369)).replace("(Continuing)", config.get_localized_string(70369)) - patron = r'<a href="([^"]+)" class="link-title">(.*?)</a>.*?<span>(\? ep|\d+ ep).*?<div class="genres-inner js-genre-inner">(.*?)</div>.*?<div class="image".*?src="(.*?).jpg.*?<span class="preline">(.*?)</span>.*?<div class="info">\s*(.*?)\s*-.*?(\d{4}).*?title="Score">\s*(N/A|\d\.\d+)' - matches = match(block, patron=patron, debug=True).matches - if matches: - itemlist.append(Item(channel=item.channel, action="", title=head_title, )) - for url, scrapedtitle, episode, genres, thumb, plot, Type, year, score in matches: - if ("Hentai" in genres or "Yaoi" in genres or "Yuri" in genres) and adult_mal: continue - scrapedtitle = scrapedtitle.replace("(TV)", "").replace("(Movie)", "") - if Type == "Movie": title = scrapedtitle + " (%s)" % year - else: title = scrapedtitle + " %ss (%s)" % (episode, year) - infoLabels = {} - if score != "N/A": - title += " %s" % (score) - infoLabels["rating"] = float(score) - infoLabels["plot"] = htmlclean(plot) - infoLabels["year"] = year - - genres = match(genres, patron=r'title="([^"]+)"').matches - infoLabels["genre"] = ", ".join(genres) - Type = Type.lower() - if Type == "movie" or Type == "special": - args = "movie" - contentType = "movie" - else: - args = "tv" - contentType = "tvshow" - thumb = thumb.replace("r/167x242/", "") + "l.jpg" - itemlist.append(Item(channel=item.channel, action="details_mal", url=url, title=title, thumbnail=thumb, infoLabels=infoLabels, args=args, Type=Type, contentTitle=scrapedtitle, contentType=contentType, fanart=default_fan)) - else: - patron = r'<a href="([^"]+)" class="link-title">([^<]+)</a>.*?<span>(\? ep|\d+ ep).*?<div class="genres-inner js-genre-inner">(.*?)</div>.*?<div class="image".*?src="([^"]+).*?<span class="preline">(.*?)</span>.*?<div class="info">\s*(.*?)\s*-.*?(\d{4}).*?title="Score">\s*(N/A|\d\.\d+)' - matches = match(data, patron=patron).matches - for url, scrapedtitle, epis, scrapedgenres, thumbnail, plot, Type, year, score in matches: - if ("Hentai" in scrapedgenres or "Yaoi" in scrapedgenres or "Yuri" in scrapedgenres) and not adult_mal: - continue - scrapedtitle = scrapedtitle.replace("(TV)", "").replace("(Movie)", "") - if Type == "Movie": - title = scrapedtitle + " (%s)" % year - else: - title = scrapedtitle + " %ss (%s)" % (epis, year) - infoLabels = {} - if score != "N/A": - title += " %s" % (score) - infoLabels["rating"] = float(score) - infoLabels["plot"] = htmlclean(plot) - infoLabels["year"] = year - - genres = match(scrapedgenres, patron=r'title="([^"]+)"').matches - infoLabels["genre"] = ", ".join(genres) - Type = Type.lower() - if Type == "movie" or Type == "special": - args = "movie" - contentType = "movie" - else: - args = "tv" - contentType = "tvshow" - thumbnail = thumbnail.replace(".webp", ".jpg") - itemlist.append(Item(channel=item.channel, action="details_mal", url=url, title=title, - thumbnail=thumbnail, infoLabels=infoLabels, args=args, Type=Type, - contentTitle=scrapedtitle, contentType=contentType, - fanart=default_fan)) - next_page = match(data, patron=r'<a class="link current" href.*?href="([^"]+)"').match - if next_page: - itemlist.append(Item(channel=item.channel, action="season_mal", url=next_page, - title=config.get_localized_string(70065), thumbnail=item.thumbnail)) - - return itemlist - - -def staff_mal(item): - # Benders / Filming Equipment - itemlist = [] - data = match(item.url, cookies=False).data - patron = r'(/character/[^"]+)".*?data-src="([^"]+)".*?href=.*?>([^<]+)<.*?<small>([^<]+)</small>(.*?)</table>' - matches = match(data, patron=patron).matches - if matches: - # itemlist.append(item.clone(title=config.get_localized_string(70370), action="", )) - for url, thumbnail, nombre, rol, voces in matches: - url = "https://myanimelist.net%s" % url - nombre = "%s [%s]" % (nombre, rol) - thumbnail = thumbnail.replace("r/46x64/", "").replace("r/42x62/", "") - itemlist.append(Item(channel=item.channel, action="detail_staff", url=url, thumbnail=thumbnail, fanart=default_fan, title=nombre, args="character")) - patron_voces = r'(/people[^"]+)">([^<]+)<.*?<small>([^<]+)</small>.*?data-src="([^"]+)"' - voces_match = match(voces, patron=patron_voces).matches - for vurl, vnombre, vidioma, vthumb in voces_match: - vurl = "https://myanimelist.net%s" % vurl - vnombre = " - %s [%s]" % (vnombre, vidioma) - vthumb = vthumb.replace("r/46x64/", "").replace("r/42x62/", "") - itemlist.append(Item(channel=item.channel, action="detail_staff", url=vurl, thumbnail=vthumb, fanart=default_fan, title=vnombre)) - patronBlock = r'<a name="staff">(.*?)</table>' - patron = r'(/people[^"]+)".*?data-src="([^"]+)".*?href=.*?>([^<]+)<.*?<small>([^<]+)</small>' - matches = match(data, patronBlock=patronBlock, patron=patron).matches - if matches: - itemlist.append(item.clone(title="Staff", action="", )) - for url, thumb, nombre, rol in matches: - url = "https://myanimelist.net%s" % url - nombre = " - %s [%s]" % (nombre, rol) - thumb = thumb.replace("r/46x64/", "").replace("r/42x62/", "") - itemlist.append(Item(channel=item.channel, action="detail_staff", url=url, thumbnail=thumb, fanart=default_fan, title=nombre)) - - return itemlist - - -def detail_staff(item): - itemlist = [] - data = match(item.url, cookies=False).data - if item.args == "character" and not "No biography written" in data: - bio = match(data,patron=r'<div class="normal_header">[^>]+>(.*?)<div class="normal_header"').match - bio = bio.replace("<br />", "\n") - bio = htmlclean(bio) - if not "questionmark" in item.thumbnail: - itemlist.append(Item(channel=item.channel, title=typo(config.get_localized_string(70316),'bold, bullet'), action="", thumbnail=thumb('info'))) - data_img = match(item.url + "/pictures", cookies=False).data - matches = match(data_img, patron=r'rel="gallery-character"><img.*?src="([^"]+)"').matches - for i, thumbnail in enumerate(matches): - title = typo(i + 1,'submenu') - infoLabels = {'plot': bio} - itemlist.append(Item(channel=item.channel, action="", title=title, infoLabels=infoLabels, thumbnail=thumbnail)) - - matches = match(data, patron=r'(/anime[^"]+)"><img.*?src="([^"]+)".*?href.*?>(.*?)</a>').matches - if matches: - itemlist.append(Item(channel=item.channel, title=typo(config.get_localized_string(70373),'bold, bullet'), action="", thumbnail=thumb('info') )) - for url, thumbnail, title in matches: - url = "https://myanimelist.net%s" % url - thumbnail = thumbnail.replace("r/23x32/", "").replace("r/42x62/", "") - itemlist.append(Item(channel=item.channel, action="details_mal", url=url, thumbnail=thumbnail, fanart=default_fan, title= typo(title, 'submenu'), contentTitle=title)) - else: - patron_bio = r'<?<div class="spaceit_pad">(.*?)</td>' - bio = match(data, patron=patron_bio).match - bio = htmlclean(bio.replace("</div>", "\n")) - logger.debug(bio) - infoLabels = {'plot': bio} - if not "No voice acting roles" in data: - itemlist.append(Item(channel=item.channel, title=typo(config.get_localized_string(70374),'bold bullet'), action="", thumbnail=item.thumbnail, infoLabels=infoLabels)) - patronBlock = r'Voice Acting Roles</div>(.*?)</table>' - patron = r'(/anime[^"]+)"><img data-src="([^"]+)"[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>([^<]+)<[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>.*?(/character[^"]+)"[^>]*>([^<]+)<[^>]*>[^>]*>[^>]*>[^>]*>[^>]*>[^>]*>[^>]*><img data-src="([^"]+)"' - matches = match(data, patronBlock=patronBlock, patron=patron).matches - for url, thumbnail, title, url_p, personaje, thumb_p in matches: - url = "https://myanimelist.net%s" % url - url_p = "https://myanimelist.net%s" % url_p - thumbnail = thumbnail.replace("r/46x64/", "") - thumb_p = thumb_p.replace("r/46x64/", "") - itemlist.append(Item(channel=item.channel, action="details_mal", url=url, thumbnail=thumbnail, title=typo(title, 'bold submenu'), contentTitle=title)) - itemlist.append(Item(channel=item.channel, action="detail_staff", url=url_p, thumbnail=thumb_p, title=typo(personaje,'_ submenu'), args="character")) - - if not "No staff positions" in data: - itemlist.append(Item(channel=item.channel, title=typo(config.get_localized_string(70375),'bold bullet'), action="", thumbnail=item.thumbnail, infoLabels=infoLabels)) - patronBlock = r'Anime Staff Positions</div>(.*?)</table>' - patron = r'(/anime[^"]+)"><img data-src="([^"]+)".*?href.*?>(.*?)</a>.*?<small>(.*?)</div>' - matches = match(data, patronBlock=patronBlock, patron=patron).matches - for url, thumbnails, title, rol in matches: - url = "https://myanimelist.net%s" % url - thumbnails = thumbnails.replace("r/46x64/", "").replace("r/84x124/", "") - rol = htmlclean(rol) - titulo = typo("%s [%s]" % (title, rol), 'submenu') - itemlist.append(Item(channel=item.channel, action="details_mal", url=url, thumbnail=thumbnails, fanart=default_fan, title=titulo, contentTitle=title)) - - return itemlist - - -def searching_mal(item): - # Scraper for myanimelist searches - itemlist = [] - - cookie_session = get_cookie_value() - header_mal = {'Cookie': '%s search_sort_anime=score; search_view=tile; is_logged_in=1' % cookie_session} - data = match(item.url, headers=header_mal, cookies=False).data - patron = r'<a class="hoverinfo_trigger" href="([^"]+)".*?(?:data-src|src)="([^"]+)".*?<div class="hoverinfo".*?href.*?><strong>([^<]+)<.*?<div class="pt4">(.*?)<.*?<td.*?>(.*?)</td>.*?<td.*?>(.*?)</td>.*?<td.*?>(.*?)</td>.*?<td.*?>(.*?)</td>' - matches = match(data, patron=patron).matches - for url, thumb, title, plot, Type, epis, rating, date in matches: - infolabels = {"mediatype": "tvshow"} - contentType = "tvshow" - args = "tv" - title = title.strip() - Type = Type.strip() - rating = rating.strip() - epis = epis.strip() - infolabels["plot"] = htmlclean(plot.strip()) - thumb = thumb.replace("r/50x70/", "").replace(".jpg", "l.jpg") - show = title - contentitle = title - try: - year = date.strip().rsplit("-", 1)[1] - if year.isdigit(): - if int(year) < 30: - year = "20%s" % year - else: - year = "19%s" % year - infolabels["year"] = year - if not year in title: - title += " (%s)" % year - except: - import traceback - logger.error(traceback.format_exc()) - - if Type == "Movie" or Type == "OVA": - infolabels["mediatype"] = "movie" - contentType = "movie" - args = "movie" - show = "" - - if epis and Type != "Movie": - title += " %s eps" % epis - if rating != "0.00" and rating != "N/A": - infolabels["rating"] = float(rating) - title += " %s" % (rating) - itemlist.append(Item(channel=item.channel, title=title, action="details_mal", url=url, show=show, - thumbnail=thumb, infoLabels=infolabels, contentTitle=contentitle, - contentType=contentType, Type=Type.lower(), args=args)) - - if not "&show=" in item.url: - next_page = item.url + "&show=50" - else: - pagina = int(item.url.rsplit("=", 1)[1]) - next_page = item.url.replace("&show=%s" % str(pagina), "&show=%s" % str(pagina + 50)) - - check_page = next_page.replace("https://myanimelist.net/anime.php", "") - if check_page in data: - itemlist.append(item.clone(title=config.get_localized_string(70065), url=next_page, )) - else: - check_page = check_page.replace("[", "%5B").replace("]", "%5D") - if check_page in data: - itemlist.append(item.clone(title=config.get_localized_string(70065), url=next_page, )) - - return itemlist - - -def info_anidb(item, itemlist, url): - # Extract info, score and fansubs on anidb - data = match(url).data - - infoLabels = {'mediatype': item.contentType} - plot = match(data, patron=r'itemprop="description">(.*?)</div>').match - infoLabels["plot"] = htmlclean(plot) - - generos = match(data, patron=r'<div class="tag".*?<span class="tagname">(.*?)</span>').matches - for i, genero in enumerate(generos): - generos[i] = genero.capitalize() - infoLabels["genre"] = ", ".join(generos) - rating = match(data, patron=r'itemprop="ratingValue">(.*?)</span>').match - try: - infoLabels["rating"] = float(rating) - except: - pass - infoLabels["votes"] = match(data, patron=r'itemprop="ratingCount">(.*?)</span>').match - thumbnail = match(data, patron=r'<div class="image">.*?src="([^"]+)"').match - if infoLabels: - title = config.get_localized_string(70376) % (rating) - if re.search(r'(?:subtitle|audio) | language: spanish"', data): - title += config.get_localized_string(70377) - itemlist.append(Item(channel=item.channel, title=title, infoLabels=infoLabels, action="", thumbnail=thumbnail)) - - if re.search(r'(?:subtitle|audio) | language: spanish"', data): - epi_total = match(data, patron=r'itemprop="numberOfEpisodes">([^<]+)</span>').match - patron = r'<td class="name group">.*?title="([^"]+)">(.*?)</a>.*?>([^<]+)</a>.*?<td class="epno lastep">([^<]+)</td>.*?title="audio(.*?)</td>.*?class="source" title="([^"]+)"' - matches = match(data, patron=patron).matches - for fansub, abrev, estado, epis, lang, source in matches: - if not "spanish" in lang: - continue - title = " " + fansub - if abrev != title: - title += " [%s]" % abrev - estado = estado.replace("complete", config.get_localized_string(70378)).replace("finished", config.get_localized_string(70379)).replace("stalled", config.get_localized_string(70380)).replace("dropped", config.get_localized_string(70381)) - title += " (%s) %s/%s [%s]" % (estado, epis, epi_total, source) - itemlist.append(Item(channel=item.channel, title=title, infoLabels=infoLabels, action="", thumbnail=thumbnail)) - - -def filter_mal(item): - logger.debug() - - list_controls = [] - valores = {} - dict_values = None - # Default / saved values ​​are used - saved_values = config.get_setting("default_filter_mal", item.channel) - if saved_values: - dict_values = saved_values - - list_controls.append({'id': 'keyword', 'label': config.get_localized_string(70465), 'enabled': True, - 'type': 'text', 'default': '', 'visible': True}) - list_controls.append({'id': 'tipo', 'label': config.get_localized_string(70482), 'enabled': True, - 'type': 'list', 'default': -1, 'visible': True}) - list_controls[1]['lvalues'] = [config.get_localized_string(70483), config.get_localized_string(70484), config.get_localized_string(60244), config.get_localized_string(70136), config.get_localized_string(70450)] - valores["tipo"] = ['4', '2', '3', '1', '0'] - list_controls.append({'id': 'valoracion', 'label': config.get_localized_string(70473), 'enabled': True, - 'type': 'list', 'default': -1, 'visible': True}) - list_controls[2]['lvalues'] = [config.get_localized_string(70486), config.get_localized_string(70487), config.get_localized_string(70488), config.get_localized_string(70489), - config.get_localized_string(70490), config.get_localized_string(70491), config.get_localized_string(70492), config.get_localized_string(70493), - config.get_localized_string(70494), config.get_localized_string(70495), config.get_localized_string(70450)] - valores["valoracion"] = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '0'] - - list_controls.append({'id': 'estado', 'label': config.get_localized_string(70485), 'enabled': True, - 'type': 'list', 'default': -1, 'visible': True}) - list_controls[3]['lvalues'] = ['Por estrenar', config.get_localized_string(60264), config.get_localized_string(70379), config.get_localized_string(70450)] - valores["estado"] = ['3', '1', '2', '0'] - - try: - data = httptools.downloadpage('https://myanimelist.net/anime.php', cookies=False).data - - patron = r'name="genre\[\]" type="checkbox" value="([^"]+)">.*?>([^<]+)<' - generos = scrapertools.find_multiple_matches(data, patron) - if generos: - list_controls.append({'id': 'labelgenre', 'enabled': True, 'type': 'label', 'default': None, 'label': config.get_localized_string(70451), 'visible': True}) - for value, genre in generos: - list_controls.append({'id': 'genre' + value, 'label': genre, 'enabled': True, 'type': 'bool', 'default': False, 'visible': True}) - except: - pass - - list_controls.append({'id': 'espacio', 'label': '', 'enabled': False, 'type': 'label', 'default': None, 'visible': True}) - list_controls.append({'id': 'save', 'label': config.get_localized_string(70464), 'enabled': True, 'type': 'bool', 'default': False, 'visible': True}) - - item.valores = valores - return platformtools.show_channel_settings(list_controls=list_controls, dict_values=dict_values, caption=config.get_localized_string(70320), item=item, callback='callback_mal') - - -def callback_mal(item, values): - values_copy = values.copy() - # Save the filter to be the one loaded by default - if "save" in values and values["save"]: - values_copy.pop("save") - config.set_setting("default_filter_mal", values_copy, item.channel) - - genero_ids = [] - for v in values: - if "genre" in v: - if values[v]: - genero_ids.append("genre[%s]=%s" % (len(genero_ids), v.replace('genre', ''))) - - genero_ids = "&".join(genero_ids) - query = values["keyword"].replace(" ", "%20") - Type = item.valores["tipo"][values["tipo"]] - valoracion = item.valores["valoracion"][values["valoracion"]] - estado = item.valores["estado"][values["estado"]] - - item.url = "https://myanimelist.net/anime.php?q=%s&type=%s&score=%s&status=%s" \ - "&p=0&r=0&sm=0&sd=0&sy=0&em=0&ed=0&ey=0&c[0]=a&c[1]=b&c[2]=c&c[3]=d&c[4]=f&gx=0" \ - % (query, Type, valoracion, estado) - if genero_ids: - item.url += "&" + genero_ids - - item.action = "searching_mal" - return searching_mal(item) - - -def musica_anime(item): - # List available anime and songs similar to the anime title - logger.debug() - itemlist = [] - - data = match("http://www.freeanimemusic.org/song_search.php", post=item.post).data - patron = r"<span class='Estilo6'>(\d+).*?<span class='Estilo22'>([^<]+)<.*?<span class='Estilo22'>([^<]+)<.*?href='http://www.freeanimemusic.org/anime/([^/]+)/index.php\?var=(\d+)" - matches = match(data, patron=patron).matches - animes = {} - action = "" - if config.is_xbmc(): - action = "move" - for number, song, anime, id_anime, id_song in matches: - if not animes.get(anime): - animes[anime] = [] - animes[anime].append( - Item(channel=item.channel, action=action, title="[%s]" % (anime.capitalize()), - url="", - number="0", thumbnail=item.thumbnail, fanart=item.fanart)) - title = "%s - %s" % (number, song) - animes[anime].append( - Item(channel=item.channel, action="play", title=title, server="directo", url=id_anime, song=id_song, - number=number, - thumbnail=item.thumbnail, fanart=item.fanart, )) - - for k, v in sorted(animes.items()): - v.sort(key=lambda x: (x.url, int(x.number))) - for lt in v: - if lt.action == "move": - lt.args = len(v) - lt.folder = False - itemlist.append(lt) - - return itemlist - - -def login_mal(from_list=False): - logger.debug() - from core import httptools - from base64 import b64decode as bdec - - try: - user = config.get_setting("usuariomal", "tvmoviedb") - password = config.get_setting("passmal", "tvmoviedb") - generic = False - if not user or not password: - if not from_list: - user = bdec("Y3VlbnRhdHZtb3ZpZWRi") - password = bdec("dFlTakE3ekYzbng1") - generic = True - else: - return False, config.get_localized_string(70393), user - data = httptools.downloadpage("https://myanimelist.net/login.php?from=%2F").data - if re.search(r'(?i)' + user, data) and not generic: - return True, "", user - token = match(data, patron=r"name='csrf_token' content='([^']+)'").match - response = httptools.downloadpage("https://myanimelist.net/logout.php", post="csrf_token=%s" % token) - post = "user_name=%s&password=%s&cookie=1&sublogin=Login&submit=1&csrf_token=%s" % (user, password, token) - response = httptools.downloadpage("https://myanimelist.net/login.php?from=%2F", post=post) - - if not re.search(r'(?i)' + user, response.data): - logger.error("Login failed") - return False, config.get_localized_string(70330), user - else: - if generic: - return False, config.get_localized_string(70393), user - logger.debug("Correct login") - return True, "", user - except: - import traceback - logger.error(traceback.format_exc()) - return False, config.get_localized_string(70331) , '' - - -def cuenta_mal(item): - # Myanimelist account menu - itemlist = [] - login, message, user = login_mal(True) - if not login: - itemlist.append(item.clone(action="configuracion", title=message, )) - else: - itemlist.append( - item.clone(action="items_mal", title=config.get_localized_string(70382), accion="lista_mal", - url="https://myanimelist.net/animelist/%s?status=1" % user, login=True)) - itemlist.append(item.clone(action="items_mal", title=config.get_localized_string(70383), accion="lista_mal", - url="https://myanimelist.net/animelist/%s?status=2" % user, login=True)) - itemlist.append(item.clone(action="items_mal", title=config.get_localized_string(70384), accion="lista_mal", - url="https://myanimelist.net/animelist/%s?status=3" % user, login=True)) - itemlist.append(item.clone(action="items_mal", title=config.get_localized_string(70385), accion="lista_mal", - url="https://myanimelist.net/animelist/%s?status=4" % user, login=True)) - itemlist.append(item.clone(action="items_mal", title=config.get_localized_string(70386), accion="lista_mal", - url="https://myanimelist.net/animelist/%s?status=6" % user, login=True)) - - return itemlist - - -def items_mal(item): - # Scraper for personal lists - logger.debug() - itemlist = [] - data = match(item.url).data - - data_items = match(data, patron=r'data-items="([^"]+)"').match.replace(""", "'").replace("null", "None").replace("false", "False").replace("true", "True") - data_items = eval(data_items) - for d in data_items: - if d["anime_airing_status"] == 1: - title = "[E]" - if d["anime_airing_status"] == 2: - title = "[F]" - else: - title = "[P]" - title += typo(" %s [%s/%s] (%s)" % ( - d["anime_title"], d["num_watched_episodes"], d["anime_num_episodes"], d["anime_media_type_string"]),'bold') - title = title.replace("\\", "") - contentTitle = d["anime_title"].replace("\\", "") - thumbnail = d["anime_image_path"].replace("\\", "").replace("r/96x136/", "").replace(".jpg", "l.jpg") - if d["anime_url"].startswith('http'): url= d["anime_url"].replace("\\", "") - else: url = "https://myanimelist.net" + d["anime_url"].replace("\\", "") - if d["score"] != 0: - title += typo(" Punt:%s" % (d["score"]),'color kod bold') - if title.count("(TV)") == 2: - title = title.replace("] (TV)", "]") - elif title.count("(Movie)") == 2: - title = title.replace("] (Movie)", "]") - Type = "tvshow" - args = "tv" - if "Movie" in d["anime_media_type_string"]: - Type = "movie" - args = "movie" - itemlist.append(Item(channel=item.channel, action="details_mal", url=url, title=title, thumbnail=thumbnail, - - contentTitle=contentTitle, contentType=Type, args=args, login=True)) - - if itemlist: - itemlist.insert(0, Item(channel=item.channel, action="", title=config.get_localized_string(70387))) - - return itemlist - - -def menu_mal(item): - # Options BAD account, add to list / vote - itemlist = [] - - data = match(item.url).data - try: - status = {'1': config.get_localized_string(70479), '2': config.get_localized_string(70480), '3': config.get_localized_string(70384), '4': config.get_localized_string(70385), '6': config.get_localized_string(70481)} - button, estado =match(data, patron=r'myinfo_updateInfo"(.*?)>.*?option selected="selected" value="(\d+)"').match - if "disabled" in button: - title_estado = config.get_localized_string(70388) - estado = "1" - else: - title_estado = typo(config.get_localized_string(70389) % (status[estado]), 'bold') - except: - title_estado = config.get_localized_string(70388) - - score = match(data, patron=r'id="myinfo_score".*?selected" value="(\d+)"').match - if score != "0": - title_estado += " (Punt:%s)" % score - if "lista" in title_estado: - item.lista = True - - itemlist.append(item.clone(title="Anime: %s%s" % (item.contentTitle, title_estado), action="")) - status = {'1': config.get_localized_string(70479), '2': config.get_localized_string(70480), '3': config.get_localized_string(70384), '4': config.get_localized_string(70385), '6': config.get_localized_string(70481)} - for key, value in status.items(): - if not value in title_estado: - itemlist.append( - item.clone(title=typo(config.get_localized_string(70391) % value, 'bold'), action="addlist_mal", value=key, estado=value)) - - for i in range(10, 0, -1): - if i != int(score): - itemlist.append(item.clone(title=typo(config.get_localized_string(70392) % (i), 'bold'), action="addlist_mal", value=estado, estado=status[estado], score=i)) - return itemlist - - -def addlist_mal(item): - data = match(item.url).data - - anime_id = match(data, patron=r'id="myinfo_anime_id" value="([^"]+)"').match - if item.value == "2": - vistos = match(data, patron=r'id="myinfo_watchedeps".*?<span id="curEps">(\d+)').match - else: - vistos = match(data, patron=r'id="myinfo_watchedeps".*?value="(\d+)"').match - if not item.score: - item.score = match(data, patron=r'id="myinfo_score".*?selected" value="(\d+)"').match - token = match(data, patron=r"name='csrf_token' content='([^']+)'").match - - post = {'anime_id': int(anime_id), 'status': int(item.value), 'score': int(item.score), - 'num_watched_episodes': int(vistos), 'csrf_token': token} - headers_mal = {'User-Agent': 'Mozilla/5.0', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', - 'Referer': item.url, 'X-Requested-With': 'XMLHttpRequest'} - url = "https://myanimelist.net/ownlist/anime/add.json" - if item.lista: - url = "https://myanimelist.net/ownlist/anime/edit.json" - # data = httptools.downloadpage(url, post=jsontools.dump(post), headers=headers_mal, replace_headers=True).data - data = match(url, post=jsontools.dump(post), headers=headers_mal).data - item.title = "En tu lista" - if config.is_xbmc(): - import xbmc - xbmc.executebuiltin("Container.Refresh") - - -def move(item): - import xbmcgui, xbmc - item_focus = str(item.args) - wnd = xbmcgui.Window(xbmcgui.getCurrentWindowId()) - id = wnd.getFocusId() - return xbmc.executebuiltin('Control.Move(' + str(id) + ',' + item_focus + ')') - - -def play(item): - itemlist = [] - if not item.server: - data = match(item.url).data - if "Sorry, this video is not available to be embedded" in data: - id_video = match(data, patron=r'<div class="video-embed.*?-(\d+)\&aff').match - crunchy = "https://www.crunchyroll.com/affiliate_iframeplayer?aff=af-12299-plwa&media_id=%s&video_format=106&video_quality=60&auto_play=0" % id_video - else: - crunchy = match(data, patron=r'<iframe src="([^"]+)"').match - itemlist.append(item.clone(server="crunchyroll", url=crunchy)) - else: - if item.server == "directo" and item.song: - url = "" - data_music = jsontools.load(match("http://www.musicaanime.org/scripts/resources/artists1.php").data) - for child in data_music["data"]: - if child["title"] == item.url.upper(): - url = "http://www.musicaanime.org/aannmm11/%s/imagen%s.mp3" % (child["artist"], item.song.zfill(3)) - break - if url: - itemlist.append(item.clone(url=url)) - else: - itemlist.append(item) - - return itemlist - - -def get_cookie_value(): - cookies = filetools.join(config.get_data_path(), 'cookies.dat') - cookiedata = filetools.read(cookies) - malsess = match(cookiedata, patron=r"myanimelist.*?MALHLOGSESSID\s+([A-z0-9\+\=]+)").match - cookievalue = "MALHLOGSESSID=" + malsess - mal_id = match(cookiedata, patron=r"myanimelist.*?MALSESSIONID\s+([A-z0-9\+\=\-]+)").match - if mal_id: - cookievalue += "; MALSESSIONID=%s;" % mal_id - - return cookievalue diff --git a/specials/videolibrary.py b/specials/videolibrary.py index 836ad55d..9ffc75ea 100644 --- a/specials/videolibrary.py +++ b/specials/videolibrary.py @@ -413,7 +413,7 @@ def findvideos(item): if config.get_setting('autoplay'): itemlist = autoplay.start(itemlist, item) else: - servertools.sort_servers(itemlist) + itemlist = servertools.sort_servers(itemlist) if config.get_setting('checklinks') and not config.get_setting('autoplay'): itemlist = servertools.check_list_links(itemlist, config.get_setting('checklinks_number'))