Example #1
0
def buildCollection(inetref, opts):
    from MythTV.tmdb3 import Collection
    from MythTV import VideoMetadata
    from lxml import etree
    collection = Collection(inetref)
    tree = etree.XML(u'<metadata></metadata>')
    m = VideoMetadata()
    m.collectionref = str(collection.id)
    m.title = collection.name
    if collection.backdrop:
        b = collection.backdrop
        m.images.append({
            'type': 'fanart',
            'url': b.geturl(),
            'thumb': b.geturl(b.sizes()[0])
        })
    if collection.poster:
        p = collection.poster
        m.images.append({
            'type': 'coverart',
            'url': p.geturl(),
            'thumb': p.geturl(p.sizes()[0])
        })
    tree.append(m.toXML())
    sys.stdout.write(
        etree.tostring(tree,
                       encoding='UTF-8',
                       pretty_print=True,
                       xml_declaration=True))
    sys.exit()
Example #2
0
def buildCollection(inetref, opts):
    from MythTV.tmdb3.tmdb_exceptions import TMDBRequestInvalid
    from MythTV.tmdb3 import Collection
    from MythTV import VideoMetadata
    from lxml import etree
    collection = Collection(inetref)
    tree = etree.XML(u'<metadata></metadata>')
    m = VideoMetadata()
    m.collectionref = str(collection.id)
    try:
        m.title = collection.name
    except TMDBRequestInvalid:
        sys.stdout.write(etree.tostring(tree, encoding='UTF-8', pretty_print=True,
                                        xml_declaration=True))
        sys.exit()
    if collection.backdrop:
        b = collection.backdrop
        m.images.append({'type':'fanart', 'url':b.geturl(),
                  'thumb':b.geturl(b.sizes()[0])})
    if collection.poster:
        p = collection.poster
        m.images.append({'type':'coverart', 'url':p.geturl(),
                  'thumb':p.geturl(p.sizes()[0])})
    tree.append(m.toXML())
    sys.stdout.write(etree.tostring(tree, encoding='UTF-8', pretty_print=True,
                                    xml_declaration=True))
    sys.exit()
Example #3
0
def buildList(query, opts):
    # TEMPORARY FIX:
    # replace all dashes from queries to work around search behavior
    # as negative to all text that comes afterwards
    query = query.replace("-", " ")

    from MythTV.tmdb3 import searchMovie
    from MythTV import VideoMetadata
    from lxml import etree

    results = searchMovie(query)
    tree = etree.XML(u"<metadata></metadata>")
    mapping = [
        ["runtime", "runtime"],
        ["title", "originaltitle"],
        ["releasedate", "releasedate"],
        ["tagline", "tagline"],
        ["description", "overview"],
        ["homepage", "homepage"],
        ["userrating", "userrating"],
        ["popularity", "popularity"],
    ]

    count = 0
    for res in results:
        if res is None:
            continue

        m = VideoMetadata()
        for i, j in mapping:
            if getattr(res, j):
                setattr(m, i, getattr(res, j))
        m.inetref = str(res.id)

        if res.title:
            m.title = res.title

        # TODO:
        # should releasedate and year be pulled from the country-specific data
        # or should it be left to the default information to cut down on
        # traffic from searches
        if res.releasedate:
            m.year = res.releasedate.year
        if res.backdrop:
            b = res.backdrop
            m.images.append({"type": "fanart", "url": b.geturl(), "thumb": b.geturl(b.sizes()[0])})
        if res.poster:
            p = res.poster
            m.images.append({"type": "coverart", "url": p.geturl(), "thumb": p.geturl(p.sizes()[0])})
        tree.append(m.toXML())
        count += 1
        if count >= 60:
            # page limiter, dont want to overload the server
            break

    sys.stdout.write(etree.tostring(tree, encoding="UTF-8", pretty_print=True, xml_declaration=True))
    sys.exit(0)
Example #4
0
def buildList(query, opts):
    # TEMPORARY FIX:
    # replace all dashes from queries to work around search behavior
    # as negative to all text that comes afterwards
    query = query.replace('-',' ')

    from MythTV.tmdb3 import searchMovie
    from MythTV import VideoMetadata
    from lxml import etree
    results = searchMovie(query)
    tree = etree.XML(u'<metadata></metadata>')
    mapping = [['runtime',      'runtime'],     ['title',       'originaltitle'],
               ['releasedate',  'releasedate'], ['tagline',     'tagline'],
               ['description',  'overview'],    ['homepage',    'homepage'],
               ['userrating',   'userrating'],  ['popularity',  'popularity']]

    count = 0
    for res in results:
        m = VideoMetadata()
        for i,j in mapping:
            if getattr(res, j):
                setattr(m, i, getattr(res, j))
        m.inetref = str(res.id)
        m.imdb = str(res.imdb).lstrip("t")

        if res.title:
            m.title = res.title

        #TODO:
        # should releasedate and year be pulled from the country-specific data
        # or should it be left to the default information to cut down on
        # traffic from searches
        if res.releasedate:
            m.year = res.releasedate.year
        if res.backdrop:
            b = res.backdrop
            m.images.append({'type':'fanart', 'url':b.geturl(),
                             'thumb':b.geturl(b.sizes()[0])})
        if res.poster:
            p = res.poster
            m.images.append({'type':'coverart', 'url':p.geturl(),
                             'thumb':p.geturl(p.sizes()[0])})
        tree.append(m.toXML())
        count += 1
        if count >= 60:
            # page limiter, dont want to overload the server
            break

    sys.stdout.write(etree.tostring(tree, encoding='UTF-8', pretty_print=True,
                                    xml_declaration=True))
    sys.exit(0)
Example #5
0
def buildCollection(inetref, language):
    collection = Collection(inetref)
    tree = etree.XML(u'<metadata></metadata>')
    m = VideoMetadata()
    m.collectionref = str(collection.id)
    m.title = collection.name
    if collection.backdrop:
        m.images.append({'type':'fanart', 'url':collection.backdrop.geturl(),
                  'thumb':collection.backdrop.geturl(collection.backdrop.sizes()[0])})
    if collection.poster:
        m.images.append({'type':'coverart', 'url':collection.poster.geturl(),
                  'thumb':collection.poster.geturl(collection.poster.sizes()[0])})
    tree.append(m.toXML())
    sys.stdout.write(etree.tostring(tree, encoding='UTF-8', pretty_print=True))
    sys.exit()
