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.

366 lines
14 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
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
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. # From Youtube samples: https://raw.githubusercontent.com/youtube/api-samples/master/python/upload_video.py # noqa
  4. import http.client
  5. import httplib2
  6. import random
  7. import time
  8. import copy
  9. import json
  10. from os.path import splitext, basename, exists
  11. import os
  12. import google.oauth2.credentials
  13. import datetime
  14. import pytz
  15. import logging
  16. from tzlocal import get_localzone
  17. from googleapiclient.discovery import build
  18. from googleapiclient.errors import HttpError
  19. from googleapiclient.http import MediaFileUpload
  20. from google_auth_oauthlib.flow import InstalledAppFlow
  21. from . import utils
  22. logger = logging.getLogger('Prismedia')
  23. # Explicitly tell the underlying HTTP transport library not to retry, since
  24. # we are handling retry logic ourselves.
  25. httplib2.RETRIES = 1
  26. # Maximum number of times to retry before giving up.
  27. MAX_RETRIES = 10
  28. # Youtube retriables cases
  29. RETRIABLE_EXCEPTIONS = (
  30. IOError,
  31. httplib2.HttpLib2Error,
  32. http.client.NotConnected,
  33. http.client.IncompleteRead,
  34. http.client.ImproperConnectionState,
  35. http.client.CannotSendRequest,
  36. http.client.CannotSendHeader,
  37. http.client.ResponseNotReady,
  38. http.client.BadStatusLine,
  39. )
  40. RETRIABLE_STATUS_CODES = [500, 502, 503, 504]
  41. CLIENT_SECRETS_FILE = 'youtube_secret.json'
  42. CREDENTIALS_PATH = ".youtube_credentials.json"
  43. SCOPES = ['https://www.googleapis.com/auth/youtube.upload', 'https://www.googleapis.com/auth/youtube.force-ssl']
  44. API_SERVICE_NAME = 'youtube'
  45. API_VERSION = 'v3'
  46. # Authorize the request and store authorization credentials.
  47. def get_authenticated_service():
  48. check_authenticated_scopes()
  49. flow = InstalledAppFlow.from_client_secrets_file(
  50. CLIENT_SECRETS_FILE, SCOPES)
  51. if exists(CREDENTIALS_PATH):
  52. with open(CREDENTIALS_PATH, 'r') as f:
  53. credential_params = json.load(f)
  54. credentials = google.oauth2.credentials.Credentials(
  55. credential_params["token"],
  56. refresh_token=credential_params["_refresh_token"],
  57. token_uri=credential_params["_token_uri"],
  58. client_id=credential_params["_client_id"],
  59. client_secret=credential_params["_client_secret"]
  60. )
  61. else:
  62. credentials = flow.run_console()
  63. with open(CREDENTIALS_PATH, 'w') as f:
  64. p = copy.deepcopy(vars(credentials))
  65. del p["expiry"]
  66. json.dump(p, f)
  67. return build(API_SERVICE_NAME, API_VERSION, credentials=credentials, cache_discovery=False)
  68. def check_authenticated_scopes():
  69. if exists(CREDENTIALS_PATH):
  70. with open(CREDENTIALS_PATH, 'r') as f:
  71. credential_params = json.load(f)
  72. # Check if all scopes are present
  73. if credential_params["_scopes"] != SCOPES:
  74. logger.warning("Youtube: Credentials are obsolete, need to re-authenticate.")
  75. os.remove(CREDENTIALS_PATH)
  76. def convert_youtube_date(date):
  77. # Youtube needs microsecond and the local timezone from ISO 8601
  78. date = date + ".000001"
  79. date = datetime.datetime.strptime(date, '%Y-%m-%dT%H:%M:%S.%f')
  80. tz = get_localzone()
  81. tz = pytz.timezone(str(tz))
  82. return tz.localize(date).isoformat()
  83. def initialize_upload(youtube, options):
  84. path = options.get('--file')
  85. tags = None
  86. if options.get('--tags'):
  87. tags = options.get('--tags').split(',')
  88. category = None
  89. if options.get('--category'):
  90. category = utils.getCategory(options.get('--category'), 'youtube')
  91. language = None
  92. if options.get('--language'):
  93. language = utils.getLanguage(options.get('--language'), "youtube")
  94. license = None
  95. if options.get('--cca'):
  96. license = "creativeCommon"
  97. # We set recordingDetails empty because it's easier to add options if it already exists
  98. # and if empty, it does not cause problem during upload
  99. body = {
  100. "snippet": {
  101. "title": options.get('--name') or splitext(basename(path))[0],
  102. "description": options.get('--description') or "default description",
  103. "tags": tags,
  104. # if no category, set default to 1 (Films)
  105. "categoryId": str(category or 1),
  106. "defaultAudioLanguage": str(language or 'en')
  107. },
  108. "status": {
  109. "privacyStatus": str(options.get('--privacy') or "private"),
  110. "license": str(license or "youtube"),
  111. },
  112. "recordingDetails": {
  113. }
  114. }
  115. # If peertubeAt exists, use instead of publishAt
  116. if options.get('--youtubeAt'):
  117. publishAt = options.get('--youtubeAt')
  118. elif options.get('--publishAt'):
  119. publishAt = options.get('--publishAt')
  120. # Check if publishAt variable exists in local variables
  121. if 'publishAt' in locals():
  122. publishAt = convert_youtube_date(publishAt)
  123. body['status']['publishAt'] = str(publishAt)
  124. # Set originalDate except if the user force no originalDate
  125. if options.get('--originalDate'):
  126. originalDate = convert_youtube_date(options.get('--originalDate'))
  127. body['recordingDetails']['recordingDate'] = str(originalDate)
  128. if options.get('--playlist'):
  129. playlist_id = get_playlist_by_name(youtube, options.get('--playlist'))
  130. if not playlist_id and options.get('--playlistCreate'):
  131. playlist_id = create_playlist(youtube, options.get('--playlist'))
  132. elif not playlist_id:
  133. logger.warning("Youtube: Playlist `" + options.get('--playlist') + "` is unknown.")
  134. logger.warning("Youtube: If you want to create it, set the --playlistCreate option.")
  135. playlist_id = ""
  136. else:
  137. playlist_id = ""
  138. # Call the API's videos.insert method to create and upload the video.
  139. insert_request = youtube.videos().insert(
  140. part=','.join(list(body.keys())),
  141. body=body,
  142. media_body=MediaFileUpload(path, chunksize=-1, resumable=True)
  143. )
  144. video_id = resumable_upload(insert_request, 'video', 'insert', options)
  145. # If we get a video_id, upload is successful and we are able to set thumbnail
  146. if video_id and options.get('--thumbnail'):
  147. set_thumbnail(options, youtube, options.get('--thumbnail'), videoId=video_id)
  148. # If we get a video_id and a playlist_id, upload is successful and we are able to set playlist
  149. if video_id and playlist_id != "":
  150. set_playlist(youtube, playlist_id, video_id)
  151. def get_playlist_by_name(youtube, playlist_name):
  152. pageToken = ""
  153. while pageToken != None:
  154. response = youtube.playlists().list(
  155. part='snippet,id',
  156. mine=True,
  157. maxResults=50,
  158. pageToken=pageToken
  159. ).execute()
  160. for playlist in response["items"]:
  161. if playlist["snippet"]["title"] == playlist_name:
  162. return playlist["id"]
  163. # Ask next page if there are any
  164. if "nextPageToken" in response:
  165. pageToken = response["nextPageToken"]
  166. else:
  167. pageToken = None
  168. def create_playlist(youtube, playlist_name):
  169. template = 'Youtube: Playlist %s does not exist, creating it.'
  170. logger.info(template % (str(playlist_name)))
  171. resources = build_resource({'snippet.title': playlist_name,
  172. 'snippet.description': '',
  173. 'status.privacyStatus': 'public'})
  174. response = youtube.playlists().insert(
  175. body=resources,
  176. part='status,snippet,id'
  177. ).execute()
  178. return response["id"]
  179. def build_resource(properties):
  180. resource = {}
  181. for p in properties:
  182. # Given a key like "snippet.title", split into "snippet" and "title", where
  183. # "snippet" will be an object and "title" will be a property in that object.
  184. prop_array = p.split('.')
  185. ref = resource
  186. for pa in range(0, len(prop_array)):
  187. is_array = False
  188. key = prop_array[pa]
  189. # For properties that have array values, convert a name like
  190. # "snippet.tags[]" to snippet.tags, and set a flag to handle
  191. # the value as an array.
  192. if key[-2:] == '[]':
  193. key = key[0:len(key)-2:]
  194. is_array = True
  195. if pa == (len(prop_array) - 1):
  196. # Leave properties without values out of inserted resource.
  197. if properties[p]:
  198. if is_array:
  199. ref[key] = properties[p].split(',')
  200. else:
  201. ref[key] = properties[p]
  202. elif key not in ref:
  203. # For example, the property is "snippet.title", but the resource does
  204. # not yet have a "snippet" object. Create the snippet object here.
  205. # Setting "ref = ref[key]" means that in the next time through the
  206. # "for pa in range ..." loop, we will be setting a property in the
  207. # resource's "snippet" object.
  208. ref[key] = {}
  209. ref = ref[key]
  210. else:
  211. # For example, the property is "snippet.description", and the resource
  212. # already has a "snippet" object.
  213. ref = ref[key]
  214. return resource
  215. def set_thumbnail(options, youtube, media_file, **kwargs):
  216. kwargs = utils.remove_empty_kwargs(**kwargs)
  217. request = youtube.thumbnails().set(
  218. media_body=MediaFileUpload(media_file, chunksize=-1,
  219. resumable=True),
  220. **kwargs
  221. )
  222. return resumable_upload(request, 'thumbnail', 'set', options)
  223. def set_playlist(youtube, playlist_id, video_id):
  224. logger.info('Youtube: Configuring playlist...')
  225. resource = build_resource({'snippet.playlistId': playlist_id,
  226. 'snippet.resourceId.kind': 'youtube#video',
  227. 'snippet.resourceId.videoId': video_id,
  228. 'snippet.position': ''}
  229. )
  230. try:
  231. youtube.playlistItems().insert(
  232. body=resource,
  233. part='snippet'
  234. ).execute()
  235. except Exception as e:
  236. if hasattr(e, 'message'):
  237. logger.critical("Youtube: " + str(e.message))
  238. exit(1)
  239. else:
  240. logger.critical("Youtube: " + str(e))
  241. exit(1)
  242. logger.info('Youtube: Video is correctly added to the playlist.')
  243. # This method implements an exponential backoff strategy to resume a
  244. # failed upload.
  245. def resumable_upload(request, resource, method, options):
  246. response = None
  247. error = None
  248. retry = 0
  249. logger_stdout = None
  250. if options.get('--url-only') or options.get('--batch'):
  251. logger_stdout = logging.getLogger('stdoutlogs')
  252. while response is None:
  253. try:
  254. template = 'Youtube: Uploading %s...'
  255. logger.info(template % resource)
  256. status, response = request.next_chunk()
  257. if response is not None:
  258. if method == 'insert' and 'id' in response:
  259. logger.info('Youtube: Video was successfully uploaded.')
  260. template = 'Youtube: Watch it at https://youtu.be/%s (post-encoding could take some time)'
  261. logger.info(template % response['id'])
  262. template_stdout = 'https://youtu.be/%s'
  263. if options.get('--url-only'):
  264. logger_stdout.info(template_stdout % response['id'])
  265. elif options.get('--batch'):
  266. logger_stdout.info("Youtube: " + template_stdout % response['id'])
  267. return response['id']
  268. elif method != 'insert' or "id" not in response:
  269. logger.info('Youtube: Thumbnail was successfully set.')
  270. else:
  271. template = ('Youtube: The upload failed with an '
  272. 'unexpected response: %s')
  273. logger.critical(template % response)
  274. exit(1)
  275. except HttpError as e:
  276. if e.resp.status in RETRIABLE_STATUS_CODES:
  277. template = 'Youtube: A retriable HTTP error %d occurred:\n%s'
  278. error = template % (e.resp.status, e.content)
  279. else:
  280. raise
  281. except RETRIABLE_EXCEPTIONS as e:
  282. error = 'Youtube: A retriable error occurred: %s' % e
  283. if error is not None:
  284. logger.warning(error)
  285. retry += 1
  286. if retry > MAX_RETRIES:
  287. logger.error('Youtube: No longer attempting to retry.')
  288. max_sleep = 2 ** retry
  289. sleep_seconds = random.random() * max_sleep
  290. logger.warning('Youtube: Sleeping %f seconds and then retrying...'
  291. % sleep_seconds)
  292. time.sleep(sleep_seconds)
  293. def hearthbeat():
  294. """Use the minimums credits possibles of the API so google does not readuce to 0 the allowed credits.
  295. This apparently happens after 90 days without any usage of credits.
  296. For more info see the official documentations:
  297. - General informations about quotas: https://developers.google.com/youtube/v3/getting-started#quota
  298. - Quota costs for API requests: https://developers.google.com/youtube/v3/determine_quota_cost
  299. - ToS (Americas) #Usage and Quotas: https://developers.google.com/youtube/terms/api-services-terms-of-service#usage-and-quotas"""
  300. youtube = get_authenticated_service()
  301. try:
  302. get_playlist_by_name(youtube, "Foo")
  303. except HttpError as e:
  304. logger.error('Youtube: An HTTP error %d occurred on hearthbeat:\n%s' %
  305. (e.resp.status, e.content))
  306. def run(options):
  307. youtube = get_authenticated_service()
  308. try:
  309. initialize_upload(youtube, options)
  310. except HttpError as e:
  311. logger.error('Youtube: An HTTP error %d occurred:\n%s' % (e.resp.status,
  312. e.content))