/
NetflixSession.py
2161 lines (1906 loc) · 77.8 KB
/
NetflixSession.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# pylint: skip-file
# -*- coding: utf-8 -*-
# Author: asciidisco
# Module: default
# Created on: 13.01.2017
# License: MIT https://goo.gl/5bMj3H
"""Netflix API management"""
import os
import sys
import json
from time import time
try:
from urllib.parse import quote, unquote
except ImportError:
from urllib import quote, unquote
from re import compile as recompile, DOTALL
from base64 import urlsafe_b64encode
from requests import session, cookies
from resources.lib.compat import itername
from resources.lib.utils import noop, get_user_agent
from collections import OrderedDict
try:
import cPickle as pickle
except:
import pickle
FETCH_VIDEO_REQUEST_COUNT = 26
ART_FANART_SIZE = '1080'
# Lower quality for episodes than 1080, because it provides more variance
# (1080 is usually the same as interestingMoment for episodes)
ART_FANART_SIZE_EPISODE = '720'
ART_MOMENT_SIZE_SMALL = '_665x375'
ART_MOMENT_SIZE_LARGE = '_1920x1080'
ART_BOX_SIZE_POSTER = '_342x684'
ART_BOX_SIZE_SMALL = '_665x375'
ART_BOX_SIZE_LARGE = '_1920x1080'
ART_LOGO_SIZE = '_550x124'
class NetflixSession(object):
"""Helps with login/session management of Netflix users & API handling"""
base_url = 'https://www.netflix.com'
"""str: Secure Netflix url"""
urls = {
'login': '/login',
'browse': '/browse',
'video_list_ids': '/preflight',
'shakti': '/pathEvaluator',
'profiles': '/profiles/manage',
'switch_profiles': '/profiles/switch',
'adult_pin': '/pin/service',
'metadata': '/metadata',
'set_video_rating': '/setVideoRating',
'update_my_list': '/playlistop',
'kids': '/Kids'
}
""":obj:`dict` of :obj:`str`
List of all static endpoints for HTML/JSON POST/GET requests"""
video_list_keys = ['user', 'genres', 'recommendations']
""":obj:`list` of :obj:`str`
Divide the users video lists into
3 different categories (for easier digestion)"""
profiles = {}
""":obj:`dict`
Dict of user profiles, user id is the key:
"72ERT45...": {
"profileName": "username",
"avatar": "http://..../avatar.png",
"id": "72ERT45...",
"isAccountOwner": False,
"isActive": True,
"isFirstUse": False
}
"""
user_data = {}
""":obj:`dict`
dict of user data (used for authentication):
{
"guid": "72ERT45...",
"authURL": "145637....",
"gpsModel": "harris"
}
"""
api_data = {}
""":obj:`dict`
dict of api data (used to build up the api urls):
{
"API_BASE_URL": "/shakti",
"API_ROOT": "https://www.netflix.com/api",
"BUILD_IDENTIFIER": "113b89c9", "
ICHNAEA_ROOT": "/ichnaea"
}
"""
esn = ''
"""str: ESN - something like: NFCDCH-MC-D7D6F54LOPY8J416T72MQXX3RD20ME"""
page_items = [
'models/userInfo/data/authURL',
'models/serverDefs/data/BUILD_IDENTIFIER',
'models/serverDefs/data/ICHNAEA_ROOT',
'models/serverDefs/data/API_ROOT',
'models/serverDefs/data/API_BASE_URL',
'models/playerModel/data/config/ui/initParams/apiUrl',
'models/esnGeneratorModel/data/esn',
'gpsModel',
'models/userInfo/data/countryOfSignup',
'models/userInfo/data/membershipStatus',
'models/memberContext/data/geo/preferredLocale'
]
def __init__(self, cookie_path, data_path, verify_ssl, nx_common):
"""Stores the cookie path for later use & instanciates a requests
session with a proper user agent & stored cookies/data if available
Parameters
----------
cookie_path : :obj:`str`
Cookie location
data_path : :obj:`str`
User data cache location
log_fn : :obj:`fn`
optional log function
"""
self.cookie_path = cookie_path
self.data_path = data_path
self.verify_ssl = verify_ssl
self.nx_common = nx_common
self.parsed_cookies = {}
self.parsed_user_data = {}
self._init_session()
def extract_json(self, content, name):
# Extract json from netflix content page
json_array = recompile(r"netflix\.%s\s*=\s*(.*?);\s*</script>" % name, DOTALL).findall(content)
if not json_array:
return {} # Return an empty dict if json not found !
json_str = json_array[0]
json_str = json_str.replace('\"', '\\"') # Hook for escape double-quotes
json_str = json_str.replace('\\s', '\\\\s') # Hook for escape \s in json regex
json_str = json_str.encode().decode('unicode_escape') # finally decoding...
return json.loads(json_str, encoding='utf-8', strict=False)
def extract_inline_netflix_page_data(self, content='', items=None):
"""Extract the essential data from the page contents
The contents of the parsable tags looks something like this:
<script>
window.netflix = window.netflix || {} ;
netflix.notification = {
"constants":{"sessionLength":30,"ownerToken":"ZDD...};
</script>
:return: List
List of all the serialized data pulled out of the pages <script/> tags
"""
# Uncomment the two lines below for saving content to disk (if ask you for debug)
# DO NOT PASTE THE CONTENT OF THIS FILE PUBLICALLY ON THE INTERNET, IT MAY CONTAIN SENSITIVE INFORMATION
# USE IT ONLY FOR DEBUGGING
# with open(self.data_path + 'raw_content', "wb") as f:
# f.write(content)
self.nx_common.log(msg='Parsing inline data...')
items = self.page_items if items is None else items
user_data = {'gpsModel': 'harris'}
content = content.decode('utf-8');
react_context = self.extract_json(content, 'reactContext')
# iterate over all wanted item keys & try to fetch them
for item in items:
keys = item.split("/")
val = None
for key in keys:
val = val.get(key, None) if val else react_context.get(key, None)
if not val:
break
if val:
user_data.update({key: val})
# fetch profiles & avatars
profiles = self.get_profiles(content=content)
# get guid of active user
for guid in profiles:
if profiles[guid].get('isActive', False) is True:
user_data['guid'] = guid
# verify the data based on the authURL
is_valid_user_data = self._verfify_auth_and_profiles_data(
data=user_data,
profiles=profiles)
if is_valid_user_data is not False:
self.nx_common.log(msg='Parsing inline data parsing successfull')
return (user_data, profiles)
self.nx_common.log(msg='Parsing inline data failed')
return (user_data, profiles)
def get_profiles(self, content):
"""ADD ME"""
profiles = {}
falkor_cache = self.extract_json(content, 'falcorCache')
_profiles = falkor_cache.get('profiles', {})
for guid in _profiles:
if not isinstance(_profiles[guid], dict):
continue
_profile = _profiles[guid]['summary']
if 'value' in _profile:
_profile = _profile['value']
_avatar_path = _profiles[guid]['avatar']
if 'value' in _avatar_path:
_avatar_path = _avatar_path['value']
_avatar_path.extend([u'images', u'byWidth', u'320', u'value'])
_profile['avatar'] = self.__recursive_dict(_avatar_path, falkor_cache)
profiles.update({guid: _profile})
return profiles
@staticmethod
def __recursive_dict(search, dict, index=0):
if (index + 1 == len(search)):
return dict[search[index]]
return NetflixSession.__recursive_dict(search, dict[search[index]], index + 1)
def is_logged_in(self, account):
"""
Determines if a user is already logged in (with a valid cookie)
Parameters
----------
account : :obj:`dict` of :obj:`str`
Dict containing an email, country & a password property
Returns
-------
bool
User is already logged in (e.g. Cookie is valid) or not
"""
# load cookies
account_hash = self._generate_account_hash(account=account)
cookies = self._load_cookies(
filename=self.cookie_path + '_' + account_hash)
if cookies is False:
return False
# find the earliest expiration date in the cookies
expires = 99999999999999999999
cur_stamp = int(time())
for domains in cookies[0]:
for domain in cookies[0][domains].keys():
for cookie_key in cookies[0][domains][domain]:
if cookies[0][domains][domain][cookie_key].expires is not None:
exp = int(cookies[0][domains][domain][cookie_key].expires)
if expires > exp:
expires = exp
if expires > cur_stamp:
self.nx_common.log(
msg='Cookie expires: ' + str(expires) + ' / ' + str(cur_stamp))
return True
# load the profiles page (to verify the user)
if not self.profiles:
response = self._session_get(component='profiles')
if response:
# parse out the needed inline information
user_data, profiles = self.extract_inline_netflix_page_data(
content=response.content)
self.profiles = profiles
# if we have profiles, cookie is still valid
if self.profiles:
return True
else:
return True
return False
def logout(self, mslResetCmd=None):
"""
Delete all cookies and session data
Parameters
----------
account : :obj:`dict` of :obj:`str`
Dict containing an email, country & a password property
"""
self._delete_cookies(path=self.cookie_path)
self._delete_data(path=self.data_path)
if mslResetCmd:
response = session().get(url=mslResetCmd)
self.nx_common.log(msg='MSL reset return code:' + response)
def login(self, account):
"""
Try to log in a user with its credentials
Stores the cookies & session data if the action is successfull
Parameters
----------
account : :obj:`dict` of :obj:`str`
Dict containing an email, country & a password property
Returns
-------
bool
User could be logged in or not
"""
page = self._session_get(component='profiles')
user_data, profiles = self.extract_inline_netflix_page_data(
content=page.content)
login_payload = {
'userLoginId': account.get('email'),
'email': account.get('email'),
'password': account.get('password'),
'rememberMe': 'true',
'flow': 'websiteSignUp',
'mode': 'login',
'action': 'loginAction',
'withFields': 'rememberMe,nextPage,userLoginId,password,email',
'authURL': user_data.get('authURL'),
'nextPage': '',
'showPassword': ''
}
# perform the login
login_response = self._session_post(
component='login',
data=login_payload)
user_data = self._parse_page_contents(content=login_response.content)
account_hash = self._generate_account_hash(account=account)
# we know that the login was successfull if we find ???
if user_data.get('membershipStatus') == 'CURRENT_MEMBER':
# store cookies for later requests
self._save_cookies(filename=self.cookie_path + '_' + account_hash)
self._save_data(filename=self.data_path + '_' + account_hash)
return True
return False
def switch_profile(self, profile_id, account):
"""
Switch the user profile based on a given profile id
Note: All available profiles & their ids can be found in
the ´profiles´ property after a successfull login
Parameters
----------
profile_id : :obj:`str`
User profile id
account : :obj:`dict` of :obj:`str`
Dict containing an email, country & a password property
Returns
-------
bool
User could be switched or not
"""
payload = {
'switchProfileGuid': profile_id,
'_': int(time()),
'authURL': self.user_data['authURL']
}
response = self._session_get(
component='switch_profiles',
type='api',
params=payload)
if response is None or response.status_code != 200:
return False
account_hash = self._generate_account_hash(account=account)
self.user_data['guid'] = profile_id
return self._save_data(filename=self.data_path + '_' + account_hash)
def send_adult_pin(self, pin):
"""
Send the adult pin to Netflix in case an adult rated video requests it
Parameters
----------
pin : :obj:`str`
The users adult pin
Returns
-------
bool
Pin was accepted or not
or
:obj:`dict` of :obj:`str`
Api call error
"""
payload = {
'pin': pin,
'authURL': self.user_data.get('authURL', '')
}
response = self._session_post(
component='adult_pin',
type='api',
data=payload)
pin_response = self._process_response(
response=response,
component=self._get_api_url_for(component='adult_pin'))
if 'error' in pin_response.keys():
self.nx_common.log(msg='Pin error')
self.nx_common.log(msg=str(pin_response))
return False
return pin_response.get('success', False)
def add_to_list(self, video_id):
"""Adds a video to "my list" on Netflix
Parameters
----------
video_id : :obj:`str`
ID of th show/video/movie to be added
Returns
-------
bool
Adding was successfull
"""
return self._update_my_list(video_id=video_id, operation='add')
def remove_from_list(self, video_id):
"""Removes a video from "my list" on Netflix
Parameters
----------
video_id : :obj:`str`
ID of th show/video/movie to be removed
Returns
-------
bool
Removing was successfull
"""
return self._update_my_list(video_id=video_id, operation='remove')
def rate_video(self, video_id, rating):
"""Rate a video on Netflix
Parameters
----------
video_id : :obj:`str`
ID of th show/video/movie to be rated
rating : :obj:`int`
Rating, must be between 0 & 10
Returns
-------
bool
Rating successfull or not
"""
# dirty rating validation
rating = int(rating)
if rating > 10 or rating < 0:
return False
# In opposition to Kodi, Netflix uses a rating from 0 to in 0.5 steps
if rating != 0:
rating = rating / 2
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json, text/javascript, */*',
}
params = {
'titleid': video_id,
'rating': rating
}
payload = json.dumps({
'authURL': self.user_data['authURL']
})
response = self._session_post(
component='set_video_rating',
type='api',
params=params,
headers=headers,
data=payload)
if response and response.status_code == 200:
return True
return False
def parse_video_list_ids(self, response_data):
"""Parse the list of video ids e.g. rip out the parts we need
Parameters
----------
response_data : :obj:`dict` of :obj:`str`
Parsed response JSON from the ´fetch_video_list_ids´ call
Returns
-------
:obj:`dict` of :obj:`dict`
Video list ids in the format:
{
"genres": {
"3589e2c6-ca3b-48b4-a72d-34f2c09ffbf4_11568367": {
"displayName": "US-Serien",
"id": "3589e2c6-ca3b-48b4-a72d-34f2c09ffbf4_11568367",
"index": 3,
"name": "genre",
"size": 38
},
"3589e2c6-ca3b-48b4-a72d-34f2c09ffbf4_11568368": {
"displayName": ...
},
},
"user": {
"3589e2c6-ca3b-48b4-a72d-34f2c09ffbf4_11568364": {
"displayName": "Meine Liste",
"id": "3589e2c6-ca3b-48b4-a72d-34f2c09ffbf4_11568364",
"index": 0,
"name": "queue",
"size": 2
},
"3589e2c6-ca3b-48b4-a72d-34f2c09ffbf4_11568365": {
"displayName": ...
},
},
"recommendations": {
"3589e2c6-ca3b-48b4-a72d-34f2c09ffbf4_11568382": {
"displayName": "Passend zu Family Guy",
"id": "3589e2c6-ca3b-48b4-a72d-34f2c09ffbf4_11568382",
"index": 18,
"name": "similars",
"size": 33
},
"3589e2c6-ca3b-48b4-a72d-34f2c09ffbf4_11568397": {
"displayName": ...
}
}
}
"""
# prepare the return dictionary
video_list_ids = {}
for key in self.video_list_keys:
video_list_ids[key] = {}
# check if the list items are hidden behind a `value` sub key
# this is the case when we fetch the lists via POST,
# not via a GET preflight request
if 'value' in response_data.keys():
response_data = response_data.get('value')
# subcatogorize the lists by their context
video_lists = response_data.get('lists', {})
for video_list_id in video_lists.keys():
video_list = video_lists[video_list_id]
if video_list.get('context', False) is not False:
ctx = video_list.get('context')
video_list_entry = self.parse_video_list_ids_entry(
id=video_list_id,
entry=video_list)
if ctx == 'genre':
video_list_ids['genres'].update(video_list_entry)
elif ctx == 'similars' or ctx == 'becauseYouAdded':
video_list_ids['recommendations'].update(video_list_entry)
else:
video_list_ids['user'].update(video_list_entry)
return video_list_ids
def parse_video_list_ids_entry(self, id, entry):
"""Parse a video id entry e.g. rip out the parts we need
Parameters
----------
response_data : :obj:`dict` of :obj:`str`
Dictionary entry from the ´fetch_video_list_ids´ call
Returns
-------
id : :obj:`str`
Unique id of the video list
entry : :obj:`dict` of :obj:`str`
Video list entry in the format:
"3589e2c6-ca3b-48b4-a72d-34f2c09ffbf4_11568382": {
"displayName": "Passend zu Family Guy",
"id": "3589e2c6-ca3b-48b4-a72d-34f2c09ffbf4_11568382",
"index": 18,
"name": "similars",
"size": 33
}
"""
return {
id: {
'id': id,
'index': entry['index'],
'name': entry['context'],
'displayName': entry['displayName'],
'size': entry['length']
}
}
def parse_video_list(self, response_data, term=None):
"""Parse a list of videos
Parameters
----------
response_data : :obj:`dict` of :obj:`str`
Parsed response JSON from the `fetch_video_list` call
Returns
-------
:obj:`dict` of :obj:`dict`
Video list in the format:
{
"372203": {
"artwork": null,
"boxarts": {
"big": "https://art-s.nflximg.net/5e7d3/b....jpg",
"small": "https://art-s.nflximg.net/57543/a....jpg"
},
"cast": [
"Christine Elise",
"Brad Dourif",
"Grace Zabriskie",
"Jenny Agutter",
"John Lafia",
"Gerrit Graham",
"Peter Haskell",
"Alex Vincent",
"Beth Grant"
],
"creators": [],
"directors": [],
"episode_count": null,
"genres": [
"Horrorfilme"
],
"id": "372203",
"in_my_list": true,
"interesting_moment": "https://art-s.nflximg.net/0....jpg",
"list_id": "9588df32-f957-40e4-9055-1f6f33b60103_46891306",
"maturity": {
"board": "FSK",
"description": "Nur f\u00fcr Erwachsene geeignet.",
"level": 1000,
"value": "18"
},
"quality": "540",
"rating": 3.1707757,
"regular_synopsis": "Ein Spielzeughersteller e....",
"runtime": 5028,
"seasons_count": null,
"seasons_label": null,
"synopsis": "Die allseits beliebte, vo....",
"tags": [
"Brutal",
"Spannend"
],
"title": "Chucky 2 \u2013 Die M\u00f6rderpuppe ist...",
"type": "movie",
"watched": false,
"year": 1990
},
"80011356": {
"artwork": null,
"boxarts": {
"big": "https://art-s.nflximg.net/7c10d/5dc....jpg",
"small": "https://art-s.nflximg.net/5bc0e/f3be3....jpg"
},
"cast": [
"Bjarne M\u00e4del"
],
"creators": [],
"directors": [
"Arne Feldhusen"
],
"episode_count": 24,
"genres": [
"Deutsche Serien",
"Serien",
"Comedyserien"
],
"id": "80011356",
"in_my_list": true,
"interesting_moment": "https://art-s.nflximg.net/01...jpg",
"list_id": "9588df32-f957-40e4-9055-1f6f33b60103_46891306",
"maturity": {
"board": "FSF",
"description": "Geeignet ab 12 Jahren.",
"level": 80,
"value": "12"
},
"quality": "720",
"rating": 4.4394655,
"regular_synopsis": "Comedy-Serie \u00fcber...",
"runtime": null,
"seasons_count": 5,
"seasons_label": "5 Staffeln",
"synopsis": "In den meisten Krimiserien werde...",
"tags": [
"Zynisch"
],
"title": "Der Tatortreiniger",
"type": "show",
"watched": false,
"year": 2015
},
}
"""
video_ids = []
raw_video_list = response_data.get('value', {})
# search results have sorting given in references
if term and 'search' in raw_video_list:
try:
reference = raw_video_list.get('search').get('byTerm').get('|'+term).get('titles').get('48')[2]
references = raw_video_list.get('search').get('byReference').get(reference)
for reference_id in range (0, 48):
video_ids.append(references.get(str(reference_id)).get('reference')[1])
except:
return {}
else:
for video_id in raw_video_list.get('videos', {}):
if self._is_size_key(key=video_id) is False:
video_ids.append(video_id);
video_list = OrderedDict()
netflix_list_id = self.parse_netflix_list_id(video_list=raw_video_list)
for video_id in video_ids:
video_list_entry = self.parse_video_list_entry(
id=video_id,
list_id=netflix_list_id,
video=raw_video_list.get('videos', {}).get(video_id),
persons=raw_video_list.get('person'),
genres=raw_video_list.get('genres'))
video_list.update(video_list_entry)
return video_list
def parse_video_list_entry(self, id, list_id, video, persons, genres):
"""Parse a video list entry e.g. rip out the parts we need
Parameters
----------
id : :obj:`str`
Unique id of the video
list_id : :obj:`str`
Unique id of the containing list
video : :obj:`dict` of :obj:`str`
Video entry from the ´fetch_video_list´ call
persons : :obj:`dict` of :obj:`dict` of :obj:`str`
List of persons with reference ids
persons : :obj:`dict` of :obj:`dict` of :obj:`str`
List of genres with reference ids
Returns
-------
entry : :obj:`dict` of :obj:`dict` of :obj:`str`
Video list entry in the format:
{
"372203": {
"artwork": null,
"boxarts": {
"big": "https://art-s.nflximg.net/5e7d3/b3b...b55e7d3.jpg",
"small": "https://art-s.nflximg.net/57543/a039...957543.jpg"
},
"cast": [
"Christine Elise",
"Brad Dourif",
"Grace Zabriskie",
"Jenny Agutter",
"John Lafia",
"Gerrit Graham",
"Peter Haskell",
"Alex Vincent",
"Beth Grant"
],
"creators": [],
"directors": [],
"episode_count": null,
"genres": [
"Horrorfilme"
],
"id": "372203",
"in_my_list": true,
"interesting_moment": "https://art-s.nflximg.net/095...4.jpg",
"list_id": "9588df32-f957-40e4-9055-1f6f33b60103_46891306",
"maturity": {
"board": "FSK",
"description": "Nur f\u00fcr Erwachsene geeignet.",
"level": 1000,
"value": "18"
},
"quality": "540",
"rating": 3.1707757,
"regular_synopsis": "Ein Spielzeughersteller erweck...",
"runtime": 5028,
"seasons_count": null,
"seasons_label": null,
"synopsis": "Die allseits beliebte, von D\u00e4mone...",
"tags": [
"Brutal",
"Spannend"
],
"title": "Chucky 2 \u2013 Die M\u00f6rderpuppe ist wieder da",
"type": "movie",
"watched": false,
"year": 1990
}
}
"""
season_info = self.parse_season_information_for_video(video=video)
# determine rating
rating = 0
user_rating = video.get('userRating', {})
if user_rating.get('average', None) is not None:
rating = user_rating.get('average', 0)
else:
rating = user_rating.get('predicted', 0)
# determine maturity data
maturity_rating = video.get('maturity', {}).get('rating', {})
maturity = {
'board': maturity_rating.get('board', None),
'value': maturity_rating.get('value', None),
'description': maturity_rating.get('maturityDescription', None),
'level': maturity_rating.get('maturityLevel', None),
}
# determine artwork
boxarts = video.get('boxarts', {})
bx_small = boxarts.get(ART_BOX_SIZE_SMALL, {}).get('jpg', {}).get('url')
bx_big = boxarts.get(ART_BOX_SIZE_LARGE, {}).get('jpg', {}).get('url')
bx_poster = boxarts.get(ART_BOX_SIZE_POSTER, {}).get('jpg', {}).get('url')
moment = video.get('interestingMoment', {}).get(ART_MOMENT_SIZE_LARGE, {}).get('jpg', {}).get('url')
artwork = next(iter(video.get('BGImages', {}).get(ART_FANART_SIZE, {}).get('jpg', [{}])), {}).get('url')
logo = video.get('bb2OGLogo', {}).get(ART_LOGO_SIZE, {}).get('png', {}).get('url')
return {
id: {
'id': id,
'list_id': list_id,
'title': video.get('title'),
'synopsis': video.get('synopsis'),
'regular_synopsis': video.get('regularSynopsis'),
'type': video.get('summary', {}).get('type'),
'rating': rating,
'episode_count': season_info.get('episode_count'),
'seasons_label': season_info.get('seasons_label'),
'seasons_count': season_info.get('seasons_count'),
'in_my_list': video.get('queue', {}).get('inQueue'),
'year': video.get('releaseYear'),
'runtime': self.parse_runtime_for_video(video=video),
'watched': video.get('watched', None),
'tags': self.parse_tags_for_video(video=video),
'genres': self.parse_genres_for_video(
video=video,
genres=genres),
'quality': self.parse_quality_for_video(video=video),
'cast': self.parse_cast_for_video(
video=video,
persons=persons),
'directors': self.parse_directors_for_video(
video=video,
persons=persons),
'creators': self.parse_creators_for_video(
video=video,
persons=persons),
'maturity': maturity,
'boxarts': {
'small': bx_small,
'big': bx_big,
'poster': bx_poster
},
'interesting_moment': moment,
'artwork': artwork,
'clearlogo': logo
}
}
def parse_creators_for_video(self, video, persons):
"""Matches ids with person names to generate a list of creators
Parameters
----------
video : :obj:`dict` of :obj:`str`
Dictionary entry for one video entry
persons : :obj:`dict` of :obj:`str`
Raw resposne of all persons delivered by the API call
Returns
-------
:obj:`list` of :obj:`str`
List of creators
"""
creators = []
for person_key in dict(persons).keys():
is_size_key = self._is_size_key(key=person_key)
if is_size_key is False and person_key != 'summary':
for creator_key in dict(video.get('creators', {})).keys():
is_size_key = self._is_size_key(key=creator_key)
if is_size_key is False and creator_key != 'summary':
if video['creators'][creator_key][1] == person_key:
creators.append(persons[person_key]['name'])
return creators
def parse_directors_for_video(self, video, persons):
"""Matches ids with person names to generate a list of directors
Parameters
----------
video : :obj:`dict` of :obj:`str`
Dictionary entry for one video entry
persons : :obj:`dict` of :obj:`str`
Raw resposne of all persons delivered by the API call
Returns
-------
:obj:`list` of :obj:`str`
List of directors
"""
directors = []
for person_key in dict(persons).keys():
is_size_key = self._is_size_key(key=person_key)
if is_size_key is False and person_key != 'summary':
for director_key in dict(video.get('directors', {})).keys():
is_size_key = self._is_size_key(key=director_key)
if is_size_key is False and director_key != 'summary':
if video['directors'][director_key][1] == person_key:
directors.append(persons[person_key]['name'])
return directors
def parse_cast_for_video(self, video, persons):
"""Matches ids with person names to generate a list of cast members
Parameters
----------
video : :obj:`dict` of :obj:`str`
Dictionary entry for one video entry
persons : :obj:`dict` of :obj:`str`
Raw resposne of all persons delivered by the API call
Returns
-------
:obj:`list` of :obj:`str`
List of cast members
"""
cast = []
for person_key in dict(persons).keys():
is_size_key = self._is_size_key(key=person_key)
if is_size_key is False and person_key != 'summary':
for cast_key in dict(video['cast']).keys():
is_size_key = self._is_size_key(key=cast_key)
if is_size_key is False and cast_key != 'summary':
if video['cast'][cast_key][1] == person_key:
cast.append(persons[person_key]['name'])
return cast
def parse_genres_for_video(self, video, genres):
"""Matches ids with genre names to generate a list of genres for a video
Parameters
----------
video : :obj:`dict` of :obj:`str`
Dictionary entry for one video entry
genres : :obj:`dict` of :obj:`str`
Raw resposne of all genres delivered by the API call
Returns
-------
:obj:`list` of :obj:`str`
List of genres
"""
video_genres = []
for video_key, video_genre in getattr(video.get('genres', {}), itername)():
is_size_key = self._is_size_key(key=video_key)
if is_size_key is False and video_key != 'summary':
name = genres.get(video_genre[1], {}).get('name')