Example #6
0
def buildSingle(inetref):
    movie = Movie(inetref)
    tree = etree.XML(u'<metadata></metadata>')
    mapping = [['runtime',      'runtime'],     ['title',       'originaltitle'],
               ['releasedate',  'releasedate'], ['tagline',     'tagline'],
               ['description',  'overview'],    ['homepage',    'homepage'],
               ['userrating',   'userrating'],  ['popularity',  'popularity'],
               ['budget',       'budget'],      ['revenue',     'revenue']]
    m = VideoMetadata()
    for i,j in mapping:
        if getattr(movie, j):
            setattr(m, i, getattr(movie, j))
    m.inetref = str(movie.id)
    if movie.releasedate:
        m.year = movie.releasedate.year
    if movie.collection:
        m.collectionref = str(movie.collection.id)
    for country, release in movie.releases.items():
        if release.certification:
            m.certifications[country] = release.certification
    for genre in movie.genres:
        m.categories.append(genre.name)
    for studio in movie.studios:
        m.studios.append(studio.name)
    for country in movie.countries:
        m.countries.append(country.name)
    for cast in movie.cast:
        d = {'name':cast.name, 'character':cast.character, 'department':'Actors',
             'job':'Actor', 'url':'http://www.themoviedb.org/people/{0}'.format(cast.id)}
        if cast.profile: d['thumb'] = cast.profile.geturl()
        m.people.append(d)
    for crew in movie.crew:
        d = {'name':crew.name, 'job':crew.job, 'department':crew.department,
             'url':'http://www.themoviedb.org/people/{0}'.format(cast.id)}
        if crew.profile: d['thumb'] = crew.profile.geturl()
        m.people.append(d)
    for backdrop in movie.backdrops:
        m.images.append({'type':'fanart', 'url':backdrop.geturl(),
                        'thumb':backdrop.geturl(backdrop.sizes()[0])})
    for poster in movie.posters:
        m.images.append({'type':'coverart', 'url':poster.geturl(),
                        'thumb':poster.geturl(poster.sizes()[0])})
    tree.append(m.toXML())
    sys.stdout.write(etree.tostring(tree, encoding='UTF-8', pretty_print=True,
                                    xml_declaration=True))
    sys.exit()
Example #7
0
def buildList(query, language):
    results = searchMovie(query, language)
    tree = etree.XML(u'<metadata></metadata>')
    mapping = [['runtime',      'runtime'],     ['title',       'originaltitle'],
               ['releasedate',  'releasedate'], ['tagline',     'tagline'],
               ['description',  'overview'],    ['homepage',    'homepage'],
               ['userrating',   'userrating'],  ['popularity',  'popularity']]
    for res in results:
        m = VideoMetadata()
        for i,j in mapping:
            setattr(m, i, getattr(res, j))
        m.inetref = str(res.id)
        m.year = res.releasedate.year
        m.images.append({'type':'fanart', 'url':res.backdrop.geturl()})
        m.images.append({'type':'coverart', 'url':res.poster.geturl()})
        tree.append(m.toXML())
    sys.stdout.write(etree.tostring(tree, encoding='UTF-8', pretty_print=True))
    sys.exit(0)
Example #8
0
File: tmdb3.py Project: mdda/mythtv
def buildList(query, language):
    results = searchMovie(query, language)
    tree = etree.XML(u'<metadata></metadata>')
    mapping = [['runtime',      'runtime'],     ['title',       'originaltitle'],
               ['releasedate',  'releasedate'], ['tagline',     'tagline'],
               ['description',  'overview'],    ['homepage',    'homepage'],
               ['userrating',   'userrating'],  ['popularity',  'popularity']]
    for res in results:
        m = VideoMetadata()
        for i,j in mapping:
            setattr(m, i, getattr(res, j))
        m.inetref = str(res.id)
        m.year = res.releasedate.year
        m.images.append({'type':'fanart', 'url':res.backdrop.geturl()})
        m.images.append({'type':'coverart', 'url':res.poster.geturl()})
        tree.append(m.toXML())
    sys.stdout.write(etree.tostring(tree, encoding='UTF-8', pretty_print=True))
    sys.exit(0)
Example #9
0
def buildTVSeries(inetref, opts):

    from MythTV.tmdb3 import Series
    from MythTV import VideoMetadata
    from lxml import etree

    series = Series(inetref)

    mapping = [['language', 'original_language'], ['title', 'name'],
               ['inetref', 'id'], ['collectionref', 'id'],
               ['description', 'overview'], ['releasedate', 'first_air_date']]
    tree = etree.XML(u'<metadata></metadata>')
    m = VideoMetadata()
    for i, j in mapping:
        if getattr(series, j):
            setattr(m, i, getattr(series, j))

    # These need to be strings not ints
    m.inetref = str(series.id)
    m.collectionref = str(series.id)

    for genre in series.genres:
        m.categories.append(genre.name)

    if series.backdrop:
        b = series.backdrop
        m.images.append({
            'type': 'fanart',
            'url': b.geturl(),
            'thumb': b.geturl(b.sizes()[0])
        })
    if series.poster:
        p = series.poster
        m.images.append({
            'type': 'coverart',
            'url': p.geturl(),
            'thumb': p.geturl(p.sizes()[0])
        })
    tree.append(m.toXML())

    return etree.tostring(tree,
                          encoding='UTF-8',
                          pretty_print=True,
                          xml_declaration=True)
Example #10
0
def buildCollection(inetref, opts):
    from MythTV.tmdb3 import Collection
    from MythTV import VideoMetadata
    from lxml import etree

    collection = Collection(inetref)
    tree = etree.XML(u"<metadata></metadata>")
    m = VideoMetadata()
    m.collectionref = str(collection.id)
    m.title = collection.name
    if collection.backdrop:
        b = collection.backdrop
        m.images.append({"type": "fanart", "url": b.geturl(), "thumb": b.geturl(b.sizes()[0])})
    if collection.poster:
        p = collection.poster
        m.images.append({"type": "coverart", "url": p.geturl(), "thumb": p.geturl(p.sizes()[0])})
    tree.append(m.toXML())
    sys.stdout.write(etree.tostring(tree, encoding="UTF-8", pretty_print=True, xml_declaration=True))
    sys.exit()
Example #11
0
def buildList(query):
    # TEMPORARY FIX:
    # replace all dashes from queries to work around search behavior
    # as negative to all text that comes afterwards
    query = query.replace('-',' ')
    results = searchMovie(query)
    tree = etree.XML(u'<metadata></metadata>')
    mapping = [['runtime',      'runtime'],     ['title',       'originaltitle'],
               ['releasedate',  'releasedate'], ['tagline',     'tagline'],
               ['description',  'overview'],    ['homepage',    'homepage'],
               ['userrating',   'userrating'],  ['popularity',  'popularity']]

    count = 0
    for res in results:
        m = VideoMetadata()
        for i,j in mapping:
            if getattr(res, j):
                setattr(m, i, getattr(res, j))
        m.inetref = str(res.id)
        if res.releasedate:
            m.year = res.releasedate.year
        if res.backdrop:
            b = res.backdrop
            m.images.append({'type':'fanart', 'url':b.geturl(),
                             'thumb':b.geturl(b.sizes()[0])})
        if res.poster:
            p = res.poster
            m.images.append({'type':'coverart', 'url':p.geturl(),
                             'thumb':p.geturl(p.sizes()[0])})
        tree.append(m.toXML())
        count += 1
        if count >= 60:
            # page limiter, dont want to overload the server
            break

    sys.stdout.write(etree.tostring(tree, encoding='UTF-8', pretty_print=True,
                                    xml_declaration=True))
    sys.exit(0)
