Example #1
0
 def parse(self):
     """ Parse metafile and check pre-conditions.
     """
     try:
         if not os.path.getsize(self.ns.pathname):
             # Ignore 0-byte dummy files (Firefox creates these while downloading)
             self.job.LOG.warn("Ignoring 0-byte metafile '%s'" % (self.ns.pathname,))
             return
         self.metadata = metafile.checked_open(self.ns.pathname)
     except EnvironmentError, exc:
         self.job.LOG.error("Can't read metafile '%s' (%s)" % (
             self.ns.pathname, str(exc).replace(": '%s'" % self.ns.pathname, ""),
         ))
         return
Example #2
0
 def parse(self):
     """ Parse metafile and check pre-conditions.
     """
     try:
         if not os.path.getsize(self.ns.pathname):
             # Ignore 0-byte dummy files (Firefox creates these while downloading)
             self.job.LOG.warn("Ignoring 0-byte metafile '%s'" % (self.ns.pathname,))
             return
         self.metadata = metafile.checked_open(self.ns.pathname)
     except EnvironmentError, exc:
         self.job.LOG.error("Can't read metafile '%s' (%s)" % (
             self.ns.pathname, str(exc).replace(": '%s'" % self.ns.pathname, ""),
         ))
         return
Example #3
0
    def parse(self):
        """ Parse metafile and check pre-conditions.
        """
        try:
            if not os.path.getsize(self.ns.pathname):
                # Ignore 0-byte dummy files (Firefox creates these while downloading)
                self.job.LOG.warn("Ignoring 0-byte metafile '%s'" %
                                  (self.ns.pathname, ))
                return
            self.metadata = metafile.checked_open(self.ns.pathname)
        except EnvironmentError as exc:
            self.job.LOG.error("Can't read metafile '%s' (%s)" % (
                self.ns.pathname,
                str(exc).replace(": '%s'" % self.ns.pathname, ""),
            ))
            return
        except ValueError as exc:
            self.job.LOG.error("Invalid metafile '%s': %s" %
                               (self.ns.pathname, exc))
            return

        self.ns.info_hash = metafile.info_hash(self.metadata)
        self.ns.info_name = self.metadata["info"]["name"]
        self.job.LOG.info("Loaded '%s' from metafile '%s'" %
                          (self.ns.info_name, self.ns.pathname))

        # Check whether item is already loaded
        try:
            name = self.job.proxy.d.name(self.ns.info_hash, fail_silently=True)
        except xmlrpc.HashNotFound:
            pass
        except xmlrpc.ERRORS as exc:
            if exc.faultString != "Could not find info-hash.":
                self.job.LOG.error("While checking for #%s: %s" %
                                   (self.ns.info_hash, exc))
                return
        else:
            self.job.LOG.warn("Item #%s '%s' already added to client" %
                              (self.ns.info_hash, name))
            return

        return True
Example #4
0
    def mainloop(self):
        """ The main loop.
        """
        if not self.args:
            self.parser.print_help()
            self.parser.exit()

        for idx, filename in enumerate(self.args):
            torrent = metafile.Metafile(filename)
            if idx and not self.options.output:
                print('')
                print("~" * 79)

            try:
                # Read and check metafile
                try:
                    data = metafile.checked_open(
                        filename,
                        log=self.LOG if self.options.skip_validation else None,
                        quiet=(self.options.quiet
                               and (self.options.output or self.options.raw)))
                except EnvironmentError as exc:
                    self.fatal("Can't read '%s' (%s)" % (
                        filename,
                        str(exc).replace(": '%s'" % filename, ""),
                    ))
                    raise

                listing = None

                if self.options.raw or self.options.json:
                    if not self.options.reveal and "info" in data:
                        # Shorten useless binary piece hashes
                        data["info"]["pieces"] = "<%d piece hashes>" % (
                            len(data["info"]["pieces"]) /
                            len(hashlib.sha1().digest())  # bogus pylint: disable=E1101
                        )

                    if self.options.json:
                        listing = json.dumps(data,
                                             default=repr,
                                             indent=4,
                                             sort_keys=True)
                    else:
                        pprinter = (pprint.PrettyPrinter if self.options.reveal
                                    else metafile.MaskingPrettyPrinter)()
                        listing = pprinter.pformat(data)
                elif self.options.output:

                    def splitter(fields):
                        "Yield single names for a list of comma-separated strings."
                        for flist in fields:
                            for field in flist.split(','):
                                yield field.strip()

                    data["__file__"] = filename
                    if 'info' in data:
                        data["__hash__"] = metafile.info_hash(data)
                        data["__size__"] = metafile.data_size(data)
                    values = []
                    for field in splitter(self.options.output):
                        try:
                            val = data
                            for key in field.split('.'):
                                val = val[key]
                        except KeyError as exc:
                            self.LOG.error("%s: Field %r not found (%s)" %
                                           (filename, field, exc))
                            break
                        else:
                            values.append(str(val))
                    else:
                        listing = '\t'.join(values)
                else:
                    listing = '\n'.join(
                        torrent.listing(masked=not self.options.reveal))
            except (ValueError, KeyError, bencode.BencodeError) as exc:
                if self.options.debug:
                    raise
                self.LOG.warning("Bad metafile %r (%s: %s)" %
                                 (filename, type(exc).__name__, exc))
            else:
                if listing is not None:
                    print(fmt.to_utf8(listing))
Example #5
0
    def mainloop(self):
        """ The main loop.
        """
        if not self.args:
            self.parser.print_help()
            self.parser.exit()

        for idx, filename in enumerate(self.args):
            torrent = metafile.Metafile(filename)
            if idx and not self.options.output:
                print
                print "~" * 79

            try:
                # Read and check metafile
                try:
                    data = metafile.checked_open(filename, log=self.LOG if self.options.skip_validation else None,
                        quiet=(self.options.quiet and (self.options.output or self.options.raw)))
                except EnvironmentError, exc:
                    self.fatal("Can't read '%s' (%s)" % (
                        filename, str(exc).replace(": '%s'" % filename, ""),
                    ))
                    raise

                listing = None

                if self.options.raw:
                    if not self.options.reveal and "info" in data:
                        # Shorten useless binary piece hashes
                        data["info"]["pieces"] = "<%d piece hashes>" % (
                            len(data["info"]["pieces"]) / len(hashlib.sha1().digest()) # bogus pylint: disable=E1101 
                        )

                    pprinter = (pprint.PrettyPrinter if self.options.reveal else metafile.MaskingPrettyPrinter)() 
                    listing = pprinter.pformat(data)
                elif self.options.output:
                    def splitter(fields):
                        "Yield single names for a list of comma-separated strings."
                        for flist in fields:
                            for field in flist.split(','):
                                yield field.strip()

                    data["__file__"] = filename
                    if 'info' in data:
                        data["__hash__"] = metafile.info_hash(data)
                        data["__size__"] = metafile.data_size(data)
                    values = []
                    for field in splitter(self.options.output):
                        try:
                            val = data
                            for key in field.split('.'):
                                val = val[key]
                        except KeyError, exc:
                            self.LOG.error("%s: Field %r not found (%s)" % (filename, field, exc))
                            break
                        else:
                            values.append(str(val))
                    else:
                        listing = '\t'.join(values)
                else:
                    listing = '\n'.join(torrent.listing(masked=not self.options.reveal))