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.

454 lines
18 KiB

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