Пример #1
0
    def search(self, url):

        try:
            query = parse_qs(urlparse(url).query)['q'][0]

            url = self.search_link % quote_plus(query) + self.key_link

            result = client.request(url)

            items = json.loads(result)['items']
            items = [(i['id']['videoId']) for i in items]

            for url in items:
                url = self.resolve(url)
                if url is not None:
                    return url
        except Exception:
            return
Пример #2
0
def run_builtin(addon_id=control.addonInfo('id'),
                action=None,
                mode=None,
                content_type=None,
                url=None,
                query=None,
                path_history='',
                get_url=False,
                command=('ActivateWindow', 'Container.Update'),
                *args):
    """
    This function will construct a url starting with plugin:// attached to the addon_id, then passed into either
    the ActivateWindow built-in command or Container.Update for listing/container manipulation. You have to either pass action,
    mode, content_type or query, otherwise TypeError will be raised. Can also apply the "PlayMedia".
    Query will override action, mode, url and content_type arguments if passed as dictionary
    path_history can also be either ",return" or ",replace"
    """

    if not query and not action and not mode and not content_type:

        raise TypeError('Cannot manipulate container without arguments')

    if isinstance(query, dict):

        query_string = urlencode(query)

    else:

        query_string = ''

        if content_type:
            query_string += 'content_type={0}{1}'.format(
                content_type, ''
                if action is None and mode is None and query is None else '&')

        if action:

            query_string += 'action={0}'.format(action)

        if mode:

            query_string += 'mode={0}'.format(mode)

        if url:

            query_string += '&url={0}'.format(quote_plus(url))

        if query:

            query_string += '&query={0}'.format(query)

        if args:

            query_string += '&' + '&'.join(args)

    if 'content_type=video' in query_string:
        window_id = 'videos'
    elif 'content_type=audio' in query_string:
        window_id = 'music'
    elif 'content_type=image' in query_string:
        window_id = 'pictures'
    elif 'content_type=executable' in query_string:
        window_id = 'programs'
    elif 'content_type' in query_string and dict(
            parse_qsl(query_string))['content_type'] not in [
                'video', 'audio', 'image', 'executable'
            ]:
        raise AttributeError('Incorrect content_type specified')

    addon_id = ''.join(['plugin://', addon_id, '/'])

    if 'content_type' in query_string and isinstance(command, tuple):

        # noinspection PyUnboundLocalVariable
        executable = '{0}({1},"{2}?{3}"{4})'.format(
            command[0], window_id, addon_id, query_string,
            ',return' if not path_history else path_history)

    else:

        if isinstance(command, tuple):

            executable = '{0}({1}?{2}{3})'.format(
                command[1], addon_id, query_string,
                ',return' if not path_history else path_history)

        else:

            executable = '{0}({1}?{2}{3})'.format(
                command, addon_id, query_string,
                ',return' if not path_history else path_history)

    if get_url:

        return executable

    else:

        control.execute(executable)
Пример #3
0
def playlist_maker(items=None, argv=None):

    if items is None:
        return

    if argv is None:

        from tulip.init import sysaddon

    else:

        sysaddon = argv[0]

    m3u_list = [u'#EXTM3U\n']

    for i in items:

        try:
            action = '{0}?action={1}'.format(sysaddon, i['action'])
        except KeyError:
            return
        try:
            url = '&url={0}'.format(quote_plus(i['url']))
        except Exception:
            url = None
        try:
            title = '&title={0}'.format(quote_plus(i['title']))
        except KeyError:
            try:
                title = '&title={}'.format(
                    quote_plus(i['title'].encode('utf-8')))
            except KeyError:
                title = None
        except Exception:
            title = None

        try:
            icon = '&image={0}'.format(quote_plus(i['image']))
        except KeyError:
            try:
                icon = '&image={0}'.format(
                    quote_plus(i['image'].encode('utf-8')))
            except KeyError:
                icon = None
        except Exception:
            icon = None

        try:
            name = '&name={0}'.format(quote_plus(i['name']))
        except KeyError:
            try:
                name = '&name={0}'.format(quote_plus(
                    i['name'].encode('utf-8')))
            except KeyError:
                name = None
        except Exception:
            name = None
        try:
            year = '&year={0}'.format(quote_plus(i['year']))
        except Exception:
            year = None
        try:
            plot = '&plot={0}'.format(quote_plus(i['plot']))
        except KeyError:
            try:
                plot = '&plot={0}'.format(quote_plus(
                    i['plot'].encode('utf-8')))
            except KeyError:
                plot = None
        except Exception:
            plot = None

        parts = [
            foo for foo in [action, url, title, icon, name, year, plot] if foo
        ]

        uri = '&'.join(parts)

        if icon:
            m3u_list.append(
                u'#EXTINF:0 tvg-logo="{0}",{1}\n'.format(icon, i['title']) +
                uri + '\n')
        else:
            m3u_list.append(u'#EXTINF:0,{0}\n'.format(i['title']) + uri + '\n')

    return ''.join(m3u_list)
