]> git.bitcoin.ninja Git - youtube-dl/blob - youtube_dl/extractor/shahid.py
[pornhub] Improve locked videos detection (closes #22449, closes #22780)
[youtube-dl] / youtube_dl / extractor / shahid.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import json
5 import math
6 import re
7
8 from .aws import AWSIE
9 from ..compat import compat_HTTPError
10 from ..utils import (
11     clean_html,
12     ExtractorError,
13     InAdvancePagedList,
14     int_or_none,
15     parse_iso8601,
16     str_or_none,
17     urlencode_postdata,
18 )
19
20
21 class ShahidBaseIE(AWSIE):
22     _AWS_PROXY_HOST = 'api2.shahid.net'
23     _AWS_API_KEY = '2RRtuMHx95aNI1Kvtn2rChEuwsCogUd4samGPjLh'
24
25     def _handle_error(self, e):
26         fail_data = self._parse_json(
27             e.cause.read().decode('utf-8'), None, fatal=False)
28         if fail_data:
29             faults = fail_data.get('faults', [])
30             faults_message = ', '.join([clean_html(fault['userMessage']) for fault in faults if fault.get('userMessage')])
31             if faults_message:
32                 raise ExtractorError(faults_message, expected=True)
33
34     def _call_api(self, path, video_id, request=None):
35         query = {}
36         if request:
37             query['request'] = json.dumps(request)
38         try:
39             return self._aws_execute_api({
40                 'uri': '/proxy/v2/' + path,
41                 'access_key': 'AKIAI6X4TYCIXM2B7MUQ',
42                 'secret_key': '4WUUJWuFvtTkXbhaWTDv7MhO+0LqoYDWfEnUXoWn',
43             }, video_id, query)
44         except ExtractorError as e:
45             if isinstance(e.cause, compat_HTTPError):
46                 self._handle_error(e)
47             raise
48
49
50 class ShahidIE(ShahidBaseIE):
51     _NETRC_MACHINE = 'shahid'
52     _VALID_URL = r'https?://shahid\.mbc\.net/ar/(?:serie|show|movie)s/[^/]+/(?P<type>episode|clip|movie)-(?P<id>\d+)'
53     _TESTS = [{
54         'url': 'https://shahid.mbc.net/ar/shows/%D9%85%D8%AC%D9%84%D8%B3-%D8%A7%D9%84%D8%B4%D8%A8%D8%A7%D8%A8-%D8%A7%D9%84%D9%85%D9%88%D8%B3%D9%85-1-%D9%83%D9%84%D9%8A%D8%A8-1/clip-275286',
55         'info_dict': {
56             'id': '275286',
57             'ext': 'mp4',
58             'title': 'مجلس الشباب الموسم 1 كليب 1',
59             'timestamp': 1506988800,
60             'upload_date': '20171003',
61         },
62         'params': {
63             # m3u8 download
64             'skip_download': True,
65         }
66     }, {
67         'url': 'https://shahid.mbc.net/ar/movies/%D8%A7%D9%84%D9%82%D9%86%D8%A7%D8%B5%D8%A9/movie-151746',
68         'only_matching': True
69     }, {
70         # shahid plus subscriber only
71         'url': 'https://shahid.mbc.net/ar/series/%D9%85%D8%B1%D8%A7%D9%8A%D8%A7-2011-%D8%A7%D9%84%D9%85%D9%88%D8%B3%D9%85-1-%D8%A7%D9%84%D8%AD%D9%84%D9%82%D8%A9-1/episode-90511',
72         'only_matching': True
73     }]
74
75     def _real_initialize(self):
76         email, password = self._get_login_info()
77         if email is None:
78             return
79
80         try:
81             user_data = self._download_json(
82                 'https://shahid.mbc.net/wd/service/users/login',
83                 None, 'Logging in', data=json.dumps({
84                     'email': email,
85                     'password': password,
86                     'basic': 'false',
87                 }).encode('utf-8'), headers={
88                     'Content-Type': 'application/json; charset=UTF-8',
89                 })['user']
90         except ExtractorError as e:
91             if isinstance(e.cause, compat_HTTPError):
92                 self._handle_error(e)
93             raise
94
95         self._download_webpage(
96             'https://shahid.mbc.net/populateContext',
97             None, 'Populate Context', data=urlencode_postdata({
98                 'firstName': user_data['firstName'],
99                 'lastName': user_data['lastName'],
100                 'userName': user_data['email'],
101                 'csg_user_name': user_data['email'],
102                 'subscriberId': user_data['id'],
103                 'sessionId': user_data['sessionId'],
104             }))
105
106     def _real_extract(self, url):
107         page_type, video_id = re.match(self._VALID_URL, url).groups()
108         if page_type == 'clip':
109             page_type = 'episode'
110
111         playout = self._call_api(
112             'playout/url/' + video_id, video_id)['playout']
113
114         if playout.get('drm'):
115             raise ExtractorError('This video is DRM protected.', expected=True)
116
117         formats = self._extract_m3u8_formats(playout['url'], video_id, 'mp4')
118         self._sort_formats(formats)
119
120         # video = self._call_api(
121         #     'product/id', video_id, {
122         #         'id': video_id,
123         #         'productType': 'ASSET',
124         #         'productSubType': page_type.upper()
125         #     })['productModel']
126
127         response = self._download_json(
128             'http://api.shahid.net/api/v1_1/%s/%s' % (page_type, video_id),
129             video_id, 'Downloading video JSON', query={
130                 'apiKey': 'sh@hid0nlin3',
131                 'hash': 'b2wMCTHpSmyxGqQjJFOycRmLSex+BpTK/ooxy6vHaqs=',
132             })
133         data = response.get('data', {})
134         error = data.get('error')
135         if error:
136             raise ExtractorError(
137                 '%s returned error: %s' % (self.IE_NAME, '\n'.join(error.values())),
138                 expected=True)
139
140         video = data[page_type]
141         title = video['title']
142         categories = [
143             category['name']
144             for category in video.get('genres', []) if 'name' in category]
145
146         return {
147             'id': video_id,
148             'title': title,
149             'description': video.get('description'),
150             'thumbnail': video.get('thumbnailUrl'),
151             'duration': int_or_none(video.get('duration')),
152             'timestamp': parse_iso8601(video.get('referenceDate')),
153             'categories': categories,
154             'series': video.get('showTitle') or video.get('showName'),
155             'season': video.get('seasonTitle'),
156             'season_number': int_or_none(video.get('seasonNumber')),
157             'season_id': str_or_none(video.get('seasonId')),
158             'episode_number': int_or_none(video.get('number')),
159             'episode_id': video_id,
160             'formats': formats,
161         }
162
163
164 class ShahidShowIE(ShahidBaseIE):
165     _VALID_URL = r'https?://shahid\.mbc\.net/ar/(?:show|serie)s/[^/]+/(?:show|series)-(?P<id>\d+)'
166     _TESTS = [{
167         'url': 'https://shahid.mbc.net/ar/shows/%D8%B1%D8%A7%D9%85%D8%B2-%D9%82%D8%B1%D8%B4-%D8%A7%D9%84%D8%A8%D8%AD%D8%B1/show-79187',
168         'info_dict': {
169             'id': '79187',
170             'title': 'رامز قرش البحر',
171             'description': 'md5:c88fa7e0f02b0abd39d417aee0d046ff',
172         },
173         'playlist_mincount': 32,
174     }, {
175         'url': 'https://shahid.mbc.net/ar/series/How-to-live-Longer-(The-Big-Think)/series-291861',
176         'only_matching': True
177     }]
178     _PAGE_SIZE = 30
179
180     def _real_extract(self, url):
181         show_id = self._match_id(url)
182
183         product = self._call_api(
184             'playableAsset', show_id, {'showId': show_id})['productModel']
185         playlist = product['playlist']
186         playlist_id = playlist['id']
187         show = product.get('show', {})
188
189         def page_func(page_num):
190             playlist = self._call_api(
191                 'product/playlist', show_id, {
192                     'playListId': playlist_id,
193                     'pageNumber': page_num,
194                     'pageSize': 30,
195                     'sorts': [{
196                         'order': 'DESC',
197                         'type': 'SORTDATE'
198                     }],
199                 })
200             for product in playlist.get('productList', {}).get('products', []):
201                 product_url = product.get('productUrl', []).get('url')
202                 if not product_url:
203                     continue
204                 yield self.url_result(
205                     product_url, 'Shahid',
206                     str_or_none(product.get('id')),
207                     product.get('title'))
208
209         entries = InAdvancePagedList(
210             page_func,
211             math.ceil(playlist['count'] / self._PAGE_SIZE),
212             self._PAGE_SIZE)
213
214         return self.playlist_result(
215             entries, show_id, show.get('title'), show.get('description'))