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.

408 lines
17 KiB

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