Exemplo n.º 1
0
    def init_request(self, argv):
        if argv is None:
            return

        self.URL = tools.urlparse(argv[0])
        try:
            self.PLUGIN_HANDLE = int(argv[1])
            self.IS_SERVICE = False
        except IndexError:
            self.PLUGIN_HANDLE = 0
            self.IS_SERVICE = True

        if self.URL[1] != "":
            self.BASE_URL = "{scheme}://{netloc}".format(scheme=self.URL[0],
                                                         netloc=self.URL[1])
        else:
            self.BASE_URL = ""
        self.PATH = tools.unquote(self.URL[2])
        try:
            self.PARAM_STRING = argv[2].lstrip('?/')
        except IndexError:
            self.PARAM_STRING = ""
        self.REQUEST_PARAMS = self.legacy_params_converter(
            dict(tools.parse_qsl(self.PARAM_STRING)))
        if "action_args" in self.REQUEST_PARAMS:
            self.REQUEST_PARAMS["action_args"] = tools.deconstruct_action_args(
                self.REQUEST_PARAMS["action_args"])
            if isinstance(self.REQUEST_PARAMS["action_args"], dict):
                self.REQUEST_PARAMS[
                    "action_args"] = self.legacy_action_args_converter(
                        self.REQUEST_PARAMS["action_args"])
        self.FROM_WIDGET = self.REQUEST_PARAMS.get("from_widget",
                                                   "true") == "true"
        self.PAGE = int(g.REQUEST_PARAMS.get("page", 1))
Exemplo n.º 2
0
    def _test_direct_url(source):
        try:
            ext = source["url"].split("?")[0]
            ext = ext.split("&")[0]
            ext = ext.split("|")[0]
            ext = ext.rsplit(".")[-1]
            ext = ext.replace("/", "").lower()
            if ext == "rar":
                raise TypeError("Incorrect file format - rar file provided")

            try:
                headers = source["url"].rsplit("|", 1)[1]
            except IndexError:
                headers = ""

            headers = tools.quote_plus(headers).replace("%3D", "=") if " " in headers else headers
            headers = dict(tools.parse_qsl(headers))

            live_check = requests.head(source["url"], headers=headers, timeout=10)

            if not live_check.status_code == 200:
                g.log("Head Request failed link likely dead, skipping")
                return

            stream_link = source["url"]
        except IndexError:
            stream_link = None
        except KeyError:
            stream_link = None

        return stream_link
Exemplo n.º 3
0
 def _get_next_item_item_information():
     current_position = g.PLAYLIST.getposition()
     url = g.PLAYLIST[  # pylint: disable=unsubscriptable-object
         current_position + 1].getPath()
     params = dict(tools.parse_qsl(tools.unquote(url.split("?")[1])))
     return tools.get_item_information(
         tools.deconstruct_action_args(params.get("action_args")))
