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.

143 lines
4.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
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. from os.path import splitext, basename, abspath
  7. from ConfigParser import RawConfigParser
  8. from requests_oauthlib import OAuth2Session
  9. from oauthlib.oauth2 import LegacyApplicationClient
  10. from requests_toolbelt.multipart.encoder import MultipartEncoder
  11. import utils
  12. PEERTUBE_SECRETS_FILE = 'peertube_secret'
  13. PEERTUBE_PRIVACY = {
  14. "public": 1,
  15. "unlisted": 2,
  16. "private": 3
  17. }
  18. def get_authenticated_service(secret):
  19. peertube_url = str(secret.get('peertube', 'peertube_url'))
  20. oauth_client = LegacyApplicationClient(
  21. client_id=str(secret.get('peertube', 'client_id'))
  22. )
  23. oauth = OAuth2Session(client=oauth_client)
  24. oauth.fetch_token(
  25. token_url=peertube_url + '/api/v1/users/token',
  26. # lower as peertube does not store uppecase for pseudo
  27. username=str(secret.get('peertube', 'username').lower()),
  28. password=str(secret.get('peertube', 'password')),
  29. client_id=str(secret.get('peertube', 'client_id')),
  30. client_secret=str(secret.get('peertube', 'client_secret'))
  31. )
  32. return oauth
  33. def upload_video(oauth, secret, options):
  34. def get_userinfo():
  35. user_info = json.loads(oauth.get(url + "/api/v1/users/me").content)
  36. return str(user_info["id"])
  37. def get_videofile(path):
  38. mimetypes.init()
  39. return (basename(path), open(abspath(path), 'rb'),
  40. mimetypes.types_map[splitext(path)[1]])
  41. path = options.get('--file')
  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(path))[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_videofile(path))
  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. exit("Sorry, Peertube does not support tag with more than 30 characters, please reduce your tag size")
  64. # If Mastodon compatibility is enabled, clean tags from special characters
  65. if options.get('--mt'):
  66. strtag = utils.mastodonTag(strtag)
  67. fields.append(("tags", strtag))
  68. if options.get('--category'):
  69. fields.append(("category", str(utils.getCategory(options.get('--category'), 'peertube'))))
  70. else:
  71. # if no category, set default to 2 (Films)
  72. fields.append(("category", "2"))
  73. if options.get('--language'):
  74. fields.append(("language", str(utils.getLanguage(options.get('--language'), "peertube"))))
  75. else:
  76. # if no language, set default to 1 (English)
  77. fields.append(("language", "1"))
  78. if options.get('--privacy'):
  79. fields.append(("privacy", str(PEERTUBE_PRIVACY[options.get('--privacy').lower()])))
  80. else:
  81. fields.append(("privacy", "3"))
  82. if options.get('--disable-comments'):
  83. fields.append(("commentsEnabled", "0"))
  84. else:
  85. fields.append(("commentsEnabled", "1"))
  86. multipart_data = MultipartEncoder(fields)
  87. headers = {
  88. 'Content-Type': multipart_data.content_type
  89. }
  90. response = oauth.post(url + "/api/v1/videos/upload",
  91. data=multipart_data,
  92. headers=headers)
  93. if response is not None:
  94. if response.status_code == 200:
  95. uuid = response.json()
  96. uuid = uuid['video']
  97. uuid = uuid['uuid']
  98. template = ('Peertube : Video was successfully uploaded.\n'
  99. 'Watch it at %s/videos/watch/%s.')
  100. print(template % (url, uuid))
  101. else:
  102. exit(('Peertube : The upload failed with an unexpected response: '
  103. '%s') % response)
  104. def run(options):
  105. secret = RawConfigParser()
  106. try:
  107. secret.read(PEERTUBE_SECRETS_FILE)
  108. except Exception as e:
  109. exit("Error loading " + str(PEERTUBE_SECRETS_FILE) + ": " + str(e))
  110. insecure_transport = secret.get('peertube', 'OAUTHLIB_INSECURE_TRANSPORT')
  111. os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = insecure_transport
  112. oauth = get_authenticated_service(secret)
  113. try:
  114. print('Peertube : Uploading file...')
  115. upload_video(oauth, secret, options)
  116. except Exception as e:
  117. if hasattr(e, 'message'):
  118. print("Error: " + str(e.message))
  119. else:
  120. print("Error: " + str(e))