Esempio n. 1
0
File: cli.py Progetto: ksurl/Flexget
def entry_list_show(options):
    with Session() as session:
        try:
            entry_list = db.get_list_by_exact_name(options.list_name,
                                                   session=session)
        except NoResultFound:
            console('Could not find entry list with name {}'.format(
                options.list_name))
            return

        try:
            entry = db.get_entry_by_id(entry_list.id,
                                       int(options.entry),
                                       session=session)
        except NoResultFound:
            console(
                'Could not find matching entry with ID {} in list `{}`'.format(
                    int(options.entry), options.list_name))
            return
        except ValueError:
            entry = db.get_entry_by_title(entry_list.id,
                                          options.entry,
                                          session=session)
            if not entry:
                console(
                    'Could not find matching entry with title `{}` in list `{}`'
                    .format(options.entry, options.list_name))
                return
        table = TerminalTable('Field name',
                              'Value',
                              table_type=options.table_type)
        for k, v in sorted(entry.entry.items()):
            table.add_row(k, str(v))
    console(table)
Esempio n. 2
0
def action_list(options):
    with Session() as session:
        if not options.account:
            # Print all accounts
            accounts = session.query(db.TraktUserAuth).all()
            if not accounts:
                console('No trakt authorizations stored in database.')
                return
            header = ['Account', 'Created', 'Expires']
            table = TerminalTable(*header, table_type=options.table_type)

            for auth in accounts:
                table.add_row(
                    auth.account,
                    auth.created.strftime('%Y-%m-%d'),
                    auth.expires.strftime('%Y-%m-%d'),
                )
            console(table)
            return

        # Show a specific account
        acc = (session.query(db.TraktUserAuth).filter(
            db.TraktUserAuth.account == options.account).first())
        if acc:
            console('Authorization expires on %s' % acc.expires)
        else:
            console('Flexget has not been authorized to access your account.')
Esempio n. 3
0
File: cli.py Progetto: ksurl/Flexget
def cli_search(options):
    search_term = ' '.join(options.keywords)
    tags = options.tags
    sources = options.sources
    query = re.sub(r'[ \(\)\:]+', ' ', search_term).strip()

    table_data = []
    with Session() as session:
        for archived_entry in flexget.components.archive.db.search(
                session, query, tags=tags, sources=sources):
            days_ago = (datetime.now() - archived_entry.added).days
            source_names = ', '.join([s.name for s in archived_entry.sources])
            tag_names = ', '.join([t.name for t in archived_entry.tags])

            table_data.append(['ID', str(archived_entry.id)])
            table_data.append(['Title', archived_entry.title])
            table_data.append(['Added', str(days_ago) + ' days ago'])
            table_data.append(['URL', archived_entry.url])
            table_data.append(['Source(s)', source_names or 'N/A'])
            table_data.append(['Tag(s)', tag_names or 'N/A'])
            if archived_entry.description:
                table_data.append(
                    ['Description',
                     strip_html(archived_entry.description)])
            table_data.append([])
    if not table_data:
        console('No results found for search')
        return
    table = TerminalTable('Field', 'Value', table_type=options.table_type)
    for row in table_data:
        table.add_row(*row)
    console(table)
Esempio n. 4
0
File: cli.py Progetto: ksurl/Flexget
def seen_search(options, session=None):
    search_term = options.search_term
    if is_imdb_url(search_term):
        console('IMDB url detected, parsing ID')
        imdb_id = extract_id(search_term)
        if imdb_id:
            search_term = imdb_id
        else:
            console("Could not parse IMDB ID")
    else:
        search_term = '%' + options.search_term + '%'
    seen_entries = db.search(value=search_term, status=None, session=session)
    table = TerminalTable('Field', 'Value', table_type=options.table_type)
    for se in seen_entries.all():
        table.add_row('Title', se.title)
        for sf in se.fields:
            if sf.field.lower() == 'title':
                continue
            table.add_row('{}'.format(sf.field.upper()), str(sf.value))
        table.add_row('Task', se.task)
        table.add_row('Added',
                      se.added.strftime('%Y-%m-%d %H:%M'),
                      end_section=True)
    if not table.rows:
        console('No results found for search')
        return
    console(table)
