def library_add(content_type):
    import os
    import xbmc
    import xbmcgui
    from xbmctorrentV2.magnet import ensure_magnet, display_name
    from xbmctorrentV2.utils import get_show_info_from_name
    from urllib import quote_plus, unquote

    play_url = "plugin://plugin.video.xbmctorrentV2Beta/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
def clear_cache():
    import os
    import glob
    from xbmctorrentV2.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.")
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"]),
        }
    def init(self, uri, subtitles):
        self.display_name = ""
        self.torrent2http_options = {
            "uri": uri,
            "dlpath": xbmc.validatePath(xbmc.translatePath(plugin.get_setting("dlpath"))) or ".",
            "dlrate": plugin.get_setting("max_download_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 xbmctorrentV2.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 = []
        self.subtitles = subtitles
        return self
def firstrun():
    clear_cache()
    plugin.notify("Please review your settings.")
    plugin.open_settings()
def yify_show_data(callback):
    import xbmc
    import xbmcgui
    from contextlib import nested, closing
    from itertools import izip, chain
    from concurrent import futures
    from xbmctorrentV2 import tmdb
    from xbmctorrentV2.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),
            }