Source code for mymeco.cmdline

# coding: utf-8
"""Command line support for mymeco."""
import sys
import os
import argparse
from lxml import etree


from mymeco.config import Configuration
from mymeco import logger
from mymeco.files.video import Video
from mymeco.tmdb.utils import Tmdb
from mymeco.kodi.movie import Movie


def _compute(config, filename, searchterms=None, year=None):
    video = Video(filename)
    movie_title = '.'.join(os.path.basename(filename).split('.')[:-1])
    tmdb = Tmdb(config.tmdb()['token'], 'fr-FR')
    if searchterms is None:
        searchterms = movie_title
    output_list = list(tmdb.search_movie(searchterms, year))
    index = 1
    if not output_list:
        print('Search result is empty.', file=sys.stderr)
        return

    for result in output_list:
        print(
            '{}. {} ({}) - {} - {}'.format(
                index, result.title, result.original_title,
                result.release_date, result.poster_path
            )
        )
        index += 1

    movie_id = None
    while movie_id is None:
        try:
            if len(output_list) > 1:
                choice = int(input('Choose a movie:'))
            else:
                choice = 1
            movie_id = output_list[choice - 1].id
        except IndexError:
            print('{} is outside result range. Retry.'.format(choice),
                  file=sys.stderr)
            movie_id = None
        except ValueError:
            print('Not a number. Retry.', file=sys.stderr)
            movie_id = None

    movie = Movie(movie_id, tmdb)
    movie.set_technical(video)
    movie.sorttitle = os.path.basename(filename)

    nfo_file = '.'.join(filename.split('.')[:-1] + ['nfo'])
    with open(nfo_file, 'w') as nfo:
        movie.nfo(nfo)


def _update(config, filenames):
    for filename in filenames:
        nfo_file = '.'.join(filename.split('.')[:-1] + ['nfo'])
        if not os.path.isfile(nfo_file):
            print('NFO file not found ({})'.format(nfo_file))
            continue

        video = Video(filename)
        # Retrieve tmdb movie id in nfo file
        movie_id = None
        for action, element in etree.iterparse(nfo_file, tag='uniqueid'):
            if element.attrib['type'] == 'tmdb':
                movie_id = element.text
                break
        if movie_id is None:
            print('No TMDB id found in NFO file.')
            continue

        tmdb = Tmdb(config.tmdb()['token'], 'fr-FR')
        movie = Movie(movie_id, tmdb)
        movie.sorttitle = os.path.basename(filename)
        movie.set_technical(video)

        with open(nfo_file, 'w') as nfo:
            movie.nfo(nfo)


def __parse_args(args):
    """Parse command line arguments."""
    parser = argparse.ArgumentParser(
        description='Mymecoctl generate nfo file from Video file.'
    )
    parser.add_argument(
        '--search', '-s', help='Use these terms in TMDB movie search request.',
        type=str

    )
    parser.add_argument(
        '--year', '-y', help='Look for movie released in the given year',
        type=int
    )
    parser.add_argument(
        '--update', '-u', help='Update nfo already existing nfo files.',
        action='store_true'
    )
    parser.add_argument('FILENAME', nargs='*')

    parsed = parser.parse_args(args)

    print(parsed.update)
    print(parsed.FILENAME)
    if not parsed.update and len(parsed.FILENAME) != 1:
        print('Multiple video file is available only with --update flag.',
              file=sys.stderr)
        sys.exit(1)

    return parsed


[docs] def mymecoctl(argv=None): """Entrypoint to create nfo file next to video file.""" if argv is None: argv = sys.argv[1:] config = Configuration() logger.configure(**config.log()) parsed = __parse_args(argv) if parsed.update: _update(config, parsed.FILENAME) sys.exit(0) try: if os.path.isfile(parsed.FILENAME[0]): _compute(config, parsed.FILENAME[0], parsed.search, parsed.year) else: print( '{} does not exists.'.format(parsed.FILENAME[0]), file=sys.stderr ) except KeyboardInterrupt: print('Abort')