Ejemplo n.º 1
0
 def init(self, magnet_uri):
     self.magnet_uri = magnet_uri
     self.magnet_args = urlparse.parse_qs(self.magnet_uri.replace("magnet:?", "")) # I know about urlparse.urlsplit but this is faster
     self.magnet_display_name = ""
     if self.magnet_args["dn"]:
         self.magnet_display_name = self.magnet_args["dn"][0]
     self.torrent2http_options = {
         "magnet": magnet_uri,
         "dlpath": xbmc.validatePath(xbmc.translatePath(plugin.get_setting("dlpath"))) or ".",
         "dlrate": plugin.get_setting("max_download_rate") or "0",
         "ulrate": plugin.get_setting("max_upload_rate") or "0",
         "encryption": plugin.get_setting("encryption"),
     }
     # Check for Android and FAT32 SD card issues
     if PLATFORM["os"] == "android" and "sdcard" in self.torrent2http_options["dlpath"].lower():
         plugin.notify("Downloading to SD card is not supported (FAT32). Resetting.", delay=15000)
         plugin.set_setting("dlpath", "")
         self.torrent2http_options["dlpath"] = xbmc.validatePath(xbmc.translatePath(plugin.get_setting("dlpath"))) or "."
     # Translate smb:// url to UNC path on windows, very hacky
     if PLATFORM["os"] == "windows" and "smb://" in self.torrent2http_options["dlpath"].lower():
         self.torrent2http_options["dlpath"] = self.torrent2http_options["dlpath"].replace("smb:", "").replace("/", "\\")
     if plugin.get_setting("keep_files", bool):
         plugin.log.info("Will keep file after playback.")
         self.torrent2http_options["keep"] = None
     self.on_playback_started = []
     self.on_playback_resumed = []
     self.on_playback_paused = []
     self.on_playback_stopped = []
     return self
Ejemplo n.º 2
0
def _rutracker_login(_cookiejar):
    from xbmctorrent.utils import url_get as url_get_origin
    import urllib2

    values = {
        "login_username": plugin.get_setting("rutracker_login"),
        "login_password": plugin.get_setting("rutracker_passw"),
        'login': '******'
    }

    plugin.log.debug("Login user")
    HEADERS["Referer"] = LOGIN_URL
    HEADERS["Content-Type"] = "application/x-www-form-urlencoded"

    cookie_handler = urllib2.HTTPCookieProcessor(_cookiejar)

    html = url_get_origin(LOGIN_URL,
                          post=values,
                          headers=HEADERS,
                          handlers=[cookie_handler])
    if html.find("profile.php?mode=sendpassword") >= 0:
        plugin.notify("Проверьте настройки авторизации.", delay=15000)
    else:
        plugin.log.debug("Login sucessfull")
        return True
    _cookiejar.save()
    HEADERS["Referer"] = BASE_URL  # restore referer
    return False
Ejemplo n.º 3
0
def _rutracker_login(_cookiejar):
    from xbmctorrent.utils import url_get as url_get_origin
    import urllib2

    values = {
        "login_username": plugin.get_setting("rutracker_login"),
        "login_password": plugin.get_setting("rutracker_passw"),
        'login': '******'
    }

    plugin.log.debug("Login user")
    HEADERS["Referer"] = LOGIN_URL
    HEADERS["Content-Type"] = "application/x-www-form-urlencoded"

    cookie_handler = urllib2.HTTPCookieProcessor(_cookiejar)

    html = url_get_origin(LOGIN_URL, post=values, headers=HEADERS, handlers=[cookie_handler])
    if html.find("profile.php?mode=sendpassword") >= 0:
        plugin.notify("Проверьте настройки авторизации.", delay=15000)
    else:
        plugin.log.debug("Login sucessfull")
        return True
    _cookiejar.save()
    HEADERS["Referer"] = BASE_URL  # restore referer
    return False
Ejemplo n.º 4
0
def url_get(url, params={}, headers={}, post=None):
    from urllib2 import HTTPCookieProcessor, URLError
    from xbmctorrent.utils import url_get as url_get_origin

    _cookiejar = get_cookie_jar()
    cookie_handler = HTTPCookieProcessor(_cookiejar)

    plugin.log.debug("loading uri: %s with cookies %s params %s post %s" % (url, _cookiejar, str(params), str(post)))

    try:
        result = url_get_origin(url, params, headers, post, handlers=[cookie_handler])
    except URLError:
        result = "profile.php?mode=sendpassword"
        pass

    if url.find("dl.php?") >= 0 and result.find("profile.php?mode=sendpassword") >= 0:
        if not plugin.get_setting("rutracker_login") or not plugin.get_setting("rutracker_passw"):
            plugin.notify("Проверьте настройки авторизации.", delay=15000)
            return ""
        if not _rutracker_login(cookie_handler):
            return ""

        _cookiejar.save()
        result = url_get_origin(url, params, headers, post, handlers=[cookie_handler])
        pass

    plugin.log.debug("uri loaded: " + url)
    return result
Ejemplo n.º 5
0
    def init(self, magnet_uri):
        self.magnet_uri = magnet_uri
        self.magnet_args = urlparse.parse_qs(
            self.magnet_uri.replace(
                "magnet:?",
                ""))  # I know about urlparse.urlsplit but this is faster
        self.magnet_display_name = ""
        if self.magnet_args["dn"]:
            self.magnet_display_name = self.magnet_args["dn"][0]
        self.torrent2http_options = {
            "magnet":
            magnet_uri,
            "dlpath":
            xbmc.validatePath(xbmc.translatePath(plugin.get_setting("dlpath")))
            or ".",
            "dlrate":
            plugin.get_setting("max_download_rate") or "0",
            "ulrate":
            plugin.get_setting("max_upload_rate") or "0",
            "encryption":
            plugin.get_setting("encryption"),
        }

        if "://" in self.torrent2http_options["dlpath"]:
            # Translate smb:// url to UNC path on windows, very hackish
            if PLATFORM["os"] == "windows" and self.torrent2http_options[
                    "dlpath"].lower().startswith("smb://"):
                self.torrent2http_options[
                    "dlpath"] = self.torrent2http_options["dlpath"].replace(
                        "smb:", "").replace("/", "\\")
            else:
                plugin.notify(
                    "Downloading to an unmounted network share is not supported. Resetting.",
                    delay=15000)
                plugin.set_setting("dlpath", "")
                self.torrent2http_options["dlpath"] = "."

        # Check for Android and FAT32 SD card issues
        if PLATFORM["os"] == "android" and self.torrent2http_options[
                "dlpath"] != ".":
            from xbmctorrent.utils import get_path_fs
            fs = get_path_fs(self.torrent2http_options["dlpath"])
            plugin.log.info("Download path filesytem is %s" % fs)
            if fs == "vfat":  # FAT32 is not supported
                plugin.notify(
                    "Downloading to FAT32 is not supported. Resetting.",
                    delay=15000)
                plugin.set_setting("dlpath", "")
                self.torrent2http_options["dlpath"] = "."

        if plugin.get_setting("keep_files", bool):
            plugin.log.info("Will keep file after playback.")
            self.torrent2http_options["keep"] = None
        self.on_playback_started = []
        self.on_playback_resumed = []
        self.on_playback_paused = []
        self.on_playback_stopped = []
        return self
Ejemplo n.º 6
0
def rutor_play(tid, pulsar):
    from contextlib import closing
    from bencode import bdecode
    from urlparse import urljoin
    from xbmctorrent.magnet import generate_magnet
    from xbmctorrent.utils import first, SafeDialogProgress
    from xbmctorrent.acestream import ace_supported

    with closing(SafeDialogProgress(delay_close=0)) as dialog:
        dialog.create(plugin.name)
        dialog.update(percent=0, line1="Получение информации о раздаче...")

        torrent_url = urljoin(BASE_URL, "download/%s" % tid)
        try:
            metadata = bdecode(url_get(torrent_url, headers=HEADERS))
        except Exception:
            import xbmcgui
            plugin.log.error("Unexpected error: %s" % sys.exc_info()[0])
            xbmcgui.Dialog().ok(plugin.name, "Не удалось получить данные от сервера")
            return

        dialog.update(percent=100, line1="Готово")

        if "files" in metadata["info"]:  # and ace_supported():
            items = []
            for index, info in enumerate(metadata["info"]["files"]):
                name = "/".join(info["path"])
                if not _rutor_valid_file(name):
                    continue

                if plugin.get_setting("torrent_engine", int) == 1 and ace_supported():
                    path = plugin.url_for("torrent_play", url=torrent_url, index=index, name=name)
                else:
                    path = plugin.url_for("play_file", uri=generate_magnet(metadata, name), index=index)

                items.append({"label": name, "path": path})

            items = sorted(items, key=lambda x: x["label"])
            if len(items) == 1:  # start playback if torrent contains only one file
                plugin.redirect(items[0]["path"])
            else:               # ask to select which file to play
                import xbmcgui
                select_items = [item["label"] for item in items]
                select = xbmcgui.Dialog().select("Выберите файл для проигрывания", select_items)
                if select >= 0:
                    plugin.redirect(items[select]["path"])
        else:
            name = metadata["info"].get("name") or " / ".join(first(metadata["info"]["files"])["path"]) or "rutor.org"
            if plugin.get_setting("torrent_engine", int) == 1 and ace_supported():
                path = plugin.url_for("torrent_play", url=torrent_url, index=0, name=name)
            else:
                path = plugin.url_for(["play", "play_with_pulsar"][int(pulsar)], uri=generate_magnet(metadata, name))
            plugin.redirect(path)
