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.

321 lines
12 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
  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. logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO)
  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. logging.warning("Youtube: Credentials are obsolete, need to re-authenticate.")
  75. os.remove(CREDENTIALS_PATH)
  76. def initialize_upload(youtube, options):
  77. path = options.get('--file')
  78. tags = None
  79. if options.get('--tags'):
  80. tags = options.get('--tags').split(',')
  81. category = None
  82. if options.get('--category'):
  83. category = utils.getCategory(options.get('--category'), 'youtube')
  84. language = None
  85. if options.get('--language'):
  86. language = utils.getLanguage(options.get('--language'), "youtube")
  87. license = None
  88. if options.get('--cca'):
  89. license = "creativeCommon"
  90. body = {
  91. "snippet": {
  92. "title": options.get('--name') or splitext(basename(path))[0],
  93. "description": options.get('--description') or "default description",
  94. "tags": tags,
  95. # if no category, set default to 1 (Films)
  96. "categoryId": str(category or 1),
  97. "defaultAudioLanguage": str(language or 'en')
  98. },
  99. "status": {
  100. "privacyStatus": str(options.get('--privacy') or "private"),
  101. "license": str(license or "youtube"),
  102. }
  103. }
  104. # If peertubeAt exists, use instead of publishAt
  105. if options.get('--youtubeAt'):
  106. publishAt = options.get('--youtubeAt')
  107. elif options.get('--publishAt'):
  108. publishAt = options.get('--publishAt')
  109. if 'publishAt' in locals():
  110. # Youtube needs microsecond and the local timezone from ISO 8601
  111. publishAt = publishAt + ".000001"
  112. publishAt = datetime.datetime.strptime(publishAt, '%Y-%m-%dT%H:%M:%S.%f')
  113. tz = get_localzone()
  114. tz = pytz.timezone(str(tz))
  115. publishAt = tz.localize(publishAt).isoformat()
  116. body['status']['publishAt'] = str(publishAt)
  117. if options.get('--playlist'):
  118. playlist_id = get_playlist_by_name(youtube, options.get('--playlist'))
  119. if not playlist_id and options.get('--playlistCreate'):
  120. playlist_id = create_playlist(youtube, options.get('--playlist'))
  121. elif not playlist_id:
  122. logging.warning("Youtube: Playlist `" + options.get('--playlist') + "` is unknown.")
  123. logging.warning("If you want to create it, set the --playlistCreate option.")
  124. playlist_id = ""
  125. else:
  126. playlist_id = ""
  127. # Call the API's videos.insert method to create and upload the video.
  128. insert_request = youtube.videos().insert(
  129. part=','.join(list(body.keys())),
  130. body=body,
  131. media_body=MediaFileUpload(path, chunksize=-1, resumable=True)
  132. )
  133. video_id = resumable_upload(insert_request, 'video', 'insert')
  134. # If we get a video_id, upload is successful and we are able to set thumbnail
  135. if video_id and options.get('--thumbnail'):
  136. set_thumbnail(youtube, options.get('--thumbnail'), videoId=video_id)
  137. # If we get a video_id and a playlist_id, upload is successful and we are able to set playlist
  138. if video_id and playlist_id != "":
  139. set_playlist(youtube, playlist_id, video_id)
  140. def get_playlist_by_name(youtube, playlist_name):
  141. response = youtube.playlists().list(
  142. part='snippet,id',
  143. mine=True,
  144. maxResults=50
  145. ).execute()
  146. for playlist in response["items"]:
  147. if playlist["snippet"]['title'] == playlist_name:
  148. return playlist['id']
  149. def create_playlist(youtube, playlist_name):
  150. template = ('Youtube: Playlist %s does not exist, creating it.')
  151. logging.info(template % (str(playlist_name)))
  152. resources = build_resource({'snippet.title': playlist_name,
  153. 'snippet.description': '',
  154. 'status.privacyStatus': 'public'})
  155. response = youtube.playlists().insert(
  156. body=resources,
  157. part='status,snippet,id'
  158. ).execute()
  159. return response["id"]
  160. def build_resource(properties):
  161. resource = {}
  162. for p in properties:
  163. # Given a key like "snippet.title", split into "snippet" and "title", where
  164. # "snippet" will be an object and "title" will be a property in that object.
  165. prop_array = p.split('.')
  166. ref = resource
  167. for pa in range(0, len(prop_array)):
  168. is_array = False
  169. key = prop_array[pa]
  170. # For properties that have array values, convert a name like
  171. # "snippet.tags[]" to snippet.tags, and set a flag to handle
  172. # the value as an array.
  173. if key[-2:] == '[]':
  174. key = key[0:len(key)-2:]
  175. is_array = True
  176. if pa == (len(prop_array) - 1):
  177. # Leave properties without values out of inserted resource.
  178. if properties[p]:
  179. if is_array:
  180. ref[key] = properties[p].split(',')
  181. else:
  182. ref[key] = properties[p]
  183. elif key not in ref:
  184. # For example, the property is "snippet.title", but the resource does
  185. # not yet have a "snippet" object. Create the snippet object here.
  186. # Setting "ref = ref[key]" means that in the next time through the
  187. # "for pa in range ..." loop, we will be setting a property in the
  188. # resource's "snippet" object.
  189. ref[key] = {}
  190. ref = ref[key]
  191. else:
  192. # For example, the property is "snippet.description", and the resource
  193. # already has a "snippet" object.
  194. ref = ref[key]
  195. return resource
  196. def set_thumbnail(youtube, media_file, **kwargs):
  197. kwargs = utils.remove_empty_kwargs(**kwargs)
  198. request = youtube.thumbnails().set(
  199. media_body=MediaFileUpload(media_file, chunksize=-1,
  200. resumable=True),
  201. **kwargs
  202. )
  203. # See full sample for function
  204. return resumable_upload(request, 'thumbnail', 'set')
  205. def set_playlist(youtube, playlist_id, video_id):
  206. logging.info('Youtube: Configuring playlist...')
  207. resource = build_resource({'snippet.playlistId': playlist_id,
  208. 'snippet.resourceId.kind': 'youtube#video',
  209. 'snippet.resourceId.videoId': video_id,
  210. 'snippet.position': ''}
  211. )
  212. try:
  213. youtube.playlistItems().insert(
  214. body=resource,
  215. part='snippet'
  216. ).execute()
  217. except Exception as e:
  218. if hasattr(e, 'message'):
  219. logging.error("Youtube: Error: " + str(e.message))
  220. exit(1)
  221. else:
  222. logging.error("Youtube: Error: " + str(e))
  223. exit(1)
  224. logging.info('Youtube: Video is correctly added to the playlist.')
  225. # This method implements an exponential backoff strategy to resume a
  226. # failed upload.
  227. def resumable_upload(request, resource, method):
  228. response = None
  229. error = None
  230. retry = 0
  231. while response is None:
  232. try:
  233. template = 'Youtube: Uploading %s...'
  234. logging.info(template % resource)
  235. status, response = request.next_chunk()
  236. if response is not None:
  237. if method == 'insert' and 'id' in response:
  238. logging.info('Youtube : Video was successfully uploaded.')
  239. template = 'Youtube: Watch it at https://youtu.be/%s (post-encoding could take some time)'
  240. logging.info(template % response['id'])
  241. return response['id']
  242. elif method != 'insert' or "id" not in response:
  243. logging.info('Youtube: Thumbnail was successfully set.')
  244. else:
  245. template = ('Youtube : The upload failed with an '
  246. 'unexpected response: %s')
  247. logging.error(template % response)
  248. exit(1)
  249. except HttpError as e:
  250. if e.resp.status in RETRIABLE_STATUS_CODES:
  251. template = 'Youtube : A retriable HTTP error %d occurred:\n%s'
  252. error = template % (e.resp.status, e.content)
  253. else:
  254. raise
  255. except RETRIABLE_EXCEPTIONS as e:
  256. error = 'Youtube : A retriable error occurred: %s' % e
  257. if error is not None:
  258. logging.warning(error)
  259. retry += 1
  260. if retry > MAX_RETRIES:
  261. logging.error('Youtube : No longer attempting to retry.')
  262. exit(1)
  263. max_sleep = 2 ** retry
  264. sleep_seconds = random.random() * max_sleep
  265. logging.warning('Youtube : Sleeping %f seconds and then retrying...'
  266. % sleep_seconds)
  267. time.sleep(sleep_seconds)
  268. def run(options):
  269. youtube = get_authenticated_service()
  270. try:
  271. initialize_upload(youtube, options)
  272. except HttpError as e:
  273. logging.error('Youtube : An HTTP error %d occurred:\n%s' % (e.resp.status,
  274. e.content))