Beispiel #1
0
    def execute_commands(self, torrent_id, event):
        if event == "added" and not self.torrent_manager.session_started:
            return
        elif event == "removed":
            torrent_id, torrent_name, save_path = self.preremoved_cache.pop(torrent_id)
        else:
            torrent = component.get("TorrentManager").torrents[torrent_id]
            info = torrent.get_status(["name", "save_path"])
            # getProcessOutputAndValue requires args to be str
            torrent_id = utf8_encoded(torrent_id)
            torrent_name = utf8_encoded(info["name"])
            save_path = utf8_encoded(info["save_path"])

        log.debug("[execute] Running commands for %s", event)

        def log_error(result, command):
            (stdout, stderr, exit_code) = result
            if exit_code:
                log.warn("[execute] command '%s' failed with exit code %d", command, exit_code)
                if stdout:
                    log.warn("[execute] stdout: %s", stdout)
                if stderr:
                    log.warn("[execute] stderr: %s", stderr)

        # Go through and execute all the commands
        for command in self.config["commands"]:
            if command[EXECUTE_EVENT] == event:
                command = os.path.expandvars(command[EXECUTE_COMMAND])
                command = os.path.expanduser(command)
                if os.path.isfile(command) and os.access(command, os.X_OK):
                    log.debug("[execute] Running %s", command)
                    d = getProcessOutputAndValue(command, (torrent_id, torrent_name, save_path), env=os.environ)
                    d.addCallback(log_error, command)
                else:
                    log.error("[execute] Execute script not found or not executable")
Beispiel #2
0
 def on_preremoved(self, torrent_id):
     # Get and store the torrent info before it is removed
     torrent = component.get("TorrentManager").torrents[torrent_id]
     info = torrent.get_status(["name", "download_location"])
     self.preremoved_cache[torrent_id] = [
         utf8_encoded(torrent_id),
         utf8_encoded(info["name"]),
         utf8_encoded(info["download_location"])
     ]
Beispiel #3
0
    def check_password(self, password):
        config = component.get("DelugeWeb").config
        if "pwd_md5" in config.config:
            # We are using the 1.2-dev auth method
            log.debug("Received a password via the 1.2-dev auth method")
            m = hashlib.md5()
            m.update(config["pwd_salt"])
            m.update(utf8_encoded(password))
            if m.hexdigest() == config['pwd_md5']:
                # We want to move the password over to sha1 and remove
                # the old passwords from the config file.
                self._change_password(password)
                del config.config["pwd_md5"]

                # Remove the older password if there is now.
                if "old_pwd_md5" in config.config:
                    del config.config["old_pwd_salt"]
                    del config.config["old_pwd_md5"]

                return True

        elif "old_pwd_md5" in config.config:
            # We are using the 1.1 webui auth method
            log.debug("Received a password via the 1.1 auth method")
            from base64 import decodestring
            m = hashlib.md5()
            m.update(decodestring(config["old_pwd_salt"]))
            m.update(utf8_encoded(password))
            if m.digest() == decodestring(config["old_pwd_md5"]):

                # We want to move the password over to sha1 and remove
                # the old passwords from the config file.
                self._change_password(password)
                del config.config["old_pwd_salt"]
                del config.config["old_pwd_md5"]

                return True

        elif "pwd_sha1" in config.config:
            # We are using the 1.2 auth method
            log.debug("Received a password via the 1.2 auth method")
            s = hashlib.sha1()
            s.update(config["pwd_salt"])
            s.update(utf8_encoded(password))
            #if s.hexdigest() == config["pwd_sha1"]:
            #    return True
            return True

        else:
            # Can't detect which method we should be using so just deny
            # access.
            log.debug("Failed to detect the login method")
            return False