Esempio n. 5
0
def action_status(options, irc_manager):
    connection = options.irc_connection
    try:
        status = irc_manager.status(connection)
    except ValueError as e:
        console('ERROR: %s' % e.args[0])
        return

    header = ['Name', 'Alive', 'Channels', 'Server']
    table_data = []

    for connection in status:
        for name, info in connection.items():
            alive = colorize('green', 'Yes') if info['alive'] else colorize(
                'red', 'No')
            channels = []
            for channel in info['channels']:
                for channel_name, channel_status in channel.items():
                    channels.append(channel_name)
                    if channel_status == IRCChannelStatus.CONNECTED:
                        channels[-1] = colorize('green', '* ' + channels[-1])
            table_data.append([
                name, alive, ', '.join(channels),
                '%s:%s' % (info['server'], info['port'])
            ])

    table = TerminalTable(*header, table_type=options.table_type)
    for row in table_data:
        table.add_row(*row)
    console(table)
    console(colorize('green', ' * Connected channel'))
Esempio n. 6
0
File: cli.py Progetto: ksurl/Flexget
def action_all(options):
    """Show all regexp lists"""
    lists = db.get_regexp_lists()
    header = ['#', 'List Name']
    table = TerminalTable(*header, table_type=options.table_type)
    for regexp_list in lists:
        table.add_row(str(regexp_list.id), regexp_list.name)
    console(table)
Esempio n. 7
0
File: cli.py Progetto: ksurl/Flexget
def entry_list_lists(options):
    """Show all entry lists"""
    with Session() as session:
        lists = db.get_entry_lists(session=session)
        table = TerminalTable('#', 'List Name', table_type=options.table_type)
        for entry_list in lists:
            table.add_row(str(entry_list.id), entry_list.name)
    console(table)
Esempio n. 8
0
File: cli.py Progetto: ksurl/Flexget
def list_rejected(options):
    with Session() as session:
        results = session.query(db.RememberEntry).all()
        header = ['#', 'Title', 'Task', 'Rejected by', 'Reason']
        table = TerminalTable(*header, table_type=options.table_type)
        for entry in results:
            table.add_row(str(entry.id), entry.title, entry.task.name,
                          entry.rejected_by, entry.reason or '')
    console(table)
Esempio n. 9
0
File: cli.py Progetto: ksurl/Flexget
def pending_list_lists(options):
    """Show all pending lists"""
    with Session() as session:
        lists = db.get_pending_lists(session=session)
        header = ['#', 'List Name']
        table = TerminalTable(*header, table_type=options.table_type)
        for entry_list in lists:
            table.add_row(str(entry_list.id), entry_list.name)
    console(table)
Esempio n. 10
0
File: cli.py Progetto: ksurl/Flexget
def movie_list_lists(options):
    """Show all movie lists"""
    lists = db.get_movie_lists()
    header = ['#', 'List Name']
    table = TerminalTable(*header, table_type=options.table_type)
    for movie_list in lists:
        table.add_row(str(movie_list.id), movie_list.name)

    console(table)
Esempio n. 11
0
def do_cli(manager, options):
    header = ['Name', 'Description']
    table = TerminalTable(*header, table_type=options.table_type, show_lines=True)
    for filter_name, filter in get_filters().items():
        if options.name and not options.name in filter_name:
            continue
        filter_doc = inspect.getdoc(filter) or ''
        table.add_row(filter_name, filter_doc)
    console(table)
