Example #1
0
def get(imdb_id):
    from xbmctorrent.caching import shelf
    with shelf("com.imdb.%s" % imdb_id) as movie:
        if not movie:
            try:
                import urllib2
                from xbmctorrent.utils import url_get_json
                movie.update(url_get_json("%s/movie/%s" % (BASE_URL, imdb_id), params={"api_key": API_KEY,"language": LANG, "append_to_response": "credits"}, headers=HEADERS, with_immunicity=False) or {})
                overview = movie.get('overview')
                if overview == None: movie.update(url_get_json("%s/movie/%s" % (BASE_URL, imdb_id), params={"api_key": API_KEY,"language": "en", "append_to_response": "credits"}, headers=HEADERS, with_immunicity=False) or {})		
                else: pass				
            except urllib2.HTTPError:
                pass
        return dict(movie)
Example #2
0
    def loop(self):
        from xbmctorrent.utils import SafeDialogProgress

        has_resolved = False

        plugin.log.info("Starting torrent2http...")
        with closing(torrent2http.start(**self.torrent2http_options)) as t2h_instance:
            t2h = lambda cmd: url_get_json("http://%s/%s" % (t2h_instance.bind_address, cmd), with_immunicity=False)

            if not self._wait_t2h_startup(t2h):
                return

            plugin.log.info("Opening download dialog...")
            with closing(SafeDialogProgress(delay_create=0)) as dialog:
                dialog.create(plugin.name)

                plugin.log.info("Waiting for file resolution...")
                while not has_resolved:
                    if xbmc.abortRequested or dialog.iscanceled():
                        return

                    status = t2h("status")
                    self.display_name = status["name"]

                    if status["state"] < 3:
                        dialog.update(0, *self._get_status_lines(status))
                    if status["state"] >= 3 and not has_resolved: # Downloading?
                        files = t2h("ls")["files"]
                        biggest_file = sorted(files, key=lambda x: x["size"])[-1]
                        biggest_file["name"] = biggest_file["name"].encode("utf-8")
                        dialog.update(int(biggest_file["buffer"] * 100.0), *self._get_status_lines(status))

                        if biggest_file["buffer"] >= 1.0:
                            plugin.log.info("Resolving to http://%s/files/%s" % (t2h_instance.bind_address, biggest_file["name"]))
                            has_resolved = True
                            item = {
                                "path": "http://%s/files/%s" % (t2h_instance.bind_address, urllib.quote(biggest_file["name"])),
                            }
                            if not xbmc.getInfoLabel("ListItem.Title"):
                                item["label"] = self.display_name
                            plugin.set_resolved_url(item)
                            break

                    xbmc.sleep(TORRENT2HTTP_POLL)

            # We are now playing
            plugin.log.info("Now playing torrent...")
            last_playing_event = 0
            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)):
                    while not xbmc.abortRequested and self.isPlaying():
                        overlay.text = "\n".join(self._get_status_lines(t2h("status")))
                        now = time.time()
                        if (now - last_playing_event) > PLAYING_EVENT_INTERVAL:
                            track_event("video", "playing", self.display_name)
                            last_playing_event = now
                        xbmc.sleep(TORRENT2HTTP_POLL)

        plugin.log.info("Closing Torrent player.")
Example #3
0
def tmdb_config():
    from xbmctorrent.utils import url_get_json

    return url_get_json("%s/configuration" % BASE_URL,
                        params={"api_key": API_KEY},
                        headers=HEADERS,
                        with_immunicity=False)
