periscope.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. from .common import InfoExtractor
  2. from ..utils import (
  3. int_or_none,
  4. parse_iso8601,
  5. unescapeHTML,
  6. )
  7. from ..utils.traversal import traverse_obj
  8. class PeriscopeBaseIE(InfoExtractor):
  9. _M3U8_HEADERS = {
  10. 'Referer': 'https://www.periscope.tv/',
  11. }
  12. def _call_api(self, method, query, item_id):
  13. return self._download_json(
  14. f'https://api.periscope.tv/api/v2/{method}',
  15. item_id, query=query)
  16. def _parse_broadcast_data(self, broadcast, video_id):
  17. title = broadcast.get('status') or 'Periscope Broadcast'
  18. uploader = broadcast.get('user_display_name') or broadcast.get('username')
  19. title = f'{uploader} - {title}' if uploader else title
  20. thumbnails = [{
  21. 'url': broadcast[image],
  22. } for image in ('image_url', 'image_url_medium', 'image_url_small') if broadcast.get(image)]
  23. return {
  24. 'id': broadcast.get('id') or video_id,
  25. 'title': title,
  26. 'timestamp': parse_iso8601(broadcast.get('created_at')) or int_or_none(
  27. broadcast.get('created_at_ms'), scale=1000),
  28. 'release_timestamp': int_or_none(broadcast.get('scheduled_start_ms'), scale=1000),
  29. 'uploader': uploader,
  30. 'uploader_id': broadcast.get('user_id') or broadcast.get('username'),
  31. 'thumbnails': thumbnails,
  32. 'view_count': int_or_none(broadcast.get('total_watched')),
  33. 'concurrent_view_count': int_or_none(broadcast.get('total_watching')),
  34. 'tags': broadcast.get('tags'),
  35. 'live_status': {
  36. 'running': 'is_live',
  37. 'not_started': 'is_upcoming',
  38. }.get(traverse_obj(broadcast, ('state', {str.lower}))) or 'was_live',
  39. }
  40. @staticmethod
  41. def _extract_common_format_info(broadcast):
  42. return broadcast.get('state').lower(), int_or_none(broadcast.get('width')), int_or_none(broadcast.get('height'))
  43. @staticmethod
  44. def _add_width_and_height(f, width, height):
  45. for key, val in (('width', width), ('height', height)):
  46. if not f.get(key):
  47. f[key] = val
  48. def _extract_pscp_m3u8_formats(self, m3u8_url, video_id, format_id, state, width, height, fatal=True):
  49. m3u8_formats = self._extract_m3u8_formats(
  50. m3u8_url, video_id, 'mp4',
  51. entry_protocol='m3u8_native'
  52. if state in ('ended', 'timed_out') else 'm3u8',
  53. m3u8_id=format_id, fatal=fatal, headers=self._M3U8_HEADERS)
  54. if len(m3u8_formats) == 1:
  55. self._add_width_and_height(m3u8_formats[0], width, height)
  56. for f in m3u8_formats:
  57. f.setdefault('http_headers', {}).update(self._M3U8_HEADERS)
  58. return m3u8_formats
  59. class PeriscopeIE(PeriscopeBaseIE):
  60. IE_DESC = 'Periscope'
  61. IE_NAME = 'periscope'
  62. _VALID_URL = r'https?://(?:www\.)?(?:periscope|pscp)\.tv/[^/]+/(?P<id>[^/?#]+)'
  63. _EMBED_REGEX = [r'<iframe[^>]+src=([\'"])(?P<url>(?:https?:)?//(?:www\.)?(?:periscope|pscp)\.tv/(?:(?!\1).)+)\1']
  64. # Alive example URLs can be found here https://www.periscope.tv/
  65. _TESTS = [{
  66. 'url': 'https://www.periscope.tv/w/aJUQnjY3MjA3ODF8NTYxMDIyMDl2zCg2pECBgwTqRpQuQD352EMPTKQjT4uqlM3cgWFA-g==',
  67. 'md5': '65b57957972e503fcbbaeed8f4fa04ca',
  68. 'info_dict': {
  69. 'id': '56102209',
  70. 'ext': 'mp4',
  71. 'title': 'Bec Boop - πŸš βœˆοΈπŸ‡¬πŸ‡§ Fly above #London in Emirates Air Line cable car at night πŸ‡¬πŸ‡§βœˆοΈπŸš  #BoopScope πŸŽ€πŸ’—',
  72. 'timestamp': 1438978559,
  73. 'upload_date': '20150807',
  74. 'uploader': 'Bec Boop',
  75. 'uploader_id': '1465763',
  76. },
  77. 'skip': 'Expires in 24 hours',
  78. }, {
  79. 'url': 'https://www.periscope.tv/w/1ZkKzPbMVggJv',
  80. 'only_matching': True,
  81. }, {
  82. 'url': 'https://www.periscope.tv/bastaakanoggano/1OdKrlkZZjOJX',
  83. 'only_matching': True,
  84. }, {
  85. 'url': 'https://www.periscope.tv/w/1ZkKzPbMVggJv',
  86. 'only_matching': True,
  87. }]
  88. def _real_extract(self, url):
  89. token = self._match_id(url)
  90. stream = self._call_api(
  91. 'accessVideoPublic', {'broadcast_id': token}, token)
  92. broadcast = stream['broadcast']
  93. info = self._parse_broadcast_data(broadcast, token)
  94. state = broadcast.get('state').lower()
  95. width = int_or_none(broadcast.get('width'))
  96. height = int_or_none(broadcast.get('height'))
  97. def add_width_and_height(f):
  98. for key, val in (('width', width), ('height', height)):
  99. if not f.get(key):
  100. f[key] = val
  101. video_urls = set()
  102. formats = []
  103. for format_id in ('replay', 'rtmp', 'hls', 'https_hls', 'lhls', 'lhlsweb'):
  104. video_url = stream.get(format_id + '_url')
  105. if not video_url or video_url in video_urls:
  106. continue
  107. video_urls.add(video_url)
  108. if format_id != 'rtmp':
  109. m3u8_formats = self._extract_pscp_m3u8_formats(
  110. video_url, token, format_id, state, width, height, False)
  111. formats.extend(m3u8_formats)
  112. continue
  113. rtmp_format = {
  114. 'url': video_url,
  115. 'ext': 'flv' if format_id == 'rtmp' else 'mp4',
  116. }
  117. self._add_width_and_height(rtmp_format)
  118. formats.append(rtmp_format)
  119. info['formats'] = formats
  120. return info
  121. class PeriscopeUserIE(PeriscopeBaseIE):
  122. _VALID_URL = r'https?://(?:www\.)?(?:periscope|pscp)\.tv/(?P<id>[^/]+)/?$'
  123. IE_DESC = 'Periscope user videos'
  124. IE_NAME = 'periscope:user'
  125. _TEST = {
  126. 'url': 'https://www.periscope.tv/LularoeHusbandMike/',
  127. 'info_dict': {
  128. 'id': 'LularoeHusbandMike',
  129. 'title': 'LULAROE HUSBAND MIKE',
  130. 'description': 'md5:6cf4ec8047768098da58e446e82c82f0',
  131. },
  132. # Periscope only shows videos in the last 24 hours, so it's possible to
  133. # get 0 videos
  134. 'playlist_mincount': 0,
  135. }
  136. def _real_extract(self, url):
  137. user_name = self._match_id(url)
  138. webpage = self._download_webpage(url, user_name)
  139. data_store = self._parse_json(
  140. unescapeHTML(self._search_regex(
  141. r'data-store=(["\'])(?P<data>.+?)\1',
  142. webpage, 'data store', default='{}', group='data')),
  143. user_name)
  144. user = next(iter(data_store['UserCache']['users'].values()))['user']
  145. user_id = user['id']
  146. session_id = data_store['SessionToken']['public']['broadcastHistory']['token']['session_id']
  147. broadcasts = self._call_api(
  148. 'getUserBroadcastsPublic',
  149. {'user_id': user_id, 'session_id': session_id},
  150. user_name)['broadcasts']
  151. broadcast_ids = [
  152. broadcast['id'] for broadcast in broadcasts if broadcast.get('id')]
  153. title = user.get('display_name') or user.get('username') or user_name
  154. description = user.get('description')
  155. entries = [
  156. self.url_result(
  157. f'https://www.periscope.tv/{user_name}/{broadcast_id}')
  158. for broadcast_id in broadcast_ids]
  159. return self.playlist_result(entries, user_id, title, description)