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.

345 lines
13 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
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. import os
  4. import mimetypes
  5. import json
  6. import logging
  7. import sys
  8. import datetime
  9. import pytz
  10. from os.path import splitext, basename, abspath
  11. from tzlocal import get_localzone
  12. from configparser import RawConfigParser
  13. from requests_oauthlib import OAuth2Session
  14. from oauthlib.oauth2 import LegacyApplicationClient
  15. from requests_toolbelt.multipart.encoder import MultipartEncoder
  16. from . import utils
  17. logger = logging.getLogger('Prismedia')
  18. PEERTUBE_SECRETS_FILE = 'peertube_secret'
  19. PEERTUBE_PRIVACY = {
  20. "public": 1,
  21. "unlisted": 2,
  22. "private": 3
  23. }
  24. def get_authenticated_service(secret):
  25. peertube_url = str(secret.get('peertube', 'peertube_url')).rstrip("/")
  26. oauth_client = LegacyApplicationClient(
  27. client_id=str(secret.get('peertube', 'client_id'))
  28. )
  29. try:
  30. oauth = OAuth2Session(client=oauth_client)
  31. oauth.fetch_token(
  32. token_url=str(peertube_url + '/api/v1/users/token'),
  33. # lower as peertube does not store uppercase for pseudo
  34. username=str(secret.get('peertube', 'username').lower()),
  35. password=str(secret.get('peertube', 'password')),
  36. client_id=str(secret.get('peertube', 'client_id')),
  37. client_secret=str(secret.get('peertube', 'client_secret'))
  38. )
  39. except Exception as e:
  40. if hasattr(e, 'message'):
  41. logger.critical("Peertube: " + str(e.message))
  42. exit(1)
  43. else:
  44. logger.critical("Peertube: " + str(e))
  45. exit(1)
  46. return oauth
  47. def get_default_channel(user_info):
  48. return user_info['videoChannels'][0]['id']
  49. def get_channel_by_name(user_info, options):
  50. for channel in user_info["videoChannels"]:
  51. if channel['displayName'] == options.get('--channel'):
  52. return channel['id']
  53. def create_channel(oauth, url, options):
  54. template = ('Peertube: Channel %s does not exist, creating it.')
  55. logger.info(template % (str(options.get('--channel'))))
  56. channel_name = utils.cleanString(str(options.get('--channel')))
  57. # Peertube allows 20 chars max for channel name
  58. channel_name = channel_name[:19]
  59. data = '{"name":"' + channel_name + '", \
  60. "displayName":"' + options.get('--channel') + '", \
  61. "description":null, \
  62. "support":null}'
  63. headers = {
  64. 'Content-Type': "application/json; charset=UTF-8"
  65. }
  66. try:
  67. response = oauth.post(url + "/api/v1/video-channels/",
  68. data=data.encode('utf-8'),
  69. headers=headers)
  70. except Exception as e:
  71. if hasattr(e, 'message'):
  72. logger.error("Peertube: " + str(e.message))
  73. else:
  74. logger.error("Peertube: " + str(e))
  75. if response is not None:
  76. if response.status_code == 200:
  77. jresponse = response.json()
  78. jresponse = jresponse['videoChannel']
  79. return jresponse['id']
  80. if response.status_code == 409:
  81. logger.critical('Peertube: It seems there is a conflict with an existing channel named '
  82. + channel_name + '.'
  83. ' Please beware Peertube internal name is compiled from 20 firsts characters of channel name.'
  84. ' Also note that channel name are not case sensitive (no uppercase nor accent)'
  85. ' Please check your channel name and retry.')
  86. exit(1)
  87. else:
  88. logger.critical(('Peertube: Creating channel failed with an unexpected response: '
  89. '%s') % response)
  90. exit(1)
  91. def get_default_playlist(user_info):
  92. return user_info['videoChannels'][0]['id']
  93. def get_playlist_by_name(oauth, url, username, options):
  94. start = 0
  95. user_playlists = json.loads(oauth.get(
  96. url+"/api/v1/accounts/"+username+"/video-playlists?start="+str(start)+"&count=100").content)
  97. total = user_playlists["total"]
  98. data = user_playlists["data"]
  99. # We need to iterate on pagination as peertube returns max 100 playlists (see #41)
  100. while start < total:
  101. for playlist in data:
  102. if playlist['displayName'] == options.get('--playlist'):
  103. return playlist['id']
  104. start = start + 100
  105. user_playlists = json.loads(oauth.get(
  106. url+"/api/v1/accounts/"+username+"/video-playlists?start="+str(start)+"&count=100").content)
  107. data = user_playlists["data"]
  108. def create_playlist(oauth, url, options, channel):
  109. template = ('Peertube: Playlist %s does not exist, creating it.')
  110. logger.info(template % (str(options.get('--playlist'))))
  111. # We use files for form-data Content
  112. # see https://requests.readthedocs.io/en/latest/user/quickstart/#post-a-multipart-encoded-file
  113. # None is used to mute "filename" field
  114. files = {'displayName': (None, str(options.get('--playlist'))),
  115. 'privacy': (None, "1"),
  116. 'description': (None, "null"),
  117. 'videoChannelId': (None, str(channel)),
  118. 'thumbnailfile': (None, "null")}
  119. try:
  120. response = oauth.post(url + "/api/v1/video-playlists/",
  121. files=files)
  122. except Exception as e:
  123. if hasattr(e, 'message'):
  124. logger.error("Peertube: " + str(e.message))
  125. else:
  126. logger.error("Peertube: " + str(e))
  127. if response is not None:
  128. if response.status_code == 200:
  129. jresponse = response.json()
  130. jresponse = jresponse['videoPlaylist']
  131. return jresponse['id']
  132. else:
  133. logger.critical(('Peertube: Creating the playlist failed with an unexpected response: '
  134. '%s') % response)
  135. exit(1)
  136. def set_playlist(oauth, url, video_id, playlist_id):
  137. logger.info('Peertube: add video to playlist.')
  138. data = '{"videoId":"' + str(video_id) + '"}'
  139. headers = {
  140. 'Content-Type': "application/json"
  141. }
  142. try:
  143. response = oauth.post(url + "/api/v1/video-playlists/"+str(playlist_id)+"/videos",
  144. data=data,
  145. headers=headers)
  146. except Exception as e:
  147. if hasattr(e, 'message'):
  148. logger.error("Peertube: " + str(e.message))
  149. else:
  150. logger.error("Peertube: " + str(e))
  151. if response is not None:
  152. if response.status_code == 200:
  153. logger.info('Peertube: Video is successfully added to the playlist.')
  154. else:
  155. logger.critical(('Peertube: Configuring the playlist failed with an unexpected response: '
  156. '%s') % response)
  157. exit(1)
  158. def upload_video(oauth, secret, options):
  159. def get_userinfo():
  160. return json.loads(oauth.get(url+"/api/v1/users/me").content)
  161. def get_file(path):
  162. mimetypes.init()
  163. return (basename(path), open(abspath(path), 'rb'),
  164. mimetypes.types_map[splitext(path)[1]])
  165. path = options.get('--file')
  166. url = str(secret.get('peertube', 'peertube_url')).rstrip('/')
  167. user_info = get_userinfo()
  168. username = str(secret.get('peertube', 'username').lower())
  169. # We need to transform fields into tuple to deal with tags as
  170. # MultipartEncoder does not support list refer
  171. # https://github.com/requests/toolbelt/issues/190 and
  172. # https://github.com/requests/toolbelt/issues/205
  173. fields = [
  174. ("name", options.get('--name') or splitext(basename(options.get('--file')))[0]),
  175. ("licence", "1"),
  176. ("description", options.get('--description') or "default description"),
  177. ("nsfw", str(int(options.get('--nsfw')) or "0")),
  178. ("videofile", get_file(path))
  179. ]
  180. if options.get('--tags'):
  181. tags = options.get('--tags').split(',')
  182. tag_number = 0
  183. for strtag in tags:
  184. tag_number = tag_number + 1
  185. # Empty tag crashes Peertube, so skip them
  186. if strtag == "":
  187. continue
  188. # Tag more than 30 chars crashes Peertube, so skip tags
  189. if len(strtag) >= 30:
  190. logger.warning("Peertube: Sorry, Peertube does not support tag with more than 30 characters, please reduce tag: " + strtag)
  191. logger.warning("Peertube: Meanwhile, this tag will be skipped")
  192. continue
  193. # Peertube supports only 5 tags at the moment
  194. if tag_number > 5:
  195. logger.warning("Peertube: Sorry, Peertube support 5 tags max, additional tag will be skipped")
  196. logger.warning("Peertube: Skipping tag " + strtag)
  197. continue
  198. fields.append(("tags[]", strtag))
  199. if options.get('--category'):
  200. fields.append(("category", str(utils.getCategory(options.get('--category'), 'peertube'))))
  201. else:
  202. # if no category, set default to 2 (Films)
  203. fields.append(("category", "2"))
  204. if options.get('--language'):
  205. fields.append(("language", str(utils.getLanguage(options.get('--language'), "peertube"))))
  206. else:
  207. # if no language, set default to 1 (English)
  208. fields.append(("language", "en"))
  209. if options.get('--disable-comments'):
  210. fields.append(("commentsEnabled", "0"))
  211. else:
  212. fields.append(("commentsEnabled", "1"))
  213. privacy = None
  214. if options.get('--privacy'):
  215. privacy = options.get('--privacy').lower()
  216. # If peertubeAt exists, use instead of publishAt
  217. if options.get('--peertubeAt'):
  218. publishAt = options.get('--peertubeAt')
  219. elif options.get('--publishAt'):
  220. publishAt = options.get('--publishAt')
  221. if 'publishAt' in locals():
  222. publishAt = datetime.datetime.strptime(publishAt, '%Y-%m-%dT%H:%M:%S')
  223. tz = get_localzone()
  224. tz = pytz.timezone(str(tz))
  225. publishAt = tz.localize(publishAt).isoformat()
  226. fields.append(("scheduleUpdate[updateAt]", publishAt))
  227. fields.append(("scheduleUpdate[privacy]", str(PEERTUBE_PRIVACY["public"])))
  228. fields.append(("privacy", str(PEERTUBE_PRIVACY["private"])))
  229. else:
  230. fields.append(("privacy", str(PEERTUBE_PRIVACY[privacy or "private"])))
  231. if options.get('--thumbnail'):
  232. fields.append(("thumbnailfile", get_file(options.get('--thumbnail'))))
  233. fields.append(("previewfile", get_file(options.get('--thumbnail'))))
  234. if options.get('--channel'):
  235. channel_id = get_channel_by_name(user_info, options)
  236. if not channel_id and options.get('--channelCreate'):
  237. channel_id = create_channel(oauth, url, options)
  238. elif not channel_id:
  239. logger.warning("Peertube: Channel `" + options.get('--channel') + "` is unknown, using default channel.")
  240. channel_id = get_default_channel(user_info)
  241. else:
  242. channel_id = get_default_channel(user_info)
  243. fields.append(("channelId", str(channel_id)))
  244. if options.get('--playlist'):
  245. playlist_id = get_playlist_by_name(oauth, url, username, options)
  246. if not playlist_id and options.get('--playlistCreate'):
  247. playlist_id = create_playlist(oauth, url, options, channel_id)
  248. elif not playlist_id:
  249. logger.critical("Peertube: Playlist `" + options.get('--playlist') + "` does not exist, please set --playlistCreate"
  250. " if you want to create it")
  251. exit(1)
  252. logger_stdout = None
  253. if options.get('--url-only') or options.get('--batch'):
  254. logger_stdout = logging.getLogger('stdoutlogs')
  255. multipart_data = MultipartEncoder(fields)
  256. headers = {
  257. 'Content-Type': multipart_data.content_type
  258. }
  259. response = oauth.post(url + "/api/v1/videos/upload",
  260. data=multipart_data,
  261. headers=headers)
  262. if response is not None:
  263. if response.status_code == 200:
  264. jresponse = response.json()
  265. jresponse = jresponse['video']
  266. uuid = jresponse['uuid']
  267. video_id = str(jresponse['id'])
  268. logger.info('Peertube: Video was successfully uploaded.')
  269. template = 'Peertube: Watch it at %s/videos/watch/%s.'
  270. logger.info(template % (url, uuid))
  271. template_stdout = '%s/videos/watch/%s'
  272. if options.get('--url-only'):
  273. logger_stdout.info(template_stdout % (url, uuid))
  274. elif options.get('--batch'):
  275. logger_stdout.info("Peertube: " + template_stdout % (url, uuid))
  276. # Upload is successful we may set playlist
  277. if options.get('--playlist'):
  278. set_playlist(oauth, url, video_id, playlist_id)
  279. else:
  280. logger.critical(('Peertube: The upload failed with an unexpected response: '
  281. '%s') % response)
  282. exit(1)
  283. def run(options):
  284. secret = RawConfigParser()
  285. try:
  286. secret.read(PEERTUBE_SECRETS_FILE)
  287. except Exception as e:
  288. logger.critical("Peertube: Error loading " + str(PEERTUBE_SECRETS_FILE) + ": " + str(e))
  289. exit(1)
  290. insecure_transport = secret.get('peertube', 'OAUTHLIB_INSECURE_TRANSPORT')
  291. os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = insecure_transport
  292. oauth = get_authenticated_service(secret)
  293. try:
  294. logger.info('Peertube: Uploading video...')
  295. upload_video(oauth, secret, options)
  296. except Exception as e:
  297. if hasattr(e, 'message'):
  298. logger.error("Peertube: " + str(e.message))
  299. else:
  300. logger.error("Peertube: " + str(e))