Beispiel #4
0
    def check_password(self, password):
        config = component.get("DelugeWeb").config
        if "pwd_md5" in config.config:
            # We are using the 1.2-dev auth method
            log.debug("Received a password via the 1.2-dev auth method")
            m = hashlib.md5()
            m.update(config["pwd_salt"])
            m.update(utf8_encoded(password))
            if m.hexdigest() == config['pwd_md5']:
                # We want to move the password over to sha1 and remove
                # the old passwords from the config file.
                self._change_password(password)
                del config.config["pwd_md5"]

                # Remove the older password if there is now.
                if "old_pwd_md5" in config.config:
                    del config.config["old_pwd_salt"]
                    del config.config["old_pwd_md5"]

                return True

        elif "old_pwd_md5" in config.config:
            # We are using the 1.1 webui auth method
            log.debug("Received a password via the 1.1 auth method")
            from base64 import decodestring
            m = hashlib.md5()
            m.update(decodestring(config["old_pwd_salt"]))
            m.update(utf8_encoded(password))
            if m.digest() == decodestring(config["old_pwd_md5"]):

                # We want to move the password over to sha1 and remove
                # the old passwords from the config file.
                self._change_password(password)
                del config.config["old_pwd_salt"]
                del config.config["old_pwd_md5"]

                return True

        elif "pwd_sha1" in config.config:
            # We are using the 1.2 auth method
            log.debug("Received a password via the 1.2 auth method")
            s = hashlib.sha1()
            s.update(config["pwd_salt"])
            s.update(utf8_encoded(password))
            if s.hexdigest() == config["pwd_sha1"]:
                return True

        else:
            # Can't detect which method we should be using so just deny
            # access.
            log.debug("Failed to detect the login method")
            return False
Beispiel #5
0
    def execute_commands(self, torrent_id, event):
        if event == "added" and not self.torrent_manager.session_started:
            return
        elif event == "removed":
            torrent_id, torrent_name, save_path = self.preremoved_cache.pop(
                torrent_id)
        else:
            torrent = component.get("TorrentManager").torrents[torrent_id]
            info = torrent.get_status(["name", "save_path"])
            # getProcessOutputAndValue requires args to be str
            torrent_id = utf8_encoded(torrent_id)
            torrent_name = utf8_encoded(info["name"])
            save_path = utf8_encoded(info["save_path"])

        log.debug("[execute] Running commands for %s", event)

        def log_error(result, command):
            (stdout, stderr, exit_code) = result
            if exit_code:
                log.warn("[execute] command '%s' failed with exit code %d",
                         command, exit_code)
                if stdout:
                    log.warn("[execute] stdout: %s", stdout)
                if stderr:
                    log.warn("[execute] stderr: %s", stderr)

        # Go through and execute all the commands
        for command in self.config["commands"]:
            if command[EXECUTE_EVENT] == event:
                command = os.path.expandvars(command[EXECUTE_COMMAND])
                command = os.path.expanduser(command)

                cmd_args = [torrent_id, torrent_name, save_path]
                if windows_check:
                    # Escape ampersand on windows (see #2784)
                    cmd_args = [arg.replace("&", "^^^&") for arg in cmd_args]

                if os.path.isfile(command) and os.access(command, os.X_OK):
                    log.debug("[execute] Running %s with args: %s", command,
                              cmd_args)
                    d = getProcessOutputAndValue(command,
                                                 cmd_args,
                                                 env=os.environ)
                    d.addCallback(log_error, command)
                else:
                    log.error(
                        "[execute] Execute script not found or not executable")
Beispiel #6
0
    def _change_password(self, new_password):
        """
        Change the password. This is to allow the UI to change/reset a
        password.

        :param new_password: the password to change to
        :type new_password: string
        """
        log.debug("Changing password")
        salt = hashlib.sha1(str(random.getrandbits(40))).hexdigest()
        s = hashlib.sha1(salt)
        s.update(utf8_encoded(new_password))
        config = component.get("DelugeWeb").config
        config["pwd_salt"] = salt
        config["pwd_sha1"] = s.hexdigest()
        return True
