예제 #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
예제 #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
예제 #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
예제 #4
0
def library_add(content_type):
    import os
    import xbmc
    import json
    from xbmctorrent.magnet import ensure_magnet, display_name
    from xbmctorrent.utils import get_show_info_from_name
    from urllib import quote, unquote

    play_url = "plugin://plugin.video.xbmctorrent/play/"
    for name, entry in LIBRARY_PATHS.items():
        if entry["strContent"] == content_type:
            real_path = xbmc.translatePath(entry["strPath"])
            uri = unquote(plugin.request.args_dict["href"].replace(play_url, ""))
            magnet_uri = ensure_magnet(uri)
            filename = display_name(magnet_uri)
            if not filename:
                plugin.notify("Unable to add this file. Magnet is incomplete.")
                return
            if content_type == "tvshows":
                show_info = get_show_info_from_name(filename)
                if show_info:
                    real_path = os.path.join(real_path, show_info["show"])
                    if not os.path.exists(real_path):
                        os.makedirs(real_path)
            with open(os.path.join(real_path, "%s.strm" % filename), "w") as fp:
                fp.write("%s%s" % (play_url, quote(magnet_uri)))
            xbmc.executeJSONRPC(json.dumps({
                "jsonrpc": "2.0",
                "id": 1,
                "method": "VideoLibrary.Scan",
                "params": {"directory": entry["strPath"]},
            }))
            plugin.notify("Added to %s." % name)
            break
예제 #5
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
예제 #6
0
def library_add(content_type):
    import os
    import xbmc
    import xbmcgui
    from xbmctorrent.magnet import ensure_magnet, display_name
    from xbmctorrent.utils import get_show_info_from_name
    from urllib import quote_plus, unquote

    play_url = "plugin://plugin.video.xbmctorrent/play/"
    for name, entry in LIBRARY_PATHS.items():
        if entry["strContent"] == content_type:

            if not xbmcgui.Dialog().yesno("Add to %s" % name, "Add \"%s\" to %s ?" % (plugin.request.args_dict["label"], name), ""):
                return

            real_path = xbmc.translatePath(entry["strPath"])
            uri = unquote(plugin.request.args_dict["href"].replace(play_url, ""))
            magnet_uri = ensure_magnet(uri)
            filename = display_name(magnet_uri)
            if not filename:
                plugin.notify("Unable to add this file. Magnet is incomplete.")
                return
            if content_type == "tvshows":
                show_info = get_show_info_from_name(filename)
                if show_info:
                    real_path = os.path.join(real_path, show_info["show"])
                    if not os.path.exists(real_path):
                        os.makedirs(real_path)
            with open(os.path.join(real_path, "%s.strm" % filename), "w") as fp:
                fp.write("%s%s" % (play_url, quote_plus(magnet_uri)))
            _rescan_library(entry["strPath"])
            plugin.notify("Added to %s." % name)
            break
예제 #7
0
def _ensure_settings():
    import os
    firstrun = os.path.join(plugin.addon.getAddonInfo("path"), ".firstrun")
    if not os.path.exists(firstrun):
        with open(firstrun, "w"):
            plugin.set_setting("base_tpb", "http://thepiratebay.org") # Properly set TPB for now
            plugin.notify("Please review your settings.")
            plugin.open_settings()
예제 #8
0
파일: cmd.py 프로젝트: afedchin/xbmctorrent
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.")
예제 #9
0
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.")
예제 #10
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
예제 #11
0
파일: index.py 프로젝트: elbowz/xbmctorrent
def index():
    if PLATFORM["os"] not in ["android", "linux", "windows", "darwin"]:
        plugin.notify("Your system \"%(os)s_%(arch)s\" is not supported." % PLATFORM, delay=15000)

    for module in MODULES:
        yield {
            "label": module["name"],
            "thumbnail": module["image"],
            "path": plugin.url_for(module["view"]),
        }
