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.

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