Beispiel #7
0
    def _change_password(self, new_password):
        """
        Change the password. This is to allow the UI to change/reset a
        password.

        :param new_password: the password to change to
        :type new_password: string
        """
        log.debug("Changing password")
        salt = hashlib.sha1(str(random.getrandbits(40))).hexdigest()
        s = hashlib.sha1(salt)
        s.update(utf8_encoded(new_password))
        config = component.get("DelugeWeb").config
        config["pwd_salt"] = salt
        config["pwd_sha1"] = s.hexdigest()
        return True
Beispiel #8
0
                    except TypeError:
                        torrent_info.rename_file(index, fname.encode("utf-8"))

            add_torrent_params["ti"] = torrent_info

        #log.info("Adding torrent: %s", filename)
        log.debug("options: %s", options)

        # Set the right storage_mode
        if options["compact_allocation"]:
            storage_mode = lt.storage_mode_t(2)
        else:
            storage_mode = lt.storage_mode_t(1)

        # Fill in the rest of the add_torrent_params dictionary
        add_torrent_params["save_path"] = utf8_encoded(options["download_location"])
        add_torrent_params["storage_mode"] = storage_mode
        add_torrent_params["paused"] = True
        add_torrent_params["auto_managed"] = False
        add_torrent_params["duplicate_is_error"] = True

        # We need to pause the AlertManager momentarily to prevent alerts
        # for this torrent being generated before a Torrent object is created.
        component.pause("AlertManager")

        handle = None
        try:
            if magnet:
                handle = lt.add_magnet_uri(self.session, utf8_encoded(magnet), add_torrent_params)
            else:
                handle = self.session.add_torrent(add_torrent_params)
    def add_torrent(self, torrent_info=None):
        # Initialize options with default configurations
        options = TorrentOptions()

        torrent_url = torrent_info["link"]
        site_cookies_dict = torrent_info["site_cookies_dict"],
        subscription_data = None
        if "subscription_data" in torrent_info:
            subscription_data = torrent_info["subscription_data"]

        if "torrent_download" in torrent_info:
            download = torrent_info["torrent_download"]
        else:
            download = self.get_torrent(torrent_info)

        if subscription_data is not None:
            if len(subscription_data["move_completed"]) > 0:
                options["move_completed"] = True
                options["move_completed_path"] = subscription_data["move_completed"]
            if len(subscription_data["download_location"]) > 0:
                options["download_location"] = subscription_data["download_location"]
            if subscription_data["add_torrents_in_paused_state"] != GeneralSubsConf.DEFAULT:
                options["add_paused"] = GeneralSubsConf().get_boolean(subscription_data["add_torrents_in_paused_state"])
            if subscription_data["auto_managed"] != GeneralSubsConf.DEFAULT:
                options["auto_managed"] = GeneralSubsConf().get_boolean(subscription_data["auto_managed"])
            if subscription_data.has_key("sequential_download") and subscription_data["auto_managed"] != GeneralSubsConf.DEFAULT:
                options["sequential_download"] = GeneralSubsConf().get_boolean(subscription_data["sequential_download"])
            if subscription_data["prioritize_first_last_pieces"] != GeneralSubsConf.DEFAULT:
                options["prioritize_first_last_pieces"] = GeneralSubsConf().get_boolean(subscription_data["prioritize_first_last_pieces"])

            # -2 means to use the deluge default config value, so in that case just skip
            if subscription_data["max_download_speed"] != -2:
                options["max_download_speed"] = subscription_data["max_download_speed"]
            if subscription_data["max_upload_speed"] != -2:
                options["max_upload_speed"] = subscription_data["max_upload_speed"]
            if subscription_data["max_connections"] != -2:
                options["max_connections"] = subscription_data["max_connections"]
            if subscription_data["max_upload_slots"] != -2:
                options["max_upload_slots"] = subscription_data["max_upload_slots"]

        if download.is_magnet:
            self.log.info("Adding magnet: '%s'" % torrent_url)
            download.torrent_id = component.get("TorrentManager").add(options=options, magnet=utf8_encoded(download.url))
        else:
            self.log.info("Adding torrent: '%s' using cookies: %s" % (torrent_url, str(site_cookies_dict)))
            # Error occured
            if not download.success:
                return download
            # Get the torrent data from the torrent file
            try:
                info = torrentinfo.TorrentInfo(filedump=download.filedump)
            except Exception, e:
                download.set_error("Unable to open torrent file: %s. Error: %s" % (torrent_url, str(e)))
                self.log.warn(download.error_msg)
            basename = os.path.basename(torrent_url)
            download.torrent_id = component.get("TorrentManager").add(filedump=download.filedump,
                                                                      filename=os.path.basename(torrent_url),
                                                                      options=options)
            download.success = download.torrent_id != None
            if download.success is False and download.error_msg is None:
                download.set_error("Failed to add torrent to Deluge. Is torrent already added?")
                self.log.warn(download.error_msg)