예제 #12
0
def index():
    if PLATFORM["os"] not in ["android", "linux", "windows", "darwin"]:
        plugin.notify("Your system \"%(os)s_%(arch)s\" is not supported." %
                      PLATFORM,
                      delay=15000)

    for module in MODULES:
        yield {
            "label": module["name"],
            "thumbnail": module["image"],
            "path": plugin.url_for(module["view"]),
        }
예제 #13
0
파일: t3d.py 프로젝트: afedchin/xbmctorrent
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
예제 #14
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
예제 #15
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
예제 #16
0
def index():
    import os
    firstrun = os.path.join(plugin.addon.getAddonInfo("path"), ".firstrun")
    if not os.path.exists(firstrun):
        with open(firstrun, "w"):
            # This doesn't get set properly
            plugin.set_setting("encryption", "1")
            plugin.open_settings()

    if PLATFORM["os"] not in ["android", "linux", "windows", "darwin"]:
        plugin.notify("Your system \"%(os)s_%(arch)s\" is not supported." %
                      PLATFORM,
                      delay=15000)

    for module in MODULES:
        yield {
            "label": module["name"],
            "thumbnail": module["image"],
            "path": plugin.url_for(module["view"]),
        }
예제 #17
0
def filelist_page(cat, page):
    import re
    from bs4 import BeautifulSoup
    from urlparse import urljoin
    
    page = int(page)
    url = urljoin(BASE_URL, "browse.php")

    html_data = url_get(url, params = {"cat": cat, "page": page}, headers = HEADERS)
    soup = BeautifulSoup(html_data, "html5lib")
    
    login = soup.find('input', {"value": "Login"})
    #print "login: %s" % login
    if login is not None:
      plugin.notify("You have to login", 'Msg', 100)
      _filelist_login(referer=BASE_URL)
      html_data = url_get(url, params = {"cat": cat, "page": page}, headers = HEADERS)
      soup = BeautifulSoup(html_data, "html5lib")
  
    trs = soup.find('table', {"class": "visitedlinks"}).findAll('tr')[1:]
 

    for tr in trs:
        tds = tr.findAll('td')
        title = tds[1].find('a').text
        link = tds[2].find('a')["href"]
        link = urljoin(BASE_URL, link)

        yield {
            "label": title,
            "path": plugin.url_for("play_torrent", uri=link),
            #"path": plugin.url_for("filelist_page", cat=cat, page=page+1),
            "is_playable": True,
        }
    next_page = {
        "label": "Next page...",
        "path": plugin.url_for("filelist_page", cat=1, page=0),
        "is_playable": False,
    }

    yield next_page
예제 #18
0
def _iplay_login(referer = BASE_URL):
    from bs4 import BeautifulSoup
    from urlparse import urljoin
    from xbmctorrent.utils import url_get

    html_data = url_get(urljoin(BASE_URL, "user"))
    
    soup = BeautifulSoup(html_data, "html5lib")
    form_build_id = soup.find('input', {"name": "form_build_id"}).get("value")
    #plugin.notify(form_build_id)
    
    HEADERS["Referer"] = referer
    HEADERS["Origin"] = BASE_URL
    HEADERS["Content-Type"] = "application/x-www-form-urlencoded"

    values = {
        "name": "admin",
        "pass": "******",
        "form_id": "user_login",
        "form_build_id": form_build_id,
        "op": "Log in",
        #"returnto": "/browse.php"
    }
    
    # #values = None

    html_data = url_get(urljoin(BASE_URL, "user"), post=values, headers = HEADERS)
    plugin.notify(html_data)
    # #html_data = url_get(urljoin(BASE_URL, "test/proxy.php"), headers=HEADERS)
    #soup = BeautifulSoup(html_data, "html5lib")
    
    # #login = soup.find('div', {"id": "ilogin"})
    #login = soup.find('form', {"id": "user-login"})
    
    # if login is not None:
    #     plugin.notify("You have to login", 'Msg', 100)
    # else:
    #     plugin.notify('Logged in', 'Msg', 100)
    return ""