Example #12
0
def buildList(tvtitle, opts):
    # option -M title
    from lxml import etree
    from MythTV import VideoMetadata, datetime
    from MythTV.utility import levenshtein
    from MythTV.tvmaze import tvmaze_api as tvmaze
    from MythTV.tvmaze import locales

    # set the session
    if opts.session:
        tvmaze.set_session(opts.session)

    if opts.debug:
        print("Function 'buildList' called with argument '%s'" % tvtitle)

    showlist = tvmaze.search_show(tvtitle)

    if opts.debug:
        print("tvmaze.search_show(%s) returned :" % tvtitle)
        for l in showlist:
            print(l, type(l))
            for k, v in l.__dict__.items():
                print(k, " : ", v)

    tree = etree.XML(u'<metadata></metadata>')

    for show_info in showlist:
        m = VideoMetadata()
        m.title = check_item(m, ("title", show_info.name), ignore=False)
        m.description = check_item(m, ("description", show_info.summary))
        m.inetref = check_item(m, ("inetref", str(show_info.id)), ignore=False)
        m.collectionref = check_item(m, ("collectionref", str(show_info.id)),
                                     ignore=False)
        m.language = check_item(
            m,
            ("language", str(locales.Language.getstored(show_info.language))))
        m.userrating = check_item(m,
                                  ("userrating", show_info.rating['average']))
        try:
            m.popularity = check_item(m,
                                      ("popularity", float(show_info.weight)),
                                      ignore=False)
        except (TypeError, ValueError):
            pass
        if show_info.premiere_date:
            m.releasedate = check_item(
                m, ("releasedate", show_info.premiere_date))
            m.year = check_item(m, ("year", show_info.premiere_date.year))

        posterList, fanartList, bannerList = get_show_art_lists(show_info.id)

        # Generate one image line for each type of artwork
        if posterList:
            posterEntry = posterList[0]
            if (posterEntry[0] is not None) and (posterEntry[1] is not None):
                m.images.append({
                    'type': 'coverart',
                    'url': posterEntry[0],
                    'thumb': posterEntry[1]
                })
            elif posterEntry[0] is not None:
                m.images.append({'type': 'coverart', 'url': posterEntry[0]})

        if fanartList:
            fanartEntry = fanartList[0]
            if (fanartEntry[0] is not None) and (fanartEntry[1] is not None):
                m.images.append({
                    'type': 'fanart',
                    'url': fanartEntry[0],
                    'thumb': fanartEntry[1]
                })
            elif fanartEntry[0] is not None:
                m.images.append({'type': 'fanart', 'url': fanartEntry[0]})

        if bannerList:
            bannerEntry = bannerList[0]
            if (bannerEntry[0] is not None) and (bannerEntry[1] is not None):
                m.images.append({
                    'type': 'banner',
                    'url': bannerEntry[0],
                    'thumb': bannerEntry[1]
                })
            elif bannerEntry[0] is not None:
                m.images.append({'type': 'banner', 'url': bannerEntry[0]})

        tree.append(m.toXML())

    print_etree(
        etree.tostring(tree,
                       encoding='UTF-8',
                       pretty_print=True,
                       xml_declaration=True))
Example #13
0
def buildCollection(tvinetref, opts):
    # option -C inetref
    from lxml import etree
    from MythTV import VideoMetadata, datetime
    from MythTV.utility import levenshtein
    from MythTV.tvmaze import tvmaze_api as tvmaze
    from MythTV.tvmaze import locales

    # set the session
    if opts.session:
        tvmaze.set_session(opts.session)

    if opts.debug:
        print("Function 'buildCollection' called with argument '%s'" %
              tvinetref)

    show_info = tvmaze.get_show(tvinetref)
    if opts.debug:
        for k, v in show_info.__dict__.items():
            print(k, " : ", v)

    tree = etree.XML(u'<metadata></metadata>')
    m = VideoMetadata()
    m.title = check_item(m, ("title", show_info.name), ignore=False)
    m.description = check_item(m, ("description", show_info.summary))
    if show_info.genres is not None and len(show_info.genres) > 0:
        for g in show_info.genres:
            try:
                if g is not None and len(g) > 0:
                    m.categories.append(g)
            except:
                pass
    m.inetref = check_item(m, ("inetref", str(show_info.id)), ignore=False)
    m.collectionref = check_item(m, ("collectionref", str(show_info.id)),
                                 ignore=False)
    m.imdb = check_item(m, ("imdb", str(show_info.external_ids['imdb'])))
    m.language = check_item(
        m, ("language", str(locales.Language.getstored(show_info.language))))
    m.userrating = check_item(m, ("userrating", show_info.rating['average']))
    try:
        m.popularity = check_item(m, ("popularity", float(show_info.weight)),
                                  ignore=False)
    except (TypeError, ValueError):
        pass
    if show_info.premiere_date:
        m.releasedate = check_item(m, ("releasedate", show_info.premiere_date))
        m.year = check_item(m, ("year", show_info.premiere_date.year))
    try:
        sinfo = show_info.network['name']
        if sinfo is not None and len(sinfo) > 0:
            m.studios.append(sinfo)
    except:
        pass

    posterList, fanartList, bannerList = get_show_art_lists(show_info.id)

    # Generate image lines for every piece of artwork
    for posterEntry in posterList:
        if (posterEntry[0] is not None) and (posterEntry[1] is not None):
            m.images.append({
                'type': 'coverart',
                'url': posterEntry[0],
                'thumb': posterEntry[1]
            })
        elif posterEntry[0] is not None:
            m.images.append({'type': 'coverart', 'url': posterEntry[0]})

    for fanartEntry in fanartList:
        if (fanartEntry[0] is not None) and (fanartEntry[1] is not None):
            m.images.append({
                'type': 'fanart',
                'url': fanartEntry[0],
                'thumb': fanartEntry[1]
            })
        elif fanartEntry[0] is not None:
            m.images.append({'type': 'fanart', 'url': fanartEntry[0]})

    for bannerEntry in bannerList:
        if (bannerEntry[0] is not None) and (bannerEntry[1] is not None):
            m.images.append({
                'type': 'banner',
                'url': bannerEntry[0],
                'thumb': bannerEntry[1]
            })
        elif bannerEntry[0] is not None:
            m.images.append({'type': 'banner', 'url': bannerEntry[0]})

    tree.append(m.toXML())

    print_etree(
        etree.tostring(tree,
                       encoding='UTF-8',
                       pretty_print=True,
                       xml_declaration=True))