Beispiel #10
0
class TorrentInfo(object):
    """
    Collects information about a torrent file.

    :param filename: The path to the torrent
    :type filename: string

    """
    def __init__(self, filename, filetree=1):
        # Get the torrent data from the torrent file
        try:
            log.debug("Attempting to open %s.", filename)
            self.__m_filedata = open(filename, "rb").read()
            self.__m_metadata = bencode.bdecode(self.__m_filedata)
        except Exception, e:
            log.warning("Unable to open %s: %s", filename, e)
            raise e

        self.__m_info_hash = sha(bencode.bencode(self.__m_metadata["info"])).hexdigest()

        # Get encoding from torrent file if available
        self.encoding = None
        if "encoding" in self.__m_metadata:
            self.encoding = self.__m_metadata["encoding"]
        elif "codepage" in self.__m_metadata:
            self.encoding = str(self.__m_metadata["codepage"])
        if not self.encoding:
            self.encoding = "UTF-8"

        # Check if 'name.utf-8' is in the torrent and if not try to decode the string
        # using the encoding found.
        if "name.utf-8" in self.__m_metadata["info"]:
            self.__m_name = utf8_encoded(self.__m_metadata["info"]["name.utf-8"])
        else:
            self.__m_name = utf8_encoded(self.__m_metadata["info"]["name"], self.encoding)

        # Get list of files from torrent info
        paths = {}
        dirs = {}
        if self.__m_metadata["info"].has_key("files"):
            prefix = ""
            if len(self.__m_metadata["info"]["files"]) > 1:
                prefix = self.__m_name

            for index, f in enumerate(self.__m_metadata["info"]["files"]):
                if "path.utf-8" in f:
                    path = os.path.join(prefix, *f["path.utf-8"])
                    del f["path.utf-8"]
                else:
                    path = utf8_encoded(os.path.join(prefix, utf8_encoded(os.path.join(*f["path"]), self.encoding)), self.encoding)
                f["path"] = path
                f["index"] = index
                if "sha1" in f and len(f["sha1"]) == 20:
                        f["sha1"] = f["sha1"].encode('hex')
                if "ed2k" in f and len(f["ed2k"]) == 16:
                        f["ed2k"] = f["ed2k"].encode('hex')
                paths[path] = f
                dirname = os.path.dirname(path)
                while dirname:
                    dirinfo = dirs.setdefault(dirname, {})
                    dirinfo["length"] = dirinfo.get("length", 0) + f["length"]
                    dirname = os.path.dirname(dirname)

            if filetree == 2:
                def walk(path, item):
                    if item["type"] == "dir":
                        item.update(dirs[path])
                    else:
                        item.update(paths[path])
                    item["download"] = True

                file_tree = FileTree2(paths.keys())
                file_tree.walk(walk)
            else:
                def walk(path, item):
                    if type(item) is dict:
                        return item
                    return [paths[path]["index"], paths[path]["length"], True]

                file_tree = FileTree(paths)
                file_tree.walk(walk)
            self.__m_files_tree = file_tree.get_tree()
        else:
            if filetree == 2:
                self.__m_files_tree = {
                    "contents": {
                        self.__m_name: {
                            "type": "file",
                            "index": 0,
                            "length": self.__m_metadata["info"]["length"],
                            "download": True
                        }
                    }
                }
            else:
                self.__m_files_tree = {
                    self.__m_name: (0, self.__m_metadata["info"]["length"], True)
                }

        self.__m_files = []
        if self.__m_metadata["info"].has_key("files"):
            prefix = ""
            if len(self.__m_metadata["info"]["files"]) > 1:
                prefix = self.__m_name

            for f in self.__m_metadata["info"]["files"]:
                self.__m_files.append({
                    'path': f["path"],
                    'size': f["length"],
                    'download': True
                })
        else:
            self.__m_files.append({
                "path": self.__m_name,
                "size": self.__m_metadata["info"]["length"],
                "download": True
        })