예제 #19
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
예제 #20
0
def library_add(content_type):
    import os
    import xbmc
    import xbmcgui
    from xbmctorrent.magnet import ensure_magnet, display_name
    from xbmctorrent.utils import get_show_info_from_name
    from urllib import quote_plus, unquote

    play_url = "plugin://plugin.video.xbmctorrent/play/"
    for name, entry in LIBRARY_PATHS.items():
        if entry["strContent"] == content_type:

            if not xbmcgui.Dialog().yesno(
                    "Add to %s" % name, "Add \"%s\" to %s ?" %
                (plugin.request.args_dict["label"], name), ""):
                return

            real_path = xbmc.translatePath(entry["strPath"])
            uri = unquote(plugin.request.args_dict["href"].replace(
                play_url, ""))
            magnet_uri = ensure_magnet(uri)
            filename = display_name(magnet_uri)
            if not filename:
                plugin.notify("Unable to add this file. Magnet is incomplete.")
                return
            if content_type == "tvshows":
                show_info = get_show_info_from_name(filename)
                if show_info:
                    real_path = os.path.join(real_path, show_info["show"])
                    if not os.path.exists(real_path):
                        os.makedirs(real_path)
            with open(os.path.join(real_path, "%s.strm" % filename),
                      "w") as fp:
                fp.write("%s%s" % (play_url, quote_plus(magnet_uri)))
            _rescan_library(entry["strPath"])
            plugin.notify("Added to %s." % name)
            break
예제 #21
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
예제 #22
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
예제 #23
0
파일: cmd.py 프로젝트: vizzah/xbmctorrent
def clear_cache():
    plugin.notify("Coucou les aminches!")
예제 #24
0
def yify_show_data(callback):
    import xbmc
    import xbmcgui
    from contextlib import nested, closing
    from itertools import izip, chain
    from concurrent import futures
    from xbmctorrent import tmdb
    from xbmctorrent.utils import url_get_json, terminating, SafeDialogProgress

    plugin.set_content("movies")
    args = dict((k, v[0]) for k, v in plugin.request.args.items())

    current_page = int(args["set"])
    limit = int(args["limit"])

    with closing(SafeDialogProgress(delay_close=0)) as dialog:
        dialog.create(plugin.name)
        dialog.update(percent=0, line1="Fetching movie information...", line2="", line3="")

        try:
            search_result = url_get_json("%s/api/list.json" % BASE_URL, params=args, headers=HEADERS)
        except:
            plugin.notify("Unable to connect to %s." % BASE_URL)
            raise
        movies = search_result.get("MovieList") or []

        if not movies:
            return

        state = {"done": 0}
        def on_movie(future):
            data = future.result()
            state["done"] += 1
            dialog.update(
                percent=int(state["done"] * 100.0 / len(movies)),
                line2=data.get("title") or data.get("MovieTitleClean") or "",
            )

        with futures.ThreadPoolExecutor(max_workers=2) as pool_tmdb:
            tmdb_list = [pool_tmdb.submit(tmdb.get, movie["ImdbCode"]) for movie in movies]
            [future.add_done_callback(on_movie) for future in tmdb_list]
            while not all(job.done() for job in tmdb_list):
                if dialog.iscanceled():
                    return
                xbmc.sleep(100)

        tmdb_list = map(lambda job: job.result(), tmdb_list)
        for movie, tmdb_meta in izip(movies, tmdb_list):
            if tmdb_meta:
                item = tmdb.get_list_item(tmdb_meta)
                if args.get("quality") == "all" and movie["Quality"] != "720p":
                    item["label"] = "%s (%s)" % (item["label"], movie["Quality"])
                item.update({
                    "path": plugin.url_for("play", uri=movie["TorrentMagnetUrl"]),
                    "is_playable": True,
                })
                item.setdefault("info", {}).update({
                    "count": movie["MovieID"],
                    "genre": "%s (%s S:%s P:%s)" % (item["info"]["genre"], movie["Size"], movie["TorrentSeeds"], movie["TorrentPeers"]),
                    "plot_outline": tmdb_meta["overview"],
                    "video_codec": "h264",
                })
                width = 1920
                height = 1080
                if movie["Quality"] == "720p":
                    width = 1280
                    height = 720
                item.setdefault("stream_info", {}).update({
                    "video": {
                        "codec": "h264",
                        "width": width,
                        "height": height,
                    },
                    "audio": {
                        "codec": "aac",
                    },
                })
                yield item

        if current_page < (int(search_result["MovieCount"]) / limit):
            next_args = args.copy()
            next_args["set"] = int(next_args["set"]) + 1
            yield {
                "label": ">> Next page",
                "path": plugin.url_for(callback, **next_args),
            }
