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.

257 lines
9.5 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
  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 get_default_channel(user_info):
  46. return user_info['videoChannels'][0]['id']
  47. def get_default_playlist(user_info):
  48. return user_info['videoChannels'][0]['id']
  49. def get_playlist_by_name(user_playlists, options):
  50. for playlist in user_playlists["data"]:
  51. if playlist['displayName'].encode('utf8') == str(options.get('--playlist')):
  52. return playlist['id']
  53. def create_playlist(oauth, url, options, default_channel):
  54. template = ('Peertube: Playlist %s does not exist, creating it.')
  55. logging.info(template % (str(options.get('--playlist'))))
  56. # We use files for form-data Content
  57. # see https://requests.readthedocs.io/en/latest/user/quickstart/#post-a-multipart-encoded-file
  58. # None is used to mute "filename" field
  59. files = {'displayName': (None, str(options.get('--playlist'))),
  60. 'privacy': (None, "1"),
  61. 'description': (None, "null"),
  62. 'videoChannelId': (None, str(default_channel)),
  63. 'thumbnailfile': (None, "null")}
  64. try:
  65. response = oauth.post(url + "/api/v1/video-playlists/",
  66. files=files)
  67. except Exception as e:
  68. if hasattr(e, 'message'):
  69. logging.error("Error: " + str(e.message))
  70. else:
  71. logging.error("Error: " + str(e))
  72. if response is not None:
  73. if response.status_code == 200:
  74. jresponse = response.json()
  75. jresponse = jresponse['videoPlaylist']
  76. return jresponse['id']
  77. else:
  78. logging.error(('Peertube: Creating the playlist failed with an unexpected response: '
  79. '%s') % response)
  80. exit(1)
  81. def set_playlist(oauth, url, video_id, playlist_id):
  82. logging.info('Peertube: add video to playlist.')
  83. data = '{"videoId":"' + str(video_id) + '"}'
  84. headers = {
  85. 'Content-Type': "application/json"
  86. }
  87. try:
  88. response = oauth.post(url + "/api/v1/video-playlists/"+str(playlist_id)+"/videos",
  89. data=data,
  90. headers=headers)
  91. except Exception as e:
  92. if hasattr(e, 'message'):
  93. logging.error("Error: " + str(e.message))
  94. else:
  95. logging.error("Error: " + str(e))
  96. if response is not None:
  97. if response.status_code == 200:
  98. logging.info('Peertube: Video is successfully added to the playlist.')
  99. else:
  100. logging.error(('Peertube: Configuring the playlist failed with an unexpected response: '
  101. '%s') % response)
  102. exit(1)
  103. def upload_video(oauth, secret, options):
  104. def get_userinfo():
  105. return json.loads(oauth.get(url+"/api/v1/users/me").content)
  106. def get_file(path):
  107. mimetypes.init()
  108. return (basename(path), open(abspath(path), 'rb'),
  109. mimetypes.types_map[splitext(path)[1]])
  110. def get_playlist(username):
  111. return json.loads(oauth.get(url+"/api/v1/accounts/"+username+"/video-playlists").content)
  112. path = options.get('--file')
  113. url = str(secret.get('peertube', 'peertube_url')).rstrip('/')
  114. user_info = get_userinfo()
  115. user_playlists = get_playlist(str(secret.get('peertube', 'username').lower()))
  116. # We need to transform fields into tuple to deal with tags as
  117. # MultipartEncoder does not support list refer
  118. # https://github.com/requests/toolbelt/issues/190 and
  119. # https://github.com/requests/toolbelt/issues/205
  120. fields = [
  121. ("name", options.get('--name') or splitext(basename(options.get('--file')))[0]),
  122. ("licence", "1"),
  123. ("description", options.get('--description') or "default description"),
  124. ("nsfw", str(int(options.get('--nsfw')) or "0")),
  125. ("videofile", get_file(path))
  126. ]
  127. if options.get('--tags'):
  128. tags = options.get('--tags').split(',')
  129. for strtag in tags:
  130. # Empty tag crashes Peertube, so skip them
  131. if strtag == "":
  132. continue
  133. # Tag more than 30 chars crashes Peertube, so exit and check tags
  134. if len(strtag) >= 30:
  135. logging.warning("Peertube: Sorry, Peertube does not support tag with more than 30 characters, please reduce your tag size")
  136. exit(1)
  137. fields.append(("tags", strtag))
  138. if options.get('--category'):
  139. fields.append(("category", str(utils.getCategory(options.get('--category'), 'peertube'))))
  140. else:
  141. # if no category, set default to 2 (Films)
  142. fields.append(("category", "2"))
  143. if options.get('--language'):
  144. fields.append(("language", str(utils.getLanguage(options.get('--language'), "peertube"))))
  145. else:
  146. # if no language, set default to 1 (English)
  147. fields.append(("language", "en"))
  148. if options.get('--disable-comments'):
  149. fields.append(("commentsEnabled", "0"))
  150. else:
  151. fields.append(("commentsEnabled", "1"))
  152. privacy = None
  153. if options.get('--privacy'):
  154. privacy = options.get('--privacy').lower()
  155. if options.get('--publishAt'):
  156. publishAt = options.get('--publishAt')
  157. publishAt = datetime.datetime.strptime(publishAt, '%Y-%m-%dT%H:%M:%S')
  158. tz = get_localzone()
  159. tz = pytz.timezone(str(tz))
  160. publishAt = tz.localize(publishAt).isoformat()
  161. fields.append(("scheduleUpdate[updateAt]", publishAt))
  162. fields.append(("scheduleUpdate[privacy]", str(PEERTUBE_PRIVACY["public"])))
  163. fields.append(("privacy", str(PEERTUBE_PRIVACY["private"])))
  164. else:
  165. fields.append(("privacy", str(PEERTUBE_PRIVACY[privacy or "private"])))
  166. if options.get('--thumbnail'):
  167. fields.append(("thumbnailfile", get_file(options.get('--thumbnail'))))
  168. fields.append(("previewfile", get_file(options.get('--thumbnail'))))
  169. default_channel = get_default_channel(user_info)
  170. fields.append(("channelId", str(default_channel)))
  171. if options.get('--playlist'):
  172. playlist_id = get_playlist_by_name(user_playlists, options)
  173. if not playlist_id and options.get('--playlistCreate'):
  174. playlist_id = create_playlist(oauth, url, options, default_channel)
  175. elif not playlist_id:
  176. logging.warning("Playlist `" + options.get('--playlist') + "` does not exist, please set --playlistCreate"
  177. " if you want to create it")
  178. exit(1)
  179. multipart_data = MultipartEncoder(fields)
  180. headers = {
  181. 'Content-Type': multipart_data.content_type
  182. }
  183. response = oauth.post(url + "/api/v1/videos/upload",
  184. data=multipart_data,
  185. headers=headers)
  186. if response is not None:
  187. if response.status_code == 200:
  188. jresponse = response.json()
  189. jresponse = jresponse['video']
  190. uuid = jresponse['uuid']
  191. video_id = str(jresponse['id'])
  192. logging.info('Peertube : Video was successfully uploaded.')
  193. template = 'Peertube: Watch it at %s/videos/watch/%s.'
  194. logging.info(template % (url, uuid))
  195. # Upload is successful we may set playlist
  196. if options.get('--playlist'):
  197. set_playlist(oauth, url, video_id, playlist_id)
  198. else:
  199. logging.error(('Peertube: The upload failed with an unexpected response: '
  200. '%s') % response)
  201. exit(1)
  202. def run(options):
  203. secret = RawConfigParser()
  204. try:
  205. secret.read(PEERTUBE_SECRETS_FILE)
  206. except Exception as e:
  207. logging.error("Peertube: Error loading " + str(PEERTUBE_SECRETS_FILE) + ": " + str(e))
  208. exit(1)
  209. insecure_transport = secret.get('peertube', 'OAUTHLIB_INSECURE_TRANSPORT')
  210. os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = insecure_transport
  211. oauth = get_authenticated_service(secret)
  212. try:
  213. logging.info('Peertube: Uploading video...')
  214. upload_video(oauth, secret, options)
  215. except Exception as e:
  216. if hasattr(e, 'message'):
  217. logging.error("Peertube: Error: " + str(e.message))
  218. else:
  219. logging.error("Peertube: Error: " + str(e))