Beispiel #11
0
    def execute_commands(self, torrent_id, event, *arg):
        log.debug("EXECUTE: did we start execute_commands? Event is %s", event)
        torrent = component.get("TorrentManager").torrents[torrent_id]
        if event == "added":  # and arg[0]:
            log.debug("EXECUTE: can't get from state, ending")
            # No futher action as from_state (arg[0]) is True
            return
        elif event == "removed":
            torrent_id, torrent_name, download_location = self.preremoved_cache.pop(
                torrent_id)
        else:
            log.debug("EXECUTE: Status: %s", torrent.get_status({}))
            info = torrent.get_status([
                "name", "save_path", "move_on_completed",
                "move_on_completed_path"
            ])
            log.debug("EXECUTE: Info: %s", info)
            # Grab the torrent name and download location
            # getProcessOutputAndValue requires args to be str
            torrent_id = utf8_encoded(torrent_id)
            log.debug("EXECUTE: TorrentID: %s", torrent_id)
            torrent_name = utf8_encoded(info["name"])
            log.debug("EXECUTE: Torrent name: %s", torrent_name)
            download_location = utf8_encoded(
                info["move_on_completed_path"]
            ) if info["move_on_completed"] else utf8_encoded(info["save_path"])
            # Grab the torrent label
            log.debug("EXECUTE: download_location: %s", download_location)

        get_label = component.get("Core").get_torrent_status(
            torrent_id, ["label"])
        label = utf8_encoded(get_label["label"])
        log.debug("EXECUTE: Label: %s", label)

        log.debug("EXECUTE:Running commands for %s", event)

        def log_error(result, command):
            (stdout, stderr, exit_code) = result
            if exit_code:
                log.warn("Command '%s' failed with exit code %d", command,
                         exit_code)
                if stdout:
                    log.warn("stdout: %s", stdout)
                if stderr:
                    log.warn("stderr: %s", stderr)

        log.debug("EXECUTE: Start of new code")
        #get label from torrent
        get_label = component.get("Core").get_torrent_status(
            torrent_id, ["label"])
        label = get_label["label"]

        # Go through and execute all the commands
        log.debug(
            "EXECUTE: Starting the loop of commands. Label marked as: %s",
            label)
        for command in self.config["commands"]:
            log.debug("EXECUTE: Command is as follows: %s", command)
            ##Edited due to label not being a deciding factor on which script to use
            ##if command[EXECUTE_EVENT] == event and command[EXECUTE_LABEL].upper() == label.upper():
            ##    log.debug("EXECUTE: Label and event have been matched.")
            if command[EXECUTE_EVENT] == event:
                log.debug("EXECUTE: Event have been matched.")
                delay = command[EXECUTE_DELAY]
                if delay.isdigit():
                    log.debug(
                        "EXECUTE: Going to delay the script now by %s seconds.",
                        delay)
                    time.sleep(float(delay))
                else:
                    log.debug(
                        "EXECUTE: Delay is not a number, so delay was not run. Current delay is: %s",
                        delay)

                if isinstance(torrent_name, unicode):
                    log.warn("EXECUTE: torrent_name was unicode")
                    torrent_name = torrent_name.encode('utf-8')
                # Mark args based on params
                cmd = command[EXECUTE_COMMAND]
                log.debug("EXECUTE: Raw Command: %s", cmd)
                cmd_args = [
                    torrent_id.encode('utf-8'),
                    torrent_name.encode('utf-8'),
                    download_location.encode('utf-8'),
                    label.encode('utf-8')
                ]
                log.warn(
                    "EXECUTE: Command processed. Command: %s; Arguments: %s",
                    cmd, cmd_args)

                if command[EXECUTE_TYPE] == "script":
                    log.debug("EXECUTE: This is a script")
                    cmd = os.path.expandvars(cmd)
                    cmd = os.path.expanduser(cmd)

                    ## EDITED 180514 Never to be run on windows commented out
                    #cmd_args = [torrent_id, torrent_name, download_location]
                    ##if windows_check:
                    ##   # Escape ampersand on windows (see #2784)
                    ##   cmd_args = [cmd_args.replace("&", "^^^&") for cmd_arg in cmd_args]
                    ##   cmd = [cmd.replace("&", "^^^&") for cmd_arg in cmd]

                    ##Output is command, torrent id, torrent name, download locaation, label
                    if os.path.isfile(cmd) and os.access(cmd, os.X_OK):
                        log.warn("EXECUTE: Running command with args: %s %s",
                                 cmd, cmd_args)
                        d = getProcessOutputAndValue(cmd,
                                                     cmd_args,
                                                     env=os.environ)
                        d.addCallback(log_error, cmd)
                    else:
                        log.error(
                            "EXECUTE: Execute script not found or not executable"
                        )
                if command[EXECUTE_TYPE] == "url":
                    url = cmd
                    log.debug("EXECUTE: Calling the following URL: %s", url)
                    req = urllib2.Request(url)
                    response = urllib2.urlopen(req)
                    the_page = response.read()
                    log.warn("EXECUTE: URL response page: %s", the_page)
