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.

146 lines
4.7 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
  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. from googleapiclient.discovery import build
  13. from googleapiclient.errors import HttpError
  14. from googleapiclient.http import MediaFileUpload
  15. from google_auth_oauthlib.flow import InstalledAppFlow
  16. # Explicitly tell the underlying HTTP transport library not to retry, since
  17. # we are handling retry logic ourselves.
  18. httplib2.RETRIES = 1
  19. # Maximum number of times to retry before giving up.
  20. MAX_RETRIES = 10
  21. # Youtube retriables cases
  22. RETRIABLE_EXCEPTIONS = (
  23. IOError,
  24. httplib2.HttpLib2Error,
  25. httplib.NotConnected,
  26. httplib.IncompleteRead,
  27. httplib.ImproperConnectionState,
  28. httplib.CannotSendRequest,
  29. httplib.CannotSendHeader,
  30. httplib.ResponseNotReady,
  31. httplib.BadStatusLine,
  32. )
  33. RETRIABLE_STATUS_CODES = [500, 502, 503, 504]
  34. CLIENT_SECRETS_FILE = 'youtube_secret.json'
  35. CREDENTIALS_PATH = ".youtube_credentials.json"
  36. SCOPES = ['https://www.googleapis.com/auth/youtube.upload']
  37. API_SERVICE_NAME = 'youtube'
  38. API_VERSION = 'v3'
  39. # Authorize the request and store authorization credentials.
  40. def get_authenticated_service():
  41. flow = InstalledAppFlow.from_client_secrets_file(
  42. CLIENT_SECRETS_FILE, SCOPES)
  43. if exists(CREDENTIALS_PATH):
  44. with open(CREDENTIALS_PATH, 'r') as f:
  45. credential_params = json.load(f)
  46. credentials = google.oauth2.credentials.Credentials(
  47. credential_params["token"],
  48. refresh_token=credential_params["_refresh_token"],
  49. token_uri=credential_params["_token_uri"],
  50. client_id=credential_params["_client_id"],
  51. client_secret=credential_params["_client_secret"]
  52. )
  53. else:
  54. credentials = flow.run_local_server()
  55. with open(CREDENTIALS_PATH, 'w') as f:
  56. p = copy.deepcopy(vars(credentials))
  57. del p["expiry"]
  58. json.dump(p, f)
  59. return build(API_SERVICE_NAME, API_VERSION, credentials=credentials)
  60. def initialize_upload(youtube, options):
  61. path = options.get('--file')
  62. tags = None
  63. if options.get('--tags'):
  64. tags = options.get('--tags').split(',')
  65. body = {
  66. "snippet": {
  67. "title": options.get('--name') or splitext(basename(path))[0],
  68. "description": options.get('--description') or "",
  69. "tags": tags,
  70. "categoryId": str(options.get('--category') or 1),
  71. },
  72. "status": {"privacyStatus": str(options.get('--privacy') or "private")}
  73. }
  74. # Call the API's videos.insert method to create and upload the video.
  75. insert_request = youtube.videos().insert(
  76. part=','.join(body.keys()),
  77. body=body,
  78. media_body=MediaFileUpload(path, chunksize=-1, resumable=True)
  79. )
  80. resumable_upload(insert_request)
  81. # This method implements an exponential backoff strategy to resume a
  82. # failed upload.
  83. def resumable_upload(request):
  84. response = None
  85. error = None
  86. retry = 0
  87. while response is None:
  88. try:
  89. print('Youtube : Uploading file...')
  90. status, response = request.next_chunk()
  91. if response is not None:
  92. if 'id' in response:
  93. template = ('Youtube : Video id "%s" was successfully '
  94. 'uploaded.')
  95. print(template % response['id'])
  96. else:
  97. template = ('Youtube : The upload failed with an '
  98. 'unexpected response: %s')
  99. exit(template % response)
  100. except HttpError as e:
  101. if e.resp.status in RETRIABLE_STATUS_CODES:
  102. template = 'Youtube : A retriable HTTP error %d occurred:\n%s'
  103. error = template % (e.resp.status, e.content)
  104. else:
  105. raise
  106. except RETRIABLE_EXCEPTIONS as e:
  107. error = 'Youtube : A retriable error occurred: %s' % e
  108. if error is not None:
  109. print(error)
  110. retry += 1
  111. if retry > MAX_RETRIES:
  112. exit('Youtube : No longer attempting to retry.')
  113. max_sleep = 2 ** retry
  114. sleep_seconds = random.random() * max_sleep
  115. print('Youtube : Sleeping %f seconds and then retrying...'
  116. % sleep_seconds)
  117. time.sleep(sleep_seconds)
  118. def run(options):
  119. youtube = get_authenticated_service()
  120. try:
  121. initialize_upload(youtube, options)
  122. except HttpError as e:
  123. print('Youtube : An HTTP error %d occurred:\n%s' % (e.resp.status,
  124. e.content))