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.

154 lines
5.4 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
  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 upload_video(oauth, secret, options):
  35. def get_userinfo():
  36. user_info = json.loads(oauth.get(url + "/api/v1/users/me").content)
  37. return str(user_info["id"])
  38. def get_file(path):
  39. mimetypes.init()
  40. return (basename(path), open(abspath(path), 'rb'),
  41. mimetypes.types_map[splitext(path)[1]])
  42. url = secret.get('peertube', 'peertube_url')
  43. # We need to transform fields into tuple to deal with tags as
  44. # MultipartEncoder does not support list refer
  45. # https://github.com/requests/toolbelt/issues/190 and
  46. # https://github.com/requests/toolbelt/issues/205
  47. fields = [
  48. ("name", options.get('--name') or splitext(basename(options.get('--file')))[0]),
  49. ("licence", "1"),
  50. ("description", options.get('--description') or "default description"),
  51. ("nsfw", str(int(options.get('--nsfw')) or "0")),
  52. ("channelId", get_userinfo()),
  53. ("videofile", get_file(options.get('--file')))
  54. ]
  55. if options.get('--tags'):
  56. tags = options.get('--tags').split(',')
  57. for strtag in tags:
  58. # Empty tag crashes Peertube, so skip them
  59. if strtag == "":
  60. continue
  61. # Tag more than 30 chars crashes Peertube, so exit and check tags
  62. if len(strtag) >= 30:
  63. logging.warning("Peertube: Sorry, Peertube does not support tag with more than 30 characters, please reduce your tag size")
  64. exit(1)
  65. # If Mastodon compatibility is enabled, clean tags from special characters
  66. if options.get('--mt'):
  67. strtag = utils.mastodonTag(strtag)
  68. fields.append(("tags", strtag))
  69. if options.get('--category'):
  70. fields.append(("category", str(utils.getCategory(options.get('--category'), 'peertube'))))
  71. else:
  72. # if no category, set default to 2 (Films)
  73. fields.append(("category", "2"))
  74. if options.get('--language'):
  75. fields.append(("language", str(utils.getLanguage(options.get('--language'), "peertube"))))
  76. else:
  77. # if no language, set default to 1 (English)
  78. fields.append(("language", "en"))
  79. if options.get('--privacy'):
  80. fields.append(("privacy", str(PEERTUBE_PRIVACY[options.get('--privacy').lower()])))
  81. else:
  82. fields.append(("privacy", "3"))
  83. if options.get('--disable-comments'):
  84. fields.append(("commentsEnabled", "0"))
  85. else:
  86. fields.append(("commentsEnabled", "1"))
  87. if options.get('--thumbnail'):
  88. fields.append(("thumbnailfile", get_file(options.get('--thumbnail'))))
  89. fields.append(("previewfile", get_file(options.get('--thumbnail'))))
  90. multipart_data = MultipartEncoder(fields)
  91. headers = {
  92. 'Content-Type': multipart_data.content_type
  93. }
  94. response = oauth.post(url + "/api/v1/videos/upload",
  95. data=multipart_data,
  96. headers=headers)
  97. if response is not None:
  98. if response.status_code == 200:
  99. jresponse = response.json()
  100. jresponse = jresponse['video']
  101. uuid = jresponse['uuid']
  102. idvideo = str(jresponse['id'])
  103. logging.info('Peertube : Video was successfully uploaded.')
  104. template = 'Peertube: Watch it at %s/videos/watch/%s.'
  105. logging.info(template % (url, uuid))
  106. if options.get('--publishAt'):
  107. utils.publishAt(str(options.get('--publishAt')), oauth, url, idvideo, secret)
  108. else:
  109. logging.error(('Peertube: The upload failed with an unexpected response: '
  110. '%s') % response)
  111. exit(1)
  112. def run(options):
  113. secret = RawConfigParser()
  114. try:
  115. secret.read(PEERTUBE_SECRETS_FILE)
  116. except Exception as e:
  117. logging.error("Peertube: Error loading " + str(PEERTUBE_SECRETS_FILE) + ": " + str(e))
  118. exit(1)
  119. insecure_transport = secret.get('peertube', 'OAUTHLIB_INSECURE_TRANSPORT')
  120. os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = insecure_transport
  121. oauth = get_authenticated_service(secret)
  122. try:
  123. logging.info('Peertube: Uploading video...')
  124. upload_video(oauth, secret, options)
  125. except Exception as e:
  126. if hasattr(e, 'message'):
  127. logging.error("Peertube: Error: " + str(e.message))
  128. else:
  129. logging.error("Peertube: Error: " + str(e))