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.

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