Пример #4
0
def add(items,
        cacheToDisc=True,
        content=None,
        mediatype=None,
        infotype='video',
        argv=None,
        as_playlist=False,
        pd_heading=None,
        pd_message='',
        clear_first=True,
        progress=False,
        category=None):

    if argv is None:

        from tulip.init import sysaddon, syshandle

    else:

        sysaddon = argv[0]
        syshandle = int(argv[1])

    if items is None or len(items) == 0:
        return

    # sysicon = control.join(control.addonInfo('path'), 'resources', 'media')
    sysimage = control.addonInfo('icon')
    sysfanart = control.addonInfo('fanart')

    if progress:

        pd = control.progressDialogGB
        pd.create(heading=control.name() if not pd_heading else pd_heading,
                  message=pd_message)

    else:

        pd = None

    if as_playlist and clear_first:

        control.playlist(1 if infotype == 'video' else 0).clear()

    meta_tags = [
        'count', 'size', 'date', 'genre', 'country', 'year', 'episode',
        'season', 'sortepisode', 'sortseason', 'episodeguide', 'showlink',
        'top250', 'setid', 'tracknumber', 'rating', 'userrating', 'watched',
        'playcount', 'overlay', 'cast', 'castandrole', 'director', 'mpaa',
        'plot', 'plotoutline', 'title', 'originaltitle', 'sorttitle',
        'duration', 'studio', 'tagline', 'writer', 'tvshowtitle', 'premiered',
        'status', 'set', 'gameclient', 'setoverview', 'tag', 'imdbnumber',
        'code', 'aired', 'credits', 'lastplayed', 'album', 'artist', 'votes',
        'path', 'trailer', 'dateadded', 'mediatype', 'dbid', 'tracknumber',
        'discnumber', 'lyrics', 'listeners', 'musicbrainztrackid', 'comment',
        'picturepath', 'platform', 'genres', 'publisher', 'developer',
        'overview'
    ]

    for c, i in list(enumerate(items)):

        try:

            if progress:

                p = control.per_cent(c, len(items))
                pd.update(p)

            try:
                label = control.lang(i['title']).encode('utf-8')
            except Exception:
                label = i['title']

            if 'label' in i and not i['label'] == '0':
                label = i['label']

            if 'image' in i and not i['image'] == '0':
                image = i['image']
            elif 'poster' in i and not i['poster'] == '0':
                image = i['poster']
            elif 'icon' in i and not i['icon'] == '0':
                image = control.addonmedia(i['icon'])
            else:
                image = sysimage

            if 'banner' in i and not i['banner'] == '0':
                banner = i['banner']
            elif 'fanart' in i and not i['fanart'] == '0':
                banner = i['fanart']
            else:
                banner = image

            fanart = i['fanart'] if 'fanart' in i and not i[
                'fanart'] == '0' else sysfanart

            isFolder = False if 'isFolder' in i and not i[
                'isFolder'] == '0' else True

            try:
                is_play_boolean = i.get('isPlayable') in [
                    'True', 'true', '1', 'yes', 'Yes'
                ]
            except Exception:
                is_play_boolean = False

            isPlayable = True if not isFolder and 'isPlayable' not in i else is_play_boolean

            if isPlayable:

                isFolder = False

            try:
                action = '{0}?action={1}'.format(sysaddon, i['action'])
            except KeyError:
                return

            try:
                url = 'url={0}'.format(quote_plus(i['url']))
            except Exception:
                url = None

            try:
                title = 'title={0}'.format(quote_plus(i['title']))
            except KeyError:
                try:
                    title = 'title={0}'.format(
                        quote_plus(i['title'].encode('utf-8')))
                except KeyError:
                    title = None
            except Exception:
                title = None

            try:
                icon = 'image={0}'.format(quote_plus(i['image']))
            except KeyError:
                try:
                    icon = 'image={0}'.format(
                        quote_plus(i['image'].encode('utf-8')))
                except KeyError:
                    icon = None
            except Exception:
                icon = None
            try:
                name = 'name={0}'.format(quote_plus(i['name']))
            except KeyError:
                try:
                    name = 'name={0}'.format(
                        quote_plus(i['name'].encode('utf-8')))
                except KeyError:
                    name = None
            except Exception:
                name = None
            try:
                year = 'year={0}'.format(quote_plus(i['year']))
            except Exception:
                year = None
            try:
                plot = 'plot={0}'.format(quote_plus(i['plot']))
            except KeyError:
                try:
                    plot = 'plot={0}'.format(
                        quote_plus(i['plot'].encode('utf-8')))
                except KeyError:
                    plot = None
            except Exception:
                plot = None
            try:
                genre = 'genre={0}'.format(quote_plus(i['genre']))
            except KeyError:
                try:
                    genre = 'genre={0}'.format(
                        quote_plus(i['genre'].encode('utf-8')))
                except KeyError:
                    genre = None
            except Exception:
                genre = None
            try:
                dash = 'dash={0}'.format(quote_plus(i['dash']))
            except Exception:
                dash = None
            try:
                query = 'query={0}'.format(quote_plus(i['query']))
            except Exception:
                query = None

            parts = [
                foo for foo in [
                    action, url, title, icon, name, year, plot, genre, dash,
                    query
                ] if foo
            ]

            uri = '&'.join(parts)

            cm = []
            menus = i['cm'] if 'cm' in i else []

            for menu in menus:

                try:

                    try:
                        tmenu = control.lang(menu['title']).encode('utf-8')
                    except Exception:
                        tmenu = menu['title']
                    try:
                        qmenu = urlencode(menu['query'])
                    except Exception:
                        qmenu = urlencode(
                            dict((k, v.encode('utf-8'))
                                 for k, v in menu['query'].items()))
                    cm.append(
                        (tmenu, 'RunPlugin({0}?{1})'.format(sysaddon, qmenu)))

                except Exception:

                    pass

            meta = dict((k, v) for k, v in iteritems(i)
                        if k in meta_tags and (not v == '0' or v is None))

            if mediatype is not None:
                meta['mediatype'] = mediatype

            item = control.item(label=label)

            item.setArt({
                'icon': image,
                'thumb': image,
                'poster': image,
                'tvshow.poster': image,
                'season.poster': image,
                'banner': banner,
                'tvshow.banner': banner,
                'season.banner': banner,
                'fanart': fanart
            })

            item.addContextMenuItems(cm)
            item.setInfo(
                type=infotype if 'infotype' not in i else i['infotype'],
                infoLabels=meta)

            if isPlayable:

                if not i['action'] == 'pvr_client':
                    item.setProperty('IsPlayable', 'true')
                else:
                    item.setProperty('IsPlayable', 'false')

                if not i['action'] == 'pvr_client':
                    if 'streaminfo' not in i and infotype == 'video':
                        item.addStreamInfo(infotype, {'codec': 'h264'})
                    else:
                        item.addStreamInfo(infotype, i.get('streaminfo'))

            if as_playlist and isPlayable:
                control.playlist(1 if infotype == 'video' else 0).add(
                    url=uri, listitem=item, index=c)
            else:
                control.addItem(handle=syshandle,
                                url=uri,
                                listitem=item,
                                isFolder=isFolder,
                                totalItems=len(items))

        except Exception as reason:
            log('Directory not added, reason of failure: ' + repr(reason))

    if progress:
        pd.update(100)
        pd.close()

    if as_playlist:

        control.openPlaylist(1 if infotype == 'video' else 0)

        return

    try:

        i = items[0]
        if i['next'] == '':
            raise Exception()

        url = '{0}?action={1}&url={2}'.format(sysaddon, i['nextaction'],
                                              quote_plus(i['next']))
        icon = i['nexticon'] if 'nexticon' in i else control.addonmedia(
            'next.png')
        fanart = i['nextfanart'] if 'nextfanart' in i else sysfanart

        try:
            label = control.lang(i['nextlabel']).encode('utf-8')
        except Exception:
            label = 'Next'

        item = control.item(label=label)

        item.setArt({
            'icon': icon,
            'thumb': icon,
            'poster': icon,
            'tvshow.poster': icon,
            'season.poster': icon,
            'banner': icon,
            'tvshow.banner': icon,
            'season.banner': icon,
            'fanart': fanart
        })

        control.addItem(handle=syshandle,
                        url=url,
                        listitem=item,
                        isFolder=True,
                        totalItems=len(items))

    except Exception:

        pass

    if content is not None:
        control.content(syshandle, content)

    if category is not None:
        control.setcategory(syshandle, category)

    control.directory(syshandle, cacheToDisc=cacheToDisc)