Example #14
0
def buildSingle(inetref, opts):
    from MythTV.tmdb3.tmdb_exceptions import TMDBRequestInvalid
    from MythTV.tmdb3 import Movie, get_locale
    from MythTV import VideoMetadata
    from lxml import etree

    import locale as py_locale
    import re

    if re.match('^0[0-9]{6}$', inetref):
        movie = Movie.fromIMDB(inetref)
    else:
        movie = Movie(inetref)

    tree = etree.XML(u'<metadata></metadata>')
    mapping = [['runtime', 'runtime'], ['title', 'originaltitle'],
               ['releasedate', 'releasedate'], ['tagline', 'tagline'],
               ['description', 'overview'], ['homepage', 'homepage'],
               ['userrating', 'userrating'], ['popularity', 'popularity'],
               ['budget', 'budget'], ['revenue', 'revenue']]
    m = VideoMetadata()
    for i, j in mapping:
        try:
            if getattr(movie, j):
                setattr(m, i, getattr(movie, j))
        except TMDBRequestInvalid:
            return etree.tostring(tree,
                                  encoding='UTF-8',
                                  pretty_print=True,
                                  xml_declaration=True)

    if movie.title:
        m.title = movie.title

    releases = list(movie.releases.items())

    # get the release date for the wanted country
    # TODO if that is not part of the reply use the primary release date (Primary=true)
    # if that is not part of the reply use whatever release date is first in list
    # if there is not a single release date in the reply, then leave it empty
    if len(releases) > 0:
        if opts.country:
            # resort releases with selected country at top to ensure it
            # is selected by the metadata libraries
            r = list(zip(*releases))
            if opts.country in r[0]:
                index = r[0].index(opts.country)
                releases.insert(0, releases.pop(index))

        m.releasedate = releases[0][1].releasedate

    m.inetref = str(movie.id)
    if movie.collection:
        m.collectionref = str(movie.collection.id)
    if m.releasedate:
        m.year = m.releasedate.year
    for country, release in releases:
        if release.certification:
            m.certifications[country] = release.certification
    for genre in movie.genres:
        m.categories.append(genre.name)
    for studio in movie.studios:
        m.studios.append(studio.name)
    for country in movie.countries:
        m.countries.append(country.name)
    for cast in movie.cast:
        d = {
            'name': cast.name,
            'character': cast.character,
            'department': 'Actors',
            'job': 'Actor',
            'url': 'http://www.themoviedb.org/people/{0}'.format(cast.id)
        }
        if cast.profile: d['thumb'] = cast.profile.geturl()
        m.people.append(d)
    for crew in movie.crew:
        d = {
            'name': crew.name,
            'job': crew.job,
            'department': crew.department,
            'url': 'http://www.themoviedb.org/people/{0}'.format(crew.id)
        }
        if crew.profile: d['thumb'] = crew.profile.geturl()
        m.people.append(d)
    for backdrop in movie.backdrops:
        m.images.append({
            'type': 'fanart',
            'url': backdrop.geturl(),
            'thumb': backdrop.geturl(backdrop.sizes()[0]),
            'height': str(backdrop.height),
            'width': str(backdrop.width)
        })

    # tmdb already sorts the posters by language
    # if no poster of given language was found,
    # try to sort by system language and then by language "en"
    system_language = py_locale.getdefaultlocale()[0].split("_")[0]
    locale_language = get_locale().language
    if opts.debug:
        print("system_language : ", system_language)
        print("locale_language : ", locale_language)

    loc_posters = movie.posters
    if loc_posters[0].language != locale_language \
                    and locale_language != system_language:
        if opts.debug:
            print(
                "1: No poster found for language '%s', trying to sort posters by '%s' :"
                % (locale_language, system_language))
        loc_posters = sorted(movie.posters,
                             key=lambda x: x.language == system_language,
                             reverse=True)

    if loc_posters[0].language != system_language \
                    and loc_posters[0].language != locale_language:
        if opts.debug:
            print(
                "2: No poster found for language '%s', trying to sort posters by '%s' :"
                % (system_language, "en"))
        loc_posters = sorted(movie.posters,
                             key=lambda x: x.language == "en",
                             reverse=True)

    for poster in loc_posters:
        if opts.debug:
            print("Poster : ", poster.language, " | ", poster.userrating,
                  "\t | ", poster.geturl())
        m.images.append({
            'type': 'coverart',
            'url': poster.geturl(),
            'thumb': poster.geturl(poster.sizes()[0]),
            'height': str(poster.height),
            'width': str(poster.width)
        })

    tree.append(m.toXML())
    return etree.tostring(tree,
                          encoding='UTF-8',
                          pretty_print=True,
                          xml_declaration=True)
Example #15
0
def buildList(query, opts):
    # TEMPORARY FIX:
    # replace all dashes from queries to work around search behavior
    # as negative to all text that comes afterwards
    query = query.replace('-',' ')
    query = query.strip() # trim extra whitespace
    # extract year from name -- note that we require a space before the year
    # so we don't confuse movie names for years (example: "2012 - 2009",
    # a 2009 movie); also note that we accept optional paranthesis around
    # the year:
    yearRegex = re.compile(r"\s\(?((19|20)[0-9]{2})\)?$")
    year = yearRegex.search(query)
    if year is not None:
        year = year.group(1)
    # if no year was found, we'll pass year=None to searchMovie,
    # which is the default anyway

    # get rid of the year (if any) from the query text, because
    # it causes bad TMDB results
    query = yearRegex.sub("", query)
    query = query.strip()

    from MythTV.tmdb3 import searchMovie
    from MythTV import VideoMetadata
    from lxml import etree
    results = iter(searchMovie(query, locale=None, adult=False, year=year))
    tree = etree.XML(u'<metadata></metadata>')
    mapping = [['runtime',      'runtime'],     ['title',       'originaltitle'],
               ['releasedate',  'releasedate'], ['tagline',     'tagline'],
               ['description',  'overview'],    ['homepage',    'homepage'],
               ['userrating',   'userrating'],  ['popularity',  'popularity']]

    count = 0
    while True:
        try:
            res = results.next()
        except StopIteration:
            # end of results
            break
        except IndexError:
            # unexpected end of results
            # we still want to return whatever we have so far
            break

        if res is None:
            # faulty data, skip it and continue
            continue

        m = VideoMetadata()
        for i,j in mapping:
            if getattr(res, j):
                setattr(m, i, getattr(res, j))
        m.inetref = str(res.id)

        if res.title:
            m.title = res.title

        #TODO:
        # should releasedate and year be pulled from the country-specific data
        # or should it be left to the default information to cut down on
        # traffic from searches
        if res.releasedate:
            m.year = res.releasedate.year
        if res.backdrop:
            b = res.backdrop
            m.images.append({'type':'fanart', 'url':b.geturl(),
                             'thumb':b.geturl(b.sizes()[0])})
        if res.poster:
            p = res.poster
            m.images.append({'type':'coverart', 'url':p.geturl(),
                             'thumb':p.geturl(p.sizes()[0])})
        tree.append(m.toXML())
        count += 1
        if count >= 60:
            # page limiter, dont want to overload the server
            break

    sys.stdout.write(etree.tostring(tree, encoding='UTF-8', pretty_print=True,
                                    xml_declaration=True))
    sys.exit(0)