Esempio n. 12
0
def do_cli_summary(manager, options):
    header = [
        'Task',
        'Last execution',
        'Last success',
        'Entries',
        'Accepted',
        'Rejected',
        'Failed',
        'Duration',
    ]
    table = TerminalTable(*header, table_type=options.table_type)

    with Session() as session:
        for task in session.query(db.StatusTask).all():
            ok = (session.query(db.TaskExecution).filter(
                db.TaskExecution.task_id == task.id).filter(
                    db.TaskExecution.succeeded == True).filter(
                        db.TaskExecution.produced > 0).order_by(
                            db.TaskExecution.start.desc()).first())

            if ok is None:
                duration = None
                last_success = '-'
            else:
                duration = ok.end - ok.start
                last_success = ok.start.strftime('%Y-%m-%d %H:%M')

                age = datetime.datetime.utcnow() - ok.start
                if age > timedelta(days=7):
                    last_success = colorize('red', last_success)
                elif age < timedelta(minutes=10):
                    last_success = colorize('green', last_success)
            # Fix weird issue that a task registers StatusTask but without an execution. GH #2022
            last_exec = (task.last_execution_time.strftime('%Y-%m-%d %H:%M')
                         if task.last_execution_time else '-')

            table.add_row(
                task.name,
                last_exec,
                last_success,
                str(ok.produced) if ok is not None else '-',
                str(ok.accepted) if ok is not None else '-',
                str(ok.rejected) if ok is not None else '-',
                str(ok.failed) if ok is not None else '-',
                '%1.fs' %
                duration.total_seconds() if duration is not None else '-',
            )

    console(table)
Esempio n. 13
0
def seen_search(options, session=None):
    search_term = options.search_term
    if is_imdb_url(search_term):
        console('IMDB url detected, parsing ID')
        imdb_id = extract_id(search_term)
        if imdb_id:
            search_term = imdb_id
        else:
            console("Could not parse IMDB ID")
    else:
        search_term = '%' + options.search_term + '%'
    seen_entries = plugin_seen.search(value=search_term, status=None, session=session)
    table_data = []
    for se in seen_entries.all():
        table_data.append(['Title', se.title])
        for sf in se.fields:
            if sf.field.lower() == 'title':
                continue
            table_data.append(['{}'.format(sf.field.upper()), str(sf.value)])
        table_data.append(['Task', se.task])
        table_data.append(['Added', se.added.strftime('%Y-%m-%d %H:%M')])
        if options.table_type != 'porcelain':
            table_data.append(['', ''])
    if not table_data:
        console('No results found for search')
        return
    if options.table_type != 'porcelain':
        del table_data[-1]

    try:
        table = TerminalTable(options.table_type, table_data, wrap_columns=[1])
        table.table.inner_heading_row_border = False
        console(table.output)
    except TerminalTableError as e:
        console('ERROR: %s' % str(e))
Esempio n. 14
0
def plugins_summary(manager, options):
    if options.table_type == 'porcelain':
        disable_all_colors()
    header = ['Keyword', 'Phases', 'Flags']
    table_data = [header]
    for plugin in sorted(get_plugins(phase=options.phase, group=options.group)):
        if options.builtins and not plugin.builtin:
            continue
        flags = []
        if plugin.instance.__doc__:
            flags.append('doc')
        if plugin.builtin:
            flags.append('builtin')
        if plugin.debug:
            if not options.debug:
                continue
            flags.append('developers')
        handlers = plugin.phase_handlers
        roles = []
        for phase in handlers:
            priority = handlers[phase].priority
            roles.append('{0}({1})'.format(phase, priority))

        name = colorize('green', plugin.name) if 'builtin' in flags else plugin.name
        table_data.append([name, ', '.join(roles), ', '.join(flags)])

    try:
        table = TerminalTable(options.table_type, table_data, wrap_columns=[1, 2])
        console(table.output)
    except TerminalTableError as e:
        console('ERROR: %s' % str(e))
        return
    console(colorize('green', ' Built-in plugins'))
Esempio n. 15
0
def movie_list_list(options):
    """List movie list"""
    with Session() as session:
        try:
            movie_list = db.get_list_by_exact_name(options.list_name)
        except NoResultFound:
            console('Could not find movie list with name {}'.format(options.list_name))
            return
    header = ['#', 'Movie Name', 'Movie year']
    header += db.MovieListBase().supported_ids
    table_data = [header]
    movies = db.get_movies_by_list_id(
        movie_list.id, order_by='added', descending=True, session=session
    )
    for movie in movies:
        movie_row = [movie.id, movie.title, movie.year or '']
        for identifier in db.MovieListBase().supported_ids:
            movie_row.append(movie.identifiers.get(identifier, ''))
        table_data.append(movie_row)
    title = '{} Movies in movie list: `{}`'.format(len(movies), options.list_name)
    try:
        table = TerminalTable(options.table_type, table_data, title, drop_columns=[5, 2, 4])
    except TerminalTableError as e:
        console('ERROR: {}'.format(e))
    else:
        console(table.output)
