Guest User

Python upload to youtube script

a guest
Mar 31st, 2020
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.79 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3. import httplib
  4. import httplib2
  5. import os
  6. import random
  7. import sys
  8. import time
  9. import argparse
  10.  
  11. from apiclient.discovery import build
  12. from apiclient.errors import HttpError
  13. from apiclient.http import MediaFileUpload
  14. from oauth2client.client import flow_from_clientsecrets
  15. from oauth2client.file import Storage
  16. from oauth2client.tools import argparser, run_flow
  17.  
  18.  
  19. httplib2.RETRIES = 1
  20. MAX_RETRIES = 10
  21. RETRIABLE_EXCEPTIONS = (httplib2.HttpLib2Error, IOError, httplib.NotConnected,
  22.   httplib.IncompleteRead, httplib.ImproperConnectionState,
  23.   httplib.CannotSendRequest, httplib.CannotSendHeader,
  24.   httplib.ResponseNotReady, httplib.BadStatusLine)
  25. RETRIABLE_STATUS_CODES = [500, 502, 503, 504]
  26. CLIENT_SECRETS_FILE = "client_secrets.json"
  27. YOUTUBE_UPLOAD_SCOPE = "https://www.googleapis.com/auth/youtube"
  28. YOUTUBE_API_SERVICE_NAME = "youtube"
  29. YOUTUBE_API_VERSION = "v3"
  30. MISSING_CLIENT_SECRETS_MESSAGE = """WARNING: Please configure OAuth 2.0"""
  31. VALID_PRIVACY_STATUSES = ("unlisted", "public", "private")
  32. VALID_PLAYLIST_CHOICES = ("Methow Valley", "Methow Valley North Facing", "Testing Methow Valley")
  33. def get_authenticated_service(args):
  34.   flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE,
  35.     scope=YOUTUBE_UPLOAD_SCOPE,
  36.     message=MISSING_CLIENT_SECRETS_MESSAGE)
  37.  
  38.   storage = Storage("%s-oauth2.json" % sys.argv[0])
  39.   credentials = storage.get()
  40.  
  41.   if credentials is None or credentials.invalid:
  42.     credentials = run_flow(flow, storage, args)
  43.  
  44.   return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
  45.     http=credentials.authorize(httplib2.Http()))
  46.  
  47. def add_video_to_playlist(youtube,videoID,playlistID):
  48.   add_video_request=youtube.playlistItems().insert(
  49.   part="snippet",
  50.   body={
  51.         'snippet': {
  52.           'playlistId': playlistID,
  53.           'resourceId': {
  54.                   'kind': 'youtube#video',
  55.               'videoId': videoID
  56.             }
  57.         #'position': 0
  58.         }
  59.     }
  60. ).execute()
  61.   return add_video_request["id"]
  62.  
  63. def remove_video_from_playlist(playlistItemID):
  64.   request = youtube.playlistItems().delete(
  65.         id=playlistItemID
  66.     )
  67.   request.execute()
  68.  
  69. def initialize_upload(youtube, options):
  70.   tags = None
  71.   if options.keywords:
  72.     tags = options.keywords.split(",")
  73.  
  74.   body=dict(
  75.     snippet=dict(
  76.       title=options.title,
  77.       description=options.description,
  78.       tags=tags,
  79.       categoryId=options.category
  80.     ),
  81.     status=dict(
  82.       privacyStatus=options.privacyStatus
  83.     )
  84.   )
  85.  
  86.   insert_request = youtube.videos().insert(
  87.     part=",".join(body.keys()),
  88.     body=body,
  89.     media_body=MediaFileUpload(options.file, chunksize=-1, resumable=True)
  90.   )
  91.  
  92.   return resumable_upload(insert_request)
  93.  
  94. # This method implements an exponential backoff strategy to resume a
  95. # failed upload.
  96. def resumable_upload(insert_request):
  97.   response = None
  98.   error = None
  99.   retry = 0
  100.   while response is None:
  101.     try:
  102.       #print "Uploading file..."
  103.       status, response = insert_request.next_chunk()
  104.       if response is not None:
  105.         if 'id' in response:
  106.       #    print "Video id '%s' was successfully uploaded." % response['id']
  107.           return response['id']
  108.         else:
  109.           exit("The upload failed with an unexpected response: %s" % response)
  110.     except HttpError, e:
  111.       if e.resp.status in RETRIABLE_STATUS_CODES:
  112.         error = "A retriable HTTP error %d occurred:\n%s" % (e.resp.status,
  113.                                                              e.content)
  114.       else:
  115.         raise
  116.     except RETRIABLE_EXCEPTIONS, e:
  117.       error = "A retriable error occurred: %s" % e
  118.  
  119.     if error is not None:
  120.       print error
  121.       retry += 1
  122.       if retry > MAX_RETRIES:
  123.         exit("No longer attempting to retry.")
  124.  
  125.       max_sleep = 2 ** retry
  126.       sleep_seconds = random.random() * max_sleep
  127.       print "Sleeping %f seconds and then retrying..." % sleep_seconds
  128.       time.sleep(sleep_seconds)
  129.  
  130. if __name__ == '__main__':
  131.   #parser = argparse.ArgumentParser(prog='PROG')
  132.   #group = parser.add_mutually_exclusive_group(required=True)
  133.   argparser.add_argument("--refresh_creds", help="Refresh Oauth Creds by adding and removing a video from a playlist")
  134.   argparser.add_argument("--playlist", choices=VALID_PLAYLIST_CHOICES, help="Playlist to add video to", default="Testing Methow Valley")
  135.   argparser.add_argument("--video_id", help="ID of the video", default="dQw4w9WgXcQ")
  136.   argparser.add_argument("--file", help="Video file to upload")
  137.   argparser.add_argument("--title", help="Video title", default="Test Title")
  138.   argparser.add_argument("--description", help="Video description",
  139.     default="Test Description")
  140.   argparser.add_argument("--category", default="22",
  141.     help="Numeric video category. " +
  142.       "See https://developers.google.com/youtube/v3/docs/videoCategories/list")
  143.   argparser.add_argument("--keywords", help="Video keywords, comma separated",
  144.     default="")
  145.   argparser.add_argument("--privacyStatus", choices=VALID_PRIVACY_STATUSES,
  146.     default=VALID_PRIVACY_STATUSES[0], help="Video privacy status.")
  147.   args = argparser.parse_args()
  148.  
  149.   youtube = get_authenticated_service(args)
  150.   if args.playlist:
  151.     if args.playlist == "Methow Valley":
  152.       playlist_id="PL1RaOHEevOf2E8w9K-wjGyKz76VUI5Rg4"
  153.     if args.playlist == "Methow Valley North Facing":
  154.       playlist_id="PL1RaOHEevOf3e65qFUUN1utZ-kUTU2M4I"
  155.     if args.playlist == "Testing Methow Valley":
  156.       playlist_id="PL1RaOHEevOf33aPvZ_skcSWqNA03cYAhr"
  157.   print("Playlist: ",playlist_id)
  158.   if args.file:
  159.     if not os.path.exists(args.file):
  160.       exit("Please specify a valid file")
  161.     try:
  162.       video_id = initialize_upload(youtube, args)
  163.     except HttpError, e:
  164.       print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)
  165.   add_video_to_playlist(youtube,video_id,playlist_id)
Advertisement
Add Comment
Please, Sign In to add comment