mymeco.cmdline

mymeco/cmdline.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# 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


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