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.

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