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.

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