Exemplo n.º 4
0
    def next_info(self):

        current_info = self.args
        current_episode = {}
        current_episode["episodeid"] = current_info['ids']['trakt']
        current_episode["tvshowid"] = current_info['showInfo']['info']['imdbnumber']
        current_episode["title"] = current_info['info']['title']
        current_episode["art"] = {}
        current_episode["art"]["tvshow.poster"] = current_info['art']['poster']
        current_episode["art"]["thumb"] = current_info['art']['thumb']
        current_episode["art"]["tvshow.fanart"] = current_info['art']['fanart']
        current_episode["art"]["tvshow.landscape"] = current_info['art']['fanart']
        current_episode["art"]["tvshow.clearart"] = current_info['art'].get('clearart', '')
        current_episode["art"]["tvshow.clearlogo"] = current_info['art'].get('clearlogo', '')
        current_episode["plot"] = current_info['info']['plot']
        current_episode["showtitle"] = current_info['showInfo']['info']['tvshowtitle']
        current_episode["playcount"] = current_info['info'].get('playcount', 0)
        current_episode["season"] = current_info['info']['season']
        current_episode["episode"] = current_info['info']['episode']
        current_episode["rating"] = current_info['info']['rating']
        current_episode["firstaired"] = current_info['info']['premiered'][:10]

        current_position = tools.playList.getposition()
        url = tools.playList[current_position + 1].getPath()
        params = dict(tools.parse_qsl(url.replace('?', '')))
        next_info = tools.get_item_information(params.get('actionArgs'))

        next_episode = {}
        next_episode["episodeid"] = next_info['ids']['trakt']
        next_episode["tvshowid"] = next_info['showInfo']['info']['imdbnumber']
        next_episode["title"] = next_info['info']['title']
        next_episode["art"] = {}
        next_episode["art"]["tvshow.poster"] = next_info['art']['poster']
        next_episode["art"]["thumb"] = next_info['art']['thumb']
        next_episode["art"]["tvshow.fanart"] = next_info['art']['fanart']
        next_episode["art"]["tvshow.landscape"] = next_info['art']['fanart']
        next_episode["art"]["tvshow.clearart"] = next_info['art'].get('clearart', '')
        next_episode["art"]["tvshow.clearlogo"] = next_info['art'].get('clearlogo', '')
        next_episode["plot"] = next_info['info']['plot']
        next_episode["showtitle"] = next_info['showInfo']['info']['tvshowtitle']
        next_episode["playcount"] = next_info['info'].get('playcount', 0)
        next_episode["season"] = next_info['info']['season']
        next_episode["episode"] = next_info['info']['episode']
        next_episode["rating"] = next_info['info']['rating']
        next_episode["firstaired"] = next_info['info']['premiered'][:10]

        play_info = {}
        play_info["item_id"] = current_info['ids']['trakt']

        next_info = {
            "current_episode": current_episode,
            "next_episode": next_episode,
            "play_info": play_info,
            "notification_time": int(tools.getSetting('smartplay.upnexttime'))
        }

        return next_info
Exemplo n.º 5
0
    def playlist_present_check(self, ignore_setting=False):
        """
        Confirms if a playlist is currently present. If not or playlist is for a different item, clear current list
        and build a new one
        :param ignore_setting: Force playlist building if setting is disabled
        :type ignore_setting: bool
        :return: Playlist if playlist is present else False
        :rtype: any
        """
        if g.get_bool_setting("smartplay.playlistcreate") or ignore_setting:

            if not self.item_information["info"]["mediatype"] == "episode":
                g.log("Movie playback requested, clearing playlist")
                g.PLAYLIST.clear()
                return False

            playlist_uris = [
                g.PLAYLIST[i].getPath()  # pylint: disable=unsubscriptable-object
                for i in range(g.PLAYLIST.size())
            ]

            # Check to see if we are just starting playback and kodi has created a playlist
            if len(playlist_uris) == 1 and playlist_uris[0].split(
                    '/')[-1].lstrip('?') == g.PARAM_STRING:
                return False

            if g.PLAYLIST.getposition() == -1:
                return self.create_single_item_playlist_from_info()

            if [i for i in playlist_uris if g.ADDON_NAME.lower() not in i]:
                g.log("Cleaning up other addon items from playlsit", "debug")
                playlist_uris = []

            action_args = [
                g.legacy_action_args_converter(
                    g.legacy_params_converter(
                        dict(tools.parse_qsl(
                            i.split("?")[-1]))))["action_args"]
                for i in playlist_uris
            ]

            show_ids = set(
                tools.deconstruct_action_args(i).get('trakt_show_id')
                for i in action_args)

            if len(show_ids) > 1 and self.show_trakt_id not in show_ids:
                g.log("Cleaning up items from other shows", "debug")
                playlist_uris = []

            if (len(playlist_uris) == 0 or
                (len(playlist_uris) > 1 and not any(g.PARAM_STRING in i for i in playlist_uris))) or \
                    g.PLAYLIST.getposition() == -1:
                return self.create_single_item_playlist_from_info()

        return False
