Scripting 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.

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