コード例 #1
0
ファイル: rutor.py プロジェクト: afedchin/xbmctorrent
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)
コード例 #2
0
ファイル: rutracker.py プロジェクト: afedchin/xbmctorrent
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)
コード例 #3
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
コード例 #4
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
コード例 #5
0
ファイル: lostfilm.py プロジェクト: afedchin/xbmctorrent
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)
コード例 #6
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
コード例 #7
0
def lostfilm_index(page = ""):

    from bs4 import BeautifulSoup
    from urlparse import urljoin
    from contextlib import closing
    from xbmctorrent.utils import SafeDialogProgress
    from xbmctorrent.acestream import ace_supported

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

        try:
            html_data = url_get(urljoin(BASE_URL, "browse.php"), params={"o":page*15}, headers=HEADERS)
            soup = BeautifulSoup(html_data, "html5lib", from_encoding="windows-1251")
            div_body = soup.select("div.content_body")
            episodes = div_body[0].findAll("span", class_="torrent_title")
        except:
            plugin.log.error("Unexpected error: %s" % sys.exc_info()[0])
            xbmcgui.Dialog().ok(plugin.name, "Не удалось получить данные от сервера.")
            return

        yield {
            "label": "[COLOR FF00FF00][Полный список сериалов][/COLOR]",
            "path": plugin.url_for("lostfilm_all"),
        }

        done = 0
        for episode in episodes:
            tvshow_name = episode.find_previous_sibling("a").img["title"] # needs if not found in db
            a_download = episode.find_next("a", class_="a_download")["onclick"]
            tvshowid, season, episode_num = a_download[a_download.rfind("(")+2:a_download.rfind(")")-1].split("','")

            if dialog.iscanceled():
                return

            item = _lostfilm_updateitem_from_db({
                "label" : "[COLOR FFFFFFCC][%s.%s][/COLOR] [COLOR FFFFFFFF][B]%s[/B][/COLOR]: %s" % (season, episode_num, tvshow_name, episode.text),
                "path"  : plugin.url_for("lostfilm_play", showid=tvshowid, season=season, episode=episode_num),
                "is_playable" : True,
                "info" : {
                    "title"   : episode.text,
                    "season"  : season,
                    "episode" : episode_num
                }
            }, tvshowid)

            if not "-" in episode_num and int(episode_num) == 99:
                item.update({
                    "label" : "[COLOR FFFFFFCC][%s.xx][/COLOR] [COLOR FFFFFFFF][B]%s[/B][/COLOR]: %s" % (season, tvshow_name, episode.text),
                    "is_playable" : not ace_supported(),
                    "info" : {
                        "title"   : episode.text,
                        "season"  : season,
                        "episode" : "all"
                    }
                })

            done += 1
            dialog.update(
                percent = int(done * 100.0 / len(episodes)),
                line2 = item.get("info", {}).get("tvshowtitle", "") or item.get("info", {}).get("title", "") or item["label"],
                line3 = ""
            )

            yield item;

        if len(episodes) >= 15:
            yield {
                "label": "[COLOR FF00FF00][Далее >][/COLOR]",
                "path": plugin.url_for("lostfilm_index", page=page + 1),
            }

        _lostfilm_close_dbase()
コード例 #8
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))
コード例 #9
0
def lostfilm_tvshow(showid, season):
    from bs4 import BeautifulSoup
    from urlparse import urljoin
    from contextlib import closing
    from xbmctorrent.utils import SafeDialogProgress
    from xbmctorrent.acestream import ace_supported

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

        try:
            html_data = url_get(urljoin(BASE_URL, "browse.php"), params={"cat" : showid}, headers=HEADERS)
            soup = BeautifulSoup(html_data, "html5lib", from_encoding="windows-1251")
            div_mid = soup.select("div.mid")
            episodes = div_mid[0].findAll("td", class_="t_episode_title")
        except:
            import xbmcgui
            plugin.log.error("Unexpected error: %s" % sys.exc_info()[0])
            xbmcgui.Dialog().ok(plugin.name, "Не удалось получить данные от сервера")
            return

        show_info = _lostfilm_get_db_info(showid)
        showid = int(showid)
        season = int(season)

        done = 0
        for episode in episodes:
            script = episode["onclick"]
            tvshowid, season_num, episode_num = script[script.rfind("(")+2:script.rfind(")")-1].split("','")

            if season > 0 and season != int(season_num):
                continue

            is_full_season = (not "-" in episode_num and int(episode_num) == 99) or ("." in season_num and "-" in episode_num)
            nobr = episode.findAll("nobr")[0]
            if is_full_season:
                episode_name = nobr.contents[0].text
                label = "[COLOR FFFFFFCC][%s.xx][/COLOR] [COLOR FF00FF00][B]%s[/B][/COLOR]" % (season_num, episode_name)
            else:
                episode_name = "%s %s" % (nobr.contents[0].text, _safe_list_get(nobr.contents, 2, ""))
                label = "[COLOR FFFFFFCC][%s.%s][/COLOR] [COLOR FFFFFFFF][B]%s[/B][/COLOR] %s" % (
                    season_num, episode_num, nobr.contents[0].text, _safe_list_get(nobr.contents, 2, ""))

            if dialog.iscanceled():
                return

            item = _lostfilm_updateitem_from_info({
                "label" : label,
                "path"  : plugin.url_for("lostfilm_play", showid=tvshowid, season=season_num, episode=episode_num),
                "is_playable" : True,
                "info"  : {
                    "title"   : episode_name,
                    "season"  : season_num,
                    "episode" : episode_num
                }
            }, show_info)

            if is_full_season and ace_supported():
                item.update({ "is_playable" : False })

            done += 1
            dialog.update(
                percent = int(done * 100.0 / len(episodes)),
                line2 = item.get("info", {}).get("tvshowtitle", "") or item.get("info", {}).get("title", "") or item["label"],
                line3 = ""
            )

            yield item;           

        _lostfilm_close_dbase()
コード例 #10
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