Exemple #1
0
    def validate_output_format(self, default_format):
        """ Prepare output format for later use.
        """
        output_format = self.options.output_format

        # Use default format if none is given
        if output_format is None:
            output_format = default_format

        # Check if it's a custom output format from configuration
        # (they take precedence over field names, so name them wisely)
        output_format = config.formats.get(output_format, output_format)

        # Expand plain field list to usable form
        if re.match(r"^[,._0-9a-zA-Z]+$", output_format):
            self.plain_output_format = True
            output_format = "%%(%s)s" % ")s\t%(".join(formatting.validate_field_list(output_format, allow_fmt_specs=True))

        # Replace some escape sequences
        output_format = (output_format
            .replace(r"\\", "\\")
            .replace(r"\n", "\n")
            .replace(r"\t", "\t")
            .replace(r"\$", "\0") # the next 3 allow using $() instead of %()
            .replace("$(", "%(")
            .replace("\0", "$")
            .replace(r"\ ", " ") # to prevent stripping in config file
            #.replace(r"\", "\")
        )

        self.options.output_format = formatting.preparse(output_format)
Exemple #2
0
    def validate_output_format(self, default_format):
        """ Prepare output format for later use.
        """
        output_format = self.options.output_format

        # Use default format if none is given
        if output_format is None:
            output_format = default_format

        # Check if it's a custom output format from configuration
        # (they take precedence over field names, so name them wisely)
        output_format = config.formats.get(output_format, output_format)

        # Expand plain field list to usable form
        if re.match(r"^[,._0-9a-zA-Z]+$", output_format):
            self.plain_output_format = True
            output_format = "%%(%s)s" % ")s\t%(".join(
                formatting.validate_field_list(output_format,
                                               allow_fmt_specs=True))

        # Replace some escape sequences
        output_format = (
            output_format.replace(r"\\", "\\").replace(r"\n", "\n").replace(
                r"\t", "\t").replace(
                    r"\$", "\0")  # the next 3 allow using $() instead of %()
            .replace("$(", "%(").replace("\0", "$").replace(
                r"\ ", " ")  # to prevent stripping in config file
            #.replace(r"\", "\")
        )

        self.options.output_format = formatting.preparse(output_format)
Exemple #3
0
    def validate(self):
        """ Validate filter condition (template method).
        """
        from pyrocore.torrent import formatting

        super(PatternFilter, self).validate()
        self._value = self._value.lower()
        self._template = None
        self._is_regex = self._value.startswith('/') and self._value.endswith(
            '/')
        if self._is_regex:
            self._matcher = re.compile(self._value[1:-1]).search
        elif self._value.startswith('{{') or self._value.endswith('}}'):

            def _template_globber(val, item):
                """Helper."""
                pattern = formatting.format_item(self._template,
                                                 item).replace('[', '[[]')
                ##print('!!!', val, '~~~', pattern, '???')
                return fnmatch.fnmatchcase(val, pattern.lower())

            self._template = formatting.preparse(self._value)
            self._matcher = _template_globber
        else:
            self._matcher = lambda val, _: fnmatch.fnmatchcase(
                val, self._value)
Exemple #4
0
    def __init__(self, config=None):
        self.config = config or {}
        self.LOG = pymagic.get_class_logger(self)
        if 'log_level' in self.config:
            self.LOG.setLevel(config.log_level)
        self.LOG.debug("Tree watcher created with config %r" % self.config)

        self.manager = None
        self.handler = None
        self.notifier = None

        bool_param = lambda key, default: matching.truth(
            self.config.get(key, default), "job.%s.%s" %
            (self.config.job_name, key))

        if not self.config.path:
            raise error.UserError(
                "You need to set 'job.%s.path' in the configuration!" %
                self.config.job_name)

        self.config.quiet = bool_param("quiet", False)
        self.config.queued = bool_param("queued", False)
        self.config.trace_inotify = bool_param("trace_inotify", False)

        self.config.path = set([
            os.path.abspath(os.path.expanduser(path.strip()).rstrip(os.sep))
            for path in self.config.path.split(os.pathsep)
        ])
        for path in self.config.path:
            if not os.path.isdir(path):
                raise error.UserError("Path '%s' is not a directory!" % path)

        # Assemble custom commands
        self.custom_cmds = {}
        for key, val in self.config.items():
            if key.startswith("cmd."):
                _, key = key.split('.', 1)
                if key in self.custom_cmds:
                    raise error.UserError(
                        "Duplicate custom command definition '%s'"
                        " (%r already registered, you also added %r)!" %
                        (key, self.custom_cmds[key], val))
                self.custom_cmds[key] = formatting.preparse(val)
        self.LOG.debug("custom commands = %r" % self.custom_cmds)

        # Get client proxy
        self.proxy = xmlrpc.RTorrentProxy(configuration.scgi_url)
        self.proxy._set_mappings()  # pylint: disable=W0212

        if self.config.active:
            self.setup()