Ejemplo n.º 7
0
def rutracker_play(tid, pulsar):
    from contextlib import closing
    from bencode import bdecode
    from urlparse import urljoin
    from xbmctorrent.magnet import generate_magnet
    from xbmctorrent.utils import first, SafeDialogProgress
    from xbmctorrent.acestream import ace_supported

    with closing(SafeDialogProgress(delay_close=0)) as dialog:
        dialog.create(plugin.name)
        dialog.update(percent=0, line1="Получение информации о раздаче...")

        try:
            data = url_get(urljoin(BASE_URL, "dl.php?t=%s" % tid))
            metadata = bdecode(data)
        except Exception:
            plugin.log.error("Unexpected error: %s " % format_exc().split('\n')[-2])
            xbmcgui.Dialog().ok(plugin.name, "Не удалось получить данные от сервера")
            return

        dialog.update(percent=100, line1="Готово")

        if "files" in metadata["info"]:  # and ace_supported():
            items = []
            for index, info in enumerate(metadata["info"]["files"]):
                name = "/".join(info["path"])
                decname = _rutracker_decode_try(name)
                if not _rutracker_valid_file(decname):
                    continue
                name = uenc(decname)

                if plugin.get_setting("torrent_engine", int) == 1 and ace_supported():
                    path = plugin.url_for("play_torrent_raw", raw=data, index=index, name=name)
                else:
                    path = plugin.url_for("play_file", uri=generate_magnet(metadata, name), index=index)

                items.append({"label": name, "path": path})

            if len(items) == 1:  # start playback if torrent contains only one file
                plugin.redirect(items[0]["path"])
            else:
                select_items = [item["label"] for item in items]
                select = xbmcgui.Dialog().select("Выберите файл для проигрывания", select_items)
                if select >= 0:
                    plugin.redirect(items[select]["path"])
        else:
            name = metadata["info"].get("name") or " / ".join(first(metadata["info"]["files"])["path"]) or "rutracker.org"
            if plugin.get_setting("torrent_engine", int) == 1 and ace_supported():
                path = plugin.url_for("play_torrent_raw", raw=data, index=0, name=name)
            else:
                path = plugin.url_for(["play", "play_with_pulsar"][int(pulsar)], uri=generate_magnet(metadata, name))
            plugin.redirect(path)
Ejemplo n.º 8
0
def torrents3d_play(article):
    import xbmcgui
    from bs4 import BeautifulSoup
    from contextlib import closing
    from urlparse import urljoin
    from xbmctorrent.magnet import generate_magnet
    from xbmctorrent.utils import SafeDialogProgress

    article = int(article)

    with closing(SafeDialogProgress(delay_close=0)) as dialog:
        dialog.create(plugin.name)
        dialog.update(percent=0, line1=u"Получение информации о релизе...", line2="", line3="")

        url = urljoin(BASE_URL, "article/%d" % article)

        try:
            html_data = url_get(url, headers=HEADERS)
            soup = BeautifulSoup(html_data, "html5lib")
            torrent_href = soup.find("a", class_="genmed")

            if not torrent_href:
                dialog.update(percent=50, line2=u"Требуется авторизация. Авторизация...")

                if not plugin.get_setting("t3d_login") and not plugin.get_setting("t3d_passwd"):
                    plugin.notify("Проверьте настройки авторизации.", delay=15000)
                    return

                html_data = _torrents3d_login(url)
                soup = BeautifulSoup(html_data, "html5lib")
                torrent_href = soup.find("a", class_="genmed")

            if not torrent_href:
                xbmcgui.Dialog().ok(plugin.name, "Авторизация неудалась. Проверьте настройки авторизации.")
                return

            dialog.update(percent=100, line2=u"Обработка данных.")

            from bencode import bdecode

            title = "[%s] %s" % _torrents3d_cleantitle(soup.find("a", class_="tt-text").text)
            torrent_data = url_get(torrent_href["href"], headers=HEADERS)
            metadata = bdecode(torrent_data)

            plugin.redirect(plugin.url_for("play", uri=generate_magnet(metadata, uenc(title))))

        except Exception:
            plugin.log.error("Cannot get data from remote server")
            xbmcgui.Dialog().ok(plugin.name, u"Не удалось получить данные от сервера")
            return
Ejemplo n.º 9
0
def _lostfilm_login():
    from json import loads

    values = {
        "act": "users",
        "type": "login",
        "mail": plugin.get_setting("lostfilm_login"),
        "pass": plugin.get_setting("lostfilm_passw"),
        "rem": 1,
    }

    jsn = url_get(AJAX_URL, post=values)
    result = loads(jsn)

    return result.get("result", "") == "ok" and result.get("success", False)
Ejemplo n.º 10
0
def url_get(url, params={}, headers={}, post=None, cookie=None):
    global _cookiejar
    import xbmcvfs, urllib2
    from xbmctorrent.utils import url_get as url_get_origin

    if not _cookiejar:
        import os, xbmc, cookielib

        sid_file = os.path.join(xbmc.translatePath('special://temp/'),
                                plugin.id, 'LostFilm.cookies.dat')  #
        if not xbmcvfs.exists(os.path.dirname(sid_file)):
            xbmcvfs.mkdir(os.path.dirname(sid_file))

        _cookiejar = cookielib.MozillaCookieJar(sid_file)

        if not xbmcvfs.exists(sid_file):
            _cookiejar.save()

        _cookiejar.load()

    if cookie:
        _cookiejar.set_cookie(cookie)
    cookie_handler = urllib2.HTTPCookieProcessor(_cookiejar)
    plugin.log.debug("Loading uri: %s with cookies %s params %s post %s" %
                     (url, _cookiejar, str(params), str(post)))
    result = url_get_origin(url,
                            params,
                            headers,
                            post,
                            handlers=[cookie_handler])
    _cookiejar.save()
    plugin.log.debug("Uri loaded: " + url)

    if result.find("profile.php?mode=sendpassword") >= 0:
        if not plugin.get_setting(
                "rutracker_login") and not plugin.get_setting(
                    "rutracker_passwd"):
            plugin.notify("Проверьте настройки авторизации.", delay=15000)
            return
        if _rutracker_login(_cookiejar):
            result = url_get_origin(url,
                                    params,
                                    headers,
                                    post,
                                    handlers=[cookie_handler])
            _cookiejar.save()

    return result
Ejemplo n.º 11
0
def url_get(url, params={}, headers={}, with_immunicity=True):
    import urllib2
    from contextlib import closing
    from xbmctorrent import plugin
    from xbmctorrent.common import USER_AGENT

    if params:
        import urllib
        url = "%s?%s" % (url, urllib.urlencode(params))

    req = urllib2.Request(url)
    req.add_header("User-Agent", USER_AGENT)
    for k, v in headers.items():
        req.add_header(k, v)

    if with_immunicity and plugin.get_setting("immunicity", bool):
        from xbmctorrent import immunicity
        proxy = immunicity.get_proxy_for(url)
        if proxy:
            from urlparse import urlsplit
            parts = urlsplit(url)
            req.set_proxy(proxy, parts[0])

    try:
        with closing(urllib2.urlopen(req)) as response:
            data = response.read()
            if response.headers.get("Content-Encoding", "") == "gzip":
                import zlib
                return zlib.decompressobj(16 + zlib.MAX_WBITS).decompress(data)
            return data
    except urllib2.HTTPError:
        return None
Ejemplo n.º 12
0
def url_get(url, params={}, headers={}, with_immunicity=True):
    import urllib2
    from contextlib import closing
    from xbmctorrent import plugin
    from xbmctorrent.common import USER_AGENT

    if params:
        import urllib
        url = "%s?%s" % (url, urllib.urlencode(params))

    req = urllib2.Request(url)
    req.add_header("User-Agent", USER_AGENT)
    for k, v in headers.items():
        req.add_header(k, v)

    if with_immunicity and plugin.get_setting("immunicity", bool):
        from xbmctorrent import immunicity
        proxy = immunicity.get_proxy_for(url)
        if proxy:
            from urlparse import urlsplit
            parts = urlsplit(url)
            req.set_proxy(proxy, parts[0])

    try:
        with closing(urllib2.urlopen(req)) as response:
            data = response.read()
            if response.headers.get("Content-Encoding", "") == "gzip":
                import zlib
                return zlib.decompressobj(16 + zlib.MAX_WBITS).decompress(data)
            return data
    except urllib2.HTTPError:
        return None
Ejemplo n.º 13
0
def kat_index():
    cats = [
        {
            "label":
            "Search",
            "path":
            plugin.url_for("kat_search",
                           sort_field="seeders",
                           sort_order="desc")
        },
        {
            "label": "Movies",
            "path": plugin.url_for("kat_movies")
        },
        {
            "label":
            "Series",
            "path":
            plugin.url_for("kat_series",
                           sort_field="seeders",
                           sort_order="desc")
        },
        {
            "label": "Anime",
            "path": plugin.url_for("kat_anime")
        },
    ]
    if plugin.get_setting("p**n", bool):
        cats += [
            {
                "label": "XXX",
                "path": plugin.url_for("kat_porn")
            },
        ]
    return cats
