periscope.py 6.7 KB

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