Example #16
0
def buildEpisode(args, opts):

    query = args[0]

    from MythTV.tmdb3 import Series, Season, Episode
    from MythTV import VideoMetadata
    from lxml import etree
    from MythTV.tmdb3 import searchSeries

    if query.isnumeric():
        inetref = query
    else:
        results = searchSeries(query)
        series = results[0]
        inetref = str(series.id)

    series = Series(inetref)
    season_number = series.number_of_seasons
    episode_number = None
    subtitle = None
    if len(args) == 2:
        subtitle = args[1]
    elif len(args) == 3:
        season_number = int(args[1])
        episode_number = int(args[2])

    episode = None
    # process seasons backwards because it is more likely
    # that you have a recent one than an old one
    while season_number > 0:
        season = Season(inetref, str(season_number))
        if episode_number:
            episode = season.episodes[episode_number]
            break
        for ep_num, ep in season.episodes.items():
            if ep.name == subtitle:
                episode = ep
                episode_number = int(ep_num)
                break
        if episode:
            break
        season_number = season_number - 1

    if not episode_number and not episode:
        sys.stdout.write('ERROR: Episode not found: ' + str(args))
        return 9

    # reload episode with full details
    episode = Episode(inetref, season_number, episode_number)

    tree = etree.XML(u'<metadata></metadata>')
    mapping = [['subtitle', 'name'], ['description', 'overview'],
               ['season', 'season_number'], ['episode', 'episode_number'],
               ['releasedate', 'air_date']]
    m = VideoMetadata()
    m.title = series.name
    for i, j in mapping:
        if getattr(episode, j):
            setattr(m, i, getattr(episode, j))

    # These need to be strings not ints
    m.inetref = inetref
    m.collectionref = inetref

    for cast in episode.cast:
        d = {
            'name': cast.name,
            'character': cast.character,
            'department': 'Actors',
            'job': 'Actor',
            'url': 'http://www.themoviedb.org/people/{0}'.format(cast.id)
        }
        if cast.profile: d['thumb'] = cast.profile.geturl()
        m.people.append(d)
    for crew in episode.crew:
        d = {
            'name': crew.name,
            'job': crew.job,
            'department': crew.department,
            'url': 'http://www.themoviedb.org/people/{0}'.format(crew.id)
        }
        if crew.profile: d['thumb'] = crew.profile.geturl()
        m.people.append(d)
    for guest in episode.guest_stars:
        d = {
            'name': guest.name,
            'job': "Guest Star",
            'url': 'http://www.themoviedb.org/people/{0}'.format(guest.id)
        }
        if guest.profile: d['thumb'] = guest.profile.geturl()
        m.people.append(d)
    if episode.still:
        b = episode.still
        m.images.append({
            'type': 'screenshot',
            'url': b.geturl(),
            'thumb': b.geturl(b.sizes()[0])
        })
    if season.poster:
        p = season.poster
        m.images.append({
            'type': 'coverart',
            'url': p.geturl(),
            'thumb': p.geturl(p.sizes()[0])
        })
    m.language = series.original_language
    if series.backdrop:
        b = series.backdrop
        m.images.append({
            'type': 'fanart',
            'url': b.geturl(),
            'thumb': b.geturl(b.sizes()[0])
        })
    for genre in series.genres:
        m.categories.append(genre.name)

    tree.append(m.toXML())

    return etree.tostring(tree,
                          encoding='UTF-8',
                          pretty_print=True,
                          xml_declaration=True)
Example #17
0
def buildTVList(query, opts):
    from MythTV.tmdb3 import searchSeries
    from MythTV import VideoMetadata
    from lxml import etree
    from datetime import date

    resultsx = searchSeries(query)
    results = iter(resultsx)  # searchSeries(query))
    mapping = [['language', 'original_language'], ['title', 'name'],
               ['inetref', 'id'], ['collectionref', 'id'],
               ['description', 'overview'], ['releasedate', 'first_air_date']]
    tree = etree.XML(u'<metadata></metadata>')

    count = 0
    while True:
        try:
            res = next(results)
        except StopIteration:
            # end of results
            break
        except IndexError:
            # unexpected end of results
            # we still want to return whatever we have so far
            break

        if res is None:
            # faulty data, skip it and continue
            continue

        m = VideoMetadata()
        for i, j in mapping:
            if getattr(res, j):
                setattr(m, i, getattr(res, j))

        # These need to be strings not ints
        m.inetref = str(res.id)
        m.collectionref = str(res.id)

        if res.backdrop:
            b = res.backdrop
            m.images.append({
                'type': 'fanart',
                'url': b.geturl(),
                'thumb': b.geturl(b.sizes()[0])
            })
        if res.poster:
            p = res.poster
            m.images.append({
                'type': 'coverart',
                'url': p.geturl(),
                'thumb': p.geturl(p.sizes()[0])
            })
        tree.append(m.toXML())
        count += 1
        if count >= 60:
            # page limiter, dont want to overload the server
            break

    return etree.tostring(tree,
                          encoding='UTF-8',
                          pretty_print=True,
                          xml_declaration=True)
Example #18
0
def buildSingle(inetref, opts):
    from MythTV.tmdb3 import Movie
    from MythTV import VideoMetadata
    from lxml import etree

    import re
    if re.match('^0[0-9]{6}$', inetref):
        movie = Movie.fromIMDB(inetref)
    else:
        movie = Movie(inetref)

    tree = etree.XML(u'<metadata></metadata>')
    mapping = [['runtime',      'runtime'],     ['title',       'originaltitle'],
               ['releasedate',  'releasedate'], ['tagline',     'tagline'],
               ['description',  'overview'],    ['homepage',    'homepage'],
               ['userrating',   'userrating'],  ['popularity',  'popularity'],
               ['budget',       'budget'],      ['revenue',     'revenue']]
    m = VideoMetadata()
    for i,j in mapping:
        if getattr(movie, j):
            setattr(m, i, getattr(movie, j))

    if movie.title:
        m.title = movie.title

    releases = movie.releases.items()

    if opts.country:
        try:
            # resort releases with selected country at top to ensure it
            # is selected by the metadata libraries
            index = zip(*releases)[0].index(opts.country)
            releases.insert(0, releases.pop(index))
        except ValueError:
            pass
        else:
            m.releasedate = releases[0][1].releasedate

    m.inetref = str(movie.id)
    if movie.collection:
        m.collectionref = str(movie.collection.id)
    if movie.releasedate:
        m.year = movie.releasedate.year
    for country, release in releases:
        if release.certification:
            m.certifications[country] = release.certification
    for genre in movie.genres:
        m.categories.append(genre.name)
    for studio in movie.studios:
        m.studios.append(studio.name)
    for country in movie.countries:
        m.countries.append(country.name)
    for cast in movie.cast:
        d = {'name':cast.name, 'character':cast.character, 'department':'Actors',
             'job':'Actor', 'url':'http://www.themoviedb.org/people/{0}'.format(cast.id)}
        if cast.profile: d['thumb'] = cast.profile.geturl()
        m.people.append(d)
    for crew in movie.crew:
        d = {'name':crew.name, 'job':crew.job, 'department':crew.department,
             'url':'http://www.themoviedb.org/people/{0}'.format(crew.id)}
        if crew.profile: d['thumb'] = crew.profile.geturl()
        m.people.append(d)
    for backdrop in movie.backdrops:
        m.images.append({'type':'fanart', 'url':backdrop.geturl(),
                        'thumb':backdrop.geturl(backdrop.sizes()[0]),
                        'height':str(backdrop.height),
                        'width':str(backdrop.width)})
    for poster in movie.posters:
        m.images.append({'type':'coverart', 'url':poster.geturl(),
                        'thumb':poster.geturl(poster.sizes()[0]),
                        'height':str(poster.height),
                        'width':str(poster.width)})
    tree.append(m.toXML())
    sys.stdout.write(etree.tostring(tree, encoding='UTF-8', pretty_print=True,
                                    xml_declaration=True))
    sys.exit()
