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.

202 lines
6.9 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
  1. #!/usr/bin/python
  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 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. 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. httplib.NotConnected,
  32. httplib.IncompleteRead,
  33. httplib.ImproperConnectionState,
  34. httplib.CannotSendRequest,
  35. httplib.CannotSendHeader,
  36. httplib.ResponseNotReady,
  37. httplib.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']
  43. API_SERVICE_NAME = 'youtube'
  44. API_VERSION = 'v3'
  45. # Authorize the request and store authorization credentials.
  46. def get_authenticated_service():
  47. flow = InstalledAppFlow.from_client_secrets_file(
  48. CLIENT_SECRETS_FILE, SCOPES)
  49. if exists(CREDENTIALS_PATH):
  50. with open(CREDENTIALS_PATH, 'r') as f:
  51. credential_params = json.load(f)
  52. credentials = google.oauth2.credentials.Credentials(
  53. credential_params["token"],
  54. refresh_token=credential_params["_refresh_token"],
  55. token_uri=credential_params["_token_uri"],
  56. client_id=credential_params["_client_id"],
  57. client_secret=credential_params["_client_secret"]
  58. )
  59. else:
  60. credentials = flow.run_local_server()
  61. with open(CREDENTIALS_PATH, 'w') as f:
  62. p = copy.deepcopy(vars(credentials))
  63. del p["expiry"]
  64. json.dump(p, f)
  65. return build(API_SERVICE_NAME, API_VERSION, credentials=credentials, cache_discovery=False)
  66. def initialize_upload(youtube, options):
  67. path = options.get('--file')
  68. tags = None
  69. if options.get('--tags'):
  70. tags = options.get('--tags').split(',')
  71. category = None
  72. if options.get('--category'):
  73. category = utils.getCategory(options.get('--category'), 'youtube')
  74. language = None
  75. if options.get('--language'):
  76. language = utils.getLanguage(options.get('--language'), "youtube")
  77. license = None
  78. if options.get('--cca'):
  79. license = "creativeCommon"
  80. body = {
  81. "snippet": {
  82. "title": options.get('--name') or splitext(basename(path))[0],
  83. "description": options.get('--description') or "default description",
  84. "tags": tags,
  85. # if no category, set default to 1 (Films)
  86. "categoryId": str(category or 1),
  87. "defaultAudioLanguage": str(language or 'en')
  88. },
  89. "status": {
  90. "privacyStatus": str(options.get('--privacy') or "private"),
  91. "license": str(license or "youtube"),
  92. }
  93. }
  94. if options.get('--publishAt'):
  95. # Youtube needs microsecond and the local timezone from ISO 8601
  96. publishAt = options.get('--publishAt') + ".000001"
  97. publishAt = datetime.datetime.strptime(publishAt, '%Y-%m-%dT%H:%M:%S.%f')
  98. tz = get_localzone()
  99. tz = pytz.timezone(str(tz))
  100. publishAt = tz.localize(publishAt).isoformat()
  101. body['status']['publishAt'] = str(publishAt)
  102. # Call the API's videos.insert method to create and upload the video.
  103. insert_request = youtube.videos().insert(
  104. part=','.join(body.keys()),
  105. body=body,
  106. media_body=MediaFileUpload(path, chunksize=-1, resumable=True)
  107. )
  108. video_id = resumable_upload(insert_request, 'video', 'insert')
  109. # If we get a video_id, upload is successful and we are able to set thumbnail
  110. if video_id and options.get('--thumbnail'):
  111. set_thumbnail(youtube, options.get('--thumbnail'), videoId=video_id)
  112. def set_thumbnail(youtube, media_file, **kwargs):
  113. kwargs = utils.remove_empty_kwargs(**kwargs) # See full sample for function
  114. request = youtube.thumbnails().set(
  115. media_body=MediaFileUpload(media_file, chunksize=-1,
  116. resumable=True),
  117. **kwargs
  118. )
  119. # See full sample for function
  120. return resumable_upload(request, 'thumbnail', 'set')
  121. # This method implements an exponential backoff strategy to resume a
  122. # failed upload.
  123. def resumable_upload(request, resource, method):
  124. response = None
  125. error = None
  126. retry = 0
  127. while response is None:
  128. try:
  129. template = 'Youtube: Uploading %s...'
  130. logging.info(template % resource)
  131. status, response = request.next_chunk()
  132. if response is not None:
  133. if method == 'insert' and 'id' in response:
  134. logging.info('Youtube : Video was successfully uploaded.')
  135. template = 'Youtube: Watch it at https://youtu.be/%s (post-encoding could take some time)'
  136. logging.info(template % response['id'])
  137. return response['id']
  138. elif method != 'insert' or "id" not in response:
  139. logging.info('Youtube: Thumbnail was successfully set.')
  140. else:
  141. template = ('Youtube : The upload failed with an '
  142. 'unexpected response: %s')
  143. logging.error(template % response)
  144. exit(1)
  145. except HttpError as e:
  146. if e.resp.status in RETRIABLE_STATUS_CODES:
  147. template = 'Youtube : A retriable HTTP error %d occurred:\n%s'
  148. error = template % (e.resp.status, e.content)
  149. else:
  150. raise
  151. except RETRIABLE_EXCEPTIONS as e:
  152. error = 'Youtube : A retriable error occurred: %s' % e
  153. if error is not None:
  154. logging.warning(error)
  155. retry += 1
  156. if retry > MAX_RETRIES:
  157. logging.error('Youtube : No longer attempting to retry.')
  158. exit(1)
  159. max_sleep = 2 ** retry
  160. sleep_seconds = random.random() * max_sleep
  161. logging.warning('Youtube : Sleeping %f seconds and then retrying...'
  162. % sleep_seconds)
  163. time.sleep(sleep_seconds)
  164. def run(options):
  165. youtube = get_authenticated_service()
  166. try:
  167. initialize_upload(youtube, options)
  168. except HttpError as e:
  169. logging.error('Youtube : An HTTP error %d occurred:\n%s' % (e.resp.status,
  170. e.content))