Пример #5
0
    def get(self, query):

        query = py3_dec(query)

        try:

            query = ' '.join(
                unquote_plus(re.sub(r'%\w\w', ' ', quote_plus(query))).split())

            url = ''.join([
                self.base_link,
                '/search.php?name={0}'.format(quote_plus(query))
            ])

            result = client.request(url, timeout=control.setting('timeout'))

            try:
                result = result.decode('utf-8', errors='replace')
            except AttributeError:
                pass

            items = client.parseDOM(result, 'tr', attrs={'on.+?': '.+?'})

            if not items:
                log_debug('Subtitles.gr did not provide any results')
                return

        except Exception as e:

            _, __, tb = sys.exc_info()

            print(traceback.print_tb(tb))

            log_debug('Subtitles.gr failed at get function, reason: ' + str(e))

            return

        for item in items:

            try:

                if u'flags/el.gif' not in item:

                    continue

                try:
                    uploader = client.parseDOM(item,
                                               'a',
                                               attrs={'class':
                                                      'link_from'})[0].strip()
                    uploader = client.replaceHTMLCodes(uploader)
                except IndexError:
                    uploader = ''

                try:
                    uploader = uploader.decode('utf-8')
                except AttributeError:
                    pass

                if not uploader:
                    uploader = 'other'

                try:
                    downloads = client.parseDOM(
                        item, 'td', attrs={'class':
                                           'latest_downloads'})[0].strip()
                except:
                    downloads = '0'

                downloads = re.sub('[^0-9]', '', downloads)

                name = client.parseDOM(item,
                                       'a',
                                       attrs={'onclick': 'runme.+?'})[0]
                name = ' '.join(re.sub('<.+?>', '', name).split())
                name = client.replaceHTMLCodes(name)
                label = u'[{0}] {1} [{2} DLs]'.format(uploader, name,
                                                      downloads)

                url = client.parseDOM(item,
                                      'a',
                                      ret='href',
                                      attrs={'onclick': 'runme.+?'})[0]
                url = url.split('"')[0].split('\'')[0].split(' ')[0]
                url = client.replaceHTMLCodes(url)
                url = url.encode('utf-8')

                rating = self._rating(downloads)

                self.list.append({
                    'name': label,
                    'url': url,
                    'source': 'subtitlesgr',
                    'rating': rating,
                    'title': name,
                    'downloads': downloads
                })

            except Exception as e:

                _, __, tb = sys.exc_info()

                print(traceback.print_tb(tb))

                log_debug(
                    'Subtitles.gr failed at self.list formation function, reason: '
                    + str(e))

                return

        return self.list
