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.

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