Rename NetflixSession.parse_season_entry() to _parse_season_entry()...
[plugin.video.netflix.git] / resources / lib / NetflixSession.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 # Module: NetflixSession
4 # Created on: 13.01.2017
5
6 import os
7 import json
8 from requests import session, cookies
9 from urllib import quote, unquote
10 from time import time
11 from base64 import urlsafe_b64encode
12 from bs4 import BeautifulSoup, SoupStrainer
13 from utils import noop, get_user_agent_for_current_platform
14 try:
15    import cPickle as pickle
16 except:
17    import pickle
18
19 class NetflixSession:
20     """Helps with login/session management of Netflix users & API data fetching"""
21
22     base_url = 'https://www.netflix.com'
23     """str: Secure Netflix url"""
24
25     urls = {
26         'login': '/login',
27         'browse': '/profiles/manage',
28         'video_list_ids': '/preflight',
29         'shakti': '/pathEvaluator',
30         'profiles':  '/profiles/manage',
31         'switch_profiles': '/profiles/switch',
32         'adult_pin': '/pin/service',
33         'metadata': '/metadata',
34         'set_video_rating': '/setVideoRating',
35         'update_my_list': '/playlistop',
36         'kids': '/Kids'
37     }
38     """:obj:`dict` of :obj:`str` List of all static endpoints for HTML/JSON POST/GET requests"""
39
40     video_list_keys = ['user', 'genres', 'recommendations']
41     """:obj:`list` of :obj:`str` Divide the users video lists into 3 different categories (for easier digestion)"""
42
43     profiles = {}
44     """:obj:`dict`
45         Dict of user profiles, user id is the key:
46
47         "72ERT45...": {
48             "profileName": "username",
49             "avatar": "http://..../avatar.png",
50             "id": "72ERT45...",
51             "isAccountOwner": False,
52             "isActive": True,
53             "isFirstUse": False
54         }
55     """
56
57     user_data = {}
58     """:obj:`dict`
59         dict of user data (used for authentication):
60
61         {
62             "guid": "72ERT45...",
63             "authURL": "145637....",
64             "gpsModel": "harris"
65         }
66     """
67
68     api_data = {}
69     """:obj:`dict`
70         dict of api data (used to build up the api urls):
71
72         {
73             "API_BASE_URL": "/shakti",
74             "API_ROOT": "https://www.netflix.com/api",
75             "BUILD_IDENTIFIER": "113b89c9", "
76             ICHNAEA_ROOT": "/ichnaea"
77         }
78     """
79
80     esn = ''
81     """str: ESN - something like: NFCDCH-MC-D7D6F54LOPY8J416T72MQXX3RD20ME"""
82
83     def __init__(self, cookie_path, data_path, verify_ssl=True, log_fn=noop):
84         """Stores the cookie path for later use & instanciates a requests
85            session with a proper user agent & stored cookies/data if available
86
87         Parameters
88         ----------
89         cookie_path : :obj:`str`
90             Cookie location
91
92         data_path : :obj:`str`
93             User data cache location
94
95         log_fn : :obj:`fn`
96              optional log function
97         """
98         self.cookie_path = cookie_path
99         self.data_path = data_path
100         self.verify_ssl = verify_ssl
101         self.log = log_fn
102
103         # start session, fake chrome on the current platform (so that we get a proper widevine esn) & enable gzip
104         self.session = session()
105         self.session.headers.update({
106             'User-Agent': get_user_agent_for_current_platform(),
107             'Accept-Encoding': 'gzip'
108         })
109
110     def parse_login_form_fields (self, form_soup):
111         """Fetches all the inputfields from the login form, so that we
112            can build a request with all the fields needed besides the known email & password ones
113
114         Parameters
115         ----------
116         form_soup : :obj:`BeautifulSoup`
117             Instance of an BeautifulSoup documet or node containing the login form
118
119         Returns
120         -------
121             :obj:`dict` of :obj:`str`
122                 Dictionary of all input fields with their name as the key & the default
123                 value from the form field
124         """
125         login_input_fields = {}
126         login_inputs = form_soup.find_all('input')
127         # gather all form fields, set an empty string as the default value
128         for item in login_inputs:
129             keys = dict(item.attrs).keys()
130             if 'name' in keys and 'value' not in keys:
131                 login_input_fields[item['name']] = ''
132             elif 'name' in keys and 'value' in keys:
133                 login_input_fields[item['name']] = item['value']
134         return login_input_fields
135
136     def extract_inline_netflix_page_data (self, page_soup):
137         """Extracts all <script/> tags from the given document and parses the contents of each one of `em.
138         The contents of the parsable tags looks something like this:
139             <script>window.netflix = window.netflix || {} ; netflix.notification = {"constants":{"sessionLength":30,"ownerToken":"ZDD...};</script>
140         We use a JS parser to generate an AST of the code given & then parse that AST into a python dict.
141         This should be okay, as we´re only interested in a few static values & put the rest aside
142
143         Parameters
144         ----------
145         page_soup : :obj:`BeautifulSoup`
146             Instance of an BeautifulSoup document or node containing the complete page contents
147         Returns
148         -------
149             :obj:`list` of :obj:`dict`
150                 List of all the serialized data pulled out of the pagws <script/> tags
151         """
152         scripts = page_soup.find_all('script', attrs={'src': None})
153         self.log(msg='Trying sloppy inline data parser')
154         inline_data = self._sloppy_parse_inline_data(scripts=scripts)
155         if self._verfify_auth_and_profiles_data(data=inline_data) != False:
156             self.log(msg='Sloppy inline data parsing successfull')
157             return inline_data
158         self.log(msg='Sloppy inline parser failed, trying JS parser')
159         return self._accurate_parse_inline_data(scripts=scripts)
160
161     def is_logged_in (self, account):
162         """Determines if a user is already logged in (with a valid cookie),
163            by fetching the index page with the current cookie & checking for the
164            `membership status` user data
165
166         Parameters
167         ----------
168         account : :obj:`dict` of :obj:`str`
169             Dict containing an email, country & a password property
170
171         Returns
172         -------
173         bool
174             User is already logged in (e.g. Cookie is valid) or not
175         """
176         is_logged_in = False
177         # load cookies
178         account_hash = self._generate_account_hash(account=account)
179         if self._load_cookies(filename=self.cookie_path + '_' + account_hash) == False:
180             return False
181         if self._load_data(filename=self.data_path + '_' + account_hash) == False:
182             # load the profiles page (to verify the user)
183             response = self._session_get(component='profiles')
184
185             # parse out the needed inline information
186             only_script_tags = SoupStrainer('script')
187             page_soup = BeautifulSoup(response.text, 'html.parser', parse_only=only_script_tags)
188             page_data = self._parse_page_contents(page_soup=page_soup)
189
190             # check if the cookie is still valid
191             for item in page_data:
192                 if 'profilesList' in dict(item).keys():
193                     if item['profilesList']['summary']['length'] >= 1:
194                         is_logged_in = True
195             return is_logged_in
196         return True
197
198     def logout (self):
199         """Delete all cookies and session data
200
201         Parameters
202         ----------
203         account : :obj:`dict` of :obj:`str`
204             Dict containing an email, country & a password property
205
206         """
207         self._delete_cookies(path=self.cookie_path)
208         self._delete_data(path=self.data_path)
209
210     def login (self, account):
211         """Try to log in a user with its credentials & stores the cookies if the action is successfull
212
213            Note: It fetches the HTML of the login page to extract the fields of the login form,
214            again, this is dirty, but as the fields & their values could change at any time, this
215            should be the most reliable way of retrieving the information
216
217         Parameters
218         ----------
219         account : :obj:`dict` of :obj:`str`
220             Dict containing an email, country & a password property
221
222         Returns
223         -------
224         bool
225             User could be logged in or not
226         """
227         response = self._session_get(component='login')
228         if response.status_code != 200:
229             return False;
230
231         # collect all the login fields & their contents and add the user credentials
232         page_soup = BeautifulSoup(response.text, 'html.parser')
233         login_form = page_soup.find(attrs={'class' : 'ui-label-text'}).findPrevious('form')
234         login_payload = self.parse_login_form_fields(form_soup=login_form)
235         if 'email' in login_payload:
236             login_payload['email'] = account['email']
237         if 'emailOrPhoneNumber' in login_payload:
238             login_payload['emailOrPhoneNumber'] = account['email']
239         login_payload['password'] = account['password']
240
241         # perform the login
242         login_response = self._session_post(component='login', data=login_payload)
243         login_soup = BeautifulSoup(login_response.text, 'html.parser')
244
245         # we know that the login was successfull if we find an HTML element with the class of 'profile-name'
246         if login_soup.find(attrs={'class' : 'profile-name'}) or login_soup.find(attrs={'class' : 'profile-icon'}):
247             # parse the needed inline information & store cookies for later requests
248             self._parse_page_contents(page_soup=login_soup)
249             account_hash = self._generate_account_hash(account=account)
250             self._save_cookies(filename=self.cookie_path + '_' + account_hash)
251             self._save_data(filename=self.data_path + '_' + account_hash)
252             return True
253         else:
254             return False
255
256     def switch_profile (self, profile_id, account):
257         """Switch the user profile based on a given profile id
258
259         Note: All available profiles & their ids can be found in the ´profiles´ property after a successfull login
260
261         Parameters
262         ----------
263         profile_id : :obj:`str`
264             User profile id
265
266         account : :obj:`dict` of :obj:`str`
267             Dict containing an email, country & a password property
268
269         Returns
270         -------
271         bool
272             User could be switched or not
273         """
274         payload = {
275             'switchProfileGuid': profile_id,
276             '_': int(time()),
277             'authURL': self.user_data['authURL']
278         }
279
280         response = self._session_get(component='switch_profiles', type='api', params=payload)
281         if response.status_code != 200:
282             return False
283
284         account_hash = self._generate_account_hash(account=account)
285         self.user_data['guid'] = profile_id;
286         return self._save_data(filename=self.data_path + '_' + account_hash)
287
288     def send_adult_pin (self, pin):
289         """Send the adult pin to Netflix in case an adult rated video requests it
290
291         Note: Once entered, it should last for the complete session (Not so sure about this)
292
293         Parameters
294         ----------
295         pin : :obj:`str`
296             The users adult pin
297
298         Returns
299         -------
300         bool
301             Pin was accepted or not
302         or
303         :obj:`dict` of :obj:`str`
304             Api call error
305         """
306         payload = {
307             'pin': pin,
308             'authURL': self.user_data['authURL']
309         }
310         response = self._session_get(component='adult_pin', params=payload)
311         pin_response = self._process_response(response=response, component=self._get_api_url_for(component='adult_pin'))
312         keys = pin_response.keys()
313         if 'success' in keys:
314             return True
315         if 'error' in keys:
316             return pin_response
317         return False
318
319     def add_to_list (self, video_id):
320         """Adds a video to "my list" on Netflix
321
322         Parameters
323         ----------
324         video_id : :obj:`str`
325             ID of th show/video/movie to be added
326
327         Returns
328         -------
329         bool
330             Adding was successfull
331         """
332         return self._update_my_list(video_id=video_id, operation='add')
333
334     def remove_from_list (self, video_id):
335         """Removes a video from "my list" on Netflix
336
337         Parameters
338         ----------
339         video_id : :obj:`str`
340             ID of th show/video/movie to be removed
341
342         Returns
343         -------
344         bool
345             Removing was successfull
346         """
347         return self._update_my_list(video_id=video_id, operation='remove')
348
349     def rate_video (self, video_id, rating):
350         """Rate a video on Netflix
351
352         Parameters
353         ----------
354         video_id : :obj:`str`
355             ID of th show/video/movie to be rated
356
357         rating : :obj:`int`
358             Rating, must be between 0 & 10
359
360         Returns
361         -------
362         bool
363             Rating successfull or not
364         """
365
366         # dirty rating validation
367         ratun = int(rating)
368         if rating > 10 or rating < 0:
369             return False
370
371         # In opposition to Kodi, Netflix uses a rating from 0 to in 0.5 steps
372         if rating != 0:
373             rating = rating / 2
374
375         headers = {
376             'Content-Type': 'application/json',
377             'Accept': 'application/json, text/javascript, */*',
378         }
379
380         params = {
381             'titleid': video_id,
382             'rating': rating
383         }
384
385         payload = json.dumps({
386             'authURL': self.user_data['authURL']
387         })
388
389         response = self._session_post(component='set_video_rating', type='api', params=params, headers=headers, data=payload)
390         return response.status_code == 200
391
392     def parse_video_list_ids (self, response_data):
393         """Parse the list of video ids e.g. rip out the parts we need
394
395         Parameters
396         ----------
397         response_data : :obj:`dict` of :obj:`str`
398             Parsed response JSON from the ´fetch_video_list_ids´ call
399
400         Returns
401         -------
402         :obj:`dict` of :obj:`dict`
403             Video list ids in the format:
404
405             {
406                 "genres": {
407                     "3589e2c6-ca3b-48b4-a72d-34f2c09ffbf4_11568367": {
408                         "displayName": "US-Serien",
409                         "id": "3589e2c6-ca3b-48b4-a72d-34f2c09ffbf4_11568367",
410                         "index": 3,
411                         "name": "genre",
412                         "size": 38
413                     },
414                     "3589e2c6-ca3b-48b4-a72d-34f2c09ffbf4_11568368": {
415                         "displayName": ...
416                     },
417                 },
418                 "user": {
419                     "3589e2c6-ca3b-48b4-a72d-34f2c09ffbf4_11568364": {
420                         "displayName": "Meine Liste",
421                         "id": "3589e2c6-ca3b-48b4-a72d-34f2c09ffbf4_11568364",
422                         "index": 0,
423                         "name": "queue",
424                         "size": 2
425                     },
426                     "3589e2c6-ca3b-48b4-a72d-34f2c09ffbf4_11568365": {
427                         "displayName": ...
428                     },
429                 },
430                 "recommendations": {
431                     "3589e2c6-ca3b-48b4-a72d-34f2c09ffbf4_11568382": {
432                         "displayName": "Passend zu Family Guy",
433                         "id": "3589e2c6-ca3b-48b4-a72d-34f2c09ffbf4_11568382",
434                         "index": 18,
435                         "name": "similars",
436                         "size": 33
437                     },
438                     "3589e2c6-ca3b-48b4-a72d-34f2c09ffbf4_11568397": {
439                         "displayName": ...
440                     }
441                 }
442             }
443         """
444         # prepare the return dictionary
445         video_list_ids = {}
446         for key in self.video_list_keys:
447             video_list_ids[key] = {}
448
449         # check if the list items are hidden behind a `value` sub key
450         # this is the case when we fetch the lists via POST, not via a GET preflight request
451         if 'value' in response_data.keys():
452             response_data = response_data['value']
453
454         # subcatogorize the lists by their context
455         video_lists = response_data['lists']
456         for video_list_id in video_lists.keys():
457             video_list = video_lists[video_list_id]
458             if video_list.get('context', False) != False:
459                 if video_list['context'] == 'genre':
460                     video_list_ids['genres'].update(self.parse_video_list_ids_entry(id=video_list_id, entry=video_list))
461                 elif video_list['context'] == 'similars' or video_list['context'] == 'becauseYouAdded':
462                     video_list_ids['recommendations'].update(self.parse_video_list_ids_entry(id=video_list_id, entry=video_list))
463                 else:
464                     video_list_ids['user'].update(self.parse_video_list_ids_entry(id=video_list_id, entry=video_list))
465         return video_list_ids
466
467     def parse_video_list_ids_entry (self, id, entry):
468         """Parse a video id entry e.g. rip out the parts we need
469
470         Parameters
471         ----------
472         response_data : :obj:`dict` of :obj:`str`
473             Dictionary entry from the ´fetch_video_list_ids´ call
474
475         Returns
476         -------
477         id : :obj:`str`
478             Unique id of the video list
479
480         entry : :obj:`dict` of :obj:`str`
481             Video list entry in the format:
482
483             "3589e2c6-ca3b-48b4-a72d-34f2c09ffbf4_11568382": {
484                 "displayName": "Passend zu Family Guy",
485                 "id": "3589e2c6-ca3b-48b4-a72d-34f2c09ffbf4_11568382",
486                 "index": 18,
487                 "name": "similars",
488                 "size": 33
489             }
490         """
491         return {
492             id: {
493                 'id': id,
494                 'index': entry['index'],
495                 'name': entry['context'],
496                 'displayName': entry['displayName'],
497                 'size': entry['length']
498             }
499         }
500
501     def parse_search_results (self, response_data):
502         """Parse the list of search results, rip out the parts we need
503            and extend it with detailed show informations
504
505         Parameters
506         ----------
507         response_data : :obj:`dict` of :obj:`str`
508             Parsed response JSON from the `fetch_search_results` call
509
510         Returns
511         -------
512         :obj:`dict` of :obj:`dict` of :obj:`str`
513             Search results in the format:
514
515             {
516                 "70136140": {
517                     "boxarts": "https://art-s.nflximg.net/0d7af/d5c72668c35d3da65ae031302bd4ae1bcc80d7af.jpg",
518                     "detail_text": "Die legend\u00e4re und mit 13 Emmys nominierte Serie von Gene Roddenberry inspirierte eine ganze Generation.",
519                     "id": "70136140",
520                     "season_id": "70109435",
521                     "synopsis": "Unter Befehl von Captain Kirk begibt sich die Besatzung des Raumschiffs Enterprise in die Tiefen des Weltraums, wo sie fremde Galaxien und neue Zivilisationen erforscht.",
522                     "title": "Star Trek",
523                     "type": "show"
524                 },
525                 "70158329": {
526                     "boxarts": ...
527                 }
528             }
529         """
530         search_results = {}
531         raw_search_results = response_data['value']['videos']
532         for entry_id in raw_search_results:
533             if self._is_size_key(key=entry_id) == False:
534                 # fetch information about each show & build up a proper search results dictionary
535                 show = self.parse_show_list_entry(id=entry_id, entry=raw_search_results[entry_id])
536                 show[entry_id].update(self.parse_show_information(id=entry_id, response_data=self.fetch_show_information(id=entry_id, type=show[entry_id]['type'])))
537                 search_results.update(show)
538         return search_results
539
540     def parse_show_list_entry (self, id, entry):
541         """Parse a show entry e.g. rip out the parts we need
542
543         Parameters
544         ----------
545         response_data : :obj:`dict` of :obj:`str`
546             Dictionary entry from the ´fetch_show_information´ call
547
548         id : :obj:`str`
549             Unique id of the video list
550
551         Returns
552         -------
553         entry : :obj:`dict` of :obj:`dict` of :obj:`str`
554             Show list entry in the format:
555
556             {
557                 "3589e2c6-ca3b-48b4-a72d-34f2c09ffbf4_11568382": {
558                     "id": "3589e2c6-ca3b-48b4-a72d-34f2c09ffbf4_11568382",
559                     "title": "Enterprise",
560                     "boxarts": "https://art-s.nflximg.net/.../smth.jpg",
561                     "type": "show"
562                 }
563             }
564         """
565         return {
566             id: {
567                 'id': id,
568                 'title': entry['title'],
569                 'boxarts': entry['boxarts']['_342x192']['jpg']['url'],
570                 'type': entry['summary']['type']
571             }
572         }
573
574     def parse_video_list (self, response_data):
575         """Parse a list of videos
576
577         Parameters
578         ----------
579         response_data : :obj:`dict` of :obj:`str`
580             Parsed response JSON from the `fetch_video_list` call
581
582         Returns
583         -------
584         :obj:`dict` of :obj:`dict`
585             Video list in the format:
586
587             {
588                 "372203": {
589                     "artwork": null,
590                     "boxarts": {
591                       "big": "https://art-s.nflximg.net/5e7d3/b3b48749843fd3a36db11c319ffa60f96b55e7d3.jpg",
592                       "small": "https://art-s.nflximg.net/57543/a039845c2eb9186dc26019576d895bf5a1957543.jpg"
593                     },
594                     "cast": [
595                       "Christine Elise",
596                       "Brad Dourif",
597                       "Grace Zabriskie",
598                       "Jenny Agutter",
599                       "John Lafia",
600                       "Gerrit Graham",
601                       "Peter Haskell",
602                       "Alex Vincent",
603                       "Beth Grant"
604                     ],
605                     "creators": [],
606                     "directors": [],
607                     "episode_count": null,
608                     "genres": [
609                       "Horrorfilme"
610                     ],
611                     "id": "372203",
612                     "in_my_list": true,
613                     "interesting_moment": "https://art-s.nflximg.net/09544/ed4b3073394b4469fb6ec22b9df81a4f5cb09544.jpg",
614                     "list_id": "9588df32-f957-40e4-9055-1f6f33b60103_46891306",
615                     "maturity": {
616                       "board": "FSK",
617                       "description": "Nur f\u00fcr Erwachsene geeignet.",
618                       "level": 1000,
619                       "value": "18"
620                     },
621                     "quality": "540",
622                     "rating": 3.1707757,
623                     "regular_synopsis": "Ein Spielzeughersteller erweckt aus Versehen die Seele der M\u00f6rderpuppe Chucky erneut zum Leben, die sich unmittelbar wieder ihren m\u00f6rderischen Aktivit\u00e4ten zuwendet.",
624                     "runtime": 5028,
625                     "seasons_count": null,
626                     "seasons_label": null,
627                     "synopsis": "Die allseits beliebte, von D\u00e4monen besessene M\u00f6rderpuppe ist wieder da und verbreitet erneut Horror und Schrecken.",
628                     "tags": [
629                       "Brutal",
630                       "Spannend"
631                     ],
632                     "title": "Chucky 2 \u2013 Die M\u00f6rderpuppe ist wieder da",
633                     "type": "movie",
634                     "watched": false,
635                     "year": 1990
636                 },
637                 "80011356": {
638                     "artwork": null,
639                     "boxarts": {
640                       "big": "https://art-s.nflximg.net/7c10d/5dcc3fc8f08487e92507627068cfe26ef727c10d.jpg",
641                       "small": "https://art-s.nflximg.net/5bc0e/f3be361b8c594929062f90a8d9c6eb57fb75bc0e.jpg"
642                     },
643                     "cast": [
644                       "Bjarne M\u00e4del"
645                     ],
646                     "creators": [],
647                     "directors": [
648                       "Arne Feldhusen"
649                     ],
650                     "episode_count": 24,
651                     "genres": [
652                       "Deutsche Serien",
653                       "Serien",
654                       "Comedyserien"
655                     ],
656                     "id": "80011356",
657                     "in_my_list": true,
658                     "interesting_moment": "https://art-s.nflximg.net/0188e/19cd705a71ee08c8d2609ae01cd8a97a86c0188e.jpg",
659                     "list_id": "9588df32-f957-40e4-9055-1f6f33b60103_46891306",
660                     "maturity": {
661                       "board": "FSF",
662                       "description": "Geeignet ab 12 Jahren.",
663                       "level": 80,
664                       "value": "12"
665                     },
666                     "quality": "720",
667                     "rating": 4.4394655,
668                     "regular_synopsis": "Comedy-Serie \u00fcber die Erlebnisse eines Tatortreinigers, der seine schmutzige Arbeit erst beginnen kann, wenn die Polizei die Tatortanalyse abgeschlossen hat.",
669                     "runtime": null,
670                     "seasons_count": 5,
671                     "seasons_label": "5 Staffeln",
672                     "synopsis": "In den meisten Krimiserien werden Mordf\u00e4lle auf faszinierende und spannende Weise gel\u00f6st. Diese Serie ist anders.",
673                     "tags": [
674                       "Zynisch"
675                     ],
676                     "title": "Der Tatortreiniger",
677                     "type": "show",
678                     "watched": false,
679                     "year": 2015
680                 },
681             }
682         """
683         video_list = {};
684         raw_video_list = response_data['value']
685         netflix_list_id = self.parse_netflix_list_id(video_list=raw_video_list);
686         for video_id in raw_video_list['videos']:
687             if self._is_size_key(key=video_id) == False:
688                 video_list.update(self.parse_video_list_entry(id=video_id, list_id=netflix_list_id, video=raw_video_list['videos'][video_id], persons=raw_video_list['person'], genres=raw_video_list['genres']))
689         return video_list
690
691     def parse_video_list_entry (self, id, list_id, video, persons, genres):
692         """Parse a video list entry e.g. rip out the parts we need
693
694         Parameters
695         ----------
696         id : :obj:`str`
697             Unique id of the video
698
699         list_id : :obj:`str`
700             Unique id of the containing list
701
702         video : :obj:`dict` of :obj:`str`
703             Video entry from the ´fetch_video_list´ call
704
705         persons : :obj:`dict` of :obj:`dict` of :obj:`str`
706             List of persons with reference ids
707
708         persons : :obj:`dict` of :obj:`dict` of :obj:`str`
709             List of genres with reference ids
710
711         Returns
712         -------
713         entry : :obj:`dict` of :obj:`dict` of :obj:`str`
714             Video list entry in the format:
715
716            {
717               "372203": {
718                 "artwork": null,
719                 "boxarts": {
720                   "big": "https://art-s.nflximg.net/5e7d3/b3b48749843fd3a36db11c319ffa60f96b55e7d3.jpg",
721                   "small": "https://art-s.nflximg.net/57543/a039845c2eb9186dc26019576d895bf5a1957543.jpg"
722                 },
723                 "cast": [
724                   "Christine Elise",
725                   "Brad Dourif",
726                   "Grace Zabriskie",
727                   "Jenny Agutter",
728                   "John Lafia",
729                   "Gerrit Graham",
730                   "Peter Haskell",
731                   "Alex Vincent",
732                   "Beth Grant"
733                 ],
734                 "creators": [],
735                 "directors": [],
736                 "episode_count": null,
737                 "genres": [
738                   "Horrorfilme"
739                 ],
740                 "id": "372203",
741                 "in_my_list": true,
742                 "interesting_moment": "https://art-s.nflximg.net/09544/ed4b3073394b4469fb6ec22b9df81a4f5cb09544.jpg",
743                 "list_id": "9588df32-f957-40e4-9055-1f6f33b60103_46891306",
744                 "maturity": {
745                   "board": "FSK",
746                   "description": "Nur f\u00fcr Erwachsene geeignet.",
747                   "level": 1000,
748                   "value": "18"
749                 },
750                 "quality": "540",
751                 "rating": 3.1707757,
752                 "regular_synopsis": "Ein Spielzeughersteller erweckt aus Versehen die Seele der M\u00f6rderpuppe Chucky erneut zum Leben, die sich unmittelbar wieder ihren m\u00f6rderischen Aktivit\u00e4ten zuwendet.",
753                 "runtime": 5028,
754                 "seasons_count": null,
755                 "seasons_label": null,
756                 "synopsis": "Die allseits beliebte, von D\u00e4monen besessene M\u00f6rderpuppe ist wieder da und verbreitet erneut Horror und Schrecken.",
757                 "tags": [
758                   "Brutal",
759                   "Spannend"
760                 ],
761                 "title": "Chucky 2 \u2013 Die M\u00f6rderpuppe ist wieder da",
762                 "type": "movie",
763                 "watched": false,
764                 "year": 1990
765               }
766             }
767         """
768         season_info = self.parse_season_information_for_video(video=video)
769         return {
770             id: {
771                 'id': id,
772                 'list_id': list_id,
773                 'title': video['title'],
774                 'synopsis': video['synopsis'],
775                 'regular_synopsis': video['regularSynopsis'],
776                 'type': video['summary']['type'],
777                 'rating': video['userRating'].get('average', 0) if video['userRating'].get('average', None) != None else video['userRating'].get('predicted', 0),
778                 'episode_count': season_info['episode_count'],
779                 'seasons_label': season_info['seasons_label'],
780                 'seasons_count': season_info['seasons_count'],
781                 'in_my_list': video['queue']['inQueue'],
782                 'year': video['releaseYear'],
783                 'runtime': self.parse_runtime_for_video(video=video),
784                 'watched': video['watched'],
785                 'tags': self.parse_tags_for_video(video=video),
786                 'genres': self.parse_genres_for_video(video=video, genres=genres),
787                 'quality': self.parse_quality_for_video(video=video),
788                 'cast': self.parse_cast_for_video(video=video, persons=persons),
789                 'directors': self.parse_directors_for_video(video=video, persons=persons),
790                 'creators': self.parse_creators_for_video(video=video, persons=persons),
791                 'maturity': {
792                     'board': None if 'board' not in video['maturity']['rating'].keys() else video['maturity']['rating']['board'],
793                     'value': None if 'value' not in video['maturity']['rating'].keys() else video['maturity']['rating']['value'],
794                     'description': None if 'maturityDescription' not in video['maturity']['rating'].keys() else video['maturity']['rating']['maturityDescription'],
795                     'level': None if 'maturityLevel' not in video['maturity']['rating'].keys() else video['maturity']['rating']['maturityLevel']
796                 },
797                 'boxarts': {
798                     'small': video['boxarts']['_342x192']['jpg']['url'],
799                     'big': video['boxarts']['_1280x720']['jpg']['url']
800                 },
801                 'interesting_moment': None if 'interestingMoment' not in video.keys() else video['interestingMoment']['_665x375']['jpg']['url'],
802                 'artwork': video['artWorkByType']['BILLBOARD']['_1280x720']['jpg']['url'],
803             }
804         }
805
806     def parse_creators_for_video (self, video, persons):
807         """Matches ids with person names to generate a list of creators
808
809         Parameters
810         ----------
811         video : :obj:`dict` of :obj:`str`
812             Dictionary entry for one video entry
813
814         persons : :obj:`dict` of :obj:`str`
815             Raw resposne of all persons delivered by the API call
816
817         Returns
818         -------
819         :obj:`list` of :obj:`str`
820             List of creators
821         """
822         creators = []
823         for person_key in dict(persons).keys():
824             if self._is_size_key(key=person_key) == False and person_key != 'summary':
825                 for creator_key in dict(video['creators']).keys():
826                     if self._is_size_key(key=creator_key) == False and creator_key != 'summary':
827                         if video['creators'][creator_key][1] == person_key:
828                             creators.append(persons[person_key]['name'])
829         return creators
830
831     def parse_directors_for_video (self, video, persons):
832         """Matches ids with person names to generate a list of directors
833
834         Parameters
835         ----------
836         video : :obj:`dict` of :obj:`str`
837             Dictionary entry for one video entry
838
839         persons : :obj:`dict` of :obj:`str`
840             Raw resposne of all persons delivered by the API call
841
842         Returns
843         -------
844         :obj:`list` of :obj:`str`
845             List of directors
846         """
847         directors = []
848         for person_key in dict(persons).keys():
849             if self._is_size_key(key=person_key) == False and person_key != 'summary':
850                 for director_key in dict(video['directors']).keys():
851                     if self._is_size_key(key=director_key) == False and director_key != 'summary':
852                         if video['directors'][director_key][1] == person_key:
853                             directors.append(persons[person_key]['name'])
854         return directors
855
856     def parse_cast_for_video (self, video, persons):
857         """Matches ids with person names to generate a list of cast members
858
859         Parameters
860         ----------
861         video : :obj:`dict` of :obj:`str`
862             Dictionary entry for one video entry
863
864         persons : :obj:`dict` of :obj:`str`
865             Raw resposne of all persons delivered by the API call
866
867         Returns
868         -------
869         :obj:`list` of :obj:`str`
870             List of cast members
871         """
872         cast = []
873         for person_key in dict(persons).keys():
874             if self._is_size_key(key=person_key) == False and person_key != 'summary':
875                 for cast_key in dict(video['cast']).keys():
876                     if self._is_size_key(key=cast_key) == False and cast_key != 'summary':
877                         if video['cast'][cast_key][1] == person_key:
878                             cast.append(persons[person_key]['name'])
879         return cast
880
881     def parse_genres_for_video (self, video, genres):
882         """Matches ids with genre names to generate a list of genres for a video
883
884         Parameters
885         ----------
886         video : :obj:`dict` of :obj:`str`
887             Dictionary entry for one video entry
888
889         genres : :obj:`dict` of :obj:`str`
890             Raw resposne of all genres delivered by the API call
891
892         Returns
893         -------
894         :obj:`list` of :obj:`str`
895             List of genres
896         """
897         video_genres = []
898         for genre_key in dict(genres).keys():
899             if self._is_size_key(key=genre_key) == False and genre_key != 'summary':
900                 for show_genre_key in dict(video['genres']).keys():
901                     if self._is_size_key(key=show_genre_key) == False and show_genre_key != 'summary':
902                         if video['genres'][show_genre_key][1] == genre_key:
903                             video_genres.append(genres[genre_key]['name'])
904         return video_genres
905
906     def parse_tags_for_video (self, video):
907         """Parses a nested list of tags, removes the not needed meta information & returns a raw string list
908
909         Parameters
910         ----------
911         video : :obj:`dict` of :obj:`str`
912             Dictionary entry for one video entry
913
914         Returns
915         -------
916         :obj:`list` of :obj:`str`
917             List of tags
918         """
919         tags = []
920         for tag_key in dict(video['tags']).keys():
921             if self._is_size_key(key=tag_key) == False and tag_key != 'summary':
922                 tags.append(video['tags'][tag_key]['name'])
923         return tags
924
925     def parse_season_information_for_video (self, video):
926         """Checks if the fiven video is a show (series) and returns season & episode information
927
928         Parameters
929         ----------
930         video : :obj:`dict` of :obj:`str`
931             Dictionary entry for one video entry
932
933         Returns
934         -------
935         :obj:`dict` of :obj:`str`
936             Episode count / Season Count & Season label if given
937         """
938         season_info = {
939             'episode_count': None,
940             'seasons_label': None,
941             'seasons_count': None
942         }
943         if video['summary']['type'] == 'show':
944             season_info = {
945                 'episode_count': video['episodeCount'],
946                 'seasons_label': video['numSeasonsLabel'],
947                 'seasons_count': video['seasonCount']
948             }
949         return season_info
950
951     def parse_quality_for_video (self, video):
952         """Transforms Netflix quality information in video resolution info
953
954         Parameters
955         ----------
956         video : :obj:`dict` of :obj:`str`
957             Dictionary entry for one video entry
958
959         Returns
960         -------
961         :obj:`str`
962             Quality of the video
963         """
964         quality = '720'
965         if video['videoQuality']['hasHD']:
966             quality = '1080'
967         if video['videoQuality']['hasUltraHD']:
968             quality = '4000'
969         return quality
970
971     def parse_runtime_for_video (self, video):
972         """Checks if the video is a movie & returns the runtime if given
973
974         Parameters
975         ----------
976         video : :obj:`dict` of :obj:`str`
977             Dictionary entry for one video entry
978
979         Returns
980         -------
981         :obj:`str`
982             Runtime of the video (in seconds)
983         """
984         runtime = None
985         if video['summary']['type'] != 'show':
986             runtime = video['runtime']
987         return runtime
988
989     def parse_netflix_list_id (self, video_list):
990         """Parse a video list and extract the list id
991
992         Parameters
993         ----------
994         video_list : :obj:`dict` of :obj:`str`
995             Netflix video list
996
997         Returns
998         -------
999         entry : :obj:`str` or None
1000             Netflix list id
1001         """
1002         netflix_list_id = None
1003         if 'lists' in video_list.keys():
1004             for video_id in video_list['lists']:
1005                 if self._is_size_key(key=video_id) == False:
1006                     netflix_list_id = video_id;
1007         return netflix_list_id
1008
1009     def parse_show_information (self, id, response_data):
1010         """Parse extended show information (synopsis, seasons, etc.)
1011
1012         Parameters
1013         ----------
1014         id : :obj:`str`
1015             Video id
1016
1017         response_data : :obj:`dict` of :obj:`str`
1018             Parsed response JSON from the `fetch_show_information` call
1019
1020         Returns
1021         -------
1022         entry : :obj:`dict` of :obj:`str`
1023         Show information in the format:
1024             {
1025                 "season_id": "80113084",
1026                 "synopsis": "Aus verzweifelter Geldnot versucht sich der Familienvater und Drucker Jochen als Geldf\u00e4lscher und rutscht dabei immer mehr in die dunkle Welt des Verbrechens ab."
1027                 "detail_text": "I´m optional"
1028             }
1029         """
1030         show = {}
1031         raw_show = response_data['value']['videos'][id]
1032         show.update({'synopsis': raw_show['regularSynopsis']})
1033         if 'evidence' in raw_show:
1034             show.update({'detail_text': raw_show['evidence']['value']['text']})
1035         if 'seasonList' in raw_show:
1036             show.update({'season_id': raw_show['seasonList']['current'][1]})
1037         return show
1038
1039     def parse_seasons (self, id, response_data):
1040         """Parse a list of seasons for a given show
1041
1042         Parameters
1043         ----------
1044         id : :obj:`str`
1045             Season id
1046
1047         response_data : :obj:`dict` of :obj:`str`
1048             Parsed response JSON from the `fetch_seasons_for_show` call
1049
1050         Returns
1051         -------
1052         entry : :obj:`dict` of :obj:`dict` of :obj:`str`
1053         Season information in the format:
1054             {
1055                 "80113084": {
1056                     "id": 80113084,
1057                     "text": "Season 1",
1058                     "shortName": "St. 1",
1059                     "boxarts": {
1060                       "big": "https://art-s.nflximg.net/5e7d3/b3b48749843fd3a36db11c319ffa60f96b55e7d3.jpg",
1061                       "small": "https://art-s.nflximg.net/57543/a039845c2eb9186dc26019576d895bf5a1957543.jpg"
1062                     },
1063                     "interesting_moment": "https://art-s.nflximg.net/09544/ed4b3073394b4469fb6ec22b9df81a4f5cb09544.jpg"
1064                 },
1065                 "80113085": {
1066                     "id": 80113085,
1067                     "text": "Season 2",
1068                     "shortName": "St. 2",
1069                     "boxarts": {
1070                       "big": "https://art-s.nflximg.net/5e7d3/b3b48749843fd3a36db11c319ffa60f96b55e7d3.jpg",
1071                       "small": "https://art-s.nflximg.net/57543/a039845c2eb9186dc26019576d895bf5a1957543.jpg"
1072                     },
1073                     "interesting_moment": "https://art-s.nflximg.net/09544/ed4b3073394b4469fb6ec22b9df81a4f5cb09544.jpg"
1074                 }
1075             }
1076         """
1077         raw_seasons = response_data['value']
1078         videos = raw_seasons['videos']
1079
1080         # get art video key
1081         video = {}
1082         for key, video_candidate in videos.iteritems():
1083             if not self._is_size_key(key):
1084                 video = video_candidate
1085
1086         # get season index
1087         sorting = {}
1088         for idx, season_list_entry in video['seasonList'].iteritems():
1089             if self._is_size_key(key=idx) == False and idx != 'summary':
1090                 sorting[int(season_list_entry[1])] = int(idx)
1091
1092         seasons = {}
1093
1094         for season in raw_seasons['seasons']:
1095             if self._is_size_key(key=season) == False:
1096                 seasons.update(self._parse_season_entry(season=raw_seasons['seasons'][season], video=video, sorting=sorting))
1097         return seasons
1098
1099     def _parse_season_entry (self, season, video, sorting):
1100         """Parse a season list entry e.g. rip out the parts we need
1101
1102         Parameters
1103         ----------
1104         season : :obj:`dict` of :obj:`str`
1105             Season entry from the `fetch_seasons_for_show` call
1106
1107         Returns
1108         -------
1109         entry : :obj:`dict` of :obj:`dict` of :obj:`str`
1110             Season list entry in the format:
1111
1112             {
1113                 "80113084": {
1114                     "id": 80113084,
1115                     "text": "Season 1",
1116                     "shortName": "St. 1",
1117                     "boxarts": {
1118                       "big": "https://art-s.nflximg.net/5e7d3/b3b48749843fd3a36db11c319ffa60f96b55e7d3.jpg",
1119                       "small": "https://art-s.nflximg.net/57543/a039845c2eb9186dc26019576d895bf5a1957543.jpg"
1120                     },
1121                     "interesting_moment": "https://art-s.nflximg.net/09544/ed4b3073394b4469fb6ec22b9df81a4f5cb09544.jpg"
1122                 }
1123             }
1124         """
1125         return {
1126             season['summary']['id']: {
1127                 'idx': sorting[season['summary']['id']],
1128                 'id': season['summary']['id'],
1129                 'text': season['summary']['name'],
1130                 'shortName': season['summary']['shortName'],
1131                 'boxarts': {
1132                     'small': video['boxarts']['_342x192']['jpg']['url'],
1133                     'big': video['boxarts']['_1280x720']['jpg']['url']
1134                 },
1135                 'interesting_moment': video['interestingMoment']['_665x375']['jpg']['url'],
1136             }
1137         }
1138
1139     def parse_episodes_by_season (self, response_data):
1140         """Parse episodes for a given season/episode list
1141
1142         Parameters
1143         ----------
1144         response_data : :obj:`dict` of :obj:`str`
1145             Parsed response JSON from the `fetch_seasons_for_show` call
1146
1147         Returns
1148         -------
1149         entry : :obj:`dict` of :obj:`dict` of :obj:`str`
1150         Season information in the format:
1151
1152         {
1153           "70251729": {
1154             "banner": "https://art-s.nflximg.net/63a36/c7fdfe6604ef2c22d085ac5dca5f69874e363a36.jpg",
1155             "duration": 1387,
1156             "episode": 1,
1157             "fanart": "https://art-s.nflximg.net/74e02/e7edcc5cc7dcda1e94d505df2f0a2f0d22774e02.jpg",
1158             "genres": [
1159               "Serien",
1160               "Comedyserien"
1161             ],
1162             "id": 70251729,
1163             "mediatype": "episode",
1164             "mpaa": "FSK 16",
1165             "my_list": false,
1166             "playcount": 0,
1167             "plot": "Als die Griffins und andere Einwohner von Quahog in die Villa von James Woods eingeladen werden, muss pl\u00f6tzlich ein Mord aufgekl\u00e4rt werden.",
1168             "poster": "https://art-s.nflximg.net/72fd6/57088715e8d436fdb6986834ab39124b0a972fd6.jpg",
1169             "rating": 3.9111512,
1170             "season": 9,
1171             "thumb": "https://art-s.nflximg.net/be686/07680670a68da8749eba607efb1ae37f9e3be686.jpg",
1172             "title": "Und dann gab es weniger (Teil 1)",
1173             "year": 2010,
1174             "bookmark": -1
1175           },
1176           "70251730": {
1177             "banner": "https://art-s.nflximg.net/63a36/c7fdfe6604ef2c22d085ac5dca5f69874e363a36.jpg",
1178             "duration": 1379,
1179             "episode": 2,
1180             "fanart": "https://art-s.nflximg.net/c472c/6c10f9578bf2c1d0a183c2ccb382931efcbc472c.jpg",
1181             "genres": [
1182               "Serien",
1183               "Comedyserien"
1184             ],
1185             "id": 70251730,
1186             "mediatype": "episode",
1187             "mpaa": "FSK 16",
1188             "my_list": false,
1189             "playcount": 1,
1190             "plot": "Wer ist der M\u00f6rder? Nach zahlreichen Morden wird immer wieder jemand anderes verd\u00e4chtigt.",
1191             "poster": "https://art-s.nflximg.net/72fd6/57088715e8d436fdb6986834ab39124b0a972fd6.jpg",
1192             "rating": 3.9111512,
1193             "season": 9,
1194             "thumb": "https://art-s.nflximg.net/15a08/857d59126641987bec302bb147a802a00d015a08.jpg",
1195             "title": "Und dann gab es weniger (Teil 2)",
1196             "year": 2010,
1197             "bookmark": 1234
1198           },
1199         }
1200         """
1201         episodes = {}
1202         raw_episodes = response_data['value']['videos']
1203         for episode_id in raw_episodes:
1204             if self._is_size_key(key=episode_id) == False:
1205                 if (raw_episodes[episode_id]['summary']['type'] == 'episode'):
1206                     episodes.update(self.parse_episode(episode=raw_episodes[episode_id], genres=response_data['value']['genres']))
1207         return episodes
1208
1209     def parse_episode (self, episode, genres=None):
1210         """Parse episode from an list of episodes by season
1211
1212         Parameters
1213         ----------
1214         episode : :obj:`dict` of :obj:`str`
1215             Episode entry from the `fetch_episodes_by_season` call
1216
1217         Returns
1218         -------
1219         entry : :obj:`dict` of :obj:`dict` of :obj:`str`
1220         Episode information in the format:
1221
1222         {
1223           "70251729": {
1224             "banner": "https://art-s.nflximg.net/63a36/c7fdfe6604ef2c22d085ac5dca5f69874e363a36.jpg",
1225             "duration": 1387,
1226             "episode": 1,
1227             "fanart": "https://art-s.nflximg.net/74e02/e7edcc5cc7dcda1e94d505df2f0a2f0d22774e02.jpg",
1228             "genres": [
1229               "Serien",
1230               "Comedyserien"
1231             ],
1232             "id": 70251729,
1233             "mediatype": "episode",
1234             "mpaa": "FSK 16",
1235             "my_list": false,
1236             "playcount": 0,
1237             "plot": "Als die Griffins und andere Einwohner von Quahog in die Villa von James Woods eingeladen werden, muss pl\u00f6tzlich ein Mord aufgekl\u00e4rt werden.",
1238             "poster": "https://art-s.nflximg.net/72fd6/57088715e8d436fdb6986834ab39124b0a972fd6.jpg",
1239             "rating": 3.9111512,
1240             "season": 9,
1241             "thumb": "https://art-s.nflximg.net/be686/07680670a68da8749eba607efb1ae37f9e3be686.jpg",
1242             "title": "Und dann gab es weniger (Teil 1)",
1243             "year": 2010,
1244             "bookmark": 1234
1245           },
1246         }
1247         """
1248         mpaa = ''
1249         if episode.get('maturity', None) is not None:
1250             if episode['maturity'].get('board', None) is not None and episode['maturity'].get('value', None) is not None:
1251                 mpaa = str(episode['maturity'].get('board', '').encode('utf-8')) + '-' + str(episode['maturity'].get('value', '').encode('utf-8'))
1252
1253         return {
1254             episode['summary']['id']: {
1255                 'id': episode['summary']['id'],
1256                 'episode': episode['summary']['episode'],
1257                 'season': episode['summary']['season'],
1258                 'plot': episode['info']['synopsis'],
1259                 'duration': episode['info']['runtime'],
1260                 'title': episode['info']['title'],
1261                 'year': episode['info']['releaseYear'],
1262                 'genres': self.parse_genres_for_video(video=episode, genres=genres),
1263                 'mpaa': mpaa,
1264                 'maturity': episode['maturity'],
1265                 'playcount': (0, 1)[episode['watched']],
1266                 'rating': episode['userRating'].get('average', 0) if episode['userRating'].get('average', None) != None else episode['userRating'].get('predicted', 0),
1267                 'thumb': episode['info']['interestingMoments']['url'],
1268                 'fanart': episode['interestingMoment']['_1280x720']['jpg']['url'],
1269                 'poster': episode['boxarts']['_1280x720']['jpg']['url'],
1270                 'banner': episode['boxarts']['_342x192']['jpg']['url'],
1271                 'mediatype': {'episode': 'episode', 'movie': 'movie'}[episode['summary']['type']],
1272                 'my_list': episode['queue']['inQueue'],
1273                 'bookmark': episode['bookmarkPosition']
1274             }
1275         }
1276
1277     def fetch_browse_list_contents (self):
1278         """Fetches the HTML data for the lists on the landing page (browse page) of Netflix
1279
1280         Returns
1281         -------
1282         :obj:`BeautifulSoup`
1283             Instance of an BeautifulSoup document containing the complete page contents
1284         """
1285         response = self._session_get(component='browse')
1286         return BeautifulSoup(response.text, 'html.parser')
1287
1288     def fetch_video_list_ids_via_preflight (self, list_from=0, list_to=50):
1289         """Fetches the JSON with detailed information based on the lists on the landing page (browse page) of Netflix
1290            via the preflight (GET) request
1291
1292         Parameters
1293         ----------
1294         list_from : :obj:`int`
1295             Start entry for pagination
1296
1297         list_to : :obj:`int`
1298             Last entry for pagination
1299
1300         Returns
1301         -------
1302         :obj:`dict` of :obj:`dict` of :obj:`str`
1303             Raw Netflix API call response or api call error
1304         """
1305         payload = {
1306             'fromRow': list_from,
1307             'toRow': list_to,
1308             'opaqueImageExtension': 'jpg',
1309             'transparentImageExtension': 'png',
1310             '_': int(time()),
1311             'authURL': self.user_data['authURL']
1312         }
1313
1314         response = self._session_get(component='video_list_ids', params=payload, type='api')
1315         return self._process_response(response=response, component=self._get_api_url_for(component='video_list_ids'))
1316
1317     def fetch_video_list_ids (self, list_from=0, list_to=50):
1318         """Fetches the JSON with detailed information based on the lists on the landing page (browse page) of Netflix
1319
1320         Parameters
1321         ----------
1322         list_from : :obj:`int`
1323             Start entry for pagination
1324
1325         list_to : :obj:`int`
1326             Last entry for pagination
1327
1328         Returns
1329         -------
1330         :obj:`dict` of :obj:`dict` of :obj:`str`
1331             Raw Netflix API call response or api call error
1332         """
1333         paths = [
1334             ['lolomo', {'from': list_from, 'to': list_to}, ['displayName', 'context', 'id', 'index', 'length']]
1335         ]
1336
1337         response = self._path_request(paths=paths)
1338         return self._process_response(response=response, component='Video list ids')
1339
1340     def fetch_search_results (self, search_str, list_from=0, list_to=10):
1341         """Fetches the JSON which contains the results for the given search query
1342
1343         Parameters
1344         ----------
1345         search_str : :obj:`str`
1346             String to query Netflix search for
1347
1348         list_from : :obj:`int`
1349             Start entry for pagination
1350
1351         list_to : :obj:`int`
1352             Last entry for pagination
1353
1354         Returns
1355         -------
1356         :obj:`dict` of :obj:`dict` of :obj:`str`
1357             Raw Netflix API call response or api call error
1358         """
1359         # properly encode the search string
1360         encoded_search_string = quote(search_str)
1361
1362         paths = [
1363             ['search', encoded_search_string, 'titles', {'from': list_from, 'to': list_to}, ['summary', 'title']],
1364             ['search', encoded_search_string, 'titles', {'from': list_from, 'to': list_to}, 'boxarts', '_342x192', 'jpg'],
1365             ['search', encoded_search_string, 'titles', ['id', 'length', 'name', 'trackIds', 'requestId']],
1366             ['search', encoded_search_string, 'suggestions', 0, 'relatedvideos', {'from': list_from, 'to': list_to}, ['summary', 'title']],
1367             ['search', encoded_search_string, 'suggestions', 0, 'relatedvideos', {'from': list_from, 'to': list_to}, 'boxarts', '_342x192', 'jpg'],
1368             ['search', encoded_search_string, 'suggestions', 0, 'relatedvideos', ['id', 'length', 'name', 'trackIds', 'requestId']]
1369         ]
1370         response = self._path_request(paths=paths)
1371         return self._process_response(response=response, component='Search results')
1372
1373     def fetch_video_list (self, list_id, list_from=0, list_to=26):
1374         """Fetches the JSON which contains the contents of a given video list
1375
1376         Parameters
1377         ----------
1378         list_id : :obj:`str`
1379             Unique list id to query Netflix for
1380
1381         list_from : :obj:`int`
1382             Start entry for pagination
1383
1384         list_to : :obj:`int`
1385             Last entry for pagination
1386
1387         Returns
1388         -------
1389         :obj:`dict` of :obj:`dict` of :obj:`str`
1390             Raw Netflix API call response or api call error
1391         """
1392         paths = [
1393             ['lists', list_id, {'from': list_from, 'to': list_to}, ['summary', 'title', 'synopsis', 'regularSynopsis', 'evidence', 'queue', 'episodeCount', 'info', 'maturity', 'runtime', 'seasonCount', 'releaseYear', 'userRating', 'numSeasonsLabel', 'bookmarkPosition', 'watched', 'videoQuality']],
1394             ['lists', list_id, {'from': list_from, 'to': list_to}, 'cast', {'from': 0, 'to': 15}, ['id', 'name']],
1395             ['lists', list_id, {'from': list_from, 'to': list_to}, 'cast', 'summary'],
1396             ['lists', list_id, {'from': list_from, 'to': list_to}, 'genres', {'from': 0, 'to': 5}, ['id', 'name']],
1397             ['lists', list_id, {'from': list_from, 'to': list_to}, 'genres', 'summary'],
1398             ['lists', list_id, {'from': list_from, 'to': list_to}, 'tags', {'from': 0, 'to': 9}, ['id', 'name']],
1399             ['lists', list_id, {'from': list_from, 'to': list_to}, 'tags', 'summary'],
1400             ['lists', list_id, {'from': list_from, 'to': list_to}, ['creators', 'directors'], {'from': 0, 'to': 49}, ['id', 'name']],
1401             ['lists', list_id, {'from': list_from, 'to': list_to}, ['creators', 'directors'], 'summary'],
1402             ['lists', list_id, {'from': list_from, 'to': list_to}, 'bb2OGLogo', '_400x90', 'png'],
1403             ['lists', list_id, {'from': list_from, 'to': list_to}, 'boxarts', '_342x192', 'jpg'],
1404             ['lists', list_id, {'from': list_from, 'to': list_to}, 'boxarts', '_1280x720', 'jpg'],
1405             ['lists', list_id, {'from': list_from, 'to': list_to}, 'storyarts', '_1632x873', 'jpg'],
1406             ['lists', list_id, {'from': list_from, 'to': list_to}, 'interestingMoment', '_665x375', 'jpg'],
1407             ['lists', list_id, {'from': list_from, 'to': list_to}, 'artWorkByType', 'BILLBOARD', '_1280x720', 'jpg']
1408         ];
1409
1410         response = self._path_request(paths=paths)
1411         return self._process_response(response=response, component='Video list')
1412
1413     def fetch_video_list_information (self, video_ids):
1414         """Fetches the JSON which contains the detail information of a list of given video ids
1415
1416         Parameters
1417         ----------
1418         video_ids : :obj:`list` of :obj:`str`
1419             List of video ids to fetch detail data for
1420
1421         Returns
1422         -------
1423         :obj:`dict` of :obj:`dict` of :obj:`str`
1424             Raw Netflix API call response or api call error
1425         """
1426         paths = []
1427         for video_id in video_ids:
1428             paths.append(['videos', video_id, ['summary', 'title', 'synopsis', 'regularSynopsis', 'evidence', 'queue', 'episodeCount', 'info', 'maturity', 'runtime', 'seasonCount', 'releaseYear', 'userRating', 'numSeasonsLabel', 'bookmarkPosition', 'watched', 'videoQuality']])
1429             paths.append(['videos', video_id, 'cast', {'from': 0, 'to': 15}, ['id', 'name']])
1430             paths.append(['videos', video_id, 'cast', 'summary'])
1431             paths.append(['videos', video_id, 'genres', {'from': 0, 'to': 5}, ['id', 'name']])
1432             paths.append(['videos', video_id, 'genres', 'summary'])
1433             paths.append(['videos', video_id, 'tags', {'from': 0, 'to': 9}, ['id', 'name']])
1434             paths.append(['videos', video_id, 'tags', 'summary'])
1435             paths.append(['videos', video_id, ['creators', 'directors'], {'from': 0, 'to': 49}, ['id', 'name']])
1436             paths.append(['videos', video_id, ['creators', 'directors'], 'summary'])
1437             paths.append(['videos', video_id, 'bb2OGLogo', '_400x90', 'png'])
1438             paths.append(['videos', video_id, 'boxarts', '_342x192', 'jpg'])
1439             paths.append(['videos', video_id, 'boxarts', '_1280x720', 'jpg'])
1440             paths.append(['videos', video_id, 'storyarts', '_1632x873', 'jpg'])
1441             paths.append(['videos', video_id, 'interestingMoment', '_665x375', 'jpg'])
1442             paths.append(['videos', video_id, 'artWorkByType', 'BILLBOARD', '_1280x720', 'jpg'])
1443
1444         response = self._path_request(paths=paths)
1445         return self._process_response(response=response, component='fetch_video_list_information')
1446
1447     def fetch_metadata (self, id):
1448         """Fetches the JSON which contains the metadata for a given show/movie or season id
1449
1450         Parameters
1451         ----------
1452         id : :obj:`str`
1453             Show id, movie id or season id
1454
1455         Returns
1456         -------
1457         :obj:`dict` of :obj:`dict` of :obj:`str`
1458             Raw Netflix API call response or api call error
1459         """
1460         payload = {
1461             'movieid': id,
1462             'imageformat': 'jpg',
1463             '_': int(time())
1464         }
1465         response = self._session_get(component='metadata', params=payload, type='api')
1466         return self._process_response(response=response, component=self._get_api_url_for(component='metadata'))
1467
1468     def fetch_show_information (self, id, type):
1469         """Fetches the JSON which contains the detailed contents of a show
1470
1471         Parameters
1472         ----------
1473         id : :obj:`str`
1474             Unique show id to query Netflix for
1475
1476         type : :obj:`str`
1477             Can be 'movie' or 'show'
1478
1479         Returns
1480         -------
1481         :obj:`dict` of :obj:`dict` of :obj:`str`
1482             Raw Netflix API call response or api call error
1483         """
1484         # check if we have a show or a movie, the request made depends on this
1485         if type == 'show':
1486             paths = [
1487                 ['videos', id, ['requestId', 'regularSynopsis', 'evidence']],
1488                 ['videos', id, 'seasonList', 'current', 'summary']
1489             ]
1490         else:
1491             paths = [['videos', id, ['requestId', 'regularSynopsis', 'evidence']]]
1492         response = self._path_request(paths=paths)
1493         return self._process_response(response=response, component='Show information')
1494
1495     def fetch_seasons_for_show (self, id, list_from=0, list_to=30):
1496         """Fetches the JSON which contains the seasons of a given show
1497
1498         Parameters
1499         ----------
1500         id : :obj:`str`
1501             Unique show id to query Netflix for
1502
1503         list_from : :obj:`int`
1504             Start entry for pagination
1505
1506         list_to : :obj:`int`
1507             Last entry for pagination
1508
1509         Returns
1510         -------
1511         :obj:`dict` of :obj:`dict` of :obj:`str`
1512             Raw Netflix API call response or api call error
1513         """
1514         paths = [
1515             ['videos', id, 'seasonList', {'from': list_from, 'to': list_to}, 'summary'],
1516             ['videos', id, 'seasonList', 'summary'],
1517             ['videos', id, 'boxarts',  '_342x192', 'jpg'],
1518             ['videos', id, 'boxarts', '_1280x720', 'jpg'],
1519             ['videos', id, 'storyarts',  '_1632x873', 'jpg'],
1520             ['videos', id, 'interestingMoment', '_665x375', 'jpg']
1521         ]
1522         response = self._path_request(paths=paths)
1523         return self._process_response(response=response, component='Seasons')
1524
1525     def fetch_episodes_by_season (self, season_id, list_from=-1, list_to=40):
1526         """Fetches the JSON which contains the episodes of a given season
1527
1528         TODO: Add more metadata
1529
1530         Parameters
1531         ----------
1532         season_id : :obj:`str`
1533             Unique season_id id to query Netflix for
1534
1535         list_from : :obj:`int`
1536             Start entry for pagination
1537
1538         list_to : :obj:`int`
1539             Last entry for pagination
1540
1541         Returns
1542         -------
1543         :obj:`dict` of :obj:`dict` of :obj:`str`
1544             Raw Netflix API call response or api call error
1545         """
1546         paths = [
1547             ['seasons', season_id, 'episodes', {'from': list_from, 'to': list_to}, ['summary', 'queue', 'info', 'maturity', 'userRating', 'bookmarkPosition', 'creditOffset', 'watched', 'videoQuality']],
1548             #['videos', season_id, 'cast', {'from': 0, 'to': 15}, ['id', 'name']],
1549             #['videos', season_id, 'cast', 'summary'],
1550             #['videos', season_id, 'genres', {'from': 0, 'to': 5}, ['id', 'name']],
1551             #['videos', season_id, 'genres', 'summary'],
1552             #['videos', season_id, 'tags', {'from': 0, 'to': 9}, ['id', 'name']],
1553             #['videos', season_id, 'tags', 'summary'],
1554             #['videos', season_id, ['creators', 'directors'], {'from': 0, 'to': 49}, ['id', 'name']],
1555             #['videos', season_id, ['creators', 'directors'], 'summary'],
1556             ['seasons', season_id, 'episodes', {'from': list_from, 'to': list_to}, 'genres', {'from': 0, 'to': 1}, ['id', 'name']],
1557             ['seasons', season_id, 'episodes', {'from': list_from, 'to': list_to}, 'genres', 'summary'],
1558             ['seasons', season_id, 'episodes', {'from': list_from, 'to': list_to}, 'interestingMoment', '_1280x720', 'jpg'],
1559             ['seasons', season_id, 'episodes', {'from': list_from, 'to': list_to}, 'interestingMoment', '_665x375', 'jpg'],
1560             ['seasons', season_id, 'episodes', {'from': list_from, 'to': list_to}, 'boxarts', '_342x192', 'jpg'],
1561             ['seasons', season_id, 'episodes', {'from': list_from, 'to': list_to}, 'boxarts', '_1280x720', 'jpg']
1562         ]
1563         response = self._path_request(paths=paths)
1564         return self._process_response(response=response, component='fetch_episodes_by_season')
1565
1566     def refresh_session_data (self, account):
1567         """Reload the session data (profiles, user_data, api_data)
1568
1569         Parameters
1570         ----------
1571         account : :obj:`dict` of :obj:`str`
1572             Dict containing an email, country & a password property
1573         """
1574         # load the profiles page (to verify the user)
1575         response = self._session_get(component='profiles')
1576         # parse out the needed inline information
1577         only_script_tags = SoupStrainer('script')
1578         page_soup = BeautifulSoup(response.text, 'html.parser', parse_only=only_script_tags)
1579         page_data = self._parse_page_contents(page_soup=page_soup)
1580         account_hash = self._generate_account_hash(account=account)
1581         self._save_data(filename=self.data_path + '_' + account_hash)
1582
1583     def _path_request (self, paths):
1584         """Executes a post request against the shakti endpoint with Falcor style payload
1585
1586         Parameters
1587         ----------
1588         paths : :obj:`list` of :obj:`list`
1589             Payload with path querys for the Netflix Shakti API in Falcor style
1590
1591         Returns
1592         -------
1593         :obj:`requests.response`
1594             Response from a POST call made with Requests
1595         """
1596         headers = {
1597             'Content-Type': 'application/json',
1598             'Accept': 'application/json, text/javascript, */*',
1599         }
1600
1601         data = json.dumps({
1602             'paths': paths,
1603             'authURL': self.user_data['authURL']
1604         })
1605
1606         params = {
1607             'model': self.user_data['gpsModel']
1608         }
1609
1610         return self._session_post(component='shakti', type='api', params=params, headers=headers, data=data)
1611
1612     def _is_size_key (self, key):
1613         """Tiny helper that checks if a given key is called $size or size, as we need to check this often
1614
1615         Parameters
1616         ----------
1617         key : :obj:`str`
1618             Key to check the value for
1619
1620         Returns
1621         -------
1622         bool
1623             Key has a size value or not
1624         """
1625         return key == '$size' or key == 'size'
1626
1627     def _get_api_url_for (self, component):
1628         """Tiny helper that builds the url for a requested API endpoint component
1629
1630         Parameters
1631         ----------
1632         component : :obj:`str`
1633             Component endpoint to build the URL for
1634
1635         Returns
1636         -------
1637         :obj:`str`
1638             API Url
1639         """
1640         if self.api_data['API_ROOT'].find(self.api_data['API_BASE_URL']) > -1:
1641             return self.api_data['API_ROOT'] + '/' + self.api_data['BUILD_IDENTIFIER'] + self.urls[component]
1642         else:
1643             return self.api_data['API_ROOT'] + self.api_data['API_BASE_URL'] + '/' + self.api_data['BUILD_IDENTIFIER'] + self.urls[component]
1644
1645     def _get_document_url_for (self, component):
1646         """Tiny helper that builds the url for a requested document endpoint component
1647
1648         Parameters
1649         ----------
1650         component : :obj:`str`
1651             Component endpoint to build the URL for
1652
1653         Returns
1654         -------
1655         :obj:`str`
1656             Document Url
1657         """
1658         return self.base_url + self.urls[component]
1659
1660     def _process_response (self, response, component):
1661         """Tiny helper to check responses for API requests
1662
1663         Parameters
1664         ----------
1665         response : :obj:`requests.response`
1666             Response from a requests instance
1667
1668         component : :obj:`str`
1669             Component endpoint
1670
1671         Returns
1672         -------
1673         :obj:`dict` of :obj:`dict` of :obj:`str` or :obj:`dict` of :obj:`str`
1674             Raw Netflix API call response or api call error
1675         """
1676         # check if we´re not authorized to make thios call
1677         if response.status_code == 401:
1678             return {
1679                 'error': True,
1680                 'message': 'Session invalid',
1681                 'code': 401
1682             }
1683         # check if somethign else failed
1684         if response.status_code != 200:
1685             return {
1686                 'error': True,
1687                 'message': 'API call for "' + component + '" failed',
1688                 'code': response.status_code
1689             }
1690         # return the parsed response & everything´s fine
1691         return response.json()
1692
1693     def _to_unicode(self, str):
1694         '''Attempt to fix non uft-8 string into utf-8, using a limited set of encodings
1695
1696         Parameters
1697         ----------
1698         str : `str`
1699             String to decode
1700
1701         Returns
1702         -------
1703         `str`
1704             Decoded string
1705         '''
1706         # fuller list of encodings at http://docs.python.org/library/codecs.html#standard-encodings
1707         if not str:  return u''
1708         u = None
1709         # we could add more encodings here, as warranted.
1710         encodings = ('ascii', 'utf8', 'latin1')
1711         for enc in encodings:
1712             if u:  break
1713             try:
1714                 u = unicode(str,enc)
1715             except UnicodeDecodeError:
1716                 pass
1717         if not u:
1718             u = unicode(str, errors='replace')
1719         return u
1720
1721     def _update_my_list (self, video_id, operation):
1722         """Tiny helper to add & remove items from "my list"
1723
1724         Parameters
1725         ----------
1726         video_id : :obj:`str`
1727             ID of the show/movie to be added
1728
1729         operation : :obj:`str`
1730             Either "add" or "remove"
1731
1732         Returns
1733         -------
1734         bool
1735             Operation successfull
1736         """
1737         headers = {
1738             'Content-Type': 'application/json',
1739             'Accept': 'application/json, text/javascript, */*',
1740         }
1741
1742         payload = json.dumps({
1743             'operation': operation,
1744             'videoId': int(video_id),
1745             'authURL': self.user_data['authURL']
1746         })
1747
1748         response = self._session_post(component='update_my_list', type='api', headers=headers, data=payload)
1749         return response.status_code == 200
1750
1751     def _save_data(self, filename):
1752         """Tiny helper that stores session data from the session in a given file
1753
1754         Parameters
1755         ----------
1756         filename : :obj:`str`
1757             Complete path incl. filename that determines where to store the cookie
1758
1759         Returns
1760         -------
1761         bool
1762             Storage procedure was successfull
1763         """
1764         if not os.path.isdir(os.path.dirname(filename)):
1765             return False
1766         with open(filename, 'w') as f:
1767             f.truncate()
1768             pickle.dump({
1769                 'user_data': self.user_data,
1770                 'api_data': self.api_data,
1771                 'profiles': self.profiles
1772             }, f)
1773
1774     def _load_data(self, filename):
1775         """Tiny helper that loads session data into the active session from a given file
1776
1777         Parameters
1778         ----------
1779         filename : :obj:`str`
1780             Complete path incl. filename that determines where to load the data from
1781
1782         Returns
1783         -------
1784         bool
1785             Load procedure was successfull
1786         """
1787         if not os.path.isfile(filename):
1788             return False
1789
1790         with open(filename) as f:
1791             data = pickle.load(f)
1792             if data:
1793                 self.profiles = data['profiles']
1794                 self.user_data = data['user_data']
1795                 self.api_data = data['api_data']
1796             else:
1797                 return False
1798
1799     def _delete_data (self, path):
1800         """Tiny helper that deletes session data
1801
1802         Parameters
1803         ----------
1804         filename : :obj:`str`
1805             Complete path incl. filename that determines where to delete the files
1806
1807         """
1808         head, tail = os.path.split(path)
1809         for subdir, dirs, files in os.walk(head):
1810             for file in files:
1811                 if tail in file:
1812                     os.remove(os.path.join(subdir, file))
1813
1814     def _save_cookies(self, filename):
1815         """Tiny helper that stores cookies from the session in a given file
1816
1817         Parameters
1818         ----------
1819         filename : :obj:`str`
1820             Complete path incl. filename that determines where to store the cookie
1821
1822         Returns
1823         -------
1824         bool
1825             Storage procedure was successfull
1826         """
1827         if not os.path.isdir(os.path.dirname(filename)):
1828             return False
1829         with open(filename, 'w') as f:
1830             f.truncate()
1831             pickle.dump(self.session.cookies._cookies, f)
1832
1833     def _load_cookies(self, filename):
1834         """Tiny helper that loads cookies into the active session from a given file
1835
1836         Parameters
1837         ----------
1838         filename : :obj:`str`
1839             Complete path incl. filename that determines where to load the cookie from
1840
1841         Returns
1842         -------
1843         bool
1844             Load procedure was successfull
1845         """
1846         if not os.path.isfile(filename):
1847             return False
1848
1849         with open(filename) as f:
1850             _cookies = pickle.load(f)
1851             if _cookies:
1852                 jar = cookies.RequestsCookieJar()
1853                 jar._cookies = _cookies
1854                 self.session.cookies = jar
1855             else:
1856                 return False
1857
1858     def _delete_cookies (self, path):
1859         """Tiny helper that deletes cookie data
1860
1861         Parameters
1862         ----------
1863         filename : :obj:`str`
1864             Complete path incl. filename that determines where to delete the files
1865
1866         """
1867         head, tail = os.path.split(path)
1868         for subdir, dirs, files in os.walk(head):
1869             for file in files:
1870                 if tail in file:
1871                     os.remove(os.path.join(subdir, file))
1872
1873     def _generate_account_hash (self, account):
1874         """Generates a has for the given account (used for cookie verification)
1875
1876         Parameters
1877         ----------
1878         account : :obj:`dict` of :obj:`str`
1879             Dict containing an email, country & a password property
1880
1881         Returns
1882         -------
1883         :obj:`str`
1884             Account data hash
1885         """
1886         return urlsafe_b64encode(account['email'])
1887
1888     def _session_post (self, component, type='document', data={}, headers={}, params={}):
1889         """Executes a get request using requests for the current session & measures the duration of that request
1890
1891         Parameters
1892         ----------
1893         component : :obj:`str`
1894             Component to query
1895
1896         type : :obj:`str`
1897             Is it a document or API request ('document' is default)
1898
1899         data : :obj:`dict` of :obj:`str`
1900             Payload body as dict
1901
1902         header : :obj:`dict` of :obj:`str`
1903             Additional headers as dict
1904
1905         params : :obj:`dict` of :obj:`str`
1906             Request params
1907
1908         Returns
1909         -------
1910             :obj:`str`
1911                 Contents of the field to match
1912         """
1913         url = self._get_document_url_for(component=component) if type == 'document' else self._get_api_url_for(component=component)
1914         start = time()
1915         response = self.session.post(url=url, data=data, params=params, headers=headers, verify=self.verify_ssl)
1916         end = time()
1917         self.log(msg='[POST] Request for "' + url + '" took ' + str(end - start) + ' seconds')
1918         return response
1919
1920     def _session_get (self, component, type='document', params={}):
1921         """Executes a get request using requests for the current session & measures the duration of that request
1922
1923         Parameters
1924         ----------
1925         component : :obj:`str`
1926             Component to query
1927
1928         type : :obj:`str`
1929             Is it a document or API request ('document' is default)
1930
1931         params : :obj:`dict` of :obj:`str`
1932             Request params
1933
1934         Returns
1935         -------
1936             :obj:`str`
1937                 Contents of the field to match
1938         """
1939         url = self._get_document_url_for(component=component) if type == 'document' else self._get_api_url_for(component=component)
1940         start = time()
1941         response = self.session.get(url=url, verify=self.verify_ssl, params=params)
1942         end = time()
1943         self.log(msg='[GET] Request for "' + url + '" took ' + str(end - start) + ' seconds')
1944         return response
1945
1946     def _sloppy_parse_user_and_api_data (self, key, contents):
1947         """Try to find the user & API data from the inline js by using a string parser
1948
1949         Parameters
1950         ----------
1951         key : :obj:`str`
1952             Key to match in the inline js
1953
1954         contents : :obj:`str`
1955             Inline JS contents
1956
1957         Returns
1958         -------
1959             :obj:`str`
1960                 Contents of the field to match
1961         """
1962         key_start = contents.find(key + '"')
1963         if int(key_start) == -1:
1964             return None
1965         sub_contents = contents[int(key_start):]
1966         l = sub_contents.find('",')
1967         return contents[(int(key_start)+len(key)+3):int(key_start)+l].decode('string_escape')
1968
1969     def _sloppy_parse_profiles (self, contents):
1970         """Try to find the profile data from the inline js by using a string parser & parse/convert the result to JSON
1971
1972         Parameters
1973         ----------
1974         contents : :obj:`str`
1975             Inline JS contents
1976
1977         Returns
1978         -------
1979             :obj:`dict` of :obj:`str` or None
1980                 Profile data
1981         """
1982         profile_start = contents.find('profiles":')
1983         profile_list_start = contents.find('profilesList')
1984         if int(profile_start) > -1 and int(profile_list_start) > -1:
1985             try:
1986                 try:
1987                     return json.loads('{"a":{"' + contents[profile_start:profile_list_start-2].decode('string_escape') + '}}').get('a').get('profiles')
1988                 except ValueError, e:
1989                    return None
1990             except TypeError, e:
1991                 return None
1992         return None
1993
1994     def _sloppy_parse_avatars (self, contents):
1995         """Try to find the avatar data from the inline js by using a string parser & parse/convert the result to JSON
1996
1997         Parameters
1998         ----------
1999         contents : :obj:`str`
2000             Inline JS contents
2001
2002         Returns
2003         -------
2004             :obj:`dict` of :obj:`str` or None
2005                 Avatar data
2006         """
2007         avatars_start = contents.find('"nf":')
2008         avatars_list_start = contents.find('"profiles"')
2009         if int(avatars_start) > -1 and int(avatars_list_start) > -1:
2010             try:
2011                 try:
2012                     return json.loads('{' + contents[avatars_start:avatars_list_start-2].decode('string_escape') + '}')
2013                 except ValueError, e:
2014                    return None
2015             except TypeError, e:
2016                 return None
2017         return None
2018
2019     def _verfify_auth_and_profiles_data (self, data):
2020         """Checks if the authURL has at least a certain length & doesn't overrule a certain length & if the profiles dict exists
2021         Simple validity check for the sloppy data parser
2022
2023         Parameters
2024         ----------
2025         data : :obj:`dict` of :obj:`str`
2026             Parsed JS contents
2027
2028         Returns
2029         -------
2030             bool
2031                 Data is valid
2032         """
2033         if type(data.get('profiles')) == dict:
2034             if len(str(data.get('authURL', ''))) > 10 and len(str(data.get('authURL', ''))) < 50:
2035                 return True
2036         return False
2037
2038     def _sloppy_parse_inline_data (self, scripts):
2039         """Strips out all the needed user, api & profile data from the inline JS by string parsing
2040         Might fail, so if this doesn't succeed, a proper JS parser will chime in
2041
2042         Note: This has been added for performance reasons only
2043
2044         Parameters
2045         ----------
2046         scripts : :obj:`list` of :obj:`BeautifoulSoup`
2047             Script tags & contents from the Netflix browse page
2048
2049         Returns
2050         -------
2051             :obj:`dict` of :obj:`str`
2052                 Dict containijg user, api & profile data
2053         """
2054         inline_data = {};
2055         for script in scripts:
2056             contents = str(script.contents[0])
2057             important_data = ['authURL', 'API_BASE_URL', 'API_ROOT', 'BUILD_IDENTIFIER', 'ICHNAEA_ROOT', 'gpsModel', 'guid', 'esn']
2058             res = {}
2059             for key in important_data:
2060                 _res = self._sloppy_parse_user_and_api_data(key, contents)
2061                 if _res != None:
2062                     res.update({key: _res})
2063             if res != {}:
2064                 inline_data.update(res)
2065
2066             # parse profiles
2067             profiles = self._sloppy_parse_profiles(contents)
2068             avatars = self._sloppy_parse_avatars(contents)
2069             if profiles != None:
2070                 inline_data.update({'profiles': profiles})
2071             if avatars != None:
2072                 inline_data.update(avatars)
2073         return inline_data
2074
2075     def _accurate_parse_inline_data (self, scripts):
2076         """Uses a proper JS parser to fetch all the api, iser & profile data from within the inline JS
2077
2078         Note: This is slow but accurate
2079
2080         Parameters
2081         ----------
2082         scripts : :obj:`list` of :obj:`BeautifoulSoup`
2083             Script tags & contents from the Netflix browse page
2084
2085         Returns
2086         -------
2087             :obj:`dict` of :obj:`str`
2088                 Dict containing user, api & profile data
2089         """
2090         inline_data = []
2091         from pyjsparser import PyJsParser
2092         parser = PyJsParser()
2093         for script in scripts:
2094             data = {}
2095             # unicode escape that incoming script stuff
2096             contents = self._to_unicode(str(script.contents[0]))
2097             # parse the JS & load the declarations we´re interested in
2098             parsed = parser.parse(contents)
2099             if len(parsed['body']) > 1 and parsed['body'][1]['expression']['right'].get('properties', None) != None:
2100                 declarations = parsed['body'][1]['expression']['right']['properties']
2101                 for declaration in declarations:
2102                     for key in declaration:
2103                         # we found the correct path if the declaration is a dict & of type 'ObjectExpression'
2104                         if type(declaration[key]) is dict:
2105                             if declaration[key]['type'] == 'ObjectExpression':
2106                                 # add all static data recursivly
2107                                 for expression in declaration[key]['properties']:
2108                                     data[expression['key']['value']] = self._parse_rec(expression['value'])
2109                     inline_data.append(data)
2110         return inline_data
2111
2112     def _parse_rec (self, node):
2113         """Iterates over a JavaScript AST and return values found
2114
2115         Parameters
2116         ----------
2117         value : :obj:`dict`
2118             JS AST Expression
2119         Returns
2120         -------
2121         :obj:`dict` of :obj:`dict` or :obj:`str`
2122             Parsed contents of the node
2123         """
2124         if node['type'] == 'ObjectExpression':
2125             _ret = {}
2126             for prop in node['properties']:
2127                 _ret.update({prop['key']['value']: self._parse_rec(prop['value'])})
2128             return _ret
2129         if node['type'] == 'Literal':
2130             return node['value']
2131
2132     def _parse_user_data (self, netflix_page_data):
2133         """Parse out the user data from the big chunk of dicts we got from
2134            parsing the JSON-ish data from the netflix homepage
2135
2136         Parameters
2137         ----------
2138         netflix_page_data : :obj:`list`
2139             List of all the JSON-ish data that has been extracted from the Netflix homepage
2140             see: extract_inline_netflix_page_data
2141
2142         Returns
2143         -------
2144             :obj:`dict` of :obj:`str`
2145
2146             {
2147                 "guid": "72ERT45...",
2148                 "authURL": "145637....",
2149                 "gpsModel": "harris"
2150             }
2151         """
2152         user_data = {};
2153         important_fields = [
2154             'authURL',
2155             'gpsModel',
2156             'guid'
2157         ]
2158
2159         # values are accessible via dict (sloppy parsing successfull)
2160         if type(netflix_page_data) == dict:
2161             for important_field in important_fields:
2162                 user_data.update({important_field: netflix_page_data.get(important_field, '')})
2163             return user_data
2164
2165         # values are stored in lists (returned from JS parser)
2166         for item in netflix_page_data:
2167             if 'memberContext' in dict(item).keys():
2168                 for important_field in important_fields:
2169                     user_data.update({important_field: item['memberContext']['data']['userInfo'][important_field]})
2170
2171         return user_data
2172
2173     def _parse_profile_data (self, netflix_page_data):
2174         """Parse out the profile data from the big chunk of dicts we got from
2175            parsing the JSON-ish data from the netflix homepage
2176
2177         Parameters
2178         ----------
2179         netflix_page_data : :obj:`list`
2180             List of all the JSON-ish data that has been extracted from the Netflix homepage
2181             see: extract_inline_netflix_page_data
2182
2183         Returns
2184         -------
2185             :obj:`dict` of :obj:`dict
2186
2187             {
2188                 "72ERT45...": {
2189                     "profileName": "username",
2190                     "avatar": "http://..../avatar.png",
2191                     "id": "72ERT45...",
2192                     "isAccountOwner": False,
2193                     "isActive": True,
2194                     "isFirstUse": False
2195                 }
2196             }
2197         """
2198         profiles = {};
2199         important_fields = [
2200             'profileName',
2201             'isActive',
2202             'isAccountOwner',
2203             'isKids'
2204         ]
2205         # values are accessible via dict (sloppy parsing successfull)
2206         if type(netflix_page_data) == dict:
2207             for profile_id in netflix_page_data.get('profiles'):
2208                 if self._is_size_key(key=profile_id) == False and type(netflix_page_data['profiles'][profile_id]) == dict and netflix_page_data['profiles'][profile_id].get('avatar', False) != False:
2209                     profile = {'id': profile_id}
2210                     for important_field in important_fields:
2211                         profile.update({important_field: netflix_page_data['profiles'][profile_id]['summary'][important_field]})
2212                     avatar_base = netflix_page_data['nf'].get(netflix_page_data['profiles'][profile_id]['summary']['avatarName'], False);
2213                     avatar = 'https://secure.netflix.com/ffe/profiles/avatars_v2/320x320/PICON_029.png' if avatar_base == False else avatar_base['images']['byWidth']['320']['value']
2214                     profile.update({'avatar': avatar, 'isFirstUse': False})
2215                     profiles.update({profile_id: profile})
2216             return profiles
2217
2218         # values are stored in lists (returned from JS parser)
2219         # TODO: get rid of this christmas tree of doom
2220         for item in netflix_page_data:
2221             if 'hasViewedRatingWelcomeModal' in dict(item).keys():
2222                 for profile_id in item:
2223                     if self._is_size_key(key=profile_id) == False and type(item[profile_id]) == dict and item[profile_id].get('avatar', False) != False:
2224                         profile = {'id': profile_id}
2225                         for important_field in important_fields:
2226                             profile.update({important_field: item[profile_id]['summary'][important_field]})
2227                         avatar_base = item['nf'].get(item[profile_id]['summary']['avatarName'], False);
2228                         avatar = 'https://secure.netflix.com/ffe/profiles/avatars_v2/320x320/PICON_029.png' if avatar_base == False else avatar_base['images']['byWidth']['320']['value']
2229                         profile.update({'avatar': avatar})
2230                         profiles.update({profile_id: profile})
2231         return profiles
2232
2233     def _parse_api_base_data (self, netflix_page_data):
2234         """Parse out the api url data from the big chunk of dicts we got from
2235            parsing the JSOn-ish data from the netflix homepage
2236
2237         Parameters
2238         ----------
2239         netflix_page_data : :obj:`list`
2240             List of all the JSON-ish data that has been extracted from the Netflix homepage
2241             see: extract_inline_netflix_page_data
2242
2243         Returns
2244         -------
2245             :obj:`dict` of :obj:`str
2246
2247             {
2248                 "API_BASE_URL": "/shakti",
2249                 "API_ROOT": "https://www.netflix.com/api",
2250                 "BUILD_IDENTIFIER": "113b89c9",
2251                 "ICHNAEA_ROOT": "/ichnaea"
2252             }
2253         """
2254         api_data = {};
2255         important_fields = [
2256             'API_BASE_URL',
2257             'API_ROOT',
2258             'BUILD_IDENTIFIER',
2259             'ICHNAEA_ROOT'
2260         ]
2261
2262         # values are accessible via dict (sloppy parsing successfull)
2263         if type(netflix_page_data) == dict:
2264             for important_field in important_fields:
2265                 api_data.update({important_field: netflix_page_data.get(important_field, '')})
2266             return api_data
2267
2268         for item in netflix_page_data:
2269             if 'serverDefs' in dict(item).keys():
2270                 for important_field in important_fields:
2271                     api_data.update({important_field: item['serverDefs']['data'][important_field]})
2272         return api_data
2273
2274     def _parse_esn_data (self, netflix_page_data):
2275         """Parse out the esn id data from the big chunk of dicts we got from
2276            parsing the JSOn-ish data from the netflix homepage
2277
2278         Parameters
2279         ----------
2280         netflix_page_data : :obj:`list`
2281             List of all the JSON-ish data that has been extracted from the Netflix homepage
2282             see: extract_inline_netflix_page_data
2283
2284         Returns
2285         -------
2286             :obj:`str` of :obj:`str
2287             ESN, something like: NFCDCH-MC-D7D6F54LOPY8J416T72MQXX3RD20ME
2288         """
2289         # we generate an esn from device strings for android
2290         import subprocess
2291         try:
2292             manufacturer = subprocess.check_output(["/system/bin/getprop", "ro.product.manufacturer"])
2293             if manufacturer:
2294                 esn = 'NFANDROID1-PRV-'
2295                 input = subprocess.check_output(["/system/bin/getprop", "ro.nrdp.modelgroup"])
2296                 if not input:
2297                     esn = esn + 'T-L3-'
2298                 else:
2299                     esn = esn + input.strip(' \t\n\r') + '-'
2300                 esn = esn + '{:5}'.format(manufacturer.strip(' \t\n\r').upper())
2301                 input = subprocess.check_output(["/system/bin/getprop" ,"ro.product.model"])
2302                 esn = esn + input.strip(' \t\n\r').replace(' ', '=').upper()
2303                 self.log(msg='Android generated ESN:' + esn)
2304                 return esn
2305         except OSError as e:
2306             self.log(msg='Ignoring exception for non Android devices')
2307
2308         # values are accessible via dict (sloppy parsing successfull)
2309         if type(netflix_page_data) == dict:
2310             return netflix_page_data.get('esn', '')
2311
2312         esn = ''
2313
2314         # values are stored in lists (returned from JS parser)
2315         for item in netflix_page_data:
2316             if 'esnGeneratorModel' in dict(item).keys():
2317                 esn = item['esnGeneratorModel']['data']['esn']
2318         return esn
2319
2320     def _parse_page_contents (self, page_soup):
2321         """Call all the parsers we need to extract all the session relevant data from the HTML page
2322            Directly assigns it to the NetflixSession instance
2323
2324         Parameters
2325         ----------
2326         page_soup : :obj:`BeautifulSoup`
2327             Instance of an BeautifulSoup document or node containing the complete page contents
2328         """
2329         netflix_page_data = self.extract_inline_netflix_page_data(page_soup=page_soup)
2330         self.user_data = self._parse_user_data(netflix_page_data=netflix_page_data)
2331         self.esn = self._parse_esn_data(netflix_page_data=netflix_page_data)
2332         self.api_data = self._parse_api_base_data(netflix_page_data=netflix_page_data)
2333         self.profiles = self._parse_profile_data(netflix_page_data=netflix_page_data)
2334         self.log(msg='Found ESN "' + self.esn + '"')
2335         return netflix_page_data