Пример #6
0
def cfcookie(netloc, ua, timeout):
    try:
        headers = {'User-Agent': ua}

        req = urllib2.Request(netloc, headers=headers)

        try:
            urllib2.urlopen(req, timeout=int(timeout))
        except urllib2.HTTPError as response:
            result = response.read(5242880)

        jschl = re.findall('name="jschl_vc" value="(.+?)"/>', result)[0]

        init = re.findall('setTimeout\(function\(\){\s*.*?.*:(.*?)};',
                          result)[-1]

        builder = re.findall(r"challenge-form\'\);\s*(.*)a.v", result)[0]

        decryptVal = parseJSString(init)

        lines = builder.split(';')

        for line in lines:

            if len(line) > 0 and '=' in line:

                sections = line.split('=')
                line_val = parseJSString(sections[1])
                decryptVal = int(
                    eval(
                        str(decryptVal) + str(sections[0][-1]) +
                        str(line_val)))

        answer = decryptVal + len(urlparse(netloc).netloc)

        query = '%s/cdn-cgi/l/chk_jschl?jschl_vc=%s&jschl_answer=%s' % (
            netloc, jschl, answer)

        if 'type="hidden" name="pass"' in result:
            passval = re.findall('name="pass" value="(.*?)"', result)[0]
            query = '%s/cdn-cgi/l/chk_jschl?pass=%s&jschl_vc=%s&jschl_answer=%s' % (
                netloc, quote_plus(passval), jschl, answer)
            time.sleep(5)

        cookies = cookielib.LWPCookieJar()
        handlers = [
            urllib2.HTTPHandler(),
            urllib2.HTTPSHandler(),
            urllib2.HTTPCookieProcessor(cookies)
        ]
        opener = urllib2.build_opener(*handlers)
        urllib2.install_opener(opener)

        try:
            req = urllib2.Request(query, headers=headers)
            urllib2.urlopen(req, timeout=int(timeout))
        except Exception:
            pass

        cookie = '; '.join(['%s=%s' % (i.name, i.value) for i in cookies])

        return cookie
    except Exception:
        pass
    def get(self, query):

        query = py3_dec(query)

        try:

            query = ' '.join(
                unquote_plus(re.sub(r'%\w\w', ' ', quote_plus(query))).split())

            query_link = '&'.join([
                'keywords={keywords}', 'movie_type={movie_type}',
                'language=!el', 'seasons={seasons}', 'episodes={episodes}',
                'year={year}', 'type=', 'undefined=auto', 'undefined=en'
            ])

            match = re.findall(
                r'(.+?)(?: -)?[ \.](?:\(?(\d{4})\)?|S?(\d{1,2})X?(?: |\.)?E?P?(\d{1,2})(?: \. (.+))?)',
                query,
                flags=re.I)

            if match:

                query, year, season, episode, episode_title = match[0]

                url = '?'.join([
                    self.search_link,
                    query_link.format(
                        keywords=quote_plus(query),
                        movie_type='movie'
                        if year and not (season or episode) else 'tv-series',
                        seasons=season,
                        episodes=episode,
                        year=year)
                ])

            else:

                url = '?'.join([
                    self.search_link,
                    query_link.format(keywords=quote_plus(query),
                                      movie_type='',
                                      seasons='',
                                      episodes='',
                                      year='')
                ])

            result = client.request(url,
                                    headers={
                                        'Accept':
                                        'text/html',
                                        'Accept-Language':
                                        'en-US,en;q=0.9,el;q=0.8'
                                    },
                                    timeout=control.setting('timeout'),
                                    verify=False)

            try:
                result = result.decode('utf-8', errors='replace')
            except AttributeError:
                pass

            items = client.parseDOM(result,
                                    'tr',
                                    attrs={'class': 'subtitle-entry'})

            if not items:
                log_debug('Podnapisi.net did not provide any results')
                return

        except Exception as e:

            _, __, tb = sys.exc_info()

            print(traceback.print_tb(tb))

            log_debug('Podnapisi.net failed at get function, reason: ' +
                      str(e))

            return

        for item in items:

            try:

                if '<span>el</span>' not in item:
                    continue

                table = client.parseDOM(item, 'td')

                try:
                    downloads = [i.strip() for i in table]
                    downloads = [i for i in downloads if i.isdigit()][1]
                except IndexError:
                    downloads = '0'

                downloads = re.sub('[^0-9]', '', downloads)

                label = client.parseDOM(item,
                                        'a',
                                        attrs={'alt': 'Subtitles\' page'})[0]
                label = client.replaceHTMLCodes(label)
                name = u'{0} [{1} DLs]'.format(label, downloads)

                url = [i for i in table if 'Download subtitles.' in i][0]
                url = client.parseDOM(url, 'a', ret='href')[0]
                url = ''.join([self.base_link, url])

                rating = [i for i in table if 'progress rating' in i][0]
                rating = client.parseDOM(rating,
                                         'div',
                                         attrs={'class': 'progress rating'},
                                         ret='data-title')[0]
                rating = int(rating.partition('.')[0]) / 20

                self.list.append({
                    'name': name,
                    'url': url,
                    'source': 'podnapisi',
                    'rating': rating,
                    'title': label,
                    'downloads': downloads
                })

            except Exception as e:

                _, __, tb = sys.exc_info()

                print(traceback.print_tb(tb))

                log_debug(
                    'Podnapisi.net failed at self.list formation function, reason: '
                    + str(e))

                return

        return self.list