Exemplo n.º 6
0
    def build_playlist(self, season=None, minimum_episode=None, params=None):

        if season is None:
            season = self.info_dictionary['info']['season']

        if minimum_episode is None:
            minimum_episode = int(self.info_dictionary['info']['episode']) + 1

        url_params = self.clean_playback_params(params)

        playlist = tvshowMenus.Menus().episodeListBuilder(self.show_trakt_id,
                                                          season,
                                                          smartPlay=True)

        for i in playlist:
            params = dict(tools.parse_qsl(i[0].replace('?', '')))
            actionArgs = params.get('actionArgs')

            if not tvshowMenus.Menus().is_aired(
                    tools.get_item_information(actionArgs)['info']):
                tools.log('Episode not Aired, skipping')
                continue

            actionArgs = json.loads(actionArgs)

            if actionArgs['episode'] < minimum_episode:
                continue

            url = i[0]

            if actionArgs['episode'] == minimum_episode:
                request_args = json.loads(tools.unquote(self.actionArgs))
                # actionArgs['resume'] = request_args['resume'] if 'resume' in request_args else 'false'
                url = '&actionArgs='.join([
                    url.split('&actionArgs=')[0],
                    tools.quote(json.dumps(actionArgs, sort_keys=True))
                ])

            if url_params is not None:
                url += '&{}'.format(url_params)

            tools.playList.add(url=url, listitem=i[1])
Exemplo n.º 7
0
    def _build_playlist(self, season, minimum_episode):

        playlist = tvshowMenus.Menus().episodeListBuilder(self.show_trakt_id,
                                                          season,
                                                          smartPlay=True)

        for i in playlist:
            # Confirm that the episode meta we have received from TVDB are for the correct episodes
            # If trakt provides the incorrect TVDB ID it's possible to begin play from the incorrect episode
            params = dict(tools.parse_qsl(i[0].replace('?', '')))
            actionArgs = json.loads(params.get('actionArgs'))

            if actionArgs['episode'] < minimum_episode:
                continue

            # If the episode is confirmed ok, add it to our playlist.
            if tvshowMenus.Menus().is_aired(
                    tools.get_item_information(
                        json.dumps(actionArgs))['info']):
                tools.playList.add(url=i[0], listitem=i[1])
Exemplo n.º 8
0
# -*- coding: utf-8 -*-

import sys

from resources.lib.common import tools
from resources.lib.gui import windows
from resources.lib.modules import database

params = dict(tools.parse_qsl(sys.argv[2].replace('?', '')))

url = params.get('url')

action = params.get('action')

page = params.get('page')

actionArgs = params.get('actionArgs')

pack_select = params.get('packSelect')

silent = params.get('silent')

source_select = params.get('source_select')

seren_reload = params.get('seren_reload', False)

if seren_reload == 'true':
    seren_reload = True

if action == None:
    from resources.lib.gui import homeMenu