Example #4
0
    def loop(self):
        from xbmctorrent.utils import SafeDialogProgress

        has_resolved = False

        plugin.log.info("Starting torrent2http...")
        with closing(torrent2http.start(**self.torrent2http_options)) as t2h_instance:
            t2h = lambda cmd: url_get_json("http://%s/%s" % (t2h_instance.bind_address, cmd), with_immunicity=False)

            if not self._wait_t2h_startup(t2h):
                return

            plugin.log.info("Opening download dialog...")
            with closing(SafeDialogProgress(delay_create=0)) as dialog:
                dialog.create(plugin.name)

                plugin.log.info("Waiting for file resolution...")
                while not has_resolved:
                    if xbmc.abortRequested or dialog.iscanceled():
                        return

                    status = t2h("status")
                    self.display_name = status["name"]

                    if status["state"] < 3:
                        dialog.update(0, *self._get_status_lines(status))
                    if status["state"] >= 3 and not has_resolved: # Downloading?
                        files = t2h("ls")["files"]
                        biggest_file = sorted(files, key=lambda x: x["size"])[-1]
                        biggest_file["name"] = biggest_file["name"].encode("utf-8")
                        dialog.update(int(biggest_file["buffer"] * 100.0), *self._get_status_lines(status))

                        if biggest_file["buffer"] >= 1.0:
                            plugin.log.info("Resolving to http://%s/files/%s" % (t2h_instance.bind_address, biggest_file["name"]))
                            has_resolved = True
                            item = {
                                "path": "http://%s/files/%s" % (t2h_instance.bind_address, urllib.quote(biggest_file["name"])),
                            }
                            if not xbmc.getInfoLabel("ListItem.Title"):
                                item["label"] = self.display_name
                            plugin.set_resolved_url(item)
                            break

                    xbmc.sleep(TORRENT2HTTP_POLL)

            # We are now playing
            plugin.log.info("Now playing torrent...")
            last_playing_event = 0
            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)):
                    while not xbmc.abortRequested and self.isPlaying():
                        overlay.text = "\n".join(self._get_status_lines(t2h("status")))
                        now = time.time()
                        if (now - last_playing_event) > PLAYING_EVENT_INTERVAL:
                            track_event("video", "playing", self.display_name)
                            last_playing_event = now
                        xbmc.sleep(TORRENT2HTTP_POLL)

        plugin.log.info("Closing Torrent player.")
Example #5
0
def search(query, **kwargs):
    from xbmctorrent.utils import url_get_json

    kwargs["query"] = query
    return url_get_json("%s/search/movie" % BASE_URL,
                        params=kwargs,
                        headers=HEADERS,
                        with_immunicity=False)
Example #6
0
def get(imdb_id):
    import urllib2
    from xbmctorrent.utils import url_get_json

    try:
        return url_get_json("%s/movie/%s" % (BASE_URL, imdb_id), params={"api_key": API_KEY}, headers=HEADERS) or None
    except urllib2.HTTPError:
        import xbmc
        xbmc.log("COUCOUUUUUUUU")
        return None
Example #7
0
File: tmdb.py Project: roeiba/xbmc
def get(imdb_id):
    from xbmctorrent.caching import shelf
    with shelf("com.imdb.%s" % imdb_id) as movie:
        if not movie:
            try:
                import urllib2
                from xbmctorrent.utils import url_get_json
                movie.update(url_get_json("%s/movie/%s" % (BASE_URL, imdb_id), params={"api_key": API_KEY, "append_to_response": "credits"}, headers=HEADERS, with_immunicity=False) or {})
            except urllib2.HTTPError:
                pass
        return dict(movie)
Example #8
0
def get(imdb_id):
    from xbmctorrent.caching import shelf
    with shelf("com.imdb.%s" % imdb_id) as movie:
        if not movie:
            try:
                import urllib2
                from xbmctorrent.utils import url_get_json
                movie.update(url_get_json("%s/movie/%s" % (BASE_URL, imdb_id), params={"api_key": API_KEY}, headers=HEADERS) or {})
            except urllib2.HTTPError:
                pass
        return dict(movie)
Example #9
0
def get(imdb_id):
    from xbmctorrent.caching import shelf
    with shelf("com.imdb.%s" % imdb_id) as movie:
        if not movie:
            try:
                import urllib2
                from xbmctorrent.utils import url_get_json
                movie.update(url_get_json("%s/movie/%s" % (BASE_URL, imdb_id), params={"api_key": API_KEY}, headers=HEADERS, with_immunicity=False) or {})
            except urllib2.HTTPError:
                pass
        return dict(movie)