Пример #8
0
    def download(self, path, url):

        try:

            url = re.findall(r'/(\d+)/', url + '/', re.I)[-1]
            url = ''.join([self.download_link, '/getp.php?id={0}'.format(url)])
            url = client.request(url,
                                 output='geturl',
                                 timeout=control.setting('timeout'))

            req = Request(url)
            req.add_header('User-Agent', randomagent())
            opener = urlopen(req)
            data = opener.read()
            zip_file = zipfile.ZipFile(BytesIO(data))
            opener.close()
            files = zip_file.namelist()
            files = [i for i in files if i.startswith('subs/')]

            srt = [i for i in files if i.endswith(('.srt', '.sub'))]
            archive = [i for i in files if i.endswith(('.rar', '.zip'))]

            if len(srt) > 0:

                if len(srt) > 1:
                    srt = multichoice(srt)
                else:
                    srt = srt[0]

                result = zip_file.open(srt).read()

                subtitle = basename(srt)

                try:
                    subtitle = control.join(path, subtitle.decode('utf-8'))
                except Exception:
                    subtitle = control.join(path, subtitle)

                with open(subtitle, 'wb') as subFile:
                    subFile.write(result)

                return subtitle

            elif len(archive) > 0:

                if len(archive) > 1:
                    archive = multichoice(archive)
                else:
                    archive = archive[0]

                result = zip_file.open(archive).read()

                f = control.join(path, os_split(url)[1])

                with open(f, 'wb') as subFile:
                    subFile.write(result)

                dirs, files = control.listDir(path)

                if len(files) == 0:
                    return

                if zipfile.is_zipfile(f):

                    zipped = zipfile.ZipFile(f)
                    zipped.extractall(path)

                if not zipfile.is_zipfile(f):

                    if control.infoLabel('System.Platform.Windows'):
                        uri = "rar://{0}/".format(quote(f))
                    else:
                        uri = "rar://{0}/".format(quote_plus(f))

                    dirs, files = control.listDir(uri)

                else:

                    dirs, files = control.listDir(path)

                if dirs and not zipfile.is_zipfile(f):

                    for dir in dirs:

                        _dirs, _files = control.listDir(control.join(uri, dir))

                        [files.append(control.join(dir, i)) for i in _files]

                        if _dirs:

                            for _dir in _dirs:

                                _dir = control.join(_dir, dir)

                                __dirs, __files = control.listDir(
                                    control.join(uri, _dir))

                                [
                                    files.append(control.join(_dir, i))
                                    for i in __files
                                ]

                filenames = [i for i in files if i.endswith(('.srt', '.sub'))]

                filename = multichoice(filenames)

                try:

                    filename = filename.decode('utf-8')

                except Exception:

                    pass

                if not control.exists(control.join(
                        path,
                        os_split(filename)[0])) and not zipfile.is_zipfile(f):
                    control.makeFiles(control.join(path,
                                                   os_split(filename)[0]))

                subtitle = control.join(path, filename)

                if not zipfile.is_zipfile(f):

                    with closing(control.openFile(uri + filename)) as fn:

                        try:
                            output = bytes(fn.readBytes())
                        except Exception:
                            output = bytes(fn.read())

                    content = output.decode('utf-16')

                    with closing(control.openFile(subtitle, 'w')) as subFile:
                        subFile.write(bytearray(content.encode('utf-8')))

                fileparts = os_split(subtitle)[1].split('.')
                # noinspection PyTypeChecker
                result = control.join(
                    os_split(subtitle)[0],
                    'subtitles.' + fileparts[len(fileparts) - 1])

                control.rename(subtitle, result)

                return result

        except Exception as e:

            _, __, tb = sys.exc_info()

            print(traceback.print_tb(tb))

            log_debug(
                'Subtitles.gr subtitle download failed for the following reason: '
                + str(e))

            return
    def get(self, query):

        query = py3_dec(query)

        try:

            query = ' '.join(
                unquote_plus(re.sub(r'%\w\w', ' ', quote_plus(query))).split())

            match = re.findall(
                r'(.+?)(?: -)?[ \.](?:\(?(\d{4})\)?|S?(\d{1,2})X?(?: |\.)?E?P?(\d{1,2})(?: \. (.+))?)',
                query,
                flags=re.I)

            if match:

                query, year, season, episode, episode_title = match[0]

                search = quote_plus(' '.join(
                    [query, 's', season, 'e', episode, episode_title]))

                url = self.search_show.format(search)

            else:

                url = self.search_movie.format(quote_plus(query))

            self.data = [
                client.request(url, timeout=control.setting('timeout'))
            ]

            try:
                _next_button = client.parseDOM(
                    self.data[0],
                    'a',
                    attrs={'class': 'next page-numbers'},
                    ret='href')[0]
            except IndexError:
                _next_button = None

            while _next_button:

                self.data.append(
                    client.request(_next_button,
                                   timeout=control.setting('timeout')))

                try:
                    _next_button = client.parseDOM(
                        self.data[-1],
                        'a',
                        attrs={'class': 'next page-numbers'},
                        ret='href')[0]
                    control.sleep(200)
                except IndexError:
                    _next_button = None
                    break

            html = '\n'.join(self.data)

            items = client.parseDOM(html,
                                    'div',
                                    attrs={'class': 'article__summary'})

            if not items:
                log_debug('Vipsubs.gr did not provide any results')
                return

        except Exception as e:

            _, __, tb = sys.exc_info()

            print(traceback.print_tb(tb))

            log_debug('Vipsubs.gr failed at get function, reason: ' + str(e))

            return

        for item in items:

            try:

                label = itertags_wrapper(item, 'a', attrs={'rel':
                                                           "bookmark"})[0].text

                label = client.replaceHTMLCodes(label)

                url = itertags_wrapper(item, 'a', ret='href')[-1]
                if 'vipsubs.gr' in url:
                    continue
                rating = 10.0

                self.list.append({
                    'name': label,
                    'url': url,
                    'source': 'vipsubs',
                    'rating': rating,
                    'title': label,
                    'downloads': '1000'
                })

            except Exception as e:

                _, __, tb = sys.exc_info()

                print(traceback.print_tb(tb))

                log_debug(
                    'Vipsubs.gr failed at self.list formation function, reason: '
                    + str(e))

                return

        return self.list
Пример #10
0
def url_generator(query='',
                  media=True,
                  advanced=False,
                  history=False,
                  domain=False):

    search_link = base_link(
    ) + '/search{0}?q={1}' if not domain else base_link() + '/domain/{0}/{1}'
    sr_search_link = base_link() + '/subreddits/search{0}?q={1}'
    subreddit = 'subreddit:'  # find submissions in "subreddit"
    author = 'author:'  # find submissions by "username"

    site = 'site:'  # find submissions from "example.com"
    url = 'url:'  # search for "text" in url
    selftext = 'selftext:'  # search for "text" in self post contents
    self_search = 'self:{0}'  # Set to yes for text submissions, no otherwise. 1 and 0 are also supported.
    flair = 'flair:""'

    items_limit = '&limit=' + control.setting('items.limit')  # numbered string
    if domain:
        items_limit = items_limit.replace('&', '?')

    if control.setting('include.nsfw') == 'true' and control.setting(
            'access.token') and control.setting(
                'nsfw.toggle'
            ) == 'true':  # include (or exclude) results marked as NSFW
        nsfw = 'nsfw:1'
    else:
        nsfw = ''

    nsfw_query = ' ' + nsfw if nsfw else ''

    # Operators used by reddit:
    # OR = 'OR'
    # NOT = 'NOT'
    # AND = 'AND'

    if not media:

        if not query:

            query = control.dialog.input(control.name(), nsfw_query)

            if not query:
                return

        if control.setting('history.bool') == 'true' and not history:
            add_to_history(query, history_subrs)

        output = sr_search_link.format(dotjson,
                                       quote_plus(query) + items_limit)

        return output

    else:

        if advanced:

            choices = [
                control.lang(30014),
                control.lang(30019),
                control.lang(30020),
                control.lang(30022),
                control.lang(30052),
                control.lang(30119),
                control.lang(30053),
                control.lang(30054 if control.setting('add.hosts') ==
                             'true' else 30021)
            ]

            generate = [
                nsfw, subreddit, author, url,
                self_search.format('no'), flair, selftext, site
            ]

            if control.setting('include.nsfw') == 'false':
                del choices[0]
                del generate[0]

            indices = control.dialog.multiselect(control.lang(30018), choices)

            if not indices or indices == [-1]:

                return

            else:

                generated = [generate[i] for i in indices]

                joined = ' '.join(generated)

                if control.setting('add.hosts') == 'true':
                    joined = joined.replace('site:', '')

                q = control.dialog.input(control.name(), ' ' + joined)

                if not q or q == ' ':
                    return

                if control.setting('add.hosts') == 'true' and 7 in indices:
                    q += ' ' + site + available_domains()

                output = search_link.format(dotjson,
                                            quote_plus(q) + items_limit)

                if control.setting('history.bool') == 'true':
                    add_to_history(q, history_media)

                return output

        else:

            if not query:

                query = control.dialog.input(control.name())

                if not query:
                    return

            if not domain:

                if 'self:yes' in query or 'self:1' in query:
                    self = self_search.format('yes')
                else:
                    self = self_search.format('no')

                if control.setting('add.hosts') == 'true':
                    query += ' ' + self + nsfw_query + ' ' + site + available_domains(
                    )
                else:
                    query += ' ' + self + nsfw_query

                if control.setting('history.bool') == 'true' and not history:
                    add_to_history(query, history_media)

                output = search_link.format(dotjson,
                                            quote_plus(query) + items_limit)

                return output

            else:

                output = search_link.format(query + items_limit)

                return output