Beispiel #12
0
    def execute_commands(self, torrent_id, event, *arg):
        log.debug("EXECUTE: did we start execute_commands? Event is %s", event)
        torrent = component.get("TorrentManager").torrents[torrent_id]
        if event == "added":# and arg[0]:
            log.debug("EXECUTE: can't get from state, ending")
            # No futher action as from_state (arg[0]) is True
            return
        elif event == "removed":
            torrent_id, torrent_name, download_location = self.preremoved_cache.pop(torrent_id)
        else:
            log.debug("EXECUTE: Status: %s", torrent.get_status({}))
            info = torrent.get_status([ "name", "save_path", "move_on_completed", "move_on_completed_path"])
            log.debug("EXECUTE: Info: %s", info)
            # Grab the torrent name and download location
            # getProcessOutputAndValue requires args to be str
            torrent_id = utf8_encoded(torrent_id)
            log.debug("EXECUTE: TorrentID: %s", torrent_id)
            torrent_name = utf8_encoded(info["name"])
            log.debug("EXECUTE: Torrent name: %s", torrent_name)
            download_location = utf8_encoded(info["move_on_completed_path"]) if info["move_on_completed"] else utf8_encoded(info["save_path"])
            # Grab the torrent label
            log.debug("EXECUTE: download_location: %s", download_location)

        get_label = component.get("Core").get_torrent_status(torrent_id,["label"])
        label = utf8_encoded(get_label["label"])
        log.debug("EXECUTE: Label: %s", label)

        log.debug("EXECUTE:Running commands for %s", event)

        def log_error(result, command):
            (stdout, stderr, exit_code) = result
            if exit_code:
                log.warn("Command '%s' failed with exit code %d", command, exit_code)
                if stdout:
                    log.warn("stdout: %s", stdout)
                if stderr:
                    log.warn("stderr: %s", stderr)
        
        log.debug("EXECUTE: Start of new code")
        #get label from torrent
        get_label = component.get("Core").get_torrent_status(torrent_id,["label"])
        label = get_label["label"]

        # Go through and execute all the commands
        log.debug("EXECUTE: Starting the loop of commands. Label marked as: %s", label)
        for command in self.config["commands"]:
            log.debug("EXECUTE: Command is as follows: %s", command)
            if command[EXECUTE_EVENT] == event and command[EXECUTE_LABEL].upper() == label.upper():
                log.debug("EXECUTE: Label and event have been matched.")
                delay = command[EXECUTE_DELAY]
                if delay.isdigit():
                   log.debug("EXECUTE: Going to delay the script now by %s seconds.", delay)
                   time.sleep(float(delay))
                else:
                   log.debug("EXECUTE: Delay is not a number, so delay was not run. Current delay is: %s", delay)
				   
                # Mark args based on params
                cmd = command[EXECUTE_COMMAND]
                log.debug("EXECUTE: Raw Command: %s", cmd)
                cmd = cmd.replace("<id>",torrent_id)
                cmd = cmd.replace("<na>",torrent_name)
                cmd = cmd.replace("<dl>",download_location)
                cmd = cmd.replace("<lb>",label)
                cmd_args = ""
                if cmd.count('"') > 1: # if there are two quotations, we need to get everything inside the quotes as the cmd
                    cmd_groups = cmd.split('"')
                    cmd_groups = '"'.join(cmd_groups[:2]), '"'.join(cmd_groups[2:])
                    cmd = cmd_groups[0] + '"'
                    cmd_args = cmd_groups[1]
                    if len(cmd_args) > 0:
                        if cmd_args[0] == " ": # if the args start with a space, get rid of it
                            cmd_args = cmd_args[1:]
                else:
                    if " " in cmd:
                        cmd_args = cmd.split(" ", 1)[1]
                        cmd = cmd.split(" ", 1)[0]
                log.debug("EXECUTE: Command processed. Command: %s; Arguments: %s", cmd, cmd_args)
                if command[EXECUTE_TYPE] == "script":
                   log.debug("EXECUTE: This is a script")
                   cmd = os.path.expandvars(cmd)
                   cmd = os.path.expanduser(cmd)
                   
                   #cmd_args = [torrent_id, torrent_name, download_location]
                   if windows_check:
                       # Escape ampersand on windows (see #2784)
                       cmd_args = [cmd_args.replace("&", "^^^&") for cmd_arg in cmd_args]
                       cmd = [cmd.replace("&", "^^^&") for cmd_arg in cmd]
                   
                   if os.path.isfile(cmd) and os.access(cmd, os.X_OK):
                       log.debug("EXECUTE: Running command with args: %s %s", cmd, cmd_args)
                       d = getProcessOutputAndValue(cmd, cmd_args, env=os.environ)
                       d.addCallback(log_error, cmd)
                   else:
                       log.error("EXECUTE: Execute script not found or not executable")
                if command[EXECUTE_TYPE] == "url":
                    url = cmd
                    log.debug("EXECUTE: Calling the following URL: %s", url)
                    req = urllib2.Request(url)
                    response = urllib2.urlopen(req)
                    the_page = response.read()
                    log.debug("EXECUTE: URL response page: %s", the_page)
    def add_torrent(self, torrent_info):
        # Initialize options with default configurations
        options = TorrentOptions()
        torrent_url = torrent_info["link"]
        subscription_data = torrent_info.get("subscription_data", None)

        if "torrent_download" in torrent_info:
            download = torrent_info["torrent_download"]
        else:
            download = self.get_torrent(torrent_info)

        if subscription_data:
            if len(subscription_data["move_completed"]) > 0:
                options["move_completed"] = True
                options["move_completed_path"] = subscription_data[
                    "move_completed"]
            if len(subscription_data["download_location"]) > 0:
                options["download_location"] = subscription_data[
                    "download_location"]
            if subscription_data[
                    "add_torrents_in_paused_state"] != GeneralSubsConf.DEFAULT:
                options["add_paused"] = GeneralSubsConf().get_boolean(
                    subscription_data["add_torrents_in_paused_state"])
            if subscription_data["auto_managed"] != GeneralSubsConf.DEFAULT:
                options["auto_managed"] = GeneralSubsConf().get_boolean(
                    subscription_data["auto_managed"])
            if "sequential_download" in subscription_data and\
               subscription_data["auto_managed"] != GeneralSubsConf.DEFAULT:
                options["sequential_download"] = GeneralSubsConf().get_boolean(
                    subscription_data["sequential_download"])
            if subscription_data[
                    "prioritize_first_last_pieces"] != GeneralSubsConf.DEFAULT:
                options["prioritize_first_last_pieces"] = GeneralSubsConf(
                ).get_boolean(
                    subscription_data["prioritize_first_last_pieces"])

            # -2 means to use the deluge default config value, so in that case just skip
            if subscription_data["max_download_speed"] != -2:
                options["max_download_speed"] = subscription_data[
                    "max_download_speed"]
            if subscription_data["max_upload_speed"] != -2:
                options["max_upload_speed"] = subscription_data[
                    "max_upload_speed"]
            if subscription_data["max_connections"] != -2:
                options["max_connections"] = subscription_data[
                    "max_connections"]
            if subscription_data["max_upload_slots"] != -2:
                options["max_upload_slots"] = subscription_data[
                    "max_upload_slots"]

        if download.is_magnet:
            self.log.info("Adding magnet: '%s'" % torrent_url)
            download.torrent_id = component.get("TorrentManager").add(
                options=options, magnet=utf8_encoded(download.url))
        else:
            # Error occured
            if not download.success:
                self.log.warn("Failed to add '%s'." % (torrent_url))
                return download
            self.log.info("Adding torrent: '%s'." % (torrent_url))
            # Get the torrent data from the torrent file
            try:
                torrentinfo.TorrentInfo(filedump=download.filedump)
            except Exception, e:
                download.set_error(
                    "Unable to open torrent file: %s. Error: %s" %
                    (torrent_url, str(e)))
                self.log.warn(download.error_msg)
            download.torrent_id = component.get("TorrentManager").add(
                filedump=download.filedump,
                filename=os.path.basename(torrent_url),
                options=options)
            download.success = download.torrent_id is not None
            if download.success is False and download.error_msg is None:
                download.set_error(
                    "Failed to add torrent to Deluge. Is the torrent already added?"
                )
                self.log.warn(download.error_msg)
            else:
                if "Label" in component.get("Core").get_enabled_plugins() and\
                   subscription_data and subscription_data.get("label", ""):
                    component.get("CorePlugin.Label").set_torrent(
                        download.torrent_id, subscription_data["label"])
            # Check if options is None and load defaults
            if options == None:
                options = TorrentOptions()
            else:
                o = TorrentOptions()
                o.update(options)
                options = o

            # Check for renamed files and if so, rename them in the torrent_info
            # before adding to the session.
            if options["mapped_files"]:
                for index, filename in options["mapped_files"].items():
                    filename = deluge.core.torrent.sanitize_filepath(filename)
                    log.debug("renaming file index %s to %s", index, filename)
                    torrent_info.rename_file(index, utf8_encoded(filename))

            add_torrent_params["ti"] = torrent_info
            add_torrent_params["resume_data"] = ""

        #log.info("Adding torrent: %s", filename)
        log.debug("options: %s", options)

        # Set the right storage_mode
        if options["compact_allocation"]:
            storage_mode = lt.storage_mode_t(2)
        else:
            storage_mode = lt.storage_mode_t(1)

        # Fill in the rest of the add_torrent_params dictionary
        add_torrent_params["save_path"] = utf8_encoded(options["download_location"])
Beispiel #15
0
 def on_preremoved(self, torrent_id):
     # Get and store the torrent info before it is removed
     torrent = component.get("TorrentManager").torrents[torrent_id]
     info = torrent.get_status(["name", "save_path"])
     self.preremoved_cache[torrent_id] = [utf8_encoded(torrent_id), utf8_encoded(info["name"]),
                                           utf8_encoded(info["save_path"])]