drtv.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import binascii
  4. import hashlib
  5. import re
  6. from .common import InfoExtractor
  7. from ..aes import aes_cbc_decrypt
  8. from ..compat import compat_urllib_parse_unquote
  9. from ..utils import (
  10. bytes_to_intlist,
  11. ExtractorError,
  12. int_or_none,
  13. intlist_to_bytes,
  14. float_or_none,
  15. mimetype2ext,
  16. str_or_none,
  17. unified_timestamp,
  18. update_url_query,
  19. url_or_none,
  20. )
  21. class DRTVIE(InfoExtractor):
  22. _VALID_URL = r'https?://(?:www\.)?dr\.dk/(?:tv/se|nyheder|radio/ondemand)/(?:[^/]+/)*(?P<id>[\da-z-]+)(?:[/#?]|$)'
  23. _GEO_BYPASS = False
  24. _GEO_COUNTRIES = ['DK']
  25. IE_NAME = 'drtv'
  26. _TESTS = [{
  27. 'url': 'https://www.dr.dk/tv/se/boern/ultra/klassen-ultra/klassen-darlig-taber-10',
  28. 'md5': '25e659cccc9a2ed956110a299fdf5983',
  29. 'info_dict': {
  30. 'id': 'klassen-darlig-taber-10',
  31. 'ext': 'mp4',
  32. 'title': 'Klassen - Dårlig taber (10)',
  33. 'description': 'md5:815fe1b7fa656ed80580f31e8b3c79aa',
  34. 'timestamp': 1539085800,
  35. 'upload_date': '20181009',
  36. 'duration': 606.84,
  37. 'series': 'Klassen',
  38. 'season': 'Klassen I',
  39. 'season_number': 1,
  40. 'season_id': 'urn:dr:mu:bundle:57d7e8216187a4031cfd6f6b',
  41. 'episode': 'Episode 10',
  42. 'episode_number': 10,
  43. 'release_year': 2016,
  44. },
  45. 'expected_warnings': ['Unable to download f4m manifest'],
  46. }, {
  47. # embed
  48. 'url': 'https://www.dr.dk/nyheder/indland/live-christianias-rydning-af-pusher-street-er-i-gang',
  49. 'info_dict': {
  50. 'id': 'urn:dr:mu:programcard:57c926176187a50a9c6e83c6',
  51. 'ext': 'mp4',
  52. 'title': 'christiania pusher street ryddes drdkrjpo',
  53. 'description': 'md5:2a71898b15057e9b97334f61d04e6eb5',
  54. 'timestamp': 1472800279,
  55. 'upload_date': '20160902',
  56. 'duration': 131.4,
  57. },
  58. 'params': {
  59. 'skip_download': True,
  60. },
  61. 'expected_warnings': ['Unable to download f4m manifest'],
  62. }, {
  63. # with SignLanguage formats
  64. 'url': 'https://www.dr.dk/tv/se/historien-om-danmark/-/historien-om-danmark-stenalder',
  65. 'info_dict': {
  66. 'id': 'historien-om-danmark-stenalder',
  67. 'ext': 'mp4',
  68. 'title': 'Historien om Danmark: Stenalder',
  69. 'description': 'md5:8c66dcbc1669bbc6f873879880f37f2a',
  70. 'timestamp': 1546628400,
  71. 'upload_date': '20190104',
  72. 'duration': 3502.56,
  73. 'formats': 'mincount:20',
  74. },
  75. 'params': {
  76. 'skip_download': True,
  77. },
  78. }]
  79. def _real_extract(self, url):
  80. video_id = self._match_id(url)
  81. webpage = self._download_webpage(url, video_id)
  82. if '>Programmet er ikke længere tilgængeligt' in webpage:
  83. raise ExtractorError(
  84. 'Video %s is not available' % video_id, expected=True)
  85. video_id = self._search_regex(
  86. (r'data-(?:material-identifier|episode-slug)="([^"]+)"',
  87. r'data-resource="[^>"]+mu/programcard/expanded/([^"]+)"'),
  88. webpage, 'video id', default=None)
  89. if not video_id:
  90. video_id = compat_urllib_parse_unquote(self._search_regex(
  91. r'(urn(?:%3A|:)dr(?:%3A|:)mu(?:%3A|:)programcard(?:%3A|:)[\da-f]+)',
  92. webpage, 'urn'))
  93. data = self._download_json(
  94. 'https://www.dr.dk/mu-online/api/1.4/programcard/%s' % video_id,
  95. video_id, 'Downloading video JSON', query={'expanded': 'true'})
  96. title = str_or_none(data.get('Title')) or re.sub(
  97. r'\s*\|\s*(?:TV\s*\|\s*DR|DRTV)$', '',
  98. self._og_search_title(webpage))
  99. description = self._og_search_description(
  100. webpage, default=None) or data.get('Description')
  101. timestamp = unified_timestamp(
  102. data.get('PrimaryBroadcastStartTime') or data.get('SortDateTime'))
  103. thumbnail = None
  104. duration = None
  105. restricted_to_denmark = False
  106. formats = []
  107. subtitles = {}
  108. assets = []
  109. primary_asset = data.get('PrimaryAsset')
  110. if isinstance(primary_asset, dict):
  111. assets.append(primary_asset)
  112. secondary_assets = data.get('SecondaryAssets')
  113. if isinstance(secondary_assets, list):
  114. for secondary_asset in secondary_assets:
  115. if isinstance(secondary_asset, dict):
  116. assets.append(secondary_asset)
  117. def hex_to_bytes(hex):
  118. return binascii.a2b_hex(hex.encode('ascii'))
  119. def decrypt_uri(e):
  120. n = int(e[2:10], 16)
  121. a = e[10 + n:]
  122. data = bytes_to_intlist(hex_to_bytes(e[10:10 + n]))
  123. key = bytes_to_intlist(hashlib.sha256(
  124. ('%s:sRBzYNXBzkKgnjj8pGtkACch' % a).encode('utf-8')).digest())
  125. iv = bytes_to_intlist(hex_to_bytes(a))
  126. decrypted = aes_cbc_decrypt(data, key, iv)
  127. return intlist_to_bytes(
  128. decrypted[:-decrypted[-1]]).decode('utf-8').split('?')[0]
  129. for asset in assets:
  130. kind = asset.get('Kind')
  131. if kind == 'Image':
  132. thumbnail = url_or_none(asset.get('Uri'))
  133. elif kind in ('VideoResource', 'AudioResource'):
  134. duration = float_or_none(asset.get('DurationInMilliseconds'), 1000)
  135. restricted_to_denmark = asset.get('RestrictedToDenmark')
  136. asset_target = asset.get('Target')
  137. for link in asset.get('Links', []):
  138. uri = link.get('Uri')
  139. if not uri:
  140. encrypted_uri = link.get('EncryptedUri')
  141. if not encrypted_uri:
  142. continue
  143. try:
  144. uri = decrypt_uri(encrypted_uri)
  145. except Exception:
  146. self.report_warning(
  147. 'Unable to decrypt EncryptedUri', video_id)
  148. continue
  149. uri = url_or_none(uri)
  150. if not uri:
  151. continue
  152. target = link.get('Target')
  153. format_id = target or ''
  154. preference = None
  155. if asset_target in ('SpokenSubtitles', 'SignLanguage'):
  156. preference = -1
  157. format_id += '-%s' % asset_target
  158. if target == 'HDS':
  159. f4m_formats = self._extract_f4m_formats(
  160. uri + '?hdcore=3.3.0&plugin=aasp-3.3.0.99.43',
  161. video_id, preference, f4m_id=format_id, fatal=False)
  162. if kind == 'AudioResource':
  163. for f in f4m_formats:
  164. f['vcodec'] = 'none'
  165. formats.extend(f4m_formats)
  166. elif target == 'HLS':
  167. formats.extend(self._extract_m3u8_formats(
  168. uri, video_id, 'mp4', entry_protocol='m3u8_native',
  169. preference=preference, m3u8_id=format_id,
  170. fatal=False))
  171. else:
  172. bitrate = link.get('Bitrate')
  173. if bitrate:
  174. format_id += '-%s' % bitrate
  175. formats.append({
  176. 'url': uri,
  177. 'format_id': format_id,
  178. 'tbr': int_or_none(bitrate),
  179. 'ext': link.get('FileFormat'),
  180. 'vcodec': 'none' if kind == 'AudioResource' else None,
  181. 'preference': preference,
  182. })
  183. subtitles_list = asset.get('SubtitlesList') or asset.get('Subtitleslist')
  184. if isinstance(subtitles_list, list):
  185. LANGS = {
  186. 'Danish': 'da',
  187. }
  188. for subs in subtitles_list:
  189. if not isinstance(subs, dict):
  190. continue
  191. sub_uri = url_or_none(subs.get('Uri'))
  192. if not sub_uri:
  193. continue
  194. lang = subs.get('Language') or 'da'
  195. subtitles.setdefault(LANGS.get(lang, lang), []).append({
  196. 'url': sub_uri,
  197. 'ext': mimetype2ext(subs.get('MimeType')) or 'vtt'
  198. })
  199. if not formats and restricted_to_denmark:
  200. self.raise_geo_restricted(
  201. 'Unfortunately, DR is not allowed to show this program outside Denmark.',
  202. countries=self._GEO_COUNTRIES)
  203. self._sort_formats(formats)
  204. return {
  205. 'id': video_id,
  206. 'title': title,
  207. 'description': description,
  208. 'thumbnail': thumbnail,
  209. 'timestamp': timestamp,
  210. 'duration': duration,
  211. 'formats': formats,
  212. 'subtitles': subtitles,
  213. 'series': str_or_none(data.get('SeriesTitle')),
  214. 'season': str_or_none(data.get('SeasonTitle')),
  215. 'season_number': int_or_none(data.get('SeasonNumber')),
  216. 'season_id': str_or_none(data.get('SeasonUrn')),
  217. 'episode': str_or_none(data.get('EpisodeTitle')),
  218. 'episode_number': int_or_none(data.get('EpisodeNumber')),
  219. 'release_year': int_or_none(data.get('ProductionYear')),
  220. }
  221. class DRTVLiveIE(InfoExtractor):
  222. IE_NAME = 'drtv:live'
  223. _VALID_URL = r'https?://(?:www\.)?dr\.dk/(?:tv|TV)/live/(?P<id>[\da-z-]+)'
  224. _GEO_COUNTRIES = ['DK']
  225. _TEST = {
  226. 'url': 'https://www.dr.dk/tv/live/dr1',
  227. 'info_dict': {
  228. 'id': 'dr1',
  229. 'ext': 'mp4',
  230. 'title': 're:^DR1 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
  231. },
  232. 'params': {
  233. # m3u8 download
  234. 'skip_download': True,
  235. },
  236. }
  237. def _real_extract(self, url):
  238. channel_id = self._match_id(url)
  239. channel_data = self._download_json(
  240. 'https://www.dr.dk/mu-online/api/1.0/channel/' + channel_id,
  241. channel_id)
  242. title = self._live_title(channel_data['Title'])
  243. formats = []
  244. for streaming_server in channel_data.get('StreamingServers', []):
  245. server = streaming_server.get('Server')
  246. if not server:
  247. continue
  248. link_type = streaming_server.get('LinkType')
  249. for quality in streaming_server.get('Qualities', []):
  250. for stream in quality.get('Streams', []):
  251. stream_path = stream.get('Stream')
  252. if not stream_path:
  253. continue
  254. stream_url = update_url_query(
  255. '%s/%s' % (server, stream_path), {'b': ''})
  256. if link_type == 'HLS':
  257. formats.extend(self._extract_m3u8_formats(
  258. stream_url, channel_id, 'mp4',
  259. m3u8_id=link_type, fatal=False, live=True))
  260. elif link_type == 'HDS':
  261. formats.extend(self._extract_f4m_formats(update_url_query(
  262. '%s/%s' % (server, stream_path), {'hdcore': '3.7.0'}),
  263. channel_id, f4m_id=link_type, fatal=False))
  264. self._sort_formats(formats)
  265. return {
  266. 'id': channel_id,
  267. 'title': title,
  268. 'thumbnail': channel_data.get('PrimaryImageUri'),
  269. 'formats': formats,
  270. 'is_live': True,
  271. }