Пример #11
0
    def search(self, action, query=None):

        if query is not None:
            choice = list(QUERY_MAP.keys()).index(query.split(',')[0])
            str_input = query.split(',')[1]
        else:
            choice = None
            str_input = None

        if choice is None:

            choices = [
                control.lang(30096),
                control.lang(30031),
                control.lang(30030),
                control.lang(30063),
                control.lang(30068),
                control.lang(30097),
                control.lang(30101)
            ]

            choice = control.selectDialog(heading=control.lang(30095),
                                          list=choices)

        if choice == 0:

            if str_input is None:

                str_input = control.dialog.input(
                    heading=control.lang(30095).partition(' ')[0] +
                    control.lang(30100) + control.lang(30096))

                if not str_input:
                    return

            add_to_history(u"Live TV Channel,{0}".format(str_input))

            if action == 'add_to_history':
                control.refresh()
                return

            self.list = live.Indexer().live_tv(zapping=False,
                                               query=str_input.lower())

            if query:
                directory.add(self.list)
            else:
                directory.run_builtin(action='generic_index',
                                      query=quote_plus(json.dumps(self.list)))

        elif choice == 1:

            if str_input is None:

                str_input = control.dialog.input(
                    heading=control.lang(30095).partition(' ')[0] +
                    control.lang(30100) + control.lang(30031))

                try:
                    str_input = cleantitle.strip_accents(
                        str_input.decode('utf-8'))
                except (UnicodeEncodeError, UnicodeDecodeError,
                        AttributeError):
                    str_input = cleantitle.strip_accents(str_input)

            if not str_input:
                return

            add_to_history(u"Movie,{0}".format(str_input))

            if action == 'add_to_history':
                control.refresh()
                return

            self.list = self.wrapper(str_input, 'movies')

            if query:
                directory.add(self.list, content='movies')
            else:
                directory.run_builtin(action='generic_index',
                                      query=quote_plus(json.dumps(self.list)))

        elif choice == 2:

            if str_input is None:

                str_input = control.dialog.input(
                    heading=control.lang(30095).partition(' ')[0] +
                    control.lang(30100) + control.lang(30030))

                if not str_input:

                    return

                try:
                    str_input = cleantitle.strip_accents(
                        str_input.decode('utf-8'))
                except (UnicodeEncodeError, UnicodeDecodeError,
                        AttributeError):
                    str_input = cleantitle.strip_accents(str_input)

            add_to_history(u"TV Serie,{0}".format(str_input))

            if action == 'add_to_history':
                control.refresh()
                return

            self.list = self.wrapper(str_input, 'series')

            if query is not None:
                directory.add(self.list, content='tvshows')
            else:
                directory.run_builtin(action='generic_index',
                                      query=quote_plus(json.dumps(self.list)))

        elif choice == 3:

            if not str_input:

                str_input = control.dialog.input(
                    heading=control.lang(30095).partition(' ')[0] +
                    control.lang(30100) + control.lang(30063))

                if not str_input:

                    return

                try:
                    str_input = cleantitle.strip_accents(
                        str_input.decode('utf-8'))
                except (UnicodeEncodeError, UnicodeDecodeError,
                        AttributeError):
                    str_input = cleantitle.strip_accents(str_input)

            add_to_history(u"TV Show,{0}".format(str_input))

            if action == 'add_to_history':
                control.refresh()
                return

            self.list = self.wrapper(str_input, 'shows')

            if query is not None:
                directory.add(self.list, content='tvshows')
            else:
                directory.run_builtin(action='generic_index',
                                      query=quote_plus(json.dumps(self.list)))

        elif choice == 4:

            if str_input is None:

                str_input = control.dialog.input(
                    heading=control.lang(30095).partition(' ')[0] +
                    control.lang(30100) + control.lang(30068))

                if not str_input:

                    return

                try:
                    str_input = cleantitle.strip_accents(
                        str_input.decode('utf-8'))
                except (UnicodeEncodeError, UnicodeDecodeError,
                        AttributeError):
                    str_input = cleantitle.strip_accents(str_input)

            add_to_history(u"Theater,{0}".format(str_input))

            if action == 'add_to_history':
                control.refresh()
                return

            self.list = self.wrapper(str_input, 'theater')

            if query is not None:
                directory.add(self.list, content='movies')
            else:
                directory.run_builtin(action='generic_index',
                                      query=quote_plus(json.dumps(self.list)))

        elif choice == 5:

            if str_input is None:
                str_input = control.dialog.input(
                    heading=control.lang(30095).partition(' ')[0] +
                    control.lang(30100) + control.lang(30097))

                if not str_input:

                    return

                try:
                    str_input = cleantitle.strip_accents(
                        str_input.decode('utf-8'))
                except (UnicodeEncodeError, UnicodeDecodeError,
                        AttributeError):
                    str_input = cleantitle.strip_accents(str_input)

            add_to_history(u"Cartoon,{0}".format(str_input))

            if action == 'add_to_history':
                control.refresh()
                return

            self.list = self.wrapper(str_input, 'animation')

            if query is not None:
                directory.add(self.list, content='tvshows')
            else:
                directory.run_builtin(action='generic_index',
                                      query=quote_plus(json.dumps(self.list)))

        elif choice == 6:

            if str_input is None:

                str_input = control.dialog.input(
                    heading=control.lang(30095).partition(' ')[0] +
                    control.lang(30100) + control.lang(30101))

                if not str_input:

                    return

                try:
                    str_input = cleantitle.strip_accents(
                        str_input.decode('utf-8'))
                except (UnicodeEncodeError, UnicodeDecodeError,
                        AttributeError):
                    str_input = cleantitle.strip_accents(str_input)

            add_to_history(u"Person,{0}".format(str_input))

            if action == 'add_to_history':
                control.refresh()
                return

            self.list = self.wrapper(str_input, 'person')

            if query is not None:
                directory.add(self.list)
            else:
                directory.run_builtin(action='generic_index',
                                      query=quote_plus(json.dumps(self.list)))

        else:

            control.close_all()