Example #19
0
    def _format_xml(self, ser_x, sea_x=None, epi_x=None):
        m = VideoMetadata()
        m.inetref = check_item(m, ("inetref", str(ser_x.id)), ignore=False)
        # try to get title and description for the preferred language list:
        # note: there could be a title but no description:
        #       $ ttvdb4.py -l ja -C 360893 --debug

        # get series name and overview:
        ser_title, desc = self._get_info_from_translations(ser_x.fetched_translations)
        if not ser_title:
            ser_title = ser_x.name
        m.title = check_item(m, ("title", ser_title), ignore=False)

        # get subtitle and overview:
        if epi_x:
            sub_title, sub_desc = self._get_info_from_translations(epi_x.fetched_translations)
            if not sub_title:
                sub_title = epi_x.name
            m.subtitle = check_item(m, ("subtitle", sub_title), ignore=False)
            if sub_desc:
                desc = sub_desc
            m.season = check_item(m, ("season", epi_x.seasonNumber), ignore=False)
            m.episode = check_item(m, ("episode", epi_x.number), ignore=False)
            m.runtime = check_item(m, ("runtime", epi_x.runtime), ignore=True)
        desc = strip_tags(desc).replace("\r\n", "").replace("\n", "")
        m.description = check_item(m, ("description", desc))

        try:
            if ser_x.originalLanguage:
                lang = ser_x.originalLanguage
            else:
                lang = self.language
            if ser_x.originalCountry:
                country = ser_x.originalCountry
            else:
                country = ser_x.country
            m.language = check_item(m, ("language", Language.getstored(lang).ISO639_1))
            if country:
                m.countries.append(country.upper())  # could be 'None'
            m.year = check_item(m, ('year', int(ser_x.firstAired.split('-')[0])))
            m.userrating = check_item(m, ('userrating', ser_x.score))
            for h in [x.id for x in ser_x.remoteIds if x.type == 4]:
                # type 4 is 'Official Website'
                m.homepage = check_item(m, ('homepage', h))
                # MythTV supports only one entry
                break
        except:
            # considered as nice to have
            pass

        # add categories:
        try:
            for genre in ser_x.genres:
                if genre.name:
                    m.categories.append(genre.name)
        except:
            pass

        # add optional fields:
        if epi_x:
            try:
                # add studios
                for c in epi_x.companies:
                    m.studios.append(c.name)
            except:
                pass
            try:
                # add IMDB reference
                for r in epi_x.remoteIds:
                    if r.sourceName == 'IMDB':
                        m.imdb = check_item(m, ('imdb', r.id))
                        break
            except:
                raise
            if self.country:
                try:
                    # add certificates:
                    area = Country.getstored(self.country).alpha3
                    for c in epi_x.contentRatings:
                        if c.country.lower() == area.lower():
                            m.certifications[self.country] = c.name
                            break
                except:
                    pass

        if self.ShowPeople:
            # add characters: see class 'People'
            # characters of type 'Actor' are sorted in ascending order
            actors = [c for c in ser_x.characters if c.type == People.Actor]
            actors_sorted = sort_list_by_key(actors, "sort", 99, reverse=False)
            # prefer actors that are sorted, i.e.: 'sort' > 0
            actors_s_1 = [x for x in actors_sorted if x.sort > 0]
            # append the rest, i.e.: actors with sort == 0
            actors_s_1.extend([x for x in actors_sorted if x.sort == 0])
            m.people.extend(self._get_crew_for_xml(actors_s_1, 'Actor', list_character=True))

            # on episodes, characters of type 'Guest Star' are sorted in ascending order
            if epi_x:
                guests = [c for c in epi_x.characters if c.type == People.Guest_Star]
                guests_sorted = sort_list_by_key(guests, "sort", 99, reverse=False)
                m.people.extend(self._get_crew_for_xml(guests_sorted, 'Guest Star'))

                directors = [c for c in epi_x.characters if c.type == People.Showrunner]
                directors_sorted = sort_list_by_key(directors, "sort", 99, reverse=False)
                m.people.extend(self._get_crew_for_xml(directors_sorted, 'Director'))

        # no we have all extended records for series, season, episode, create xml for them
        series_banners = []; season_banners = []
        series_posters = []; season_posters = []
        series_fanarts = []; season_fanarts = []

        # add the artworks, season preferred
        #        art_name     what        art_type(s)   from_r / from_a
        arts = [('coverart', season_posters, (7,),   sea_x, sea_x.artwork if sea_x else []),
                ('coverart', series_posters, (2,),   ser_x, ser_x.artworks),
                ('fanart',   season_fanarts, (8, 9), sea_x, sea_x.artwork if sea_x else []),
                ('fanart',   series_fanarts, (3, 4), ser_x, ser_x.artworks),
                ('banner',   season_banners, (6,),   sea_x, sea_x.artwork if sea_x else []),
                ('banner',   series_banners, (1,),   ser_x, ser_x.artworks),
                ]
        # avoid duplicates
        used_urls = []
        for (art_name, what, art_types, from_r, from_a) in arts:
            artlist = [art for art in from_a if art.type in art_types]
            what.extend(sort_list_by_lang(artlist, self.languagelist, other_key='score'))
            for entry in what:
                try:
                    if entry.image not in used_urls:
                        used_urls.append(entry.image)
                        m.images.append({'type': art_name, 'url': entry.image,
                                         'thumb': entry.thumbnail})
                except:
                    pass
        if epi_x and epi_x.imageType in (11, 12):
            m.images.append({'type': 'screenshot', 'url': epi_x.image})

        self.tree.append(m.toXML())