Exemplo n.º 9
0
    def resolve(self, sources, args, pack_select=False):
        try:
            if 'showInfo' in args:
                background = args['showInfo']['art']['fanart']
            else:
                background = args['fanart']

            self.setText(tools.lang(33000).encode('utf-8'))
            self.setBackground(background)
            stream_link = None
            loop_count = 0
            # Begin resolving links
            tools.log('Attempting to Resolve file link', 'info')
            for i in sources:
                debrid_provider = i.get('debrid_provider', '')
                loop_count += 1
                try:
                    if self.is_canceled():
                        self.close()
                        return
                    if 'size' in i:
                        i['info'].append(tools.source_size_display(i['size']))
                    loop_count_string = "(" + str(loop_count) + " of " + str(
                        len(sources)) + ")"
                    line1 = "%s %s - %s" % (
                        tools.lang(32036).encode('utf-8'),
                        tools.colorString(
                            tools.deaccentString(
                                i['release_title']).encode('utf-8')),
                        loop_count_string)
                    line2 = "%s %s | Source: %s" % (
                        tools.lang(32037).encode('utf-8'),
                        tools.colorString(debrid_provider.upper()),
                        tools.colorString(i['source']))
                    line3 = '%s %s | Info: %s' % (
                        tools.lang(32038).encode('utf-8'),
                        tools.colorString(i['quality']),
                        tools.colorString(" ".join(i['info'])))

                    self.setText(line1)
                    self.setText2(line2)
                    self.setText3(line3)

                    if i['type'] == 'torrent':
                        if i['debrid_provider'] == 'premiumize':
                            stream_link = self.premiumizeResolve(
                                i, args, pack_select)
                        elif i['debrid_provider'] == 'real_debrid':
                            stream_link = self.realdebridResolve(i, args)

                        if stream_link is None:
                            tools.log('Failed to resolve for torrent %s' %
                                      i['release_title'])
                            continue
                        else:
                            self.return_data = stream_link
                            self.close()
                            return

                    elif i['type'] == 'hoster':
                        # Quick fallback to speed up resolving while direct and free hosters are not supported
                        if 'debrid_provider' not in i:
                            continue
                        provider = i['provider_imports']
                        providerModule = __import__('%s.%s' %
                                                    (provider[0], provider[1]),
                                                    fromlist=[''])
                        providerModule = providerModule.source()

                        try:
                            i['url'] = providerModule.resolve(i['url'])
                        except:
                            import traceback
                            traceback.print_exc()
                            pass

                        if i['url'] is None:
                            continue

                        if 'debrid_provider' in i:
                            if i['debrid_provider'] == 'premiumize' and tools.getSetting(
                                    'premiumize.enabled') == 'true':
                                stream_link = self.premiumizeResolve(i, args)
                                if stream_link is None:
                                    continue

                            if i['debrid_provider'] == 'real_debrid':
                                stream_link = self.realdebridResolve(i, args)
                                if stream_link is None:
                                    continue

                        else:
                            # Currently not supporting free hosters at this point in time
                            # ResolveURL and Direct link testing needs to be tested first
                            continue
                            try:
                                try:
                                    headers = i['url'].rsplit('|', 1)[1]
                                except:
                                    headers = ''

                                headers = tools.quote_plus(headers).replace(
                                    '%3D', '=') if ' ' in headers else headers
                                headers = dict(tools.parse_qsl(headers))

                                live_check = requests.head(i['url'],
                                                           headers=headers)

                                if not live_check.status_code == 200:
                                    continue

                                stream_link = i['url']
                            except:
                                stream_link = None

                        if stream_link is None:
                            continue
                        else:
                            if stream_link.endswith('.rar'):
                                continue
                            self.return_data = stream_link
                            self.close()
                            return
                    continue

                except:
                    import traceback
                    traceback.print_exc()
                    continue

            self.close()
            if tools.getSetting('premiumize.enabled') == 'true':
                tools.execute(
                    'RunPlugin("plugin://plugin.video.%s/?action=premiumizeCleanup")'
                    % tools.addonName.lower())
            return
        except:
            import traceback
            traceback.print_exc()
            self.close()
            return