Пример #12
0
    def get(self, query):

        try:

            try:
                match = re.findall(
                    r'(.+?) (?!\d{4})S?(\d{1,2}) ?X?E?(\d{1,2})$',
                    query,
                    flags=re.IGNORECASE)[0]
            except Exception:
                match = None

            if not match:

                match = re.findall(r'(.+?) *?\(?(\d{4})?\)?$', query)[0]

                if len(match[1]) == 4:

                    title, year = match[0], match[1]

                else:

                    title = match[0]

                query = ' '.join(
                    unquote_plus(re.sub('%\w\w', ' ',
                                        quote_plus(title))).split())

                url = 'https://subz.xyz/search?q={0}'.format(quote_plus(query))

                result = client.request(url)
                result = re.sub(r'[^\x00-\x7F]+', ' ', result)

                url = client.parseDOM(result,
                                      'section',
                                      attrs={'class': 'movies'})[0]
                url = re.findall('(/movies/\d+)', url)
                url = [x for y, x in enumerate(url) if x not in url[:y]]
                url = [urljoin('https://subz.xyz', i) for i in url]
                url = url[:20][::-1]

                for i in url:

                    c = cache.get(self.cache, 2200, i)

                    if c is not None:

                        if len(match[1]) == 4:
                            year_check = c[1] == year
                        else:
                            year_check = True

                        if cleantitle.get(
                                c[0]) == cleantitle.get(title) and year_check:

                            try:

                                item = self.r

                            except Exception:

                                item = client.request(i)

                            break

                        else:

                            self.data.append(self.r)

            else:

                title, season, episode = match

                season, episode = '{0}'.format(season), '{0}'.format(episode)

                query = ' '.join(
                    unquote_plus(re.sub('%\w\w', ' ',
                                        quote_plus(title))).split())

                url = 'https://subz.xyz/search?q={0}'.format(quote_plus(query))

                result = client.request(url)
                result = re.sub(r'[^\x00-\x7F]+', ' ', result)

                url = client.parseDOM(result,
                                      'section',
                                      attrs={'class': 'tvshows'})[0]
                url = re.findall('(/series/\d+)', url)
                url = [x for y, x in enumerate(url) if x not in url[:y]]
                url = [urljoin('https://subz.xyz', i) for i in url]
                url = url[:20][::-1]

                for i in url:

                    c = cache.get(self.cache, 2200, i)

                    if c is not None:

                        if cleantitle.get(c[0]) == cleantitle.get(title):

                            item = i

                            break

                item = '{0}/seasons/{1}/episodes/{2}'.format(
                    item, season, episode)
                item = client.request(item)

            if self.data:

                item = '\n\n'.join(self.data)

            item = re.sub(r'[^\x00-\x7F]+', ' ', item)
            items = client.parseDOM(item, 'tr', attrs={'data-id': '.+?'})

        except Exception as e:

            log.log('Subzxyz failed at get function, reason: ' + str(e))

            return

        for item in items:

            try:

                r = client.parseDOM(item, 'td', attrs={'class': '.+?'})[-1]

                url = client.parseDOM(r, 'a', ret='href')[0]
                url = client.replaceHTMLCodes(url)
                url = url.replace("'", "").encode('utf-8')

                name = url.split('/')[-1].strip()
                name = re.sub('\s\s+', ' ', name)
                name = name.replace('_', '').replace('%20', '.')
                name = client.replaceHTMLCodes(name)
                name = name.encode('utf-8')

                self.list.append({
                    'name': name,
                    'url': url,
                    'source': 'subzxyz',
                    'rating': 5
                })

            except Exception as e:

                log.log(
                    'Subzxyz failed at self.list formation function, reason: '
                    + str(e))

                return

        return self.list
Пример #13
0
    def download(path, url):

        try:

            result = client.request(url)

            f = control.join(path, os_split(url)[1])

            with open(f, 'wb') as subFile:
                subFile.write(result)

            dirs, files = control.listDir(path)

            if len(files) == 0:
                return

            if not f.lower().endswith('.rar'):

                try:
                    zipped = zipfile.ZipFile(f)
                    zipped.extractall(path)
                except Exception:
                    control.execute('Extract("{0}","{0}")'.format(f, path))

            if f.lower().endswith('.rar'):

                if control.infoLabel('System.Platform.Windows'):
                    uri = "rar://{0}/".format(quote(f))
                else:
                    uri = "rar://{0}/".format(quote_plus(f))

                dirs, files = control.listDir(uri)

            else:

                dirs, files = control.listDir(path)

            if dirs and f.lower().endswith('.rar'):

                for dir in dirs:

                    _dirs, _files = control.listDir(control.join(uri, dir))

                    [files.append(control.join(dir, i)) for i in _files]

                    if _dirs:

                        for _dir in _dirs:
                            _dir = control.join(_dir, dir)

                            __dirs, __files = control.listDir(
                                control.join(uri, _dir))

                            [
                                files.append(control.join(_dir, i))
                                for i in __files
                            ]

            filenames = [i for i in files if i.endswith(('.srt', '.sub'))]

            if len(filenames) == 1:
                filename = filenames[0]
            else:
                filename = multichoice(filenames)

            try:

                filename = filename.decode('utf-8')

            except Exception:

                pass

            if not control.exists(control.join(
                    path,
                    os_split(filename)[0])) and f.lower().endswith('.rar'):
                control.makeFiles(control.join(path, os_split(filename)[0]))

            subtitle = control.join(path, filename)

            if f.lower().endswith('.rar'):

                content = openFile(uri + filename).read()

                with open(subtitle, 'wb') as subFile:
                    subFile.write(content)

            fileparts = os_split(subtitle)[1].split('.')
            result = control.join(
                os_split(subtitle)[0],
                'subtitles.' + fileparts[len(fileparts) - 1])

            rename(subtitle, result)

            return result

        except Exception as e:

            log.log(
                'Subzxyz subtitle download failed for the following reason: ' +
                str(e))

            return