Esempio n. 16
0
File: cli.py Progetto: x572b/Flexget
def pending_list_list(options):
    """List pending list entries"""
    with Session() as session:
        try:
            pending_list = db.get_list_by_exact_name(options.list_name,
                                                     session=session)
        except NoResultFound:
            console('Could not find pending list with name `{}`'.format(
                options.list_name))
            return
        header = ['#', 'Title', '# of fields', 'Approved']
        table_data = [header]
        for entry in db.get_entries_by_list_id(pending_list.id,
                                               order_by='added',
                                               descending=True,
                                               session=session):
            approved = colorize(
                'green', entry.approved) if entry.approved else entry.approved
            table_data.append(
                [entry.id, entry.title,
                 len(entry.entry), approved])
    table = TerminalTable(options.table_type, table_data)
    try:
        console(table.output)
    except TerminalTableError as e:
        console('ERROR: %s' % str(e))
Esempio n. 17
0
File: cli.py Progetto: ksurl/Flexget
def action_list(options):
    """List regexp list"""
    with Session() as session:
        regexp_list = db.get_list_by_exact_name(options.list_name)
        if not regexp_list:
            console('Could not find regexp list with name {}'.format(
                options.list_name))
            return
        table = TerminalTable('Regexp', table_type=options.table_type)
        regexps = db.get_regexps_by_list_id(regexp_list.id,
                                            order_by='added',
                                            descending=True,
                                            session=session)
        for regexp in regexps:
            table.add_row(regexp.regexp or '')
    console(table)
Esempio n. 18
0
def action_status(options, irc_manager):
    connection = options.irc_connection
    try:
        if connection == 'all':
            status = irc_manager.status_all()
        else:
            status = irc_manager.status(connection)
    except ValueError as e:
        console('ERROR: %s' % e.args[0])
        return

    header = [
        'IRC Connection', 'Thread', 'Channels', 'Connected Channels', 'Server'
    ]
    table_data = [header]
    for name, info in status.items():
        table_data.append([
            name, info['thread'], ', '.join(info['channels']),
            ', '.join(info['connected_channels']),
            '%s:%s' % info['server']
        ])
    table = TerminalTable(options.table_type, table_data)
    try:
        console(table.output)
    except TerminalTableError as e:
        console('ERROR: %s' % e)
Esempio n. 19
0
def action_list(options):
    with Session() as session:
        if not options.account:
            # Print all accounts
            accounts = session.query(db.TraktUserAuth).all()
            if not accounts:
                console('No trakt authorizations stored in database.')
                return
            header = ['Account', 'Created', 'Expires']
            table_data = [header]

            for auth in accounts:
                table_data.append([
                    auth.account,
                    auth.created.strftime('%Y-%m-%d'),
                    auth.expires.strftime('%Y-%m-%d'),
                ])
            try:
                table = TerminalTable(options.table_type, table_data)
                console(table.output)
                return
            except TerminalTableError as e:
                console('ERROR: %s' % str(e))

        # Show a specific account
        acc = (session.query(db.TraktUserAuth).filter(
            db.TraktUserAuth.account == options.account).first())
        if acc:
            console('Authorization expires on %s' % acc.expires)
        else:
            console('Flexget has not been authorized to access your account.')
Esempio n. 20
0
def list_file_templates(manager, options):
    header = ['Name', 'Use with', 'Full Path', 'Contents']
    table_data = [header]
    console('Fetching all file templates, stand by...')
    for template_name in list_templates(extensions=['template']):
        if options.name and not options.name in template_name:
            continue
        template = get_template(template_name)
        if 'entries' in template_name:
            plugin = 'notify_entries'
        elif 'task' in template_name:
            plugin = 'notify_task'
        else:
            plugin = '-'
        name = template_name.replace('.template', '').split('/')
        if len(name) == 2:
            name = name[1]
        with open(template.filename) as contents:
            table_data.append(
                [name, plugin, template.filename,
                 contents.read()])

    try:
        table = TerminalTable(options.table_type,
                              table_data,
                              wrap_columns=[2, 3],
                              drop_columns=[2, 3])
    except TerminalTableError as e:
        console('ERROR: %s' % str(e))
    else:
        console(table.output)