Example #20
0
def buildSingle(inetref, opts):
    from MythTV.tmdb3.tmdb_exceptions import TMDBRequestInvalid
    from MythTV.tmdb3 import Movie, ReleaseType, get_locale
    from MythTV import VideoMetadata
    from lxml import etree

    import locale as py_locale
    import re

    if re.match('^0[0-9]{6}$', inetref):
        movie = Movie.fromIMDB(inetref)
    else:
        movie = Movie(inetref)

    tree = etree.XML('<metadata></metadata>')
    mapping = [['runtime', 'runtime'], ['title', 'originaltitle'],
               ['releasedate', 'releasedate'], ['tagline', 'tagline'],
               ['description', 'overview'], ['homepage', 'homepage'],
               ['userrating', 'userrating'], ['popularity', 'popularity'],
               ['budget', 'budget'], ['revenue', 'revenue']]
    m = VideoMetadata()
    for i, j in mapping:
        try:
            if getattr(movie, j):
                setattr(m, i, getattr(movie, j))
        except TMDBRequestInvalid:
            return etree.tostring(tree,
                                  encoding='UTF-8',
                                  pretty_print=True,
                                  xml_declaration=True)

    if movie.title:
        m.title = movie.title

    if movie.releasedate:
        m.releasedate = movie.releasedate

    releases = list(movie.cert_releases.items())

    if len(releases) > 0:
        if opts.country:
            # resort releases with selected country at top to ensure it
            # is selected by the metadata libraries
            r = list(zip(*releases))
            if opts.country in r[0]:
                index = r[0].index(opts.country)
                releases.insert(0, releases.pop(index))
                r_dates_country = releases[0][1].cert_release_dates
                r_types_country = [x.releasetype for x in r_dates_country]
                # from the mailing list:
                # https://www.themoviedb.org/talk/585ad032925141724d0514f4
                # sort order for release dates: 2, 3, 1, min (4 ,5, 6)
                sorted_dates = []
                for rt in [
                        ReleaseType.Theatrical_limited,  # 2
                        ReleaseType.Theatrical,  # 3
                        ReleaseType.Premiere,  # 1
                        ReleaseType.Digital,  # 4
                        ReleaseType.Physical,  # 5
                        ReleaseType.TV
                ]:  # 6
                    if rt in r_types_country:
                        r_index = r_types_country.index(rt)
                        sorted_dates.append(
                            r_dates_country[r_index].releasedate)
                        if rt < ReleaseType.Digital:
                            break
                if len(sorted_dates) > 0:
                    m.releasedate = min(sorted_dates)

    m.inetref = str(movie.id)
    if movie.collection:
        m.collectionref = str(movie.collection.id)
    if m.releasedate:
        m.year = m.releasedate.year
    for country, releaseitem in releases:
        if releaseitem.cert_release_dates[0].certification:
            m.certifications[country] = releaseitem.cert_release_dates[
                0].certification
    for genre in movie.genres:
        m.categories.append(genre.name)
    for studio in movie.studios:
        m.studios.append(studio.name)
    for country in movie.countries:
        m.countries.append(country.name)
    for cast in movie.cast:
        d = {
            'name': cast.name,
            'character': cast.character,
            'department': 'Actors',
            'job': 'Actor',
            'url': 'http://www.themoviedb.org/people/{0}'.format(cast.id)
        }
        if cast.profile: d['thumb'] = cast.profile.geturl()
        m.people.append(d)
    for crew in movie.crew:
        d = {
            'name': crew.name,
            'job': crew.job,
            'department': crew.department,
            'url': 'http://www.themoviedb.org/people/{0}'.format(crew.id)
        }
        if crew.profile: d['thumb'] = crew.profile.geturl()
        m.people.append(d)
    for backdrop in movie.backdrops:
        m.images.append({
            'type': 'fanart',
            'url': backdrop.geturl(),
            'thumb': backdrop.geturl(backdrop.sizes()[0]),
            'height': str(backdrop.height),
            'width': str(backdrop.width)
        })

    # tmdb already sorts the posters by language
    # if no poster of given language was found,
    # try to sort by system language and then by language "en"
    system_language = py_locale.getdefaultlocale()[0].split("_")[0]
    system_country = py_locale.getdefaultlocale()[0].split("_")[1]
    locale_language = get_locale().language
    locale_country = get_locale().country
    if opts.debug:
        print("system_language : ", system_language)
        print("locale_language : ", locale_language)
        print("system_country  : ", system_country)
        print("locale_country  : ", locale_country)

    loc_posters = movie.posters
    if len(loc_posters) and loc_posters[0].language != locale_language \
                    and locale_language != system_language:
        if opts.debug:
            print(
                "1: No poster found for language '%s', trying to sort posters by '%s' :"
                % (locale_language, system_language))
        loc_posters = sorted(movie.posters,
                             key=lambda x: x.language == system_language,
                             reverse=True)

    if len(loc_posters) and loc_posters[0].language != system_language \
                    and loc_posters[0].language != locale_language:
        if opts.debug:
            print(
                "2: No poster found for language '%s', trying to sort posters by '%s' :"
                % (system_language, "en"))
        loc_posters = sorted(movie.posters,
                             key=lambda x: x.language == "en",
                             reverse=True)

    for poster in loc_posters:
        if opts.debug:
            print("Poster : ", poster.language, " | ", poster.userrating,
                  "\t | ", poster.geturl())
        m.images.append({
            'type': 'coverart',
            'url': poster.geturl(),
            'thumb': poster.geturl(poster.sizes()[0]),
            'height': str(poster.height),
            'width': str(poster.width)
        })

    tree.append(m.toXML())
    return etree.tostring(tree,
                          encoding='UTF-8',
                          pretty_print=True,
                          xml_declaration=True)
Example #21
0
def buildList(query, opts):
    # TEMPORARY FIX:
    # replace all dashes from queries to work around search behavior
    # as negative to all text that comes afterwards
    query = query.replace('-', ' ')

    from MythTV.tmdb3 import searchMovie
    from MythTV import VideoMetadata
    from lxml import etree
    results = iter(searchMovie(query))
    tree = etree.XML(u'<metadata></metadata>')
    mapping = [['runtime', 'runtime'], ['title', 'originaltitle'],
               ['releasedate', 'releasedate'], ['tagline', 'tagline'],
               ['description', 'overview'], ['homepage', 'homepage'],
               ['userrating', 'userrating'], ['popularity', 'popularity']]

    count = 0
    while True:
        try:
            res = next(results)
        except StopIteration:
            # end of results
            break
        except IndexError:
            # unexpected end of results
            # we still want to return whatever we have so far
            break

        if res is None:
            # faulty data, skip it and continue
            continue

        m = VideoMetadata()
        for i, j in mapping:
            if getattr(res, j):
                setattr(m, i, getattr(res, j))
        m.inetref = str(res.id)

        if res.title:
            m.title = res.title

        #TODO:
        # should releasedate and year be pulled from the country-specific data
        # or should it be left to the default information to cut down on
        # traffic from searches
        if res.releasedate:
            m.year = res.releasedate.year
        if res.backdrop:
            b = res.backdrop
            m.images.append({
                'type': 'fanart',
                'url': b.geturl(),
                'thumb': b.geturl(b.sizes()[0])
            })
        if res.poster:
            p = res.poster
            m.images.append({
                'type': 'coverart',
                'url': p.geturl(),
                'thumb': p.geturl(p.sizes()[0])
            })
        tree.append(m.toXML())
        count += 1
        if count >= 60:
            # page limiter, dont want to overload the server
            break

    print_etree(
        etree.tostring(tree,
                       encoding='UTF-8',
                       pretty_print=True,
                       xml_declaration=True))
    sys.exit(0)