Пример #14
0
    def get(self, query):

        try:

            filtered = ['freeprojectx', 'subs4series', u'Εργαστήρι Υποτίτλων']

            query = ' '.join(
                unquote_plus(re.sub('%\w\w', ' ', quote_plus(query))).split())

            if control.setting('subtitlesgr') == 'true':

                url = 'http://www.subtitles.gr/search.php?name={0}'.format(
                    quote_plus(query))

            else:

                url = 'http://www.findsubtitles.eu/search.php?text={0}&lang=Greek&button=Search'.format(
                    quote_plus(query))

            url = client.request(url, output='geturl')

            result = client.request(url.replace('www', 'gr'))

            try:
                result = result.decode('utf-8', errors='replace')
            except AttributeError:
                pass

            items = client.parseDOM(result, 'tr', attrs={'on.+?': '.+?'})

        except Exception as e:

            log.log('Subtitles.gr failed at get function, reason: ' + str(e))

            return

        for item in items:

            try:

                if u'flags/el.gif' not in item:

                    continue

                try:

                    uploader = client.parseDOM(item,
                                               'a',
                                               attrs={'class':
                                                      'link_from'})[0].strip()
                    try:
                        uploader = uploader.decode('utf-8')
                    except AttributeError:
                        pass
                    if uploader == '':
                        raise Exception
                    if uploader in filtered:
                        continue

                except Exception:

                    uploader = 'other'

                try:
                    downloads = client.parseDOM(
                        item, 'td', attrs={'class':
                                           'latest_downloads'})[0].strip()
                except:
                    downloads = '0'

                downloads = re.sub('[^0-9]', '', downloads)

                name = client.parseDOM(item,
                                       'a',
                                       attrs={'onclick': 'runme.+?'})[0]
                name = ' '.join(re.sub('<.+?>', '', name).split())
                name = u'[{0}] {1} [{2} DLs]'.format(uploader, name, downloads)
                name = client.replaceHTMLCodes(name)
                # name = name.encode('utf-8')

                url = client.parseDOM(item,
                                      'a',
                                      ret='href',
                                      attrs={'onclick': 'runme.+?'})[0]
                url = url.split('"')[0].split('\'')[0].split(' ')[0]
                url = client.replaceHTMLCodes(url)
                url = url.encode('utf-8')

                rating = self._rating(downloads)

                self.list.append({
                    'name': name,
                    'url': url,
                    'source': 'subtitlesgr',
                    'rating': rating
                })

                self.list.sort(key=lambda k: k['rating'], reverse=True)

            except Exception as e:

                log.log(
                    'Subtitles.gr failed at self.list formation function, reason: '
                    + str(e))

                return

        return self.list
Пример #15
0
    def download(self, path, url):

        # try:

        url = re.findall('/(\d+)/', url + '/', re.I)[-1]
        url = 'http://www.greeksubtitles.info/getp.php?id={0}'.format(url)
        url = client.request(url, output='geturl')

        data = urlopen(url, timeout=20).read()
        zip_file = zipfile.ZipFile(StringIO(data))
        files = zip_file.namelist()
        files = [i for i in files if i.startswith('subs/')]

        srt = [i for i in files if i.endswith(('.srt', '.sub'))]
        archive = [i for i in files if i.endswith(('.rar', '.zip'))]

        if len(srt) > 0:

            if len(srt) > 1:
                srt = multichoice(srt)
            else:
                srt = srt[0]

            result = zip_file.open(srt).read()

            subtitle = basename(srt)

            try:
                subtitle = control.join(path, subtitle.decode('utf-8'))
            except Exception:
                subtitle = control.join(path, subtitle)

            with open(subtitle, 'wb') as subFile:
                subFile.write(result)

            return subtitle

        elif len(archive) > 0:

            if len(archive) > 1:
                archive = multichoice(archive)
            else:
                archive = archive[0]

            result = zip_file.open(archive).read()

            f = control.join(path, os_split(url)[1])

            with open(f, 'wb') as subFile:
                subFile.write(result)

            dirs, files = control.listDir(path)

            if len(files) == 0:
                return

            if zipfile.is_zipfile(f):

                # try:
                #     zipped = zipfile.ZipFile(f)
                #     zipped.extractall(path)
                # except Exception:
                control.execute('Extract("{0}","{0}")'.format(f, path))

            if not zipfile.is_zipfile(f):

                if control.infoLabel('System.Platform.Windows'):
                    uri = "rar://{0}/".format(quote(f))
                else:
                    uri = "rar://{0}/".format(quote_plus(f))

                dirs, files = control.listDir(uri)

            else:

                dirs, files = control.listDir(path)

            if dirs and not zipfile.is_zipfile(f):

                for dir in dirs:

                    _dirs, _files = control.listDir(control.join(uri, dir))

                    [files.append(control.join(dir, i)) for i in _files]

                    if _dirs:

                        for _dir in _dirs:

                            _dir = control.join(_dir, dir)

                            __dirs, __files = control.listDir(
                                control.join(uri, _dir))

                            [
                                files.append(control.join(_dir, i))
                                for i in __files
                            ]

            filenames = [i for i in files if i.endswith(('.srt', '.sub'))]

            filename = multichoice(filenames)

            try:

                filename = filename.decode('utf-8')

            except Exception:

                pass

            if not control.exists(control.join(
                    path,
                    os_split(filename)[0])) and not zipfile.is_zipfile(f):
                control.makeFiles(control.join(path, os_split(filename)[0]))

            subtitle = control.join(path, filename)

            if not zipfile.is_zipfile(f):

                content = openFile(uri + filename).read()

                with open(subtitle, 'wb') as subFile:
                    subFile.write(content)

            fileparts = os_split(subtitle)[1].split('.')
            result = control.join(
                os_split(subtitle)[0],
                'subtitles.' + fileparts[len(fileparts) - 1])

            rename(subtitle, result)

            return result