__init__.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. """Wrapper for Google OAuth2 API."""
  2. import sys
  3. import json
  4. import googleapiclient.discovery
  5. import oauth2client
  6. import httplib2
  7. from youtube_upload import lib
  8. from youtube_upload.auth import console
  9. from youtube_upload.auth import browser
  10. YOUTUBE_UPLOAD_SCOPE = "https://www.googleapis.com/auth/youtube.upload"
  11. def _get_credentials_interactively(flow, storage, get_code_callback):
  12. """Return the credentials asking the user."""
  13. flow.redirect_uri = oauth2client.client.OOB_CALLBACK_URN
  14. authorize_url = flow.step1_get_authorize_url()
  15. code = get_code_callback(authorize_url)
  16. if code:
  17. credential = flow.step2_exchange(code, http=None)
  18. storage.put(credential)
  19. credential.set_store(storage)
  20. return credential
  21. def _get_credentials(flow, storage, get_code_callback):
  22. """Return the user credentials. If not found, run the interactive flow."""
  23. existing_credentials = storage.get()
  24. if existing_credentials and not existing_credentials.invalid:
  25. return existing_credentials
  26. else:
  27. return _get_credentials_interactively(flow, storage, get_code_callback)
  28. def get_resource(client_secrets_file, credentials_file, get_code_callback):
  29. """Authenticate and return a googleapiclient.discovery.Resource object."""
  30. get_flow = oauth2client.client.flow_from_clientsecrets
  31. flow = get_flow(client_secrets_file, scope=YOUTUBE_UPLOAD_SCOPE)
  32. storage = oauth2client.file.Storage(credentials_file)
  33. credentials = _get_credentials(flow, storage, get_code_callback)
  34. if credentials:
  35. http = credentials.authorize(httplib2.Http())
  36. return googleapiclient.discovery.build("youtube", "v3", http=http)