Exemplo n.º 10
0
    def smart_play_show(self, append_playlist=False):

        self.window = windows.smart_play_background()
        self.window.setBackground(self.poster)
        self.window.setText(tools.lang(32094))

        if not append_playlist:
            self.window.show()

        self.window.setProgress(0)
        self.window.setProgress(40)
        self.window.setText(tools.lang(32095))

        if not append_playlist:
            tools.playList.clear()

        if 'episodeInfo' not in self.info_dictionary:
            if tools.getSetting('trakt.auth') == '':
                tools.showDialog.ok(tools.addonName, tools.lang(32093))
                return
            else:
                self.user_history = TraktAPI().json_response(
                    'sync/history/shows/%s' % self.show_trakt_id)

            season, episode = self.get_resume_episode()

            if self.final_episode_check(season, episode) is True:
                season = 1
                episode = 1

        else:
            season = self.info_dictionary['episodeInfo']['info']['season']
            episode = self.info_dictionary['episodeInfo']['info']['episode']

        self.window.setText(tools.lang(32096))
        self.window.setProgress(60)

        if append_playlist:
            # Add next seasons episodes to the currently playing playlist and then finish up

            playlist = tvshowMenus.Menus().episodeListBuilder(
                self.show_trakt_id, season, hide_unaired=True, smartPlay=True)
            for i in playlist:
                # Confirm that the episode meta we have received from TVDB are for the correct episodes
                # If trakt provides the incorrect TVDB ID it's possible to begin play from the incorrect episode
                params = dict(tools.parse_qsl(i[0].replace('?', '')))
                actionArgs = json.loads(params.get('actionArgs'))
                if actionArgs['episodeInfo']['info']['episode'] < episode:
                    continue

                # If the episode is confirmed ok, add it to our playlist.
                if tvshowMenus.Menus().is_aired(
                        actionArgs['episodeInfo']['info']):
                    tools.playList.add(url=i[0], listitem=i[1])
            return

        season_episodes = tvshowMenus.Menus().episodeListBuilder(
            self.show_trakt_id, season, smartPlay=True)

        self.window.setText(tools.lang(32097))
        self.window.setProgress(80)

        playlist = []

        for ep in season_episodes:
            path_arguments = dict(tools.parse_qsl(ep[0].replace('?', '')))
            episode_args = json.loads(
                tools.unquote(path_arguments['actionArgs']))
            ep_no = int(episode_args['episodeInfo']['info']['episode'])

            if ep_no >= episode and tvshowMenus.Menus().is_aired(
                    episode_args['episodeInfo']['info']):
                playlist.append(ep)

        self.window.setText('Starting Playback')
        self.window.setProgress(100)

        for i in playlist:
            tools.playList.add(url=i[0], listitem=i[1])

        tools.log(
            'Begining play from Season %s Episode %s' % (season, episode),
            'info')

        self.window.close()

        tools.player().play(tools.playList)
Exemplo n.º 11
0
    def playlist_present_check(self, ignore_setting=False):
        """
        Confirms if a playlist is currently present. If not or playlist is for a different item, clear current list
        and build a new one
        :param ignore_setting: Force playlist building if setting is disabled
        :type ignore_setting: bool
        :return: Playlist if playlist is present else False
        :rtype: any
        """
        if g.get_bool_setting("smartplay.playlistcreate") or ignore_setting:

            if not self.item_information["info"]["mediatype"] == "episode":
                g.log("Movie playback requested, clearing playlist")
                g.PLAYLIST.clear()
                return False

            playlist_uris = [
                g.PLAYLIST[i].getPath()  # pylint: disable=unsubscriptable-object
                for i in range(g.PLAYLIST.size())
            ]

            # Check to see if we are just starting playback and kodi has created a playlist
            if len(playlist_uris) == 1 and playlist_uris[0].split(
                    '/')[-1] == sys.argv[2]:
                return False

            if [i for i in playlist_uris if g.ADDON_NAME.lower() not in i]:
                g.log("Cleaning up other addon items from playlsit", "debug")
                playlist_uris = []

            action_args = [
                dict(tools.parse_qsl(i.split("?")[-1])).get("action_args")
                for i in playlist_uris
            ]
            action_args = [i for i in action_args if i is not None]

            if not action_args:
                playlist_uris = []

            show_ids = set(
                tools.deconstruct_action_args(i).get('trakt_show_id')
                for i in action_args)

            if len(show_ids) > 1 and self.show_trakt_id not in show_ids:
                g.log("Cleaning up items from other shows", "debug")
                playlist_uris = []

            if len(playlist_uris) == 0 or (len(playlist_uris) > 1 and
                                           not any(sys.argv[2] in i
                                                   for i in playlist_uris)):
                g.cancel_playback()
                name = self.item_information["info"]["title"]
                item = g.add_directory_item(
                    name,
                    action="getSources",
                    menu_item=self.item_information,
                    action_args=tools.construct_action_args(
                        self.item_information),
                    bulk_add=True,
                    is_playable=True,
                )
                g.PLAYLIST.add(url=sys.argv[0] + sys.argv[2], listitem=item[1])
                return g.PLAYLIST
        return False
