scripting your 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.

313 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
  1. #!/usr/bin/env python2
  2. # coding: utf-8
  3. # From Youtube samples : https://raw.githubusercontent.com/youtube/api-samples/master/python/upload_video.py # noqa
  4. import httplib
  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. 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. httplib.NotConnected,
  33. httplib.IncompleteRead,
  34. httplib.ImproperConnectionState,
  35. httplib.CannotSendRequest,
  36. httplib.CannotSendHeader,
  37. httplib.ResponseNotReady,
  38. httplib.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 options.get('--publishAt'):
  105. # Youtube needs microsecond and the local timezone from ISO 8601
  106. publishAt = options.get('--publishAt') + ".000001"
  107. publishAt = datetime.datetime.strptime(publishAt, '%Y-%m-%dT%H:%M:%S.%f')
  108. tz = get_localzone()
  109. tz = pytz.timezone(str(tz))
  110. publishAt = tz.localize(publishAt).isoformat()
  111. body['status']['publishAt'] = str(publishAt)
  112. if options.get('--playlist'):
  113. playlist_id = get_playlist_by_name(youtube, options.get('--playlist'))
  114. if not playlist_id and options.get('--playlistCreate'):
  115. playlist_id = create_playlist(youtube, options.get('--playlist'))
  116. elif not playlist_id:
  117. logging.warning("Youtube: Playlist `" + options.get('--playlist') + "` is unknown.")
  118. logging.warning("If you want to create it, set the --playlistCreate option.")
  119. playlist_id = ""
  120. else:
  121. playlist_id = ""
  122. # Call the API's videos.insert method to create and upload the video.
  123. insert_request = youtube.videos().insert(
  124. part=','.join(body.keys()),
  125. body=body,
  126. media_body=MediaFileUpload(path, chunksize=-1, resumable=True)
  127. )
  128. video_id = resumable_upload(insert_request, 'video', 'insert')
  129. # If we get a video_id, upload is successful and we are able to set thumbnail
  130. if video_id and options.get('--thumbnail'):
  131. set_thumbnail(youtube, options.get('--thumbnail'), videoId=video_id)
  132. # If we get a video_id, upload is successful and we are able to set playlist
  133. if video_id and options.get('--playlist'):
  134. set_playlist(youtube, playlist_id, video_id)
  135. def get_playlist_by_name(youtube, playlist_name):
  136. response = youtube.playlists().list(
  137. part='snippet,id',
  138. mine=True,
  139. maxResults=50
  140. ).execute()
  141. for playlist in response["items"]:
  142. if playlist["snippet"]['title'] == playlist_name:
  143. return playlist['id']
  144. def create_playlist(youtube, playlist_name):
  145. template = ('Youtube: Playlist %s does not exist, creating it.')
  146. logging.info(template % (str(playlist_name)))
  147. resources = build_resource({'snippet.title': playlist_name,
  148. 'snippet.description': '',
  149. 'status.privacyStatus': 'public'})
  150. response = youtube.playlists().insert(
  151. body=resources,
  152. part='status,snippet,id'
  153. ).execute()
  154. return response["id"]
  155. def build_resource(properties):
  156. resource = {}
  157. for p in properties:
  158. # Given a key like "snippet.title", split into "snippet" and "title", where
  159. # "snippet" will be an object and "title" will be a property in that object.
  160. prop_array = p.split('.')
  161. ref = resource
  162. for pa in range(0, len(prop_array)):
  163. is_array = False
  164. key = prop_array[pa]
  165. # For properties that have array values, convert a name like
  166. # "snippet.tags[]" to snippet.tags, and set a flag to handle
  167. # the value as an array.
  168. if key[-2:] == '[]':
  169. key = key[0:len(key)-2:]
  170. is_array = True
  171. if pa == (len(prop_array) - 1):
  172. # Leave properties without values out of inserted resource.
  173. if properties[p]:
  174. if is_array:
  175. ref[key] = properties[p].split(',')
  176. else:
  177. ref[key] = properties[p]
  178. elif key not in ref:
  179. # For example, the property is "snippet.title", but the resource does
  180. # not yet have a "snippet" object. Create the snippet object here.
  181. # Setting "ref = ref[key]" means that in the next time through the
  182. # "for pa in range ..." loop, we will be setting a property in the
  183. # resource's "snippet" object.
  184. ref[key] = {}
  185. ref = ref[key]
  186. else:
  187. # For example, the property is "snippet.description", and the resource
  188. # already has a "snippet" object.
  189. ref = ref[key]
  190. return resource
  191. def set_thumbnail(youtube, media_file, **kwargs):
  192. kwargs = utils.remove_empty_kwargs(**kwargs)
  193. request = youtube.thumbnails().set(
  194. media_body=MediaFileUpload(media_file, chunksize=-1,
  195. resumable=True),
  196. **kwargs
  197. )
  198. # See full sample for function
  199. return resumable_upload(request, 'thumbnail', 'set')
  200. def set_playlist(youtube, playlist_id, video_id):
  201. logging.info('Youtube: Configuring playlist...')
  202. resource = build_resource({'snippet.playlistId': playlist_id,
  203. 'snippet.resourceId.kind': 'youtube#video',
  204. 'snippet.resourceId.videoId': video_id,
  205. 'snippet.position': ''}
  206. )
  207. try:
  208. youtube.playlistItems().insert(
  209. body=resource,
  210. part='snippet'
  211. ).execute()
  212. except Exception as e:
  213. if hasattr(e, 'message'):
  214. logging.error("Youtube: Error: " + str(e.message))
  215. else:
  216. logging.error("Youtube: Error: " + str(e))
  217. logging.info('Youtube: Video is correclty added to the playlist.')
  218. # This method implements an exponential backoff strategy to resume a
  219. # failed upload.
  220. def resumable_upload(request, resource, method):
  221. response = None
  222. error = None
  223. retry = 0
  224. while response is None:
  225. try:
  226. template = 'Youtube: Uploading %s...'
  227. logging.info(template % resource)
  228. status, response = request.next_chunk()
  229. if response is not None:
  230. if method == 'insert' and 'id' in response:
  231. logging.info('Youtube : Video was successfully uploaded.')
  232. template = 'Youtube: Watch it at https://youtu.be/%s (post-encoding could take some time)'
  233. logging.info(template % response['id'])
  234. return response['id']
  235. elif method != 'insert' or "id" not in response:
  236. logging.info('Youtube: Thumbnail was successfully set.')
  237. else:
  238. template = ('Youtube : The upload failed with an '
  239. 'unexpected response: %s')
  240. logging.error(template % response)
  241. exit(1)
  242. except HttpError as e:
  243. if e.resp.status in RETRIABLE_STATUS_CODES:
  244. template = 'Youtube : A retriable HTTP error %d occurred:\n%s'
  245. error = template % (e.resp.status, e.content)
  246. else:
  247. raise
  248. except RETRIABLE_EXCEPTIONS as e:
  249. error = 'Youtube : A retriable error occurred: %s' % e
  250. if error is not None:
  251. logging.warning(error)
  252. retry += 1
  253. if retry > MAX_RETRIES:
  254. logging.error('Youtube : No longer attempting to retry.')
  255. exit(1)
  256. max_sleep = 2 ** retry
  257. sleep_seconds = random.random() * max_sleep
  258. logging.warning('Youtube : Sleeping %f seconds and then retrying...'
  259. % sleep_seconds)
  260. time.sleep(sleep_seconds)
  261. def run(options):
  262. youtube = get_authenticated_service()
  263. try:
  264. initialize_upload(youtube, options)
  265. except HttpError as e:
  266. logging.error('Youtube : An HTTP error %d occurred:\n%s' % (e.resp.status,
  267. e.content))