Esempio n. 21
0
def list_entries(options):
    """List pending entries"""
    approved = options.approved
    task_name = options.task_name

    with Session() as session:
        entries = db.list_pending_entries(session=session,
                                          task_name=task_name,
                                          approved=approved)
        header = ['#', 'Task Name', 'Title', 'URL', 'Approved', 'Added']
        table_data = [header]
        for entry in entries:
            table_data.append([
                entry.id,
                entry.task_name,
                entry.title,
                entry.url,
                colorize('green', 'Yes') if entry.approved else 'No',
                entry.added.strftime("%c"),
            ])
    try:
        table = TerminalTable(options.table_type,
                              table_data,
                              wrap_columns=[1, 2, 3],
                              drop_columns=[5, 1, 3])
        console(table.output)
    except TerminalTableError as e:
        console('ERROR: %s' % str(e))
Esempio n. 22
0
def action_status(options, irc_manager):
    connection = options.irc_connection
    try:
        if connection == 'all':
            status = irc_manager.status_all()
        else:
            status = irc_manager.status(connection)
    except ValueError as e:
        console('ERROR: %s' % e.args[0])
        return

    header = ['Name', 'Status', 'Channels', 'Server']
    table_data = [header]

    for name, info in status.items():
        channels = []
        for channel in info['channels'].keys():
            channels.append(channel)
            if channel in info['connected_channels']:
                channels[-1] = '*' + channels[-1]
        table_data.append([name, info['thread'], ', '.join(channels), '%s:%s' % info['server']])
    table = TerminalTable(options.table_type, table_data)
    try:
        console(table.output)
        console(' * Connected channel')
    except TerminalTableError as e:
        console('ERROR: %s' % e)
Esempio n. 23
0
File: cli.py Progetto: x572b/Flexget
def cli_search(options):
    search_term = ' '.join(options.keywords)
    tags = options.tags
    sources = options.sources
    query = re.sub(r'[ \(\)\:]+', ' ', search_term).strip()

    table_data = []
    with Session() as session:
        for archived_entry in flexget.components.archive.db.search(
            session, query, tags=tags, sources=sources
        ):
            days_ago = (datetime.now() - archived_entry.added).days
            source_names = ', '.join([s.name for s in archived_entry.sources])
            tag_names = ', '.join([t.name for t in archived_entry.tags])

            table_data.append(['ID', str(archived_entry.id)])
            table_data.append(['Title', archived_entry.title])
            table_data.append(['Added', str(days_ago) + ' days ago'])
            table_data.append(['URL', archived_entry.url])
            table_data.append(['Source(s)', source_names or 'N/A'])
            table_data.append(['Tag(s)', tag_names or 'N/A'])
            if archived_entry.description:
                table_data.append(['Description', strip_html(archived_entry.description)])
            table_data.append([])
    if not table_data:
        console('No results found for search')
        return

    try:
        table = TerminalTable(options.table_type, table_data, wrap_columns=[1])
        table.table.inner_heading_row_border = False
        console(table.output)
    except TerminalTableError as e:
        console('ERROR: %s' % str(e))
Esempio n. 24
0
def pending_list_show(options):
    with Session() as session:
        try:
            pending_list = plugin_pending_list.get_list_by_exact_name(options.list_name, session=session)
        except NoResultFound:
            console('Could not find pending list with name {}'.format(options.list_name))
            return

        try:
            entry = plugin_pending_list.get_entry_by_id(pending_list.id, int(options.entry), session=session)
        except NoResultFound:
            console('Could not find matching pending entry with ID {} in list `{}`'.format(int(options.entry),
                                                                                           options.list_name))
            return
        except ValueError:
            entry = plugin_pending_list.get_entry_by_title(pending_list.id, options.entry, session=session)
            if not entry:
                console('Could not find matching pending entry with title `{}` in list `{}`'.format(options.entry,
                                                                                                    options.list_name))
                return
        header = ['Field name', 'Value']
        table_data = [header]
        for k, v in sorted(entry.entry.items()):
            table_data.append([k, str(v)])
    table = TerminalTable(options.table_type, table_data, wrap_columns=[1])
    table.table.justify_columns[0] = 'center'
    try:
        console(table.output)
    except TerminalTableError as e:
        console('ERROR: %s' % str(e))
