facade.py 7.47 KB
Newer Older
richardARPANET's avatar
richardARPANET committed
1 2 3
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals

richardARPANET's avatar
richardARPANET committed
4 5 6 7
import re

from dateutil.parser import parse

richardARPANET's avatar
richardARPANET committed
8
from .imdbpie import Imdb
9
from .objects import (
richardARPANET's avatar
richardARPANET committed
10 11
    Title, TitleEpisodes, Name, TitleName, Image, TitleRelease,
    TitleSearchResult, NameSearchResult,
12
)
richardARPANET's avatar
richardARPANET committed
13

14
REGEX_IMDB_ID = re.compile(r'([a-zA-Z]{2}[0-9]{7})')
richardARPANET's avatar
richardARPANET committed
15 16 17 18


class ImdbFacade(object):

richardARPANET's avatar
richardARPANET committed
19 20
    def __init__(self, client=None):
        self._client = client or Imdb()
richardARPANET's avatar
richardARPANET committed
21 22

    def get_title(self, imdb_id):
richardARPANET's avatar
richardARPANET committed
23
        title_data, title_aux_data = self._get_title_data(imdb_id=imdb_id)
richardARPANET's avatar
richardARPANET committed
24 25 26 27
        try:
            runtime = title_aux_data['runningTimes'][0]['timeMinutes']
        except (KeyError, IndexError):
            runtime = None
28 29 30 31 32 33 34 35 36 37
        try:
            episodes = TitleEpisodes(facade=self, imdb_id=imdb_id)
        except LookupError:
            episodes = ()
        try:
            season = title_aux_data['season']
            episode = title_aux_data['episode']
        except KeyError:
            season = None
            episode = None