예제 #25
0
파일: cmd.py 프로젝트: afedchin/xbmctorrent
def firstrun():
    clear_cache()
    plugin.notify("Please review your settings.")
    plugin.set_setting("firstrun", "true")
    plugin.open_settings()
예제 #26
0
def yify_show_data(callback):
    import xbmc
    import xbmcgui
    from contextlib import nested, closing
    from itertools import izip, chain
    from concurrent import futures
    from xbmctorrent import tmdb
    from xbmctorrent.utils import url_get_json, terminating, SafeDialogProgress

    plugin.set_content("movies")
    args = dict((k, v[0]) for k, v in plugin.request.args.items())

    current_page = int(args["set"])
    limit = int(args["limit"])

    with closing(SafeDialogProgress(delay_close=0)) as dialog:
        dialog.create(plugin.name)
        dialog.update(percent=0,
                      line1="Fetching movie information...",
                      line2="",
                      line3="")

        try:
            search_result = url_get_json("%s/api/list.json" % BASE_URL,
                                         params=args,
                                         headers=HEADERS)
        except:
            plugin.notify("Unable to connect to %s." % BASE_URL)
            raise
        movies = search_result.get("MovieList") or []

        if not movies:
            return

        state = {"done": 0}

        def on_movie(future):
            data = future.result()
            state["done"] += 1
            dialog.update(
                percent=int(state["done"] * 100.0 / len(movies)),
                line2=data.get("title") or data.get("MovieTitleClean") or "",
            )

        with futures.ThreadPoolExecutor(max_workers=2) as pool_tmdb:
            tmdb_list = [
                pool_tmdb.submit(tmdb.get, movie["ImdbCode"])
                for movie in movies
            ]
            [future.add_done_callback(on_movie) for future in tmdb_list]
            while not all(job.done() for job in tmdb_list):
                if dialog.iscanceled():
                    return
                xbmc.sleep(100)

        tmdb_list = map(lambda job: job.result(), tmdb_list)
        for movie, tmdb_meta in izip(movies, tmdb_list):
            if tmdb_meta:
                magnet_link = urllib.quote_plus(
                    movie["TorrentMagnetUrl"].encode("utf-8"))
                item = tmdb.get_list_item(tmdb_meta)
                if args.get("quality") == "all" and movie["Quality"] != "720p":
                    item["label"] = "%s (%s)" % (item["label"],
                                                 movie["Quality"])
                item.update({
                    "path":
                    "plugin://plugin.video.pulsar/play?uri=" + magnet_link,
                    # "path": plugin.url_for("play", uri=movie["TorrentMagnetUrl"]),
                    "is_playable": True,
                })
                item.setdefault("info", {}).update({
                    "count":
                    movie["MovieID"],
                    "genre":
                    "%s (%s S:%s P:%s)" %
                    (item["info"]["genre"], movie["Size"],
                     movie["TorrentSeeds"], movie["TorrentPeers"]),
                    "plot_outline":
                    tmdb_meta["overview"],
                    "video_codec":
                    "h264",
                })
                width = 1920
                height = 1080
                if movie["Quality"] == "720p":
                    width = 1280
                    height = 720
                item.setdefault("stream_info", {}).update({
                    "video": {
                        "codec": "h264",
                        "width": width,
                        "height": height,
                    },
                    "audio": {
                        "codec": "aac",
                    },
                })
                yield item

        if current_page < (int(search_result["MovieCount"]) / limit):
            next_args = args.copy()
            next_args["set"] = int(next_args["set"]) + 1
            yield {
                "label": ">> Next page",
                "path": plugin.url_for(callback, **next_args),
            }