Example #10
0
    def loop(self):
        has_resolved = False

        plugin.log.info("Starting torrent2http...")
        with closing(torrent2http.start(**self.torrent2http_options)) as t2h_instance:
            t2h = lambda cmd: url_get_json("http://%s/%s" % (t2h_instance.bind_address, cmd))

            if not self._wait_t2h_startup(t2h):
                return

            plugin.log.info("Opening download dialog...")
            with closing(SafeDialogProgress()) as dialog:
                dialog.create(plugin.name)

                plugin.log.info("Waiting for file resolution...")
                while not has_resolved:
                    if xbmc.abortRequested or dialog.iscanceled():
                        return

                    status = t2h("status")

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

                    if status["state"] >= 3 and not has_resolved: # Downloading?
                        files = t2h("ls")["files"]
                        biggest_file = sorted(files, key=lambda x: x["size"])[-1]
                        percent_complete = float(biggest_file["complete_pieces"]) / float(biggest_file["total_pieces"]) * 100.0

                        if percent_complete >= 0.5:
                            plugin.log.info("Resolving to http://%s/files/%s" % (t2h_instance.bind_address, biggest_file["name"]))
                            has_resolved = True
                            url_name = "/".join(map(urllib.quote, biggest_file["name"].split("/")))
                            plugin.set_resolved_url({
                                "label": self.magnet_display_name,
                                "path": "http://%s/files/%s" % (t2h_instance.bind_address, url_name),
                                "is_playable": True,
                            })
                            break

                    xbmc.sleep(TORRENT2HTTP_POLL)

            # 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)):
                    while not xbmc.abortRequested and self.isPlaying():
                        overlay.text = "\n".join(self._get_status_lines(t2h("status")))
                        xbmc.sleep(TORRENT2HTTP_POLL)

        plugin.log.info("Closing Torrent player.")
Example #11
0
    def _movie(self, imdb_id):
        import urllib2
        from xbmctorrent.utils import first

        meta = url_get_json("%s/movie/%s" % (self.base_url, imdb_id), params=self.params, headers=self.headers, with_immunicity=False) or {}

        if not meta:
            return False, None

        def img(key, size="original", default=""):
            return meta.get(key) and self._image(meta[key], size=size) or default
        def m(key, default=""):
            return meta.get(key) or default
        def m_crew(job):
          return first([crew["name"] for crew in (m("credits", default={}).get("crew") or []) if crew["job"] == job])
        def get_studio():
          return (first(sorted(m("production_companies") or [], key=lambda x: x["id"])) or {}).get("name") or ""

        res = {
            "icon": img("poster_path", size="w500"),
            "thumbnail": img("poster_path", size="w500"),
            "info": {
                "count": m("id"),
                "title": m("title"),
                "originaltitle" : m("original_title"),
                "genre": meta.get("genres") and ", ".join([genre["name"] for genre in meta["genres"]]) or "",
                "plot": m("overview"),
                "plot_outline": m("overview"),
                "tagline": m("tagline"),
                "rating": m("vote_average"),
                "duration": m("runtime"),
                "code": m("imdb_id"),
                "cast": [cast["name"] for cast in (m("credits", default={}).get("cast") or [])],
                "director": m_crew("Director"),
                "writer": m_crew("Writer") or m_crew("Novel") or m_crew("Screenplay"),
                "studio": get_studio(),
                "year": meta.get("release_date") and meta["release_date"].split("-")[0] or 0,
            },
            "properties": {
                "fanart_image": img("backdrop_path"),
            },
        }

        timeout = True

        # если фильм свежий, то кладем в кэш НЕ на долго (могут быть обновления на сайте)
        if 'year' not in res['info'] or int(res['info']['year']) >= time.gmtime(time.time()).tm_year:
            timeout = 7*24*60*60 #week
        
        return timeout, res
