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.

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