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.

182 lines
6.1 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/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. resumable_upload(insert_request)
  109. # This method implements an exponential backoff strategy to resume a
  110. # failed upload.
  111. def resumable_upload(request):
  112. response = None
  113. error = None
  114. retry = 0
  115. while response is None:
  116. try:
  117. logging.info('Youtube : Uploading file...')
  118. status, response = request.next_chunk()
  119. if response is not None:
  120. if 'id' in response:
  121. template = ('Youtube : Video was successfully '
  122. 'uploaded.\n'
  123. 'Watch it at https://youtu.be/%s (post-encoding could take some time)')
  124. logging.info(template % response['id'])
  125. else:
  126. template = ('Youtube : The upload failed with an '
  127. 'unexpected response: %s')
  128. logging.error(template % response)
  129. exit(1)
  130. except HttpError as e:
  131. if e.resp.status in RETRIABLE_STATUS_CODES:
  132. template = 'Youtube : A retriable HTTP error %d occurred:\n%s'
  133. error = template % (e.resp.status, e.content)
  134. else:
  135. raise
  136. except RETRIABLE_EXCEPTIONS as e:
  137. error = 'Youtube : A retriable error occurred: %s' % e
  138. if error is not None:
  139. logging.warning(error)
  140. retry += 1
  141. if retry > MAX_RETRIES:
  142. logging.error('Youtube : No longer attempting to retry.')
  143. exit(1)
  144. max_sleep = 2 ** retry
  145. sleep_seconds = random.random() * max_sleep
  146. logging.warning('Youtube : Sleeping %f seconds and then retrying...'
  147. % sleep_seconds)
  148. time.sleep(sleep_seconds)
  149. def run(options):
  150. youtube = get_authenticated_service()
  151. try:
  152. initialize_upload(youtube, options)
  153. except HttpError as e:
  154. logging.error('Youtube : An HTTP error %d occurred:\n%s' % (e.resp.status,
  155. e.content))