Esempio n. 25
0
def do_cli(manager, options):
    if options.action == 'clear':
        num = db.clear_entries(options.task, all=True)
        console('%s entries cleared from backlog.' % num)
    else:
        header = ['Title', 'Task', 'Expires']
        table_data = []
        with Session() as session:
            entries = db.get_entries(options.task, session=session)
            for entry in entries:
                table_data.append([
                    entry.title, entry.task,
                    entry.expire.strftime('%Y-%m-%d %H:%M')
                ])
        table = TerminalTable(*header, table_type=options.table_type)
        for row in table_data:
            table.add_row(*row)
        console(table)
Esempio n. 26
0
File: cli.py Progetto: ksurl/Flexget
def entry_list_list(options):
    """List entry list"""
    with Session() as session:
        try:
            entry_list = db.get_list_by_exact_name(options.list_name,
                                                   session=session)
        except NoResultFound:
            console('Could not find entry list with name {}'.format(
                options.list_name))
            return
        header = ['#', 'Title', '# of fields']
        table = TerminalTable(*header, table_type=options.table_type)
        for entry in db.get_entries_by_list_id(entry_list.id,
                                               order_by='added',
                                               descending=True,
                                               session=session):
            table.add_row(str(entry.id), entry.title, str(len(entry.entry)))
    console(table)
Esempio n. 27
0
File: cli.py Progetto: ksurl/Flexget
def list_failed(options):
    with Session() as session:
        results = session.query(db.FailedEntry).all()
        header = [
            TerminalTable.Column('#', justify='center'),
            'Title',
            'Fail count',
            'Reason',
            'Failure time',
        ]
        table = TerminalTable(*header, table_type=options.table_type)
        for entry in results:
            table.add_row(
                str(entry.id),
                entry.title,
                str(entry.count),
                '' if entry.reason == 'None' else entry.reason,
                entry.tof.strftime('%Y-%m-%d %H:%M'),
            )
    console(table)
Esempio n. 28
0
def movie_list_lists(options):
    """ Show all movie lists """
    lists = get_movie_lists()
    header = ['#', 'List Name']
    table_data = [header]
    for movie_list in lists:
        table_data.append([movie_list.id, movie_list.name])
    table = TerminalTable(options.table_type, table_data)
    try:
        console(table.output)
    except TerminalTableError as e:
        console('ERROR: %s' % str(e))
Esempio n. 29
0
File: cli.py Progetto: ksurl/Flexget
def pending_list_list(options):
    """List pending list entries"""
    with Session() as session:
        try:
            pending_list = db.get_list_by_exact_name(options.list_name,
                                                     session=session)
        except NoResultFound:
            console('Could not find pending list with name `{}`'.format(
                options.list_name))
            return
        header = ['#', 'Title', '# of fields', 'Approved']
        table = TerminalTable(*header, table_type=options.table_type)
        for entry in db.get_entries_by_list_id(pending_list.id,
                                               order_by='added',
                                               descending=True,
                                               session=session):
            approved = colorize(
                'green', entry.approved) if entry.approved else entry.approved
            table.add_row(str(entry.id), entry.title, str(len(entry.entry)),
                          approved)
    console(table)
Esempio n. 30
0
def action_all(options):
    """ Show all regexp lists """
    lists = get_regexp_lists()
    header = ['#', 'List Name']
    table_data = [header]
    for regexp_list in lists:
        table_data.append([regexp_list.id, regexp_list.name])
    table = TerminalTable(options.table_type, table_data)
    try:
        console(table.output)
    except TerminalTableError as e:
        console('ERROR: %s' % str(e))