1# Copyright 2004-2019 Davide Alberani <da@erlug.linux.it>
2#
3# This program is free software; you can redistribute it and/or modify
4# it under the terms of the GNU General Public License as published by
5# the Free Software Foundation; either version 2 of the License, or
6# (at your option) any later version.
7#
8# This program is distributed in the hope that it will be useful,
9# but WITHOUT ANY WARRANTY; without even the implied warranty of
10# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11# GNU General Public License for more details.
12#
13# You should have received a copy of the GNU General Public License
14# along with this program; if not, write to the Free Software
15# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
17"""
18This module provides the Person class, used to store information about
19a given person.
20"""
21
22from __future__ import absolute_import, division, print_function, unicode_literals
23
24from copy import deepcopy
25
26from imdb.utils import _Container, analyze_name, build_name, cmpPeople, flatten, normalizeName, canonicalName
27
28
29class Person(_Container):
30    """A Person.
31
32    Every information about a person can be accessed as::
33
34        personObject['information']
35
36    to get a list of the kind of information stored in a
37    Person object, use the keys() method; some useful aliases
38    are defined (as "biography" for the "mini biography" key);
39    see the keys_alias dictionary.
40    """
41    # The default sets of information retrieved.
42    default_info = ('main', 'filmography', 'biography')
43
44    # Aliases for some not-so-intuitive keys.
45    keys_alias = {
46        'biography': 'mini biography',
47        'bio': 'mini biography',
48        'aka': 'akas',
49        'also known as': 'akas',
50        'nick name': 'nick names',
51        'nicks': 'nick names',
52        'nickname': 'nick names',
53        'nicknames': 'nick names',
54        'miscellaneouscrew': 'miscellaneous crew',
55        'crewmembers': 'miscellaneous crew',
56        'misc': 'miscellaneous crew',
57        'guest': 'notable tv guest appearances',
58        'guests': 'notable tv guest appearances',
59        'tv guest': 'notable tv guest appearances',
60        'guest appearances': 'notable tv guest appearances',
61        'spouses': 'spouse',
62        'salary': 'salary history',
63        'salaries': 'salary history',
64        'otherworks': 'other works',
65        "maltin's biography": "biography from leonard maltin's movie encyclopedia",
66        "leonard maltin's biography": "biography from leonard maltin's movie encyclopedia",
67        'real name': 'birth name',
68        'where are they now': 'where now',
69        'personal quotes': 'quotes',
70        'mini-biography author': 'imdb mini-biography by',
71        'biography author': 'imdb mini-biography by',
72        'genre': 'genres',
73        'portrayed': 'portrayed in',
74        'keys': 'keywords',
75        'trademarks': 'trade mark',
76        'trade mark': 'trade mark',
77        'trade marks': 'trade mark',
78        'trademark': 'trade mark',
79        'pictorials': 'pictorial',
80        'magazine covers': 'magazine cover photo',
81        'magazine-covers': 'magazine cover photo',
82        'tv series episodes': 'episodes',
83        'tv-series episodes': 'episodes',
84        'articles': 'article',
85        'keyword': 'keywords'
86    }
87
88    # 'nick names'???
89    keys_tomodify_list = (
90        'mini biography', 'spouse', 'quotes', 'other works',
91        'salary history', 'trivia', 'trade mark', 'news',
92        'books', 'biographical movies', 'portrayed in',
93        'where now', 'interviews', 'article',
94        "biography from leonard maltin's movie encyclopedia"
95    )
96
97    _image_key = 'headshot'
98
99    cmpFunct = cmpPeople
100
101    def _init(self, **kwds):
102        """Initialize a Person object.
103
104        *personID* -- the unique identifier for the person.
105        *name* -- the name of the Person, if not in the data dictionary.
106        *myName* -- the nickname you use for this person.
107        *myID* -- your personal id for this person.
108        *data* -- a dictionary used to initialize the object.
109        *currentRole* -- a Character instance representing the current role
110                         or duty of a person in this movie, or a Person
111                         object representing the actor/actress who played
112                         a given character in a Movie.  If a string is
113                         passed, an object is automatically build.
114        *roleID* -- if available, the characterID/personID of the currentRole
115                    object.
116        *roleIsPerson* -- when False (default) the currentRole is assumed
117                          to be a Character object, otherwise a Person.
118        *notes* -- notes about the given person for a specific movie
119                    or role (e.g.: the alias used in the movie credits).
120        *accessSystem* -- a string representing the data access system used.
121        *titlesRefs* -- a dictionary with references to movies.
122        *namesRefs* -- a dictionary with references to persons.
123        *modFunct* -- function called returning text fields.
124        *billingPos* -- position of this person in the credits list.
125        """
126        name = kwds.get('name')
127        if name and 'name' not in self.data:
128            self.set_name(name)
129        self.personID = kwds.get('personID', None)
130        self.myName = kwds.get('myName', '')
131        self.billingPos = kwds.get('billingPos', None)
132
133    def _reset(self):
134        """Reset the Person object."""
135        self.personID = None
136        self.myName = ''
137        self.billingPos = None
138
139    def _clear(self):
140        """Reset the dictionary."""
141        self.billingPos = None
142
143    def set_name(self, name):
144        """Set the name of the person."""
145        d = analyze_name(name, canonical=False)
146        self.data.update(d)
147
148    def _additional_keys(self):
149        """Valid keys to append to the data.keys() list."""
150        addkeys = []
151        if 'name' in self.data:
152            addkeys += ['canonical name', 'long imdb name',
153                        'long imdb canonical name']
154        if 'headshot' in self.data:
155            addkeys += ['full-size headshot']
156        return addkeys
157
158    def _getitem(self, key):
159        """Handle special keys."""
160        if 'name' in self.data:
161            if key == 'name':
162                return normalizeName(self.data['name'])
163            elif key == 'canonical name':
164                return canonicalName(self.data['name'])
165            elif key == 'long imdb name':
166                return build_name(self.data, canonical=False)
167            elif key == 'long imdb canonical name':
168                return build_name(self.data, canonical=True)
169        if key == 'full-size headshot':
170            return self.get_fullsizeURL()
171        elif key not in self.data and key in self.data.get('filmography', {}):
172            return self.data['filmography'][key]
173        return None
174
175    def getID(self):
176        """Return the personID."""
177        return self.personID
178
179    def __bool__(self):
180        """The Person is "false" if the self.data does not contain a name."""
181        # XXX: check the name and the personID?
182        return 'name' in self.data
183
184    def __contains__(self, item):
185        """Return true if this Person has worked in the given Movie,
186        or if the fiven Character was played by this Person."""
187        from .Movie import Movie
188        from .Character import Character
189        if isinstance(item, Movie):
190            for m in flatten(self.data, yieldDictKeys=True, scalar=Movie):
191                if item.isSame(m):
192                    return True
193        elif isinstance(item, Character):
194            for m in flatten(self.data, yieldDictKeys=True, scalar=Movie):
195                if item.isSame(m.currentRole):
196                    return True
197        elif isinstance(item, str):
198            return item in self.data
199        return False
200
201    def isSameName(self, other):
202        """Return true if two persons have the same name and imdbIndex
203        and/or personID.
204        """
205        if not isinstance(other, self.__class__):
206            return False
207        if 'name' in self.data and \
208                'name' in other.data and \
209                build_name(self.data, canonical=True) == \
210                build_name(other.data, canonical=True):
211            return True
212        if self.accessSystem == other.accessSystem and \
213                self.personID and self.personID == other.personID:
214            return True
215        return False
216
217    isSamePerson = isSameName   # XXX: just for backward compatiblity.
218
219    def __deepcopy__(self, memo):
220        """Return a deep copy of a Person instance."""
221        p = Person(name='', personID=self.personID, myName=self.myName,
222                   myID=self.myID, data=deepcopy(self.data, memo),
223                   currentRole=deepcopy(self.currentRole, memo),
224                   roleIsPerson=self._roleIsPerson,
225                   notes=self.notes, accessSystem=self.accessSystem,
226                   titlesRefs=deepcopy(self.titlesRefs, memo),
227                   namesRefs=deepcopy(self.namesRefs, memo),
228                   charactersRefs=deepcopy(self.charactersRefs, memo))
229        p.current_info = list(self.current_info)
230        p.set_mod_funct(self.modFunct)
231        p.billingPos = self.billingPos
232        return p
233
234    def __repr__(self):
235        """String representation of a Person object."""
236        # XXX: add also currentRole and notes, if present?
237        return '<Person id:%s[%s] name:_%s_>' % (
238            self.personID, self.accessSystem, self.get('long imdb name')
239        )
240
241    def __str__(self):
242        """Simply print the short name."""
243        return self.get('name', '')
244
245    def summary(self):
246        """Return a string with a pretty-printed summary for the person."""
247        if not self:
248            return ''
249        s = 'Person\n=====\nName: %s\n' % self.get('long imdb canonical name', '')
250        bdate = self.get('birth date')
251        if bdate:
252            s += 'Birth date: %s' % bdate
253            bnotes = self.get('birth notes')
254            if bnotes:
255                s += ' (%s)' % bnotes
256            s += '.\n'
257        ddate = self.get('death date')
258        if ddate:
259            s += 'Death date: %s' % ddate
260            dnotes = self.get('death notes')
261            if dnotes:
262                s += ' (%s)' % dnotes
263            s += '.\n'
264        bio = self.get('mini biography')
265        if bio:
266            s += 'Biography: %s\n' % bio[0]
267        director = self.get('director')
268        if director:
269            d_list = [x.get('long imdb canonical title', '') for x in director[:3]]
270            s += 'Last movies directed: %s.\n' % '; '.join(d_list)
271        act = self.get('actor') or self.get('actress')
272        if act:
273            a_list = [x.get('long imdb canonical title', '') for x in act[:5]]
274            s += 'Last movies acted: %s.\n' % '; '.join(a_list)
275        return s
276