richardARPANET's avatar
richardARPANET committed
38
        return Title(
richardARPANET's avatar
richardARPANET committed
39 40
            season=season, episode=episode, episodes=episodes,
            runtime=runtime, **title_data
richardARPANET's avatar
richardARPANET committed
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

    def get_name(self, imdb_id):
        name_data = self._client.get_name(imdb_id=imdb_id)
        name = name_data['base']['name']
        imdb_id = self._parse_id(name_data['base']['id'])

        try:
            image_data = name_data['base']['image']
            image = Image(
                url=image_data['url'],
                height=image_data['height'],
                width=image_data['width'],
            )
        except KeyError:
            image = None

        gender = name_data['base']['gender'].lower()
        date_of_birth = parse(name_data['base']['birthDate']).date()
        birth_place = name_data['base']['birthPlace']
        try:
            bios = tuple(b['text'] for b in name_data['base']['miniBios'])
        except KeyError:
            bios = ()

        filmography_data = self._client.get_name_filmography(imdb_id)
        filmography = tuple(
            self._parse_id(f['id']) for f in filmography_data['filmography']
richardARPANET's avatar
richardARPANET committed
69
        )
70 71 72 73
        return Name(
            name=name, imdb_id=imdb_id, date_of_birth=date_of_birth,
            gender=gender, birth_place=birth_place, bios=bios, image=image,
            filmography=filmography,
richardARPANET's avatar
richardARPANET committed
74 75
        )

richardARPANET's avatar
richardARPANET committed
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
    def search_for_name(self, query):
        results = []
        for result in self._client.search_for_name(query):
            result = NameSearchResult(
                imdb_id=result['imdb_id'], name=result['name'],
            )
            results.append(result)
        return tuple(results)

    def search_for_title(self, query):
        results = []
        for result in self._client.search_for_title(query):
            if result['year']:
                year = int(result['year'])
            else:
                year = None
            result = TitleSearchResult(
                imdb_id=result['imdb_id'], title=result['title'],
                type=result['type'], year=year,
            )
            results.append(result)
        return tuple(results)

richardARPANET's avatar
richardARPANET committed
99 100 101 102 103 104
    def _get_writers(self, top_crew_data):
        return tuple(
            TitleName(
                name=i['name'],
                job=i.get('job'),
                category=i.get('category'),
105
                imdb_id=self._parse_id(i['id'])
richardARPANET's avatar
richardARPANET committed
106 107 108
            ) for i in top_crew_data['writers']
        )

109 110 111 112 113 114 115 116 117 118 119
    def _get_stars(self, principals_data):
        return tuple(
            TitleName(
                name=i['name'],
                job=i.get('job'),
                characters=tuple(i.get('characters', ())),
                category=i.get('category'),
                imdb_id=self._parse_id(i['id'])
            ) for i in principals_data
        )

richardARPANET's avatar
richardARPANET committed
120 121 122 123 124 125
    def _get_creators(self, top_crew_data):
        return tuple(
            TitleName(
                name=i['name'],
                job=i.get('job'),
                category=i.get('category'),
126
                imdb_id=self._parse_id(i['id'])
richardARPANET's avatar
richardARPANET committed
127 128 129 130 131 132 133 134 135 136
            ) for i in top_crew_data['writers']
            if i.get('job') == 'creator'
        )

    def _get_directors(self, top_crew_data):
        return tuple(
            TitleName(
                name=i['name'],
                job=i.get('job'),
                category=i.get('category'),
137
                imdb_id=self._parse_id(i['id'])
richardARPANET's avatar
richardARPANET committed
138 139 140 141 142
            ) for i in top_crew_data['directors']
        )

    def _get_credits(self, credits_data):
        credits = []
143
        for category in credits_data.get('credits', ()):
richardARPANET's avatar
richardARPANET committed
144 145 146 147 148
            for item in credits_data['credits'][category]:
                credits.append(TitleName(
                    name=item['name'],
                    category=item.get('category'),
                    job=item.get('job'),
149
                    imdb_id=self._parse_id(item['id'])
richardARPANET's avatar
richardARPANET committed
150 151
                ))
        return tuple(credits)
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230

    def _parse_id(self, string):
        return REGEX_IMDB_ID.findall(string)[0]

    def _get_title_data(self, imdb_id):
        base_title_data = self._client.get_title(imdb_id=imdb_id)
        top_crew_data = self._client.get_title_top_crew(imdb_id=imdb_id)
        title_aux_data = self._client.get_title_auxiliary(imdb_id=imdb_id)
        credits_data = self._client.get_title_credits(imdb_id=imdb_id)

        title = base_title_data['base']['title']
        year = base_title_data['base'].get('year')
        try:
            rating = float(base_title_data['ratings']['rating'])
        except KeyError:
            rating = None
        type_ = base_title_data['base']['titleType'].lower()

        try:
            releases_data = self._client.get_title_releases(imdb_id=imdb_id)
        except LookupError:
            release_date = None
            releases = ()
        else:
            release_date = parse(releases_data['releases'][0]['date']).date()
            releases = tuple(
                TitleRelease(date=parse(r['date']).date(), region=r['region'])
                for r in releases_data['releases']
            )

        try:
            rating_count = base_title_data['ratings']['ratingCount']
        except KeyError:
            rating_count = 0

        try:
            plot_outline = base_title_data['plot']['outline']['text']
        except KeyError:
            plot_outline = None

        writers = self._get_writers(top_crew_data)
        directors = self._get_directors(top_crew_data)
        creators = self._get_creators(top_crew_data)
        genres = tuple(g.lower() for g in title_aux_data['genres'])
        credits = self._get_credits(credits_data)

        try:
            certification = title_aux_data['certificate']['certificate']
        except TypeError:
            certification = None
        stars = self._get_stars(title_aux_data['principals'])
        try:
            image_data = title_aux_data['image']
            image = Image(
                url=image_data['url'],
                height=image_data['height'],
                width=image_data['width'],
            )
        except KeyError:
            image = None
        return dict(
            imdb_id=imdb_id,
            title=title,
            year=year,
            rating=rating,
            type=type_,
            release_date=release_date,
            releases=releases,
            plot_outline=plot_outline,
            rating_count=rating_count,
            writers=writers,
            directors=directors,
            creators=creators,
            genres=genres,
            credits=credits,
            certification=certification,
            image=image,
            stars=stars,
        ), title_aux_data