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.

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