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.

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