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.

115 lines
3.4 KiB

  1. #!/usr/bin/python
  2. # coding: utf-8
  3. # From Youtube samples : https://raw.githubusercontent.com/youtube/api-samples/master/python/upload_video.py
  4. import argparse
  5. import httplib
  6. import httplib2
  7. import os
  8. import random
  9. import time
  10. import google.oauth2.credentials
  11. import google_auth_oauthlib.flow
  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 = (httplib2.HttpLib2Error, IOError, httplib.NotConnected,
  23. httplib.IncompleteRead, httplib.ImproperConnectionState,
  24. httplib.CannotSendRequest, httplib.CannotSendHeader,
  25. httplib.ResponseNotReady, httplib.BadStatusLine)
  26. RETRIABLE_STATUS_CODES = [500, 502, 503, 504]
  27. CLIENT_SECRETS_FILE = 'youtube_secret.json'
  28. SCOPES = ['https://www.googleapis.com/auth/youtube.upload']
  29. API_SERVICE_NAME = 'youtube'
  30. API_VERSION = 'v3'
  31. # Authorize the request and store authorization credentials.
  32. def get_authenticated_service():
  33. flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
  34. credentials = flow.run_console()
  35. return build(API_SERVICE_NAME, API_VERSION, credentials = credentials)
  36. def initialize_upload(youtube, options):
  37. tags = None
  38. if options.keywords:
  39. tags = options.keywords.split(',')
  40. body=dict(
  41. snippet=dict(
  42. name=options.name,
  43. description=options.description,
  44. tags=tags,
  45. categoryId=options.category
  46. ),
  47. status=dict(
  48. privacyStatus=options.privacyStatus
  49. )
  50. )
  51. # Call the API's videos.insert method to create and upload the video.
  52. insert_request = youtube.videos().insert(
  53. part=','.join(body.keys()),
  54. body=body,
  55. media_body=MediaFileUpload(options.file, chunksize=-1, resumable=True)
  56. )
  57. resumable_upload(insert_request)
  58. # This method implements an exponential backoff strategy to resume a
  59. # failed upload.
  60. def resumable_upload(request):
  61. response = None
  62. error = None
  63. retry = 0
  64. while response is None:
  65. try:
  66. print 'Uploading file...'
  67. status, response = request.next_chunk()
  68. if response is not None:
  69. if 'id' in response:
  70. print 'Video id "%s" was successfully uploaded.' % response['id']
  71. else:
  72. exit('The upload failed with an unexpected response: %s' % response)
  73. except HttpError, e:
  74. if e.resp.status in RETRIABLE_STATUS_CODES:
  75. error = 'A retriable HTTP error %d occurred:\n%s' % (e.resp.status,
  76. e.content)
  77. else:
  78. raise
  79. except RETRIABLE_EXCEPTIONS, e:
  80. error = 'A retriable error occurred: %s' % e
  81. if error is not None:
  82. print error
  83. retry += 1
  84. if retry > MAX_RETRIES:
  85. exit('No longer attempting to retry.')
  86. max_sleep = 2 ** retry
  87. sleep_seconds = random.random() * max_sleep
  88. print 'Sleeping %f seconds and then retrying...' % sleep_seconds
  89. time.sleep(sleep_seconds)
  90. def run(options):
  91. youtube = get_authenticated_service()
  92. try:
  93. initialize_upload(youtube, options)
  94. except HttpError, e:
  95. print 'An HTTP error %d occurred:\n%s' % (e.resp.status, e.content)