Example #22
0
def buildSingle(inetref, opts):
    from MythTV.tmdb3.tmdb_exceptions import TMDBRequestInvalid
    from MythTV.tmdb3 import Movie
    from MythTV import VideoMetadata
    from lxml import etree

    import re
    if re.match('^0[0-9]{6}$', inetref):
        movie = Movie.fromIMDB(inetref)
    else:
        movie = Movie(inetref)

    tree = etree.XML(u'<metadata></metadata>')
    mapping = [['runtime', 'runtime'], ['title', 'originaltitle'],
               ['releasedate', 'releasedate'], ['tagline', 'tagline'],
               ['description', 'overview'], ['homepage', 'homepage'],
               ['userrating', 'userrating'], ['popularity', 'popularity'],
               ['budget', 'budget'], ['revenue', 'revenue']]
    m = VideoMetadata()
    for i, j in mapping:
        try:
            if getattr(movie, j):
                setattr(m, i, getattr(movie, j))
        except TMDBRequestInvalid:
            print_etree(
                etree.tostring(tree,
                               encoding='UTF-8',
                               pretty_print=True,
                               xml_declaration=True))
            sys.exit()

    if movie.title:
        m.title = movie.title

    releases = list(movie.releases.items())

    # get the release date for the wanted country
    # TODO if that is not part of the reply use the primary release date (Primary=true)
    # if that is not part of the reply use whatever release date is first in list
    # if there is not a single release date in the reply, then leave it empty
    if len(releases) > 0:
        if opts.country:
            # resort releases with selected country at top to ensure it
            # is selected by the metadata libraries
            r = list(zip(*releases))
            if opts.country in r[0]:
                index = r[0].index(opts.country)
                releases.insert(0, releases.pop(index))

        m.releasedate = releases[0][1].releasedate

    m.inetref = str(movie.id)
    if movie.collection:
        m.collectionref = str(movie.collection.id)
    if m.releasedate:
        m.year = m.releasedate.year
    for country, release in releases:
        if release.certification:
            m.certifications[country] = release.certification
    for genre in movie.genres:
        m.categories.append(genre.name)
    for studio in movie.studios:
        m.studios.append(studio.name)
    for country in movie.countries:
        m.countries.append(country.name)
    for cast in movie.cast:
        d = {
            'name': cast.name,
            'character': cast.character,
            'department': 'Actors',
            'job': 'Actor',
            'url': 'http://www.themoviedb.org/people/{0}'.format(cast.id)
        }
        if cast.profile: d['thumb'] = cast.profile.geturl()
        m.people.append(d)
    for crew in movie.crew:
        d = {
            'name': crew.name,
            'job': crew.job,
            'department': crew.department,
            'url': 'http://www.themoviedb.org/people/{0}'.format(crew.id)
        }
        if crew.profile: d['thumb'] = crew.profile.geturl()
        m.people.append(d)
    for backdrop in movie.backdrops:
        m.images.append({
            'type': 'fanart',
            'url': backdrop.geturl(),
            'thumb': backdrop.geturl(backdrop.sizes()[0]),
            'height': str(backdrop.height),
            'width': str(backdrop.width)
        })
    for poster in movie.posters:
        m.images.append({
            'type': 'coverart',
            'url': poster.geturl(),
            'thumb': poster.geturl(poster.sizes()[0]),
            'height': str(poster.height),
            'width': str(poster.width)
        })
    tree.append(m.toXML())
    print_etree(
        etree.tostring(tree,
                       encoding='UTF-8',
                       pretty_print=True,
                       xml_declaration=True))
    sys.exit()
Example #23
0
def buildSingle(inetref, opts):
    from MythTV.tmdb3 import Movie
    from MythTV import VideoMetadata
    from lxml import etree

    import re

    if re.match("^0[0-9]{6}$", inetref):
        movie = Movie.fromIMDB(inetref)
    else:
        movie = Movie(inetref)

    tree = etree.XML(u"<metadata></metadata>")
    mapping = [
        ["runtime", "runtime"],
        ["title", "originaltitle"],
        ["releasedate", "releasedate"],
        ["tagline", "tagline"],
        ["description", "overview"],
        ["homepage", "homepage"],
        ["userrating", "userrating"],
        ["popularity", "popularity"],
        ["budget", "budget"],
        ["revenue", "revenue"],
    ]
    m = VideoMetadata()
    for i, j in mapping:
        if getattr(movie, j):
            setattr(m, i, getattr(movie, j))

    if movie.title:
        m.title = movie.title

    releases = movie.releases.items()

    if opts.country:
        try:
            # resort releases with selected country at top to ensure it
            # is selected by the metadata libraries
            index = zip(*releases)[0].index(opts.country)
            releases.insert(0, releases.pop(index))
        except ValueError:
            pass
        else:
            m.releasedate = releases[0][1].releasedate

    m.inetref = str(movie.id)
    if movie.collection:
        m.collectionref = str(movie.collection.id)
    if movie.releasedate:
        m.year = movie.releasedate.year
    for country, release in releases:
        if release.certification:
            m.certifications[country] = release.certification
    for genre in movie.genres:
        m.categories.append(genre.name)
    for studio in movie.studios:
        m.studios.append(studio.name)
    for country in movie.countries:
        m.countries.append(country.name)
    for cast in movie.cast:
        d = {
            "name": cast.name,
            "character": cast.character,
            "department": "Actors",
            "job": "Actor",
            "url": "http://www.themoviedb.org/people/{0}".format(cast.id),
        }
        if cast.profile:
            d["thumb"] = cast.profile.geturl()
        m.people.append(d)
    for crew in movie.crew:
        d = {
            "name": crew.name,
            "job": crew.job,
            "department": crew.department,
            "url": "http://www.themoviedb.org/people/{0}".format(crew.id),
        }
        if crew.profile:
            d["thumb"] = crew.profile.geturl()
        m.people.append(d)
    for backdrop in movie.backdrops:
        m.images.append({"type": "fanart", "url": backdrop.geturl(), "thumb": backdrop.geturl(backdrop.sizes()[0])})
    for poster in movie.posters:
        m.images.append({"type": "coverart", "url": poster.geturl(), "thumb": poster.geturl(poster.sizes()[0])})
    tree.append(m.toXML())
    sys.stdout.write(etree.tostring(tree, encoding="UTF-8", pretty_print=True, xml_declaration=True))
    sys.exit()