]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/shahid.py
Completely change project name to yt-dlp (#85)
[yt-dlp.git] / yt_dlp / extractor / shahid.py
CommitLineData
3be3c622 1# coding: utf-8
2from __future__ import unicode_literals
3
3b4b66b5 4import json
78466fca
RA
5import math
6import re
3b4b66b5 7
78466fca 8from .aws import AWSIE
3b4b66b5 9from ..compat import compat_HTTPError
02c126a7 10from ..utils import (
78466fca 11 clean_html,
02c126a7 12 ExtractorError,
78466fca 13 InAdvancePagedList,
c576ef1e
S
14 int_or_none,
15 parse_iso8601,
41aa4425 16 str_or_none,
3b4b66b5 17 urlencode_postdata,
84c0ed50 18)
114ed20e 19
3be3c622 20
78466fca
RA
21class 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': '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',
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
50class ShahidIE(ShahidBaseIE):
3b4b66b5 51 _NETRC_MACHINE = 'shahid'
414e7094 52 _VALID_URL = r'https?://shahid\.mbc\.net/ar/(?:serie|show|movie)s/[^/]+/(?P<type>episode|clip|movie)-(?P<id>\d+)'
c576ef1e 53 _TESTS = [{
414e7094 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',
c576ef1e 55 'info_dict': {
414e7094 56 'id': '275286',
5de5ab89 57 'ext': 'mp4',
414e7094
RA
58 'title': 'مجلس الشباب الموسم 1 كليب 1',
59 'timestamp': 1506988800,
60 'upload_date': '20171003',
114ed20e 61 },
c576ef1e
S
62 'params': {
63 # m3u8 download
64 'skip_download': True,
114ed20e 65 }
3b4b66b5 66 }, {
414e7094 67 'url': 'https://shahid.mbc.net/ar/movies/%D8%A7%D9%84%D9%82%D9%86%D8%A7%D8%B5%D8%A9/movie-151746',
3b4b66b5 68 'only_matching': True
c576ef1e
S
69 }, {
70 # shahid plus subscriber only
414e7094 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',
c576ef1e
S
72 'only_matching': True
73 }]
114ed20e 74
414e7094
RA
75 def _real_initialize(self):
76 email, password = self._get_login_info()
77 if email is None:
78 return
79
78466fca
RA
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
414e7094 94
3b4b66b5
RA
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
114ed20e 106 def _real_extract(self, url):
3b4b66b5 107 page_type, video_id = re.match(self._VALID_URL, url).groups()
414e7094
RA
108 if page_type == 'clip':
109 page_type = 'episode'
c576ef1e 110
78466fca
RA
111 playout = self._call_api(
112 'playout/url/' + video_id, video_id)['playout']
a62fd1af 113
63ad4d43 114 if not self._downloader.params.get('allow_unplayable_formats') and playout.get('drm'):
2334762b 115 raise ExtractorError('This video is DRM protected.', expected=True)
116
414e7094 117 formats = self._extract_m3u8_formats(playout['url'], video_id, 'mp4')
19dbaeec 118 self._sort_formats(formats)
3be3c622 119
78466fca
RA
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(
3b4b66b5
RA
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=',
78466fca
RA
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)
c576ef1e 139
78466fca 140 video = data[page_type]
c576ef1e 141 title = video['title']
c576ef1e
S
142 categories = [
143 category['name']
144 for category in video.get('genres', []) if 'name' in category]
a62fd1af 145
114ed20e 146 return {
147 'id': video_id,
148 'title': title,
41aa4425
RA
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')),
c576ef1e 153 'categories': categories,
41aa4425
RA
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,
114ed20e 160 'formats': formats,
161 }
78466fca
RA
162
163
164class 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'))