예제 #27
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
예제 #28
0
def firstrun():
    clear_cache()
    plugin.notify("Please review your settings.")
    plugin.set_setting("firstrun", "true")
    plugin.open_settings()
예제 #29
0
def lostfilm_play(showid, season, episode):
    import re
    from contextlib import closing
    from bs4 import BeautifulSoup
    from xbmctorrent.acestream import ace_supported
    from xbmctorrent.utils import SafeDialogProgress, get_quality_from_name

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

        params = {"c": showid, "s": season, "e": episode}

        try:
            search_url = BASE_URL + "v_search.php"
            html = url_get(search_url, params=params)
            # catch 'log in first' then login
            if html.find("log in first") >= 0:
                dialog.update(percent=10, line2="Требуется авторизация. Авторизация...")
                if not plugin.get_setting("lostfilm_login") and not plugin.get_setting("lostfilm_passwd"):
                    plugin.notify("Проверьте настройки авторизации.", delay=15000)
                    return

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

                dialog.update(percent=30, line2="Загрузка.", line3="")
                html = url_get(search_url, params=params)

                if html.find("log in first") >= 0:
                    xbmcgui.Dialog().ok(plugin.name, "Авторизация неудалась2. Проверьте настройки.")
                    return
        except Exception:
            plugin.log.error("Unexpected error: %s" % sys.exc_info()[0])
            xbmcgui.Dialog().ok(plugin.name, "Не удалось получить данные от сервера")
            return

        # catch redirect
        if html.find("location.replace") >= 0:
            replace_url = html[html.find("(\"") + 2:html.find("\");")]
            html = url_get(replace_url)

        dialog.update(percent=50, line2="Обработка данных.")
        soup = BeautifulSoup(html, "html5lib")
        divs = soup.find_all("div", class_=re.compile("main"))

        releases = [d.find("a") for d in divs]
        quality = plugin.get_setting("lostfilm_qlt", int) or 0

        if quality <= 0 or quality > len(releases):
            select_items = []
            for release in releases:
                lines = release.text.split("\n")
                select_items.append(lines[-1])

            select = xbmcgui.Dialog().select("Выберите желаемое качество", select_items)
        else:
            select = quality - 1

        if select >= 0:
            selected = releases[select]
            torrent_url = selected["href"]

            if (("-" not in episode and int(episode) == 999) or ("." in season and "-" in episode)):
                if "." in season:
                    season = season[:season.find(u".")]

                plugin.add_sort_method("label")

                show_info = _lostfilm_get_db_info_by_id(showid)
                _lostfilm_close_dbase()

                try:
                    from bencode import bdecode
                    torrent_data = url_get(torrent_url)
                    metadata = bdecode(torrent_data)
                except Exception:
                    plugin.log.error("Cannot get data from remote server")
                    xbmcgui.Dialog().ok(plugin.name, "Не удалось получить данные от сервера")
                    return

                e = re.compile("(e[\d]+)?e([\d]+)\.", re.I | re.S | re.U)
                for index, item in enumerate(metadata["info"]["files"]):
                    file_name = " / ".join(item["path"])
                    r = e.search(file_name)
                    if r:
                        if r.group(1):
                            episode = r.group(1)[1:]
                        else:
                            episode = r.group(2)
                    else:
                        episode = u""

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

                    yield _lostfilm_updateitem_from_info({
                        "label": file_name,
                        "path": path,
                        "is_playable": True,
                        "info": {
                            "title": file_name,
                            "season": season,
                            "episode": episode
                        },
                        "stream_info": get_quality_from_name(file_name)
                    }, show_info)
            else:
                if plugin.get_setting("torrent_engine", int) == 1 and ace_supported():
                    path = plugin.url_for("torrent_play", url=torrent_url, index=0, name="LostFilm.Tv")
                else:
                    path = plugin.url_for("play", uri=torrent_url)
                plugin.redirect(path)