Exemple #5
0
    def __init__(self, config=None):
        self.config = config or {}
        self.LOG = pymagic.get_class_logger(self)
        self.LOG.debug("Tree watcher created with config %r" % self.config)

        self.manager = None
        self.handler = None
        self.notifier = None

        bool_param = lambda key, default: matching.truth(self.config.get(key, default), "job.%s.%s" % (self.config.job_name, key))

        if not self.config.path:
            raise error.UserError("You need to set 'job.%s.path' in the configuration!" % self.config.job_name)

        self.config.quiet = bool_param("quiet", False)
        self.config.queued = bool_param("queued", False)
        self.config.trace_inotify = bool_param("trace_inotify", False)

        self.config.path = set([os.path.abspath(os.path.expanduser(path.strip()).rstrip(os.sep))
            for path in self.config.path.split(os.pathsep)
        ])
        for path in self.config.path:
            if not os.path.isdir(path):
                raise error.UserError("Path '%s' is not a directory!" % path)

        # Assemble custom commands
        self.custom_cmds = {}
        for key, val in self.config.items():
            if key.startswith("cmd."):
                _, key = key.split('.', 1)
                if key in self.custom_cmds:
                    raise error.UserError("Duplicate custom command definition '%s'"
                        " (%r already registered, you also added %r)!" % (key, self.custom_cmds[key], val))
                self.custom_cmds[key] = formatting.preparse(val)
        self.LOG.debug("custom commands = %r" % self.custom_cmds)

        # Get client proxy
        self.proxy = xmlrpc.RTorrentProxy(configuration.scgi_url)
        self.proxy._set_mappings() # pylint: disable=W0212

        if self.config.active:
            self.setup()
Exemple #6
0
                "%s %s %d out of %d torrents." % (
                    "Would" if self.options.dry_run else "About to",
                    action.label,
                    len(matches),
                    view.size(),
                ))
            action_results = []
            defaults = {"action": action.label}
            defaults.update(self.FORMATTER_DEFAULTS)

            if self.options.column_headers and matches:
                self.emit(None, stencil=stencil)

            # Perform chosen action on matches
            template_args = [
                formatting.preparse("{{#tempita}}" + i if "{{" in i else i)
                for i in action.args
            ]
            for item in matches:
                if not self.prompt.ask_bool("%s item %s" %
                                            (action.label, item.name)):
                    continue
                if (self.options.output_format and not self.options.view_only
                        and not self.options.json
                        and str(self.options.output_format) != "-"):
                    self.emit(item, defaults, to_log=self.options.cron)

                args = tuple([
                    output_formatter(i, namespace=dict(item=item))
                    for i in template_args
                ])
Exemple #7
0
            return formatting.expand_template(templ, full_ns)

        # Execute action?
        if actions:
            action = actions[0] # TODO: loop over it
            self.LOG.log(logging.DEBUG if self.options.cron else logging.INFO, "%s %s %d out of %d torrents." % (
                "Would" if self.options.dry_run else "About to", action.label, len(matches), view.size(),
            ))
            defaults = {"action": action.label}
            defaults.update(self.FORMATTER_DEFAULTS)

            if self.options.column_headers and matches:
                self.emit(None, stencil=stencil)

            # Perform chosen action on matches
            template_args = [formatting.preparse("{{#tempita}}" + i if "{{" in i else i) for i in action.args]
            for item in matches:
                if not self.prompt.ask_bool("%s item %s" % (action.label, item.name)):
                    continue
                if self.options.output_format and str(self.options.output_format) != "-":
                    self.emit(item, defaults, to_log=self.options.cron)

                args = tuple([output_formatter(i, ns=dict(item=item)) for i in template_args])

                if self.options.dry_run:
                    if self.options.debug:
                        self.LOG.debug("Would call action %s(*%r)" % (action.method, args))
                else:
                    getattr(item, action.method)(*args)
                    if self.options.flush:
                        item.flush()
Exemple #8
0
            return formatting.expand_template(templ, full_ns)

        # Execute action?
        if actions:
            action = actions[0] # TODO: loop over it
            self.LOG.log(logging.DEBUG if self.options.cron else logging.INFO, "%s %s %d out of %d torrents." % (
                "Would" if self.options.dry_run else "About to", action.label, len(matches), view.size(),
            ))
            defaults = {"action": action.label}
            defaults.update(self.FORMATTER_DEFAULTS)

            if self.options.column_headers and matches:
                self.emit(None, stencil=stencil)

            # Perform chosen action on matches
            template_args = [formatting.preparse("{{#tempita}}" + i if "{{" in i else i) for i in action.args]
            for item in matches:
                if not self.prompt.ask_bool("%s item %s" % (action.label, item.name)):
                    continue
                if self.options.output_format and str(self.options.output_format) != "-":
                    self.emit(item, defaults, to_log=self.options.cron)

                args = tuple([output_formatter(i, ns=dict(item=item)) for i in template_args])

                if self.options.dry_run:
                    if self.options.debug:
                        self.LOG.debug("Would call action %s(*%r)" % (action.method, args))
                else:
                    getattr(item, action.method)(*args)
                    if self.options.flush:
                        item.flush()
Exemple #9
0
                logging.DEBUG if self.options.cron else logging.INFO,
                "%s %s %d out of %d torrents." % (
                    "Would" if self.options.dry_run else "About to",
                    action.label,
                    len(matches),
                    view.size(),
                ))
            defaults = {"action": action.label}
            defaults.update(self.FORMATTER_DEFAULTS)

            if self.options.column_headers and matches:
                self.emit(None, stencil=stencil)

            # Perform chosen action on matches
            template_args = [
                formatting.preparse("{{#tempita}}" + i if "{{" in i else i)
                for i in action.args
            ]
            for item in matches:
                if not self.prompt.ask_bool("%s item %s" %
                                            (action.label, item.name)):
                    continue
                if self.options.output_format and str(
                        self.options.output_format) != "-":
                    self.emit(item, defaults, to_log=self.options.cron)

                args = tuple([
                    output_formatter(i, ns=dict(item=item))
                    for i in template_args
                ])