Exemplo n.º 12
0
 def _get_next_item_args():
     current_position = tools.playList.getposition()
     url = tools.playList[current_position + 1].getPath()
     params = dict(tools.parse_qsl(url.replace('?', '')))
     next_info = params.get('actionArgs')
     return next_info
Exemplo n.º 13
0
    def smart_play_show(self, append_playlist=False):

        self.window = windows.smart_play_background()

        self.window.setBackground(self.poster)

        self.window.setText(tools.lang(32094).encode('utf-8'))
        if not append_playlist:
            self.window.show()
        self.window.setProgress(0)
        self.window.setProgress(40)
        self.window.setText(tools.lang(32095).encode('utf-8'))

        if not append_playlist:
            tools.playList.clear()

        if 'episodeInfo' not in self.info_dictionary:
            if tools.getSetting('trakt.auth') == '':
                tools.showDialog.ok(tools.addonName,
                                    tools.lang(32093).encode('utf-8'))
                return
            season, episode = self.get_resume_episode()

            if self.final_episode_check(season, episode) is True:
                season = 1
                episode = 1

            season_object = TraktAPI().json_response(
                'shows/%s/seasons?extended=full' %
                self.info_dictionary['ids']['trakt'])
            season_object = [x for x in season_object if x['number'] == season]
            self.info_dictionary = tvshowMenus.Menus().seasonListBuilder(
                season_object, self.info_dictionary, smartPlay=True)
            self.info_dictionary = json.loads(
                tools.unquote(self.info_dictionary))
        else:
            season = self.info_dictionary['episodeInfo']['info']['season']
            episode = self.info_dictionary['episodeInfo']['info']['episode']

        self.window.setText(tools.lang(32096).encode('utf-8'))
        self.window.setProgress(60)

        episode_list = database.get(
            TraktAPI().json_response, 12, 'shows/%s/seasons/%s?extended=full' %
            (self.show_trakt_id, str(season)))

        playlist = []

        for i in episode_list:
            if i['number'] < episode:
                continue
            playlist.append(i)

        if append_playlist:
            tools.log("STARTING PLAYLIST GENERATION")
            playlist = tvshowMenus.Menus().episodeListBuilder(
                playlist, self.info_dictionary, smartPlay=True)
            for i in playlist:
                # Confirm that the episode meta we have received from TVDB are for the correct episodes
                # If trakt provides the incorrect TVDB ID it's possible to begin play from the incorrect episode
                params = dict(tools.parse_qsl(i[0].replace('?', '')))
                actionArgs = json.loads(params.get('actionArgs'))
                if actionArgs['episodeInfo']['info']['episode'] < episode:
                    continue

                # If the episode is confirmed ok, add it to our playlist.
                tools.log("ADDING ITEM TO PLAYLIST")
                tools.playList.add(url=i[0], listitem=i[1])
            return

        self.window.setText(tools.lang(32097).encode('utf-8'))
        self.window.setProgress(80)

        actionArgs = {}
        actionArgs['playlist'] = playlist
        actionArgs['info_dictionary'] = self.info_dictionary
        actionArgs = tools.quote(json.dumps(actionArgs))

        # Begin nasty Kodi 18 Skin workaround

        tools.execute(
            'RunPlugin(plugin://plugin.video.%s?action=buildPlaylist&actionArgs=%s)'
            % (tools.addonName.lower(), actionArgs))

        self.window.close()
