scripting your way to upload videos to peertube and youtube
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

222 lines
7.9 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. #!/usr/bin/env python2
  2. # coding: utf-8
  3. import os
  4. import mimetypes
  5. import json
  6. import logging
  7. import datetime
  8. import pytz
  9. from os.path import splitext, basename, abspath
  10. from tzlocal import get_localzone
  11. from ConfigParser import RawConfigParser
  12. from requests_oauthlib import OAuth2Session
  13. from oauthlib.oauth2 import LegacyApplicationClient
  14. from requests_toolbelt.multipart.encoder import MultipartEncoder
  15. import utils
  16. PEERTUBE_SECRETS_FILE = 'peertube_secret'
  17. PEERTUBE_PRIVACY = {
  18. "public": 1,
  19. "unlisted": 2,
  20. "private": 3
  21. }
  22. def get_authenticated_service(secret):
  23. peertube_url = str(secret.get('peertube', 'peertube_url')).rstrip("/")
  24. oauth_client = LegacyApplicationClient(
  25. client_id=str(secret.get('peertube', 'client_id'))
  26. )
  27. try:
  28. oauth = OAuth2Session(client=oauth_client)
  29. oauth.fetch_token(
  30. token_url=str(peertube_url + '/api/v1/users/token'),
  31. # lower as peertube does not store uppercase for pseudo
  32. username=str(secret.get('peertube', 'username').lower()),
  33. password=str(secret.get('peertube', 'password')),
  34. client_id=str(secret.get('peertube', 'client_id')),
  35. client_secret=str(secret.get('peertube', 'client_secret'))
  36. )
  37. except Exception as e:
  38. if hasattr(e, 'message'):
  39. logging.error("Peertube: Error: " + str(e.message))
  40. exit(1)
  41. else:
  42. logging.error("Peertube: Error: " + str(e))
  43. exit(1)
  44. return oauth
  45. def get_default_playlist(user_info):
  46. return user_info['videoChannels'][0]['id']
  47. def get_playlist_by_name(user_info, options):
  48. for playlist in user_info["videoChannels"]:
  49. if playlist['displayName'] == options.get('--playlist'):
  50. return playlist['id']
  51. def create_playlist(oauth, url, options):
  52. template = ('Peertube : Playlist %s does not exist, creating it.')
  53. logging.info(template % (str(options.get('--playlist'))))
  54. data = '{"displayName":"' + str(options.get('--playlist')) +'", \
  55. "description":null}'
  56. headers = {
  57. 'Content-Type': "application/json"
  58. }
  59. try:
  60. response = oauth.post(url + "/api/v1/video-channels/",
  61. data=data,
  62. headers=headers)
  63. except Exception as e:
  64. if hasattr(e, 'message'):
  65. logging.error("Error: " + str(e.message))
  66. else:
  67. logging.error("Error: " + str(e))
  68. if response is not None:
  69. if response.status_code == 200:
  70. jresponse = response.json()
  71. jresponse = jresponse['videoChannel']
  72. return jresponse['id']
  73. else:
  74. logging.error(('Peertube : The upload failed with an unexpected response: '
  75. '%s') % response)
  76. exit(1)
  77. def upload_video(oauth, secret, options):
  78. def get_userinfo():
  79. return json.loads(oauth.get(url+"/api/v1/users/me").content)
  80. def get_file(path):
  81. mimetypes.init()
  82. return (basename(path), open(abspath(path), 'rb'),
  83. mimetypes.types_map[splitext(path)[1]])
  84. path = options.get('--file')
  85. url = secret.get('peertube', 'peertube_url')
  86. user_info = get_userinfo()
  87. # We need to transform fields into tuple to deal with tags as
  88. # MultipartEncoder does not support list refer
  89. # https://github.com/requests/toolbelt/issues/190 and
  90. # https://github.com/requests/toolbelt/issues/205
  91. fields = [
  92. ("name", options.get('--name') or splitext(basename(options.get('--file')))[0]),
  93. ("licence", "1"),
  94. ("description", options.get('--description') or "default description"),
  95. ("nsfw", str(int(options.get('--nsfw')) or "0")),
  96. ("videofile", get_file(path))
  97. ]
  98. if options.get('--tags'):
  99. tags = options.get('--tags').split(',')
  100. for strtag in tags:
  101. # Empty tag crashes Peertube, so skip them
  102. if strtag == "":
  103. continue
  104. # Tag more than 30 chars crashes Peertube, so exit and check tags
  105. if len(strtag) >= 30:
  106. logging.warning("Peertube: Sorry, Peertube does not support tag with more than 30 characters, please reduce your tag size")
  107. exit(1)
  108. # If Mastodon compatibility is enabled, clean tags from special characters
  109. if options.get('--mt'):
  110. strtag = utils.mastodonTag(strtag)
  111. fields.append(("tags", strtag))
  112. if options.get('--category'):
  113. fields.append(("category", str(utils.getCategory(options.get('--category'), 'peertube'))))
  114. else:
  115. # if no category, set default to 2 (Films)
  116. fields.append(("category", "2"))
  117. if options.get('--language'):
  118. fields.append(("language", str(utils.getLanguage(options.get('--language'), "peertube"))))
  119. else:
  120. # if no language, set default to 1 (English)
  121. fields.append(("language", "en"))
  122. if options.get('--disable-comments'):
  123. fields.append(("commentsEnabled", "0"))
  124. else:
  125. fields.append(("commentsEnabled", "1"))
  126. privacy = None
  127. if options.get('--privacy'):
  128. privacy = options.get('--privacy').lower()
  129. if options.get('--publishAt'):
  130. publishAt = options.get('--publishAt')
  131. publishAt = datetime.datetime.strptime(publishAt, '%Y-%m-%dT%H:%M:%S')
  132. tz = get_localzone()
  133. tz = pytz.timezone(str(tz))
  134. publishAt = tz.localize(publishAt).isoformat()
  135. fields.append(("scheduleUpdate[updateAt]", publishAt))
  136. fields.append(("scheduleUpdate[privacy]", str(PEERTUBE_PRIVACY["public"])))
  137. fields.append(("privacy", str(PEERTUBE_PRIVACY["private"])))
  138. else:
  139. fields.append(("privacy", str(PEERTUBE_PRIVACY[privacy or "private"])))
  140. if options.get('--thumbnail'):
  141. fields.append(("thumbnailfile", get_file(options.get('--thumbnail'))))
  142. fields.append(("previewfile", get_file(options.get('--thumbnail'))))
  143. if options.get('--playlist'):
  144. playlist_id = get_playlist_by_name(user_info, options)
  145. if not playlist_id and options.get('--playlistCreate'):
  146. playlist_id = create_playlist(oauth, url, options)
  147. elif not playlist_id:
  148. logging.warning("Playlist `" + options.get('--playlist') + "` is unknown, using default playlist.")
  149. playlist_id = get_default_playlist(user_info)
  150. else:
  151. playlist_id = get_default_playlist(user_info)
  152. fields.append(("channelId", str(playlist_id)))
  153. multipart_data = MultipartEncoder(fields)
  154. headers = {
  155. 'Content-Type': multipart_data.content_type
  156. }
  157. response = oauth.post(url + "/api/v1/videos/upload",
  158. data=multipart_data,
  159. headers=headers)
  160. if response is not None:
  161. if response.status_code == 200:
  162. jresponse = response.json()
  163. jresponse = jresponse['video']
  164. uuid = jresponse['uuid']
  165. idvideo = str(jresponse['id'])
  166. logging.info('Peertube : Video was successfully uploaded.')
  167. template = 'Peertube: Watch it at %s/videos/watch/%s.'
  168. logging.info(template % (url, uuid))
  169. else:
  170. logging.error(('Peertube: The upload failed with an unexpected response: '
  171. '%s') % response)
  172. exit(1)
  173. def run(options):
  174. secret = RawConfigParser()
  175. try:
  176. secret.read(PEERTUBE_SECRETS_FILE)
  177. except Exception as e:
  178. logging.error("Peertube: Error loading " + str(PEERTUBE_SECRETS_FILE) + ": " + str(e))
  179. exit(1)
  180. insecure_transport = secret.get('peertube', 'OAUTHLIB_INSECURE_TRANSPORT')
  181. os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = insecure_transport
  182. oauth = get_authenticated_service(secret)
  183. try:
  184. logging.info('Peertube: Uploading video...')
  185. upload_video(oauth, secret, options)
  186. except Exception as e:
  187. if hasattr(e, 'message'):
  188. logging.error("Peertube: Error: " + str(e.message))
  189. else:
  190. logging.error("Peertube: Error: " + str(e))