Ejemplo n.º 14
0
    def init(self, magnet_uri):
        self.magnet_uri = magnet_uri
        self.magnet_args = urlparse.parse_qs(
            self.magnet_uri.replace("magnet:?", "")
        )  # I know about urlparse.urlsplit but this is faster
        self.magnet_display_name = ""
        if self.magnet_args["dn"]:
            self.magnet_display_name = self.magnet_args["dn"][0]
        self.torrent2http_options = {
            "magnet": magnet_uri,
            "dlpath": xbmc.validatePath(xbmc.translatePath(plugin.get_setting("dlpath"))) or ".",
            "dlrate": plugin.get_setting("max_download_rate") or "0",
            "ulrate": plugin.get_setting("max_upload_rate") or "0",
            "encryption": plugin.get_setting("encryption"),
        }

        if "://" in self.torrent2http_options["dlpath"]:
            # Translate smb:// url to UNC path on windows, very hackish
            if PLATFORM["os"] == "windows" and self.torrent2http_options["dlpath"].lower().startswith("smb://"):
                self.torrent2http_options["dlpath"] = (
                    self.torrent2http_options["dlpath"].replace("smb:", "").replace("/", "\\")
                )
            else:
                plugin.notify("Downloading to an unmounted network share is not supported. Resetting.", delay=15000)
                plugin.set_setting("dlpath", "")
                self.torrent2http_options["dlpath"] = "."

        # Check for Android and FAT32 SD card issues
        if PLATFORM["os"] == "android" and self.torrent2http_options["dlpath"] != ".":
            from xbmctorrent.utils import get_path_fs

            fs = get_path_fs(self.torrent2http_options["dlpath"])
            plugin.log.info("Download path filesytem is %s" % fs)
            if fs == "vfat":  # FAT32 is not supported
                plugin.notify("Downloading to FAT32 is not supported. Resetting.", delay=15000)
                plugin.set_setting("dlpath", "")
                self.torrent2http_options["dlpath"] = "."

        if plugin.get_setting("keep_files", bool):
            plugin.log.info("Will keep file after playback.")
            self.torrent2http_options["keep"] = None
        self.on_playback_started = []
        self.on_playback_resumed = []
        self.on_playback_paused = []
        self.on_playback_stopped = []
        return self
Ejemplo n.º 15
0
def _filelist_login(referer = BASE_URL):
    from bs4 import BeautifulSoup
    from urlparse import urljoin
    
    HEADERS["Referer"] = urljoin(BASE_URL, 'login.php')
    HEADERS["Origin"] = BASE_URL
    HEADERS["Content-Type"] = "application/x-www-form-urlencoded"

    values = {
        "username": plugin.get_setting("filelist_user"),
        "password": plugin.get_setting("filelist_pass"),
        "unlock": 1
    }

    html_data = url_get(urljoin(BASE_URL, "takelogin.php"), post=values, headers=HEADERS)
    #soup = BeautifulSoup(html_data, "html5lib")
    
    
Ejemplo n.º 16
0
def kat_index():
    cats = [
        {"label": "Search", "path": plugin.url_for("kat_search", sort_field="seeders", sort_order="desc")},
        {"label": "Movies", "path": plugin.url_for("kat_movies")},
        {"label": "Series", "path": plugin.url_for("kat_series", sort_field="seeders", sort_order="desc")},
        {"label": "Anime", "path": plugin.url_for("kat_anime")},
    ]
    if plugin.get_setting("p**n", bool):
        cats += [{"label": "XXX", "path": plugin.url_for("kat_porn")}]
    return cats
Ejemplo n.º 17
0
def track_page(path, force=False):
    if not plugin.get_setting("ga_disable", bool) or force:
        try:
            from pyga.requests import Page
            tracker, session, visitor = get_ga()
            plugin.log.info("GA: Tracking %s" % path)
            tracker.track_pageview(Page(path), session, visitor)
        except Exception, e:
            import traceback
            plugin.log.error("GA: Call failed.")
            plugin.log.error(traceback.format_exc())
Ejemplo n.º 18
0
def track_event(*args, **kwargs):
    if not plugin.get_setting("ga_disable", bool) or kwargs.pop("force", False):
        try:
            from pyga.requests import Event
            tracker, session, visitor = get_ga()
            plugin.log.info("GA: Tracking event %s" % repr(args))
            tracker.track_event(Event(*args, **kwargs), session, visitor)
        except Exception, e:
            import traceback
            plugin.log.error("GA: Call failed.")
            plugin.log.error(traceback.format_exc())
Ejemplo n.º 19
0
Archivo: ga.py Proyecto: roeiba/xbmc
def track_page(path, force=False):
    if not plugin.get_setting("ga_disable", bool) or force:
        try:
            from pyga.requests import Page
            tracker, session, visitor = get_ga()
            plugin.log.info("GA: Tracking %s" % path)
            tracker.track_pageview(Page(path), session, visitor)
        except Exception, e:
            import traceback
            plugin.log.error("GA: Call failed.")
            plugin.log.error(traceback.format_exc())
Ejemplo n.º 20
0
def _torrents3d_login(referer=BASE_URL):
    from urlparse import urljoin

    HEADERS["Referer"] = referer
    HEADERS["Origin"] = BASE_URL
    HEADERS["Content-Type"] = "application/x-www-form-urlencoded"

    values = {
        "login_username": plugin.get_setting("t3d_login"),
        "login_password": plugin.get_setting("t3d_passw"),
        "autologin": 1,
        "login": "******"
    }

    html_data = url_get(urljoin(BASE_URL, "login.php"), post=values, headers=HEADERS)

    HEADERS["Referer"] = BASE_URL
    del HEADERS["Origin"]

    return html_data
Ejemplo n.º 21
0
Archivo: ga.py Proyecto: roeiba/xbmc
def track_event(*args, **kwargs):
    if not plugin.get_setting("ga_disable", bool) or kwargs.pop(
            "force", False):
        try:
            from pyga.requests import Event
            tracker, session, visitor = get_ga()
            plugin.log.info("GA: Tracking event %s" % repr(args))
            tracker.track_event(Event(*args, **kwargs), session, visitor)
        except Exception, e:
            import traceback
            plugin.log.error("GA: Call failed.")
            plugin.log.error(traceback.format_exc())
Ejemplo n.º 22
0
def _torrents3d_login(referer=BASE_URL):
    from urlparse import urljoin

    HEADERS["Referer"] = referer
    HEADERS["Origin"] = BASE_URL
    HEADERS["Content-Type"] = "application/x-www-form-urlencoded"

    values = {
        "login_username": plugin.get_setting("t3d_login"),
        "login_password": plugin.get_setting("t3d_passw"),
        "autologin": 1,
        "login": "******"
    }

    html_data = url_get(urljoin(BASE_URL, "login.php"),
                        post=values,
                        headers=HEADERS)

    HEADERS["Referer"] = BASE_URL
    del HEADERS["Origin"]

    return html_data
Ejemplo n.º 23
0
def _rutracker_login(cookie_handler):
    from urlparse import urljoin
    from xbmctorrent.utils import url_get as url_get_origin

    values = {
        "login_username": plugin.get_setting("rutracker_login"),
        "login_password": plugin.get_setting("rutracker_passw"),
        "login": "******"
    }

    headers = HEADERS.copy()
    headers["Referer"] = urljoin(BASE_URL, "index.php")
    headers["Content-Type"] = "application/x-www-form-urlencoded"

    html = url_get_origin(urljoin(BASE_URL, "login.php"), post=values, headers=headers, handlers=[cookie_handler])
    if html.find("profile.php?mode=sendpassword") >= 0:
        plugin.notify("Проверьте настройки авторизации.", delay=15000)
    else:
        plugin.log.debug("login sucessfull.")
        return True

    return False
Ejemplo n.º 24
0
def _lostfilm_login():
    from urlparse import urljoin
    from urllib import urlencode
    from bs4 import BeautifulSoup

    params = {
        "referer" : BASE_URL,
    }
    values = {
        "login"     : plugin.get_setting("lostfilm_login"),
        "password"  : plugin.get_setting("lostfilm_passw"),
        "module"    : 1,
        "target"    : "http://lostfilm.tv/",
        "repage"    : "user",
        "act"       : "login"
    }

    login_url = "%s?%s" % (urljoin(LOGIN_URL, "login.php"), urlencode(params))

    html = url_get(login_url, post=values, headers=HEADERS)
    soup = BeautifulSoup(html, from_encoding="utf-8")

    #-- step 2
    HEADERS["Referer"] = login_url
    HEADERS["Origin"] = LOGIN_URL
    HEADERS["Content-Type"] = "application/x-www-form-urlencoded"

    values = {}
    for rec in soup("input", type="hidden"):
        values[rec["name"].encode("utf-8")] = (rec.has_attr("value") and rec["value"] or "").encode("utf-8")

    html = url_get(soup.find("form")["action"], post=values, headers=HEADERS)

    HEADERS["Referer"] = BASE_URL # restore referer
    del HEADERS["Origin"]         # delete unneeded origin

    return
Ejemplo n.º 25
0
    def init(self, uri, index=None):
        self.display_name = ""
        self.torrent2http_options = {
            "uri": uri,
            "dl-path": xbmc.translatePath(plugin.get_setting("dlpath") or "special://temp/" + plugin.id),
            "dl-rate": plugin.get_setting("max_download_rate") or "-1",
            "encryption": plugin.get_setting("encryption"),
            "file-index": index,
            "keep-files": plugin.get_setting("keep_files", bool),
            "tuned-storage": plugin.get_setting("tuned_storage", bool),
        }
        print repr(self.torrent2http_options)
        if "://" in self.torrent2http_options["dl-path"]:
            # Translate smb:// url to UNC path on windows, very hackish
            if PLATFORM["os"] == "windows" and self.torrent2http_options["dl-path"].lower().startswith("smb://"):
                self.torrent2http_options["dl-path"] = self.torrent2http_options["dl-path"].replace("smb:", "").replace("/", "\\")
            elif False:
                plugin.notify("Downloading to an unmounted network share is not supported. Resetting.", delay=15000)
                plugin.set_setting("dlpath", "")
                self.torrent2http_options["dl-path"] = "."

        # Check for Android and FAT32 SD card issues
        if PLATFORM["os"] == "android" and self.torrent2http_options["dl-path"] != ".":
            from xbmctorrent.utils import get_path_fs
            fs = get_path_fs(self.torrent2http_options["dl-path"])
            plugin.log.info("Download path filesytem is %s" % fs)
            if fs == "vfat":  # FAT32 is not supported
                plugin.notify("Downloading to FAT32 is not supported. Resetting.", delay=15000)
                plugin.set_setting("dlpath", "")
                self.torrent2http_options["dl-path"] = "."

        self.on_playback_started = []
        self.on_playback_resumed = []
        self.on_playback_paused = []
        self.on_playback_stopped = []
        return self