Example #12
0
    def _search(self, search, year = None):
        params = self.params
        if not isinstance(search, list):
            search = [search]

        if year:
            params["year"] = year

        results = None
        for name in search:
            params["query"] = name.encode("utf-8")
            result = url_get_json("%s/search/movie" % self.base_url, params=params, headers=self.headers, with_immunicity=False)
            if not result:
                continue
            results = result.get("results")
            if results:
                break

        if not results:
            return None

        return  results[0].get("id")
Example #13
0
def yify_get(yify_id):
    from xbmctorrent.utils import url_get_json

    return url_get_json("%s/api/movie.json" % BASE_URL, params={"id": yify_id}, headers=HEADERS)
Example #14
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),
            }
Example #15
0
    def loop(self):
        from xbmctorrent.utils import SafeDialogProgress

        has_resolved = False

        plugin.log.info("Starting torrent2http...")
        with closing(torrent2http.start(**self.torrent2http_options)) as t2h_instance:
            t2h = lambda cmd: url_get_json("http://%s/%s" % (t2h_instance.bind_address, cmd), with_immunicity=False)

            # Get currently selected item
            current_item = get_current_list_item()
            if plugin.id not in xbmc.getInfoLabel("ListItem.Path"):
                current_item = {}

            if not self._wait_t2h_startup(t2h):
                return

            plugin.log.info("Opening download dialog...")
            with closing(SafeDialogProgress(delay_create=0)) as dialog:
                dialog.create(plugin.name)

                plugin.log.info("Waiting for file resolution...")
                while not has_resolved:
                    if xbmc.abortRequested or dialog.iscanceled():
                        return

                    status = t2h("status")
                    self.display_name = status["name"]

                    if status["state"] < 3:
                        dialog.update(int(status["progress"] * 100), *self._get_status_lines(status))

                    if status["state"] >= 3 and not has_resolved:  # Downloading?
                        files = t2h("ls")["file"]  # files contains only one file which is downloading

                        # plugin.log.debug(repr(files))
                        # sometimes files is empty
                        if files is None or len(files) == 0:
                            xbmc.sleep(TORRENT2HTTP_POLL)
                            continue

                        dialog.update(int(files[0]["buffer"] * 100.0), *self._get_status_lines(status))

                        if files[0]["buffer"] >= 1.0:
                            plugin.log.info("Resolving to %s" % files[0]["url"])
                            has_resolved = True
                            if not current_item.get("info") or not current_item["info"].get("title"):
                                current_item["label"] = self.display_name
                            current_item["path"] = files[0]["url"]
                            plugin.set_resolved_url(current_item)
                            break

                    xbmc.sleep(TORRENT2HTTP_POLL)

            # 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)):
                    while not xbmc.abortRequested and self.isPlaying():
                        overlay.text = "\n".join(self._get_status_lines(t2h("status")))
                        xbmc.sleep(TORRENT2HTTP_POLL)

        plugin.log.info("Closing Torrent player.")
Example #16
0
def search(query, **kwargs):
    from xbmctorrent.utils import url_get_json

    kwargs["query"] = query
    return url_get_json("%s/search/movie" % BASE_URL, params=kwargs, headers=HEADERS, with_immunicity=False)