Exemplo n.º 14
0
    def resolve(self, sources, args, pack_select=False):

        try:

            stream_link = None
            loop_count = 0
            # Begin resolving links

            for i in sources:
                debrid_provider = i.get('debrid_provider',
                                        'None').replace('_', ' ')
                loop_count += 1
                try:
                    if self.is_canceled():
                        self.close()
                        return

                    if 'size' in i:
                        i['info'].append(tools.source_size_display(i['size']))

                    self.setProperty('release_title',
                                     tools.display_string(i['release_title']))
                    self.setProperty('debrid_provider', debrid_provider)
                    self.setProperty('source_provider', i['provider'])
                    self.setProperty('source_resolution', i['quality'])
                    self.setProperty('source_info', " ".join(i['info']))

                    if i['type'] == 'torrent':
                        stream_link = self.resolve_source(
                            self.resolvers[i['debrid_provider']], i, args,
                            pack_select)
                        if stream_link is None:
                            tools.log('Failed to resolve for torrent %s' %
                                      i['release_title'])
                            continue
                        else:
                            self.return_data = stream_link
                            self.close()
                            return

                    elif i['type'] == 'hoster' or i['type'] == 'cloud':

                        if i['url'] is None:
                            continue

                        if i['type'] == 'cloud' and i[
                                'debrid_provider'] == 'premiumize':
                            selected_file = Premiumize.Premiumize(
                            ).item_details(i['url'])
                            if tools.getSetting(
                                    'premiumize.transcoded') == 'true':
                                url = selected_file['stream_link']
                            else:
                                url = selected_file['link']
                            self.return_data = url
                            self.close()
                            return

                        if 'provider_imports' in i:
                            provider = i['provider_imports']
                            providerModule = __import__(
                                '%s.%s' % (provider[0], provider[1]),
                                fromlist=[''])
                            providerModule = providerModule.source()

                            try:
                                i['url'] = providerModule.resolve(i['url'])
                            except:
                                import traceback
                                traceback.print_exc()
                                pass

                        if 'debrid_provider' in i:
                            stream_link = self.resolve_source(
                                self.resolvers[i['debrid_provider']], i, args,
                                pack_select)
                            if stream_link is None:
                                continue
                            else:
                                try:
                                    requests.head(stream_link, timeout=1)
                                except requests.exceptions.RequestException:
                                    tools.log(
                                        'Head Request failed link likely dead, skipping'
                                    )
                                    continue

                        elif i['url'].startswith('http'):
                            try:
                                ext = i['url'].split('?')[0]
                                ext = ext.split('&')[0]
                                ext = ext.split('|')[0]
                                ext = ext.rsplit('.')[-1]
                                ext = ext.replace('/', '').lower()
                                if ext == 'rar': raise Exception()

                                try:
                                    headers = i['url'].rsplit('|', 1)[1]
                                except:
                                    headers = ''

                                headers = tools.quote_plus(headers).replace(
                                    '%3D', '=') if ' ' in headers else headers
                                headers = dict(tools.parse_qsl(headers))

                                live_check = requests.head(i['url'],
                                                           headers=headers,
                                                           timeout=10)

                                if not live_check.status_code == 200:
                                    tools.log(
                                        'Head Request failed link likely dead, skipping'
                                    )
                                    continue

                                stream_link = i['url']
                            except:
                                import traceback
                                traceback.print_exc()
                                stream_link = None

                        elif tools.file_exists(i['url']):
                            stream_link = i['url']

                        if stream_link is None:
                            continue
                        else:
                            if stream_link.endswith('.rar'):
                                continue
                            self.return_data = stream_link
                            self.close()
                            return
                    continue

                except:
                    import traceback
                    traceback.print_exc()
                    continue

            self.close()
            return
        except:
            import traceback
            traceback.print_exc()
            self.close()
            return