Ejemplo n.º 26
0
def url_get(url, params={}, headers={}, post=None, cookie=None):
    global _cookiejar
    import xbmcvfs, urllib2
    from xbmctorrent.utils import url_get as url_get_origin

    if not _cookiejar:
        import os, xbmc, cookielib

        sid_file = os.path.join(xbmc.translatePath('special://temp/'), plugin.id, 'LostFilm.cookies.dat')  #
        if not xbmcvfs.exists(os.path.dirname(sid_file)):
            xbmcvfs.mkdir(os.path.dirname(sid_file))

        _cookiejar = cookielib.MozillaCookieJar(sid_file)

        if not xbmcvfs.exists(sid_file):
            _cookiejar.save()

        _cookiejar.load()

    if cookie:
        _cookiejar.set_cookie(cookie)
    cookie_handler = urllib2.HTTPCookieProcessor(_cookiejar)
    plugin.log.debug("Loading uri: %s with cookies %s params %s post %s" % (url, _cookiejar,str(params), str(post)))
    result = url_get_origin(url, params, headers, post, handlers=[cookie_handler])
    _cookiejar.save()
    plugin.log.debug("Uri loaded: " + url)

    if result.find("profile.php?mode=sendpassword") >= 0:
        if not plugin.get_setting("rutracker_login") and not plugin.get_setting("rutracker_passwd"):
            plugin.notify("Проверьте настройки авторизации.", delay=15000)
            return
        if _rutracker_login(_cookiejar):
            result = url_get_origin(url, params, headers, post, handlers=[cookie_handler])
            _cookiejar.save()

    return result
Ejemplo n.º 27
0
        def _get_torrent_info(item):
            from xbmctorrent.search import scrapers as search
            from xbmctorrent.utils import get_quality_from_name

            scrapers = search.Scrapers()

            if not plugin.get_setting("rutor_usesearch", bool):
                meta = scrapers.default(item)
            else:
                meta = scrapers.scraper(scraper_name, item)

            meta["path"] = item["path"]
            meta["is_playable"] = item["is_playable"]
            meta.setdefault("stream_info", {}).update(get_quality_from_name(meta['label']))
            return meta
Ejemplo n.º 28
0
        def _get_torrent_info(item):
            from xbmctorrent.search import scrapers as search
            from xbmctorrent.utils import get_quality_from_name

            scrapers = search.Scrapers()

            if not plugin.get_setting("rutor_usesearch", bool):
                meta = scrapers.default(item)
            else:
                meta = scrapers.scraper(scraper_name, item)

            meta["path"] = item["path"]
            meta["is_playable"] = item["is_playable"]
            meta.setdefault("stream_info",
                            {}).update(get_quality_from_name(meta['label']))
            return meta
Ejemplo n.º 29
0
        def _get_torrent_info(item):

            from xbmctorrent.search import scrapers as search
            from xbmctorrent.utils import get_quality_from_name

            try:
                scrapers = search.Scrapers()
                if not plugin.get_setting("rutracker_usesearch", bool):
                    meta = scrapers.default(item)
                else:
                    meta = scrapers.scraper(scraper_name, item)

                meta["path"] = item["path"]
                meta["is_playable"] = item["is_playable"]
                meta.setdefault("stream_info", {}).update(get_quality_from_name(meta['label']))
                return meta
            except:
                plugin.log.error("Unexpected error: %s" % format_exc().split('\n')[-2])
                return scrapers.default(item)
Ejemplo n.º 30
0
def url_get(url,
            params={},
            headers={},
            post=None,
            with_immunicity=True,
            handlers=None):
    import urllib2
    from contextlib import closing
    from xbmctorrent import plugin
    from xbmctorrent.common import USER_AGENT

    if params:
        import urllib
        url = "%s?%s" % (url, urllib.urlencode(params))

    if post:
        import urllib
        post = urllib.urlencode(post)

    if handlers is None: handlers = []

    if with_immunicity and plugin.get_setting("immunicity", bool):
        from xbmctorrent.antizapret import AntizapretProxyHandler
        handlers.insert(0, AntizapretProxyHandler())

    if len(handlers):
        urllib2.install_opener(urllib2.build_opener(*handlers))

    req = urllib2.Request(url, post)
    req.add_header("User-Agent", USER_AGENT)
    for k, v in headers.items():
        req.add_header(k, v)

    try:
        with closing(urllib2.urlopen(req)) as response:
            data = response.read()
            if response.headers.get("Content-Encoding", "") == "gzip":
                import zlib
                return zlib.decompressobj(16 + zlib.MAX_WBITS).decompress(data)
            return data
    except urllib2.HTTPError:
        return None
Ejemplo n.º 31
0
        def _get_torrent_info(item):

            from xbmctorrent.search import scrapers as search
            from xbmctorrent.utils import get_quality_from_name

            try:
                scrapers = search.Scrapers()
                if not plugin.get_setting("rutracker_usesearch", bool):
                    meta = scrapers.default(item)
                else:
                    meta = scrapers.scraper(scraper_name, item)

                meta["path"] = item["path"]
                meta["is_playable"] = item["is_playable"]
                meta.setdefault("stream_info", {}).update(
                    get_quality_from_name(meta['label']))
                return meta
            except:
                plugin.log.error("Unexpected error: %s" %
                                 format_exc().split('\n')[-2])
                return scrapers.default(item)
Ejemplo n.º 32
0
def url_get(url, params={}, headers={}, post=None, with_immunicity=True, handlers=None):
    import urllib2
    from contextlib import closing
    from xbmctorrent import plugin
    from xbmctorrent.common import USER_AGENT

    if params:
        import urllib
        url = "%s?%s" % (url, urllib.urlencode(params))

    if post:
        import urllib
        post = urllib.urlencode(post)

    if handlers is None:
        handlers = []

    if with_immunicity and plugin.get_setting("immunicity", bool):
        from xbmctorrent.antizapret import AntizapretProxyHandler
        handlers.insert(0, AntizapretProxyHandler())

    if len(handlers):
        urllib2.install_opener(urllib2.build_opener(*handlers))

    req = urllib2.Request(url, post)
    req.add_header("User-Agent", USER_AGENT)
    for k, v in headers.items():
        req.add_header(k, v)

    try:
        with closing(urllib2.urlopen(req)) as response:
            data = response.read()
            if response.headers.get("Content-Encoding", "") == "gzip":
                import zlib
                return zlib.decompressobj(16 + zlib.MAX_WBITS).decompress(data)
            return data
    except urllib2.HTTPError:
        return None
Ejemplo n.º 33
0
 def init(self, magnet_uri):
     track_event("torrent_player", "start")
     self.magnet_uri = magnet_uri
     self.magnet_args = urlparse.parse_qs(self.magnet_uri.replace("magnet:?", "")) # I know about urlparse.urlsplit but this is faster
     self.magnet_display_name = ""
     if self.magnet_args["dn"]:
         self.magnet_display_name = self.magnet_args["dn"][0]
     self.torrent2http_options = {
         "magnet": magnet_uri,
         "dlpath": plugin.get_setting("dlpath") or ".",
         "dlrate": plugin.get_setting("max_download_rate") or "0",
         "ulrate": plugin.get_setting("max_upload_rate") or "0",
         "ulrate": plugin.get_setting("max_upload_rate") or "0",
         "encryption": plugin.get_setting("encryption"),
     }
     if plugin.get_setting("keep"):
         self.torrent2http_options["keep"] = None
     track_event("download", "start", magnet_uri)
     self.on_playback_started = []
     self.on_playback_resumed = []
     self.on_playback_paused = []
     self.on_playback_stopped = []
     return self
Ejemplo n.º 34
0
from xbmctorrent import plugin
from xbmctorrent.scrapers import scraper
from xbmctorrent.ga import tracked
from xbmctorrent.caching import cached_route
from xbmctorrent.utils import ensure_fanart
from xbmctorrent.library import library_context

BASE_URL = plugin.get_setting("base_btdigg")
HEADERS = {
    "Referer": BASE_URL,
}
SORT_RELEVANCE = 0
SORT_POPULARITY = 1
SORT_ADDTIME = 2
SORT_SIZE = 3
SORT_FILES = 4


@scraper("BTDigg - DHT Search Engine", "%s/logo.png" % BASE_URL,
         plugin.get_setting("btdigg_enabled", bool))
@plugin.route("/btdigg")
@ensure_fanart
@tracked
def btdigg_index():
    plugin.redirect(plugin.url_for("btdigg_search"))


@plugin.route("/btdigg/search/<query>/<sort>/<page>")
@library_context
@ensure_fanart
@tracked
Ejemplo n.º 35
0
#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
from xbmcswift2 import actions
from xbmctorrent import plugin
from xbmctorrent.scrapers import scraper
from xbmctorrent.ga import tracked
from xbmctorrent.caching import cached_route
from xbmctorrent.utils import ensure_fanart

BASE_URL = "%s/" % plugin.get_setting("base_rutor")
DOWNLOAD_URL = "http://d.rutor.org/"

HEADERS = {
    'Referer': BASE_URL,
    'Accept':
    'text/html, application/xml, application/xhtml+xml, image/png, image/jpeg, image/gif, image/x-xbitmap, */*',
    'Accept-Language': 'ru-RU,ru;q=0.9,en;q=0.8',
    'Accept-Charset': 'utf-8, *;q=0.1',
    'Accept-Encoding': 'identity, *;q=0'
}