Example #17
0
def yify_show_data(callback):
    import xbmc
    import xbmcgui
    from contextlib import nested, closing
    from itertools import izip, chain
    from multiprocessing.pool import ThreadPool
    from xbmctorrent import tmdb
    from xbmctorrent.utils import url_get_json, terminating

    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(xbmcgui.DialogProgress()) as dialog:
        dialog.create(plugin.name)
        dialog.update(percent=0, line1="Fetching movie information...", line2="", line3="")

        search_result = url_get_json("%s/api/list.json" % BASE_URL, params=args, headers=HEADERS)
        movies = search_result["MovieList"]

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

        with nested(terminating(ThreadPool(2)), terminating(ThreadPool(2))) as (pool_yify, pool_tmdb):
            yify_list = [pool_yify.apply_async(yify_get, [movie["MovieID"]], callback=on_movie) for movie in movies]
            tmdb_list = [pool_tmdb.apply_async(tmdb.get, [movie["ImdbCode"]], callback=on_movie) for movie in movies]
            while not all(job.ready() for job in chain(yify_list, tmdb_list)):
                if dialog.iscanceled():
                    dialog.close()
                    return
                xbmc.sleep(50)

        yify_list = map(lambda job: job.get(), yify_list)
        tmdb_list = map(lambda job: job.get(), tmdb_list)
        for movie, tmdb_meta in izip(yify_list, 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", magnet=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"]),
                    "trailer": YOUTUBE_ACTION % movie["YoutubeTrailerID"],
                    "plot_outline": movie["ShortDescription"],
                    "video_codec": "h264",
                    "mpaa": movie["AgeRating"],
                })
                width, height = map(int, movie["Resolution"].split("*"))
                item.setdefault("stream_info", {}).update({
                    "video": {
                        "codec": "h264",
                        "width": width,
                        "height": height,
                        "aspect": float(width) / float(height),
                    },
                    "audio": {
                        "codec": "aac",
                        "language": movie["Language"],
                    },
                })
                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),
            }
Example #18
0
def tmdb_config():
    from xbmctorrent.utils import url_get_json
    return url_get_json("%s/configuration" % BASE_URL, params={"api_key": API_KEY}, headers=HEADERS, with_immunicity=False)
Example #19
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),
            }
Example #20
0
 def _config(self):
     timeout = 24*60*60 # one day
     return timeout, url_get_json("%s/configuration" % self.base_url, params={"api_key": self.api_key}, headers=self.headers, with_immunicity=False)
Example #21
0
    def loop(self):
        from xbmctorrent.utils import SafeDialogProgress

        has_resolved = False

        plugin.log.info("Starting torrent2http...")
        with closing(torrent2http.start(
                **self.torrent2http_options)) as t2h_instance:
            t2h = lambda cmd: url_get_json("http://%s/%s" %
                                           (t2h_instance.bind_address, cmd))

            track_event("video", "download", self.magnet_display_name)

            if not self._wait_t2h_startup(t2h):
                return

            plugin.log.info("Opening download dialog...")
            with closing(SafeDialogProgress(delay_create=0)) as dialog:
                dialog.create(plugin.name)

                plugin.log.info("Waiting for file resolution...")
                while not has_resolved:
                    if xbmc.abortRequested or dialog.iscanceled():
                        return

                    status = t2h("status")

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

                    if status[
                            "state"] >= 3 and not has_resolved:  # Downloading?
                        files = t2h("ls")["files"]
                        biggest_file = sorted(files,
                                              key=lambda x: x["size"])[-1]
                        percent_complete = float(
                            biggest_file["complete_pieces"]) / float(
                                biggest_file["total_pieces"]) * 100.0

                        if percent_complete >= 0.5:
                            plugin.log.info("Resolving to http://%s/files/%s" %
                                            (t2h_instance.bind_address,
                                             biggest_file["name"]))
                            has_resolved = True
                            url_name = "/".join(
                                map(urllib.quote,
                                    biggest_file["name"].split("/")))
                            plugin.set_resolved_url({
                                "label":
                                self.magnet_display_name,
                                "label2":
                                self.magnet_display_name,
                                "path":
                                "http://%s/files/%s" %
                                (t2h_instance.bind_address, url_name),
                                "is_playable":
                                True,
                            })
                            break

                    xbmc.sleep(TORRENT2HTTP_POLL)

            # We are now playing
            plugin.log.info("Now playing torrent...")
            last_playing_event = 0
            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)):
                    while not xbmc.abortRequested and self.isPlaying():
                        overlay.text = "\n".join(
                            self._get_status_lines(t2h("status")))
                        now = time.time()
                        if (now - last_playing_event) > PLAYING_EVENT_INTERVAL:
                            track_event("video", "playing",
                                        self.magnet_display_name)
                            last_playing_event = now
                        xbmc.sleep(TORRENT2HTTP_POLL)

        plugin.log.info("Closing Torrent player.")