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.

110 lines
3.2 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. VALID_PRIVACY_STATUSES = ('public', 'private', 'unlisted')
  32. # Authorize the request and store authorization credentials.
  33. def get_authenticated_service():
  34. flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
  35. credentials = flow.run_console()
  36. return build(API_SERVICE_NAME, API_VERSION, credentials = credentials)
  37. def initialize_upload(youtube, options):
  38. tags = None
  39. if options.keywords:
  40. tags = options.keywords.split(',')
  41. body=dict(
  42. snippet=dict(
  43. title=options.title,
  44. description=options.description,
  45. tags=tags,
  46. categoryId=options.category
  47. ),
  48. status=dict(
  49. privacyStatus=options.privacyStatus
  50. )
  51. )
  52. # Call the API's videos.insert method to create and upload the video.
  53. insert_request = youtube.videos().insert(
  54. part=','.join(body.keys()),
  55. body=body,
  56. media_body=MediaFileUpload(options.file, chunksize=-1, resumable=True)
  57. )
  58. resumable_upload(insert_request)
  59. # This method implements an exponential backoff strategy to resume a
  60. # failed upload.
  61. def resumable_upload(request):
  62. response = None
  63. error = None
  64. retry = 0
  65. while response is None:
  66. try:
  67. print 'Uploading file...'
  68. status, response = request.next_chunk()
  69. if response is not None:
  70. if 'id' in response:
  71. print 'Video id "%s" was successfully uploaded.' % response['id']
  72. else:
  73. exit('The upload failed with an unexpected response: %s' % response)
  74. except HttpError, e:
  75. if e.resp.status in RETRIABLE_STATUS_CODES:
  76. error = 'A retriable HTTP error %d occurred:\n%s' % (e.resp.status,
  77. e.content)
  78. else:
  79. raise
  80. except RETRIABLE_EXCEPTIONS, e:
  81. error = 'A retriable error occurred: %s' % e
  82. if error is not None:
  83. print error
  84. retry += 1
  85. if retry > MAX_RETRIES:
  86. exit('No longer attempting to retry.')
  87. max_sleep = 2 ** retry
  88. sleep_seconds = random.random() * max_sleep
  89. print 'Sleeping %f seconds and then retrying...' % sleep_seconds
  90. time.sleep(sleep_seconds)