예제 #30
0
파일: cmd.py 프로젝트: vizzah/xbmctorrent
def firstrun():
    plugin.notify("Please review your settings.")
    plugin.open_settings()
예제 #31
0
def lostfilm_play(showid, season, episode):
    import re, xbmcgui
    from urlparse import urljoin
    from contextlib import closing
    from bs4 import BeautifulSoup
    from xbmctorrent.acestream import ace_supported
    from xbmctorrent.magnet import generate_magnet
    from xbmctorrent.utils import SafeDialogProgress, get_quality_from_name

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

        params = { "c" : showid, "s" : season, "e" : episode }

        try:
            html = url_get(urljoin(BASE_URL, "nrdr.php"), params=params)
            # catch 'log in first' then login
            if html.find("log in first") >= 0:
                dialog.update(percent=10, line2="Требуется авторизация. Авторизация...")
                if not plugin.get_setting("lostfilm_login") and not plugin.get_setting("lostfilm_passwd"):
                    plugin.notify("Проверьте настройки авторизации.", delay=15000)
                    return 

                _lostfilm_login()

            dialog.update(percent=30, line2="Загрузка.", line3="")
            html = url_get(urljoin(BASE_URL, "nrdr.php"), params=params)

            if html.find("log in first") >= 0:
                xbmcgui.Dialog().ok(plugin.name, "Авторизация неудалась. Проверьте настройки.")
                return

        except:
            plugin.log.error("Unexpected error: %s" % sys.exc_info()[0])
            xbmcgui.Dialog().ok(plugin.name, "Не удалось получить данные от сервера")
            return

        dialog.update(percent=50, line2="Обработка данных.")
        soup = BeautifulSoup(html, "html5lib", from_encoding="windows-1251")

        releases = soup.findAll("a", href=re.compile("tracktor.in"), style=re.compile("bold"))

        select_items = []
        for release in releases: 
            span = release.find_next("span")
            select_items.append(span.contents[0])

        select = xbmcgui.Dialog().select("Выберите желаемое качество", select_items)

        if select >= 0:
            selected = releases[select]
            torrent_url = selected["href"]

            if ((not "-" in episode and int(episode) == 99) or ("." in season and "-" in episode)) and ace_supported():
                if "." in season:
                    season = season[:season.find(u".")]

                show_info = _lostfilm_get_db_info(showid)
                plugin.add_sort_method("label")

                try:
                    from bencode import bencode, bdecode
                    torrent_data = url_get(torrent_url, headers=HEADERS)
                    metadata = bdecode(torrent_data)
                except:
                    plugin.log.error("Cannot get data from remote server")
                    xbmcgui.Dialog().ok(plugin.name, "Не удалось получить данные от сервера")
                    return

                e = re.compile("(e[\d]+)?e([\d]+)\.", re.I|re.S|re.U)
                for index, item in enumerate(metadata["info"]["files"]):
                    file_name = " / ".join(item["path"])
                    print file_name
                    r = e.search(file_name)
                    if r: 
                        if r.group(1):
                            episode = r.group(1)[1:]
                        else:
                            episode = r.group(2)
                    else: 
                        episode = u""
                    yield _lostfilm_updateitem_from_info({
                        "label"       : file_name,
                        "path"        : plugin.url_for("torrent_play", url=torrent_url, index=index, name=file_name),
                        "is_playable" : True,
                        "info"        : {
                            "title"   : file_name,
                            "season"  : season,
                            "episode" : episode
                        },
                        "stream_info" : get_quality_from_name(file_name)
                    }, show_info)
                _lostfilm_close_dbase()
            else:
                plugin.redirect(plugin.url_for("play", uri=torrent_url))