Exemplo n.º 15
0
    def resolve(self, sources, args, pack_select=False):
        try:
            if 'showInfo' in args:
                background = args['showInfo']['art']['fanart']
            else:
                background = args['art']['fanart']

            stream_link = None
            loop_count = 0
            # Begin resolving links
            tools.log('Attempting to Resolve file link', 'info')
            for i in sources:
                debrid_provider = i.get('debrid_provider',
                                        'None').replace('_', ' ')
                loop_count += 1
                try:
                    if self.is_canceled():
                        self.close()
                        return
                    if 'size' in i:
                        i['info'].append(tools.source_size_display(i['size']))

                    self.setProperty('release_title',
                                     tools.display_string(i['release_title']))
                    self.setProperty('debrid_provider', debrid_provider)
                    self.setProperty('source_provider', i['source'])
                    self.setProperty('source_resolution', i['quality'])
                    self.setProperty('source_info', " ".join(i['info']))

                    if i['type'] == 'torrent':
                        if i['debrid_provider'] == 'premiumize':
                            stream_link = self.premiumizeResolve(
                                i, args, pack_select)
                        elif i['debrid_provider'] == 'real_debrid':
                            stream_link = self.realdebridResolve(i, args)

                        if stream_link is None:
                            tools.log('Failed to resolve for torrent %s' %
                                      i['release_title'])
                            continue
                        else:
                            self.return_data = stream_link
                            self.close()
                            return

                    elif i['type'] == 'hoster' or i['type'] == 'cloud':
                        # Quick fallback to speed up resolving while direct and free hosters are not supported

                        if 'provider_imports' in i:
                            provider = i['provider_imports']
                            providerModule = __import__(
                                '%s.%s' % (provider[0], provider[1]),
                                fromlist=[''])
                            providerModule = providerModule.source()

                            try:
                                i['url'] = providerModule.resolve(i['url'])
                            except:
                                import traceback
                                traceback.print_exc()
                                pass

                        if i['url'] is None:
                            continue

                        if 'debrid_provider' in i:
                            if i['debrid_provider'] == 'premiumize' and tools.premiumize_enabled(
                            ):
                                stream_link = self.premiumizeResolve(i, args)
                                if stream_link is None:
                                    continue
                                else:
                                    try:
                                        requests.head(stream_link, timeout=1)
                                    except:
                                        tools.log(
                                            'Head Request failed link might be dead, skipping'
                                        )
                                        continue

                            if i['debrid_provider'] == 'real_debrid' and tools.real_debrid_enabled(
                            ):
                                stream_link = self.realdebridResolve(i, args)
                                if stream_link is None:
                                    continue
                                try:
                                    requests.head(stream_link, timeout=1)
                                except:
                                    tools.log(
                                        'Head Request failed link might be dead, skipping'
                                    )
                                    continue
                        else:
                            # Currently not supporting free hosters at this point in time
                            # ResolveURL and Direct link testing needs to be tested first
                            try:
                                ext = i['url'].split('?')[0].split(
                                    '&')[0].split('|')[0].rsplit(
                                        '.')[-1].replace('/', '').lower()
                                if ext == 'rar': raise Exception()
                                try:
                                    headers = i['url'].rsplit('|', 1)[1]
                                except:
                                    headers = ''

                                try:
                                    headers = i['url'].rsplit('|', 1)[1]
                                except:
                                    headers = ''
                                headers = tools.quote_plus(headers).replace(
                                    '%3D', '=') if ' ' in headers else headers
                                headers = dict(tools.parse_qsl(headers))

                                live_check = requests.head(i['url'],
                                                           headers=headers,
                                                           timeout=10)

                                if not live_check.status_code == 200:
                                    continue

                                stream_link = i['url']
                            except:
                                stream_link = None

                        if stream_link is None:
                            continue
                        else:
                            if stream_link.endswith('.rar'):
                                continue
                            self.return_data = stream_link
                            self.close()
                            return
                    continue

                except:
                    import traceback
                    traceback.print_exc()
                    continue

            self.close()
            return
        except:
            import traceback
            traceback.print_exc()
            self.close()
            return