CATEGORIES = (
    ("1", u"Зарубежные фильмы", "movies", "tmdb"),
    ("5", u"Наши фильмы", "movies", "kinopoisk"),
    ("12", u"Научно-популярные фильмы", "movies", ""),
    ("4", u"Сериалы", "tvshows", "tvdb"),
    ("6", u"Телевизор", "tvshows", ""),
    ("7", u"Мультипликация", "movies", "tmdb"),
    ("10", u"Аниме", "movies", ""),
Ejemplo n.º 36
0
from xbmctorrent import plugin
from xbmctorrent.scrapers import scraper
from xbmctorrent.ga import tracked
from xbmctorrent.caching import cached_route
from xbmctorrent.utils import ensure_fanart

BASE_URL = "%s/" % plugin.get_setting("base_kickass")
HEADERS = {
    "Referer": BASE_URL,
}

MOVIES_GENRES = [
    "Action",
    "Adult",
    "Adventure",
    "Animation",
    "Biography",
    "Comedy",
    "Crime",
    "Documentary",
    "Drama",
    "Family",
    "Fantasy",
    "Film Noir",
    "Game Show",
    "History",
    "Horror",
    "Music",
    "Musical",
    "Mystery",
    "News",
Ejemplo n.º 37
0
from xbmctorrent import plugin
from xbmctorrent.scrapers import scraper
from xbmctorrent.ga import tracked
from xbmctorrent.caching import cached_route
from xbmctorrent.utils import ensure_fanart
from xbmctorrent.library import library_context

BASE_URL = "%s/" % plugin.get_setting("base_bitsnoop")
HEADERS = {
    "Referer": BASE_URL,
}
# Cache TTLs
DEFAULT_TTL = 24 * 3600  # 24 hours


@scraper("BitSnoop - Search Engine", "%s/i/logo.png" % BASE_URL,
         plugin.get_setting("bitsnoop_enabled", bool))
@plugin.route("/bitsnoop")
@ensure_fanart
@tracked
def bitsnoop_index():
    plugin.redirect(plugin.url_for("bitsnoop_search"))


@plugin.route("/bitsnoop/browse/<root>/<page>")
@library_context
@ensure_fanart
@tracked
def bitsnoop_page(root, page):
    from urlparse import urljoin
    from xbmctorrent.scrapers import rss
Ejemplo n.º 38
0
def rutor_page(catind, page, query=None):
    import hashlib
    import xbmc
    from bs4 import BeautifulSoup
    from urlparse import urljoin
    from concurrent import futures
    from contextlib import closing
    from xbmctorrent.utils import SafeDialogProgress

    scraper_name = ""
    category = ([cat for cat in CATEGORIES if cat[0] == catind] or [("0", u"", "", "")])[0]
    scraper_name = category[3]
    plugin.set_content(category[2])

    page = int(page)
    catind = int(catind)

    mode = "browse"
    if query and query != str(None):
        mode = "search"

    with closing(SafeDialogProgress(delay_close=0)) as dialog:
        dialog.create(plugin.name)
        dialog.update(percent=0, line1=u"Получение информации о раздачах...", line2="", line3="")

        nodes = []
        try:
            html_data = url_get(urljoin(BASE_URL, "%s/%d/%d/0/0/%s" % (mode, page, catind, query)), headers=HEADERS)
            soup = BeautifulSoup(html_data, "html5lib")
            nodes = soup.findAll("tr", class_=["gai", "tum"])
        except Exception:
            import xbmcgui
            plugin.log.error("Unexpected error: %s" % sys.exc_info()[0])
            xbmcgui.Dialog().ok(plugin.name, "Не удалось получить данные от сервера")
            return

        if not nodes or len(nodes) == 0:
            yield {
                "label": u"[ Не найдено ]",
                "path": plugin.url_for("rutor_index"),
                "is_playable": False,
            }
            return

        # store length before filter
        nodeslen = len(nodes)
        nodes = [node for node in _rutor_filter_nodes(nodes)]

        items = []
        for node in nodes:
            cells = node.findAll("td")
            seeds, peers = map(lambda x: x.text.strip(), cells[len(cells) - 1].findAll("span"))
            links = cells[1].findAll("a")
            title_node = links[len(links) - 1]
            size = cells[len(cells) - 2].text
            tid = int(title_node["href"][9:title_node["href"].find(u"/", 9)])
            title = _rutor_cleantitle(title_node.text)
            label = "%s | %s (S:%s P:%s)" % (title, size, seeds, peers)
            item = {
                "label": label,
                "path": plugin.url_for("rutor_details", catind=catind, tid=tid),
                "info": {"title": title},
                "is_playable": False,
            }
            items.append(item)

        with futures.ThreadPoolExecutor(max_workers=5) as pool:
            from xbmctorrent.utils import get_item_info

            usesearch = plugin.get_setting("rutor_usesearch", bool)
            jobs = [pool.submit(get_item_info, i, usesearch and scraper_name or None) for i in items]
            state = {"done": 0}

            def on_done(future):
                if not future.cancelled():
                    state["done"] += 1
                    data = future.result()
                    dialog.update(
                        percent=int(state["done"] * 100.0 / len(jobs)),
                        line2=data["info"].get("title") or data.get("label") or "",
                    )

            [job.add_done_callback(on_done) for job in jobs]
            while not all(job.done() for job in jobs):
                if dialog.iscanceled():
                    [job.cancel() for job in jobs]
                    return
                xbmc.sleep(100)
            items = [job.result() for job in jobs if not job.cancelled()]

        passed = {}
        for item in items:
            sha1 = hashlib.sha1(uenc(item.get("subdir") and item["subdir"] or (item.get("search") and item["search"] or item["label"]))).hexdigest()
            if mode == "search" or not passed.get(sha1):
                passed[sha1] = True
                del item["search"]
                del item["subdir"]
                yield item

        if nodeslen == 100:
            next_page = {
                "label": u"[COLOR FF00FF00][Далее >][/COLOR]",
                "path": plugin.url_for("rutor_page", catind=catind, page=page + 1, query=query),
                "is_playable": False,
            }
            yield next_page
Ejemplo n.º 39
0
from xbmctorrent import plugin
from xbmctorrent.scrapers import scraper
from xbmctorrent.ga import tracked
from xbmctorrent.caching import cached_route
from xbmctorrent.utils import ensure_fanart


# Temporary, will be fixed later by them
BASE_URL = "%s/" % plugin.get_setting("base_nyaa")
HEADERS = {
    "Referer": BASE_URL,
}


CATEGORIES = [
    ("Anime", "1_0", (
        ("English-translated Anime", "1_37"),
        ("Raw Anime", "1_11"),
        ("Non-English-translated Anime", "1_38"),
        ("Anime Music Video", "1_32"),
    )),
    ("Live Action (movies)", "5_0", (
        ("English-translated Live Action", "5_19"),
        ("Raw Live Action", "5_20"),
        ("Non-English-translated Live Action", "5_21"),
        ("Live Action Promotional Video", "5_22"),
    )),
]

SORT_DATE = 1
SORT_SEEDERS = 2
Ejemplo n.º 40
0
def torrents3d_play(article):
    import re, xbmcgui
    from bs4 import BeautifulSoup
    from contextlib import closing
    from urlparse import urljoin
    from xbmctorrent.magnet import generate_magnet
    from xbmctorrent.utils import SafeDialogProgress

    article = int(article)

    with closing(SafeDialogProgress(delay_close=0)) as dialog:
        dialog.create(plugin.name)
        dialog.update(percent=0,
                      line1=u"Получение информации о релизе...",
                      line2="",
                      line3="")

        url = urljoin(BASE_URL, "article/%d" % article)

        try:
            html_data = url_get(url, headers=HEADERS)
            soup = BeautifulSoup(html_data, "html5lib")
            torrent_href = soup.find("a", class_="genmed")

            if not torrent_href:
                dialog.update(percent=50,
                              line2=u"Требуется авторизация. Авторизация...")

                if not plugin.get_setting(
                        "t3d_login") and not plugin.get_setting("t3d_passwd"):
                    plugin.notify("Проверьте настройки авторизации.",
                                  delay=15000)
                    return

                html_data = _torrents3d_login(url)
                soup = BeautifulSoup(html_data, "html5lib")
                torrent_href = soup.find("a", class_="genmed")

            if not torrent_href:
                xbmcgui.Dialog().ok(
                    plugin.name,
                    "Авторизация неудалась. Проверьте настройки авторизации.")
                return

            dialog.update(percent=100, line2=u"Обработка данных.")

            from bencode import bencode, bdecode

            title = "[%s] %s" % _torrents3d_cleantitle(
                soup.find("a", class_="tt-text").text)
            torrent_data = url_get(torrent_href["href"], headers=HEADERS)
            metadata = bdecode(torrent_data)

            plugin.redirect(
                plugin.url_for("play",
                               uri=generate_magnet(metadata, uenc(title))))

        except:
            plugin.log.error("Cannot get data from remote server")
            xbmcgui.Dialog().ok(plugin.name,
                                u"Не удалось получить данные от сервера")
            return
Ejemplo n.º 41
0
from xbmctorrent import plugin
from xbmctorrent.scrapers import scraper
from xbmctorrent.ga import tracked
from xbmctorrent.caching import cached_route
from xbmctorrent.utils import ensure_fanart
from xbmctorrent.library import library_context

# Temporary, will be fixed later by them
IMMUNICITY_TPB_URL = "http://thepiratebay.pe"
BASE_URL = "%s/" % (plugin.get_setting("immunicity", bool)
                    and IMMUNICITY_TPB_URL or plugin.get_setting("base_tpb"))
HEADERS = {
    "Referer": BASE_URL,
}

CATEGORIES = [
    ("Movies", 201, [
        ("in HD", 207),
        ("in 3D", 209),
    ]),
    ("Music videos", 203),
    ("TV shows", 205, [
        ("in HD", 208),
    ]),
    ("Other", 299),
]

if plugin.get_setting("p**n", bool):
    CATEGORIES += [
        ("XXX", 500, [
            ("Movies", 501),
Ejemplo n.º 42
0
def rutor_details(catind, tid):
    import urllib
    from bs4 import BeautifulSoup, SoupStrainer
    from urlparse import urljoin
    from xbmctorrent.utils import get_quality_from_name
    from xbmctorrent.search import scrapers as search

    scraper_name = ""
    category = ([cat for cat in CATEGORIES if cat[0] == catind]
                or [("0", u"", "", "")])[0]
    scraper_name = category[3]
    plugin.set_content(category[2])

    tid = int(tid)
    try:
        html_data = url_get(urljoin(BASE_URL, "torrent/%d/" % tid),
                            headers=HEADERS)
    except:
        import xbmcgui
        xbmcgui.Dialog().ok(plugin.name,
                            "Не удалось получить данные от сервера")
        return

    soup = BeautifulSoup(html_data, "html5lib")
    div_download = soup.select("div#download")[0]
    div_index = soup.select("div#index")

    if len(div_index) == 0:
        plugin.redirect(plugin.url_for("rutor_play", tid=tid))
        return

    scrapers = search.Scrapers()

    details = soup.select("table#details")[0].findAll("tr")
    seeds = details[4].contents[1].text
    peers = details[5].contents[1].text
    size = details[8].contents[1].text
    size = size[:size.find(" ")]
    title = _rutor_cleantitle(soup.h1.text)
    label = "%s | %s (S:%s P:%s)" % (title, size, seeds, peers)
    item = {"label": label, "info": {"title": title}}

    if plugin.get_setting("rutor_usesearch", bool):
        meta = scrapers.scraper(scraper_name, item)
    else:
        meta = scrapers.default(item)

    meta["path"] = plugin.url_for("rutor_play", tid=tid)
    meta["is_playable"] = False
    meta.setdefault("stream_info",
                    {}).update(get_quality_from_name(meta['label']))
    meta["context_menu"] = [
        ("Play with Pulsar",
         actions.update_view(plugin.url_for("rutor_play_pulsar", tid=tid)))
    ]

    del meta["search"]
    del meta["subdir"]
    yield meta

    if len(div_index) > 0:
        nodes = div_index[0].findAll("tr", class_=["gai", "tum"])
        nodes = [node for node in _rutor_filter_nodes(nodes)]

        for node in nodes:
            cells = node.findAll("td")
            seeds, peers = map(lambda x: x.text.strip(),
                               cells[len(cells) - 1].findAll("span"))
            donwload_node, magnet_node, title_node = cells[1].findAll("a")
            size = cells[len(cells) - 2].text
            title = _rutor_cleantitle(title_node.text)
            tid = int(title_node["href"][9:title_node["href"].find(u"/", 9)])
            label = "%s | %s (S:%s P:%s)" % (title, size, seeds, peers)

            item = scrapers.default({"label": label, "info": {"title": title}})
            item.update({
                "path": plugin.url_for("rutor_play", tid=tid),
                "is_playable": False,
                "thumbnail": meta["thumbnail"],
                "icon": meta["icon"]
            })
            item["info"].update(meta["info"])
            item["properties"].update(meta["properties"])
            item.setdefault("stream_info",
                            {}).update(get_quality_from_name(item['label']))
            item["context_menu"] = [("Play with Pulsar",
                                     actions.update_view(
                                         plugin.url_for("rutor_play_pulsar",
                                                        tid=tid)))]

            del item["search"]
            del item["subdir"]
            yield item
Ejemplo n.º 43
0
IGNORE_EXT = [u".srt", u".ssa", u".txt", u".ac3", u".aac", u".jpg"]


def udec(x):
    return x.decode('utf-8')


def uenc(x):
    return x.encode('utf-8')


_cookiejar = None


@scraper("Rutracker.org", "http://195.82.146.52/logo/logo.gif",
         plugin.get_setting("rutracker_enabled", bool))
@plugin.route("/rutracker")
@ensure_fanart
def rutracker_index():
    for cat in CATEGORIES:
        yield {
            "label":
            cat[1],
            "path":
            plugin.url_for("rutracker_page",
                           catind=cat[0],
                           page=0,
                           query=cat[0]),
        }

Ejemplo n.º 44
0
Archivo: nyaa.py Proyecto: roeiba/xbmc
from xbmctorrent import plugin
from xbmctorrent.scrapers import scraper
from xbmctorrent.ga import tracked
from xbmctorrent.caching import cached_route
from xbmctorrent.utils import ensure_fanart

# Temporary, will be fixed later by them
BASE_URL = "%s/" % plugin.get_setting("base_nyaa")
HEADERS = {
    "Referer": BASE_URL,
}

CATEGORIES = [
    ("Anime", "1_0", (
        ("English-translated Anime", "1_37"),
        ("Raw Anime", "1_11"),
        ("Non-English-translated Anime", "1_38"),
        ("Anime Music Video", "1_32"),
    )),
    ("Live Action (movies)", "5_0", (
        ("English-translated Live Action", "5_19"),
        ("Raw Live Action", "5_20"),
        ("Non-English-translated Live Action", "5_21"),
        ("Live Action Promotional Video", "5_22"),
    )),
]

SORT_DATE = 1
SORT_SEEDERS = 2
SORT_LEECHERS = 3
SORT_DOWNLOADS = 4
Ejemplo n.º 45
0
from xbmctorrent import plugin
from xbmctorrent.scrapers import scraper
from xbmctorrent.ga import tracked
from xbmctorrent.caching import cached_route, shelf
from xbmctorrent.utils import ensure_fanart
from xbmctorrent.library import library_context


BASE_URL = "%s/" % plugin.get_setting("base_eztv")
HEADERS = {
    "Referer": BASE_URL,
}
SHOW_LIST_CACHE_TTL = 24 * 3600 # 24 hours caching
SHOW_CACHE_TTL = 6 * 3600 # 6 hours caching


# Logo found on http://thesimurg.deviantart.com/art/Logo-for-EZTV-57874544
@scraper("EZTV - Series", "http://i.imgur.com/XcH6WOg.jpg")
@plugin.route("/eztv")
@ensure_fanart
@tracked
def eztv_index():
    import string
    for letter in ["0-9"] + list(string.ascii_uppercase):
        yield {
            "label": letter,
            "path": plugin.url_for("eztv_shows_by_letter", letter=letter),
            "is_playable": False,
        }

Ejemplo n.º 46
0
import os, string
from xbmctorrent import plugin
from xbmctorrent.scrapers import scraper
from xbmctorrent.ga import tracked
from xbmctorrent.caching import cached_route
from xbmctorrent.utils import ensure_fanart
from xbmctorrent.library import library_context
from xbmcswift2.logger import log
from bs4 import BeautifulSoup
from xbmctorrent.utils import url_get

BASE_URL = plugin.get_setting("base_cpb")
HEADERS = {
    "Referer": BASE_URL,
}

SORT_DATE = "trie-date"
SORT_NOM = "trie-nom"
SORT_TELECHARGEMENT = "trie-telechargement"
SORT_SEEDS = "trie-seeds"
SORT_LEECHS = "trie-leechs"
SORT_CATEGORIE = "trie-categorie"

SORT_DIRECTION_ASC = "-a"
SORT_DIRECTION_DESC = "-d"


@scraper("CPasBien - Torrent Francais - Films, Series",
         "%s/_template/cpasbien/_styles/_images/header1.jpg" % BASE_URL)
@plugin.route("/cpb")
@ensure_fanart
Ejemplo n.º 47
0
from xbmctorrent import plugin
from xbmctorrent.scrapers import scraper
from xbmctorrent.ga import tracked
from xbmctorrent.caching import cached_route
from xbmctorrent.utils import ensure_fanart
from xbmctorrent.library import library_context


BASE_URL = plugin.get_setting("base_btdigg")
HEADERS = {
    "Referer": BASE_URL,
}
SORT_RELEVANCE = 0
SORT_POPULARITY = 1
SORT_ADDTIME = 2
SORT_SIZE = 3
SORT_FILES = 4


@scraper("BTDigg - DHT Search Engine", "%s/logo.png" % BASE_URL)
@plugin.route("/btdigg")
@ensure_fanart
@tracked
def btdigg_index():
    plugin.redirect(plugin.url_for("btdigg_search"))


@plugin.route("/btdigg/search/<query>/<sort>/<page>")
@library_context
@ensure_fanart
@tracked
Ejemplo n.º 48
0
def rutracker_play(tid, pulsar):
    from copy import deepcopy
    from contextlib import closing
    from bencode import bencode, bdecode
    from urlparse import urljoin
    from xbmctorrent.magnet import generate_magnet
    from xbmctorrent.utils import first, SafeDialogProgress, get_quality_from_name, get_current_list_item
    from xbmctorrent.acestream import ace_supported

    with closing(SafeDialogProgress(delay_close=0)) as dialog:
        dialog.create(plugin.name)
        dialog.update(percent=0, line1="Получение информации о раздаче...")

        torrent_url = urljoin("http://dl.rutracker.org/forum/",
                              "dl.php?t=%s" % tid)
        try:

            plugin.log.debug("loading data from uri: " + torrent_url)
            params = {"t": tid}

            import os, xbmc, cookielib

            cookie = cookielib.Cookie(version=0,
                                      name='bb_dl',
                                      value=tid,
                                      port=None,
                                      port_specified=False,
                                      domain='.rutracker.org',
                                      domain_specified=False,
                                      domain_initial_dot=False,
                                      path='/',
                                      path_specified=True,
                                      secure=False,
                                      expires=None,
                                      discard=True,
                                      comment=None,
                                      comment_url=None,
                                      rest={'HttpOnly': None},
                                      rfc2109=False)

            data = url_get(torrent_url,
                           headers=HEADERS,
                           post=params,
                           cookie=cookie)
            metadata = bdecode(data)
            plugin.log.debug("Metadata received " + str(metadata))
        except:
            import xbmcgui

            plugin.log.error("Unexpected error: %s " %
                             format_exc().split('\n')[-2])
            xbmcgui.Dialog().ok(plugin.name,
                                "Не удалось получить данные от сервера")
            return

        dialog.update(percent=100, line1="Готово")

        # Get currently selected item
        current_item = get_current_list_item()
        current_item.setdefault("stream_info", {}).update(
            get_quality_from_name(current_item['label']))

        if "files" in metadata["info"] and ace_supported():
            items = {}
            for index, info in enumerate(metadata["info"]["files"]):
                name = "/".join(info["path"])

                if not _rutracker_valid_file(name):
                    continue

                items[index] = deepcopy(current_item)
                items[index].update({
                    "label":
                    name,
                    "path":
                    plugin.url_for("play_torrent_raw",
                                   raw=data,
                                   index=index,
                                   name=name),
                    "is_playable":
                    True
                })
                items[index].setdefault("info", {}).update({
                    "title": name,
                })

            # start playback if torrent contains only one file
            if len(items) == 1:
                index, item = items.popitem()

                if not plugin.get_setting("force_ace", bool):
                    item["path"] = plugin.url_for("play",
                                                  uri=generate_magnet(
                                                      metadata, item["label"]))

                plugin.play_video(item)
                yield item
            else:
                plugin.add_sort_method('label')
                for i in items.values():
                    yield i
        else:
            name = metadata["info"].get("name") or " / ".join(
                first(metadata["info"]["files"])["path"]) or "rutor.org"
            if plugin.get_setting("force_ace", bool) and ace_supported():
                current_item["path"] = plugin.url_for("play_torrent_raw",
                                                      raw=data,
                                                      index=0,
                                                      name=name)
            else:
                current_item["path"] = plugin.url_for(
                    ["play", "play_with_pulsar"][int(pulsar)],
                    uri=generate_magnet(metadata, name))

            current_item["is_playable"] = True
            plugin.play_video(current_item)

            yield current_item
Ejemplo n.º 49
0
        _cookiejar.load()

    cookie_handler = urllib2.HTTPCookieProcessor(_cookiejar)
    result = url_get_origin(url,
                            params,
                            headers,
                            post,
                            handlers=[cookie_handler])
    _cookiejar.save()

    return result


@scraper("Torrents3D.ru", "%s/images/logo/dyz_logo.gif" % BASE_URL,
         plugin.get_setting("t3d_enabled", bool))
@plugin.route("/t3d/index")
@ensure_fanart
def torrents3d_index():
    yield {
        "label": u"[COLOR FFFFFF00][ Поиск ][/COLOR]",
        "path": plugin.url_for("torrents3d_search")
    }

    def make_cats(root, prefix=""):
        for cat in root:
            yield {
                "label": "%s%s" % (prefix, cat[0]),
                "path": plugin.url_for("torrents3d_page",
                                       section=cat[1],
                                       page=0),
Ejemplo n.º 50
0
    def loop(self):
        from xbmctorrent.utils import SafeDialogProgress
        from xbmctorrent.player import OverlayText

        has_resolved = False
        plugin.log.info("Starting AceStream...")

        def safe_cast(val, to_type, default=None):
            try:
                return to_type(val)
            except ValueError:
                return default

        engine_params = {
            "filename":
            self.file_name,
            "host":
            plugin.get_setting("ace_host", str) or DEFAULT_ACESTREAM_HOST,
            "port":
            safe_cast(plugin.get_setting("ace_port"), int,
                      DEFAULT_ACESTREAM_PORT),
            "keep_enc":
            plugin.get_setting("ace_keep_encripted", bool)
        }

        if plugin.get_setting("keep_files", bool):
            plugin.log.info("Will keep file after playback.")
            engine_params["dlpath"] = xbmc.validatePath(
                xbmc.translatePath(
                    plugin.get_setting("dlpath")
                    or "special://temp/" + plugin.id))

            if engine_params["dlpath"] and "://" in engine_params["dlpath"]:
                # Translate smb:// url to UNC path on windows, very hackish
                if PLATFORM["os"] == "windows" and engine_params[
                        "dlpath"].lower().startswith("smb://"):
                    engine_params["dlpath"] = engine_params["dlpath"].replace(
                        "smb:", "").replace("/", "\\")

        with closing(AceEngine(**engine_params)) as engine:
            plugin.log.info("Opening download dialog...")

            # Get currently selected item
            current_item = get_current_list_item()

            with closing(SafeDialogProgress(delay_create=0)) as dialog:
                dialog.create("AceStream Player")

                connected = engine.try_to_connect()
                ready = False

                n = 1
                start = time.time()
                while (time.time() - start) < ACESTREAM_CONNECTION_TIMEOUT:
                    if xbmc.abortRequested or dialog.iscanceled():
                        return

                    dialog.update(0, self.file_name,
                                  "Попытка соединения с AceStream (%s)" % n)
                    if not connected:
                        plugin.log.info("Starting AceStream engine")

                        if engine.start():
                            xbmc.sleep(ACESTREAM_CONNECTION_POLL)

                        connected = engine.try_to_connect()
                        continue
                    else:
                        if engine.is_ready():
                            break
                        plugin.log.info("Engine is not ready")

                    xbmc.sleep(ACESTREAM_CONNECTION_POLL)
                    n = n + 1

                if not engine.is_ready():
                    return

                dialog.update(
                    0, self.file_name,
                    "Соединение установлено. Запуск загрузки данных...")

                if not engine.play(
                        self.torrent, self.index, is_raw=self.is_raw):
                    return

                while not has_resolved:
                    if xbmc.abortRequested or dialog.iscanceled():
                        return

                    status = engine.get_status()

                    if status["error"]:
                        dialog.update(
                            int(status["progress"]), *[
                                self.file_name, STATE_STRS[status["status"]],
                                status["error"]
                            ])
                        xbmc.sleep(PLAYING_EVENT_INTERVAL)
                        return

                    if status["state"] > 0 and status["status"]:
                        dialog.update(int(status["progress"]),
                                      *self._get_status_lines(status))

                    if status["state"] >= 2 and status[
                            "status"] == "dl" and not has_resolved:  # Downloading?
                        if int(status["progress"]) >= 0:
                            plugin.log.info("Resolving to %s" % status["url"])
                            has_resolved = True
                            if not current_item["info"].get("title"):
                                current_item["label"] = self.file_name
                            current_item["path"] = status["url"]
                            plugin.set_resolved_url(current_item)
                            break

                    xbmc.sleep(PLAYING_EVENT_INTERVAL)

            # We are now playing
            plugin.log.info("Now playing torrent...")

            with closing(
                    OverlayText(w=OVERLAY_WIDTH,
                                h=OVERLAY_HEIGHT,
                                alignment=XBFONT_CENTER_X
                                | XBFONT_CENTER_Y)) as overlay:
                with nested(
                        self.attach(overlay.show, self.on_playback_paused),
                        self.attach(overlay.hide, self.on_playback_resumed,
                                    self.on_playback_stopped),
                        self.attach(engine.on_start, self.on_playback_started),
                        self.attach(engine.on_pause, self.on_playback_paused),
                        self.attach(engine.on_resume,
                                    self.on_playback_resumed),
                        self.attach(engine.on_stop, self.on_playback_stopped),
                        self.attach(engine.on_seek, self.on_playback_seek),
                        self.attach(engine.on_end, self.on_playback_ended),
                        self.attach(self.pause, engine.on_playback_paused),
                        self.attach(self.play, engine.on_playback_resumed)):
                    while not xbmc.abortRequested and self.isPlaying(
                    ) and not engine.error:
                        overlay.text = "\n".join(
                            self._get_status_lines(engine.get_status()))
                        xbmc.sleep(PLAYING_EVENT_INTERVAL)

        plugin.log.info("Closing AceStream player.")
Ejemplo n.º 51
0
# -*- coding: utf-8 -*-

import sys
from xbmcswift2 import actions
from xbmctorrent import plugin
from xbmctorrent.scrapers import scraper
from xbmctorrent.caching import cached_route, CACHE_DIR
from xbmctorrent.utils import ensure_fanart

BASE_URL = "%s/" % plugin.get_setting("base_rutor")
# DOWNLOAD_URL = BASE_URL.replace("http://", "http://d.").replace("https://", "https://d.")  # "http://d.rutor.info/"

HEADERS = {
    'Referer': BASE_URL,
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Language': 'ru,en-US;q=0.8,en;q=0.6',
    'Accept-Charset': 'utf-8, *;q=0.1',
    'Accept-Encoding': 'gzip, deflate, sdch',
    'X-Compress': 'null'
}

CATEGORIES = (
    ("1", u"Зарубежные фильмы", "movies", "tmdb"),
    ("5", u"Наши фильмы", "movies", "kinopoisk"),
    ("12", u"Научно-популярные фильмы", "movies", ""),
    ("4", u"Сериалы", "tvshows", "tvdb"),
    ("6", u"Телевизор", "tvshows", ""),
    ("7", u"Мультипликация", "movies", "tmdb"),
    ("10", u"Аниме", "movies", ""),
    ("13", u"Спорт и Здоровье", "tvshows", ""),
    ("15", u"Юмор", "tvshows", ""),
Ejemplo n.º 52
0
from xbmctorrent import plugin
from xbmctorrent.scrapers import scraper
from xbmctorrent.ga import tracked
from xbmctorrent.caching import cached_route
from xbmctorrent.utils import ensure_fanart
from xbmctorrent.library import library_context


# Temporary, will be fixed later by them
IMMUNICITY_TPB_URL = "http://thepiratebay.pe"
BASE_URL = "%s/" % (plugin.get_setting("immunicity", bool) and IMMUNICITY_TPB_URL or plugin.get_setting("base_tpb"))
HEADERS = {
    "Referer": BASE_URL,
}


CATEGORIES = [
    ("Movies", 201, [
        ("in HD", 207),
        ("in 3D", 209),
    ]),
    ("Music videos", 203),
    ("TV shows", 205, [
        ("in HD", 208),
    ]),
    ("Other", 299),
]

if plugin.get_setting("p**n", bool):
    CATEGORIES += [
        ("XXX", 500, [
Ejemplo n.º 53
0
def rutor_details(catind, tid):
    import xbmcgui
    from bs4 import BeautifulSoup
    from urlparse import urljoin
    from xbmctorrent.utils import get_quality_from_name
    from xbmctorrent.search import scrapers as search

    scraper_name = ""
    category = ([cat for cat in CATEGORIES if cat[0] == catind] or [("0", u"", "", "")])[0]
    scraper_name = category[3]
    plugin.set_content(category[2])

    tid = int(tid)
    try:
        html_data = url_get(urljoin(BASE_URL, "torrent/%d/" % tid), headers=HEADERS)
    except Exception:
        xbmcgui.Dialog().ok(plugin.name, "Не удалось получить данные от сервера")
        return

    soup = BeautifulSoup(html_data, "html5lib")
    if len(soup.select("div#download")) == 0:
        # it may occur if site redirects a request to his mirror
        xbmcgui.Dialog().ok(plugin.name, "Раздачи не существует. Обновите список")
        return

    div_index = soup.select("div#index")

    scrapers = search.Scrapers()

    details = soup.select("table#details")[0].findAll("tr")
    shift = 1 if len(details[1].select("a")) > 0 else 0
    seeds = details[3 + shift].contents[1].text
    peers = details[4 + shift].contents[1].text
    size = details[7 + shift].contents[1].text
    size = size[:size.find(" ")]
    title = _rutor_cleantitle(soup.h1.text)
    label = "%s | %s (S:%s P:%s)" % (title, size, seeds, peers)
    item = {
        "label": label,
        "info": {"title": title}
    }

    if plugin.get_setting("rutor_usesearch", bool):
        meta = scrapers.scraper(scraper_name, item)
    else:
        meta = scrapers.default(item)

    meta["path"] = plugin.url_for("rutor_play", tid=tid)
    meta["is_playable"] = True
    meta.setdefault("stream_info", {}).update(get_quality_from_name(meta['label']))
    meta["context_menu"] = [("Play with Pulsar", actions.update_view(plugin.url_for("rutor_play_pulsar", tid=tid)))]

    del meta["search"]
    del meta["subdir"]
    yield meta

    if len(div_index) > 0:
        nodes = div_index[0].findAll("tr", class_=["gai", "tum"])
        nodes = [node for node in _rutor_filter_nodes(nodes)]

        for node in nodes:
            cells = node.findAll("td")
            seeds, peers = map(lambda x: x.text.strip(), cells[len(cells) - 1].findAll("span"))
            donwload_node, magnet_node, title_node = cells[1].findAll("a")
            size = cells[len(cells) - 2].text
            title = _rutor_cleantitle(title_node.text)
            tid = int(title_node["href"][9:title_node["href"].find(u"/", 9)])
            label = "%s | %s (S:%s P:%s)" % (title, size, seeds, peers)

            item = scrapers.default({
                "label": label,
                "info": {"title": title}
            })
            item.update({
                "path": plugin.url_for("rutor_play", tid=tid),
                "is_playable": True,
                "thumbnail": meta["thumbnail"],
                "icon": meta["icon"]
            })
            item["info"].update(meta["info"])
            item["properties"].update(meta["properties"])
            item.setdefault("stream_info", {}).update(get_quality_from_name(item['label']))
            item["context_menu"] = [("Play with Pulsar", actions.update_view(plugin.url_for("rutor_play_pulsar", tid=tid)))]

            del item["search"]
            del item["subdir"]
            yield item
Ejemplo n.º 54
0
from xbmctorrent import plugin
from xbmctorrent.scrapers import scraper
from xbmctorrent.ga import tracked
from xbmctorrent.caching import cached_route
from xbmctorrent.utils import ensure_fanart
from xbmctorrent.library import library_context

BASE_URL = "%s/" % plugin.get_setting("base_bitsnoop")
HEADERS = {
    "Referer": BASE_URL,
}
# Cache TTLs
DEFAULT_TTL = 24 * 3600  # 24 hours


@scraper("BitSnoop - Search Engine", "%s/i/logo.png" % BASE_URL)
@plugin.route("/bitsnoop")
@ensure_fanart
@tracked
def bitsnoop_index():
    plugin.redirect(plugin.url_for("bitsnoop_search"))


@plugin.route("/bitsnoop/browse/<root>/<page>")
@library_context
@ensure_fanart
@tracked
def bitsnoop_page(root, page):
    from urlparse import urljoin
    from xbmctorrent.scrapers import rss
    from xbmctorrent.utils import url_get
Ejemplo n.º 55
0
from xbmctorrent import plugin
from xbmctorrent.scrapers import scraper
from xbmctorrent.ga import tracked
from xbmctorrent.caching import cached_route
from xbmctorrent.utils import ensure_fanart


BASE_URL = "%s/" % plugin.get_setting("base_yify")
HEADERS = {
    "Referer": BASE_URL,
}
YOUTUBE_ACTION = "plugin://plugin.video.youtube/?path=/root/video&action=play_video&videoid=%s"
MOVIES_PER_PAGE = 20
GENRES = [
    "Action",
    "Adventure",
    "Animation",
    "Biography",
    "Comedy",
    "Crime",
    "Documentary",
    "Drama",
    "Family",
    "Fantasy",
    "Film-Noir",
    "Game-Show",
    "History",
    "Horror",
    "Music",
    "Musical",
    "Mystery",
Ejemplo n.º 56
0
def rutor_play(tid, pulsar):
    from copy import deepcopy
    from contextlib import closing
    from bencode import bencode, bdecode
    from urlparse import urljoin
    from xbmctorrent.magnet import generate_magnet
    from xbmctorrent.utils import first, SafeDialogProgress, get_quality_from_name, get_current_list_item
    from xbmctorrent.acestream import ace_supported

    with closing(SafeDialogProgress(delay_close=0)) as dialog:
        dialog.create(plugin.name)
        dialog.update(percent=0, line1="Получение информации о раздаче...")

        torrent_url = urljoin(DOWNLOAD_URL, "download/%s" % tid)
        try:
            metadata = bdecode(url_get(torrent_url, headers=HEADERS))
        except:
            import xbmcgui
            plugin.log.error("Unexpected error: %s" % sys.exc_info()[0])
            xbmcgui.Dialog().ok(plugin.name,
                                "Не удалось получить данные от сервера")
            return

        dialog.update(percent=100, line1="Готово")

        # Get currently selected item
        current_item = get_current_list_item()
        current_item.setdefault("stream_info", {}).update(
            get_quality_from_name(current_item['label']))

        if "files" in metadata["info"] and ace_supported():
            items = {}
            for index, info in enumerate(metadata["info"]["files"]):
                name = "/".join(info["path"])

                if not _rutor_valid_file(name):
                    continue

                items[index] = deepcopy(current_item)
                items[index].update({
                    "label":
                    name,
                    "path":
                    plugin.url_for("torrent_play",
                                   url=torrent_url,
                                   index=index,
                                   name=name),
                    "is_playable":
                    True
                })
                items[index].setdefault("info", {}).update({
                    "title": name,
                })

            # start playback if torrent contains only one file
            if len(items) == 1:
                index, item = items.popitem()

                if not plugin.get_setting("force_ace", bool):
                    item["path"] = plugin.url_for("play",
                                                  uri=generate_magnet(
                                                      metadata, item["label"]))

                plugin.play_video(item)
                yield item
            else:
                plugin.add_sort_method('label')
                for i in items.values():
                    yield i
        else:
            name = metadata["info"].get("name") or " / ".join(
                first(metadata["info"]["files"])["path"]) or "rutor.org"
            if plugin.get_setting("force_ace", bool) and ace_supported():
                current_item["path"] = plugin.url_for("torrent_play",
                                                      url=torrent_url,
                                                      index=0,
                                                      name=name)
            else:
                current_item["path"] = plugin.url_for(
                    ["play", "play_with_pulsar"][int(pulsar)],
                    uri=generate_magnet(metadata, name))

            current_item["is_playable"] = True
            plugin.play_video(current_item)

            yield current_item
Ejemplo n.º 57
0
import os
from xbmctorrent import plugin


@plugin.route("/cmd/install")
def firstrun():
    clear_cache()
    plugin.notify("Please review your settings.")
    plugin.set_setting("firstrun", "true")
    plugin.open_settings()


@plugin.route("/cmd/clear_cache")
def clear_cache():
    import os
    import glob
    from xbmctorrent.caching import CACHE_DIR
    for directory in [CACHE_DIR, plugin.storage_path]:
        for dbfile in glob.glob(os.path.join(directory, "*.db")):
            os.remove(dbfile)
    plugin.notify("Cache cleared.")


if not plugin.get_setting("firstrun", bool):
    firstrun()
Ejemplo n.º 58
0
from xbmctorrent import plugin


@plugin.route("/cmd/install")
def firstrun():
    clear_cache()
    plugin.notify("Please review your settings.")
    plugin.set_setting("firstrun", "true")
    plugin.open_settings()


@plugin.route("/cmd/clear_cache")
def clear_cache():
    import os
    import glob
    from xbmctorrent.caching import CACHE_DIR
    for directory in [CACHE_DIR, plugin.storage_path]:
        for dbfile in glob.glob(os.path.join(directory, "*.db")):
            os.remove(dbfile)
    plugin.notify("Cache cleared.")


if not plugin.get_setting("firstrun", bool):
    firstrun()