예제 #1
0
def main():
    """The entrypoint"""
    parser = define_parser()
    args = parser.parse_args()
    logger = logging.getLogger('ptp-reseed')

    logging.basicConfig(level=args.loglevel)

    # Load pyroscope
    load_config.ConfigLoader().load()
    proxy = config.engine.open()

    # Futile attempt to impose our loglevel upon pyroscope
    logging.basicConfig(level=args.loglevel)

    # Load PTP API
    ptp = ptpapi.login()


    loaded = []
    would_load = []
    already_loaded = []
    not_found = []

    if args.files == ['-'] or args.files == []:
        filelist = sys.stdin
    else:
        filelist = args.files

    if args.compare_paths:
        logger.debug('Loading existing torrents for pre-matching')
        loaded_paths = find_existing_torrents(proxy)
    else:
        loaded_paths = []

    for filename in filelist:
        match = Match(None)
        filename = filename.strip("\n").decode('utf-8')

        logger.info(u'Starting reseed attempt on file {0}'.format(filename))

        if not os.path.exists(filename):
            logger.error(u"File/directory {0} does not exist".format(filename))
            continue

        if args.url:
            parsed_url = parse_qs(urlparse(args.url).query)
            if 'torrentid' in parsed_url:
                match = match_by_torrent(ptpapi.Torrent(ID=parsed_url['torrentid'][0]), filename.encode())
            elif 'id' in parsed_url:
                match = match_by_movie(ptpapi.Movie(ID=parsed_url['id'][0]), filename.encode())
        elif filename:
            for match_type in ptpapi.config.config.get('Reseed', 'findBy').split(','):
                try:
                    if match_type == 'filename':
                        if os.path.abspath(filename) in loaded_paths:
                            logger.info(u'Path {0} already in rtorrent, skipping'.format(os.path.abspath(filename)))
                        else:
                            logger.debug(u'Path {0} not in rtorrent'.format(os.path.abspath(filename)))
                            match = match_against_file(ptp, filename, args.limit)
                    elif match_type == 'title':
                        match = match_by_guessed_name(ptp, filename, args.limit)
                    else:
                        logger.error(u"Match type {0} not recognized for {1}, skipping".format(match_type, filename))
                    if match:
                        break
                except Exception:
                    print(u"Error while attempting to match file '{0}'".format(filename))
                    raise

        # Make sure we have the minimum information required
        if not match:
            not_found.append(filename)
            logger.error(u"Could not find an associated torrent for '{0}', cannot reseed".format(filename))
            continue

        if args.create_in_directory:
            create_in = args.create_in_directory
        elif ptpapi.config.config.has_option('Reseed', 'createInDirectory'):
            create_in = ptpapi.config.config.get('Reseed', 'createInDirectory')
        else:
            create_in = None
        create_matched_files(match, directory=create_in, action=args.action, dry_run=args.dry_run)
        logger.info(u"Found match, now loading torrent {0} to path {1}".format(match.ID, match.path))
        if args.dry_run:
            would_load.append(filename)
            logger.debug("Dry-run: Stopping before actual load")
            continue
        if load_torrent(proxy, match.ID, match.path):
            loaded.append(filename)
        else:
            already_loaded.append(filename)

    if args.summary:
        print('==> Loaded:')
        print('\n'.join(loaded))
        print('==> Would have loaded:')
        print('\n'.join(would_load))
        print('==> Already loaded:')
        print('\n'.join(already_loaded))
        print('==> Not found:')
        print('\n'.join(not_found))

    exit_code = 0
    if len(not_found) == 1:
        exit_code = 1
    elif len(not_found) > 1:
        exit_code = 2
    elif len(already_loaded) > 0:
        exit_code = 3

    logger.debug("Total session tokens consumed: %s", ptpapi.session.session.consumed_tokens)
    logger.debug("Exiting...")
    sys.exit(exit_code)
예제 #2
0
    def mainloop(self):
        """ The main loop.
        """
        if self.options.create_config:
            # Create configuration
            config_loader = load_config.ConfigLoader(self.options.config_dir)
            config_loader.create(self.options.remove_all_rc_files)

            # Create directories
            for dirname in self.CONFIG_DIRS:
                dirpath = os.path.join(config_loader.config_dir, dirname)
                if not os.path.isdir(dirpath):
                    self.LOG.info("Creating %r..." % (dirpath, ))
                    os.mkdir(dirpath)

            # Initialize webserver stuff
            if matching.truth(
                    getattr(config, "torque", {}).get("httpd.active", "False"),
                    "httpd.active"):
                self.download_resource(
                    config.torque["httpd.download_url.smoothie"], "htdocs/js",
                    "smoothie.js")

        elif self.options.dump_config or self.options.output:
            config.engine.load_config()

            # Get public config attributes
            public = dict(
                (key, val) for key, val in vars(config).items()
                if not key.startswith('_') and (self.options.reveal or not (
                    callable(val) or key in config._PREDEFINED)))

            if self.options.dump_config:
                # Dump configuration
                pprinter = (pprint.PrettyPrinter if self.options.reveal else
                            metafile.MaskingPrettyPrinter)()
                pprinter.pprint(public)
            else:

                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()

                values = []
                for field in splitter(self.options.output):
                    default = None
                    if '=' in field:
                        field, default = field.split('=', 1)

                    try:
                        val = public
                        for key in field.split('.'):
                            if key in val:
                                val = val[key]
                            elif isinstance(val, list) and key.isdigit():
                                val = val[int(key, 10)]
                            else:
                                matches = [
                                    i for i in val.keys()
                                    if i.lower() == key.lower()
                                ]
                                if matches:
                                    val = val[matches[0]]
                                else:
                                    raise KeyError(key)
                    except (IndexError, KeyError), exc:
                        if default is None:
                            self.LOG.error("Field %r not found (%s)" %
                                           (field, exc))
                            break
                        values.append(default)
                    else:
                        values.append(str(val))
                else:
                    print '\t'.join(values)
예제 #3
0
    def __init__(self):
        MyGlobals.Logger.info("Initializing PyroScope.")

        load_config.ConfigLoader().load()
        self.proxy = config.engine.open()