def handle_device(): storage1 = Storage('info5.dat') credentials = storage1.get() if credentials is None or credentials.invalid == True: credentials = tools.run_flow(FLOW, storage1) print(credentials) # Create an httplib2.Http object to handle our HTTP requests and # authorize it with our good Credentials. http = httplib2.Http() http = credentials.authorize(http) service = build('calendar', 'v3', http=http) people_service = build(serviceName='people', version='v1', http=http) results = people_service.people().connections().list( resourceName='people/me', pageSize=100, personFields='names,emailAddresses', fields='connections,totalItems,nextSyncToken').execute() connections = results.get('connections', []) print("authorized") utt = "reservate a pc and keybozrd for 2020-07-01 11:00:00" print(utt) listdiv = [] liste1 = utt.split(" a ") liste2 = liste1[1].split(" for ") if ("and") in liste2[0]: listdiv = liste2[0].split(" and ") else: listdiv.append(liste2[0]) print(listdiv) date1 = liste2[1] startdt = datetime.strptime(date1, '%Y-%m-%d %H:%M:%S') local_datetime2 = local_time.localize(startdt, is_dst=None) utc_datetime2 = local_datetime2.astimezone(pytz.utc) datestart = utc_datetime2.isoformat("T") print(datestart) dmax = input("donner la date de fin") enddt = datetime.strptime(dmax, '%Y-%m-%d %H:%M:%S') local_datetime2 = local_time.localize(enddt, is_dst=None) utc_datetime2 = local_datetime2.astimezone(pytz.utc) dater = utc_datetime2.isoformat("T") nameListe = [] adsmails = [] # attendee est la liste des invités qui sont disponibles attendees = [] for person in connections: emails = person.get('emailAddresses', []) names = person.get('names', []) adsmails.append(emails[0].get('value')) nameListe.append(names[0].get('displayName')) print(nameListe) print(adsmails) nameEmp = input('u tell me your name?') mailEmp = recherche(nameListe, adsmails, nameEmp) # service.list(customer='my_customer' , orderBy=None, pageToken=None, maxResults=None, query=None) # .get(customer=*, calendarResourceId=*) listD = ['FOCUS-RDC-PCFOCUS (1)'] listDmails = [ '*****@*****.**' ] freeDevices = [] freemails = [] for i in range(len(listDmails)): x = freebusy(i, datestart, dater, service) if x == True: freeDevices.append(listD[i]) freemails.append(listDmails[i]) print(freemails) s = ",".join(freeDevices) print('free devices' + s) for device in listdiv: l = [] for i in freeDevices: print(i) if device in i.lower(): l.append(i) print(l) if l != []: print('the available devices are' + s) choice = input('what is your choice?') email = recherche(freeDevices, freemails, choice) attendees.append({'email': email}) summary = choice + "reservation for Mr/Ms" + nameEmp description = "Mr/Ms" + nameEmp + "'s email:" + mailEmp reservation = { 'summary': summary, 'description': description, 'location': 'Focus corporation', 'start': { 'dateTime': datestart, 'timeZone': 'America/Los_Angeles', }, 'end': { 'dateTime': dater, 'timeZone': 'America/Los_Angeles', }, 'recurrence': ['RRULE:FREQ=DAILY;COUNT=1'], 'attendees': attendees, 'reminders': { 'useDefault': False, 'overrides': [ { 'method': 'email', 'minutes': 24 * 60 }, { 'method': 'popup', 'minutes': 10 }, ], }, } reservation = service.events().insert(calendarId='primary', sendNotifications=True, body=reservation).execute() print('Event created: %s' % (reservation.get('htmlLink'))) print('deviceReservated') else: print('no available devices')
MISSING_CLIENT_SECRETS_MESSAGE = """ WARNING: Please configure OAuth 2.0 To make this sample run you will need to populate the client_secrets.json file #""" # This OAuth 2.0 access scope allows for read-only access to the authenticated # user's account, but not other types of account access. YOUTUBE_READONLY_SCOPE = "https://www.googleapis.com/auth/youtube.readonly" YOUTUBE_API_SERVICE_NAME = "youtube" YOUTUBE_API_VERSION = "v3" flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, message=MISSING_CLIENT_SECRETS_MESSAGE, scope=YOUTUBE_READONLY_SCOPE) storage = Storage("%s-oauth2.json" % sys.argv[0]) credentials = storage.get() if credentials is None or credentials.invalid: flags = argparser.parse_args() credentials = run_flow(flow, storage, flags) youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, http=credentials.authorize(httplib2.Http())) # Retrieve the contentDetails part of the channel resource for the # authenticated user's channel. channels_response = youtube.channels().list(mine=True, part="contentDetails").execute()
html).groupdict()['cID'].replace("%40", "@") except Exception, e: lib.print_error("fail to get calendar ID") print e lib.finish(args.name, args.url) print "~~~~~~~calendarID:%s ~~~~~~~~~~" % calendarId FLOW = OAuth2WebServerFlow( client_id= '154781234816-h5nmu0iuq3do0tsga33km22g2t0al0ru.apps.googleusercontent.com', client_secret='JRwb4_2ZXMe8iTf6t6GazJbD', scope='https://www.googleapis.com/auth/calendar.readonly', user_agent='test/0.1') storage = Storage('../calendar.dat') credentials = storage.get() if credentials is None or credentials.invalid == True: credentials = run(FLOW, storage) # Create an httplib2.Http object to handle our HTTP requests and authorize it # with our good Credentials. http = httplib2.Http() http = credentials.authorize(http) # Build a service object for interacting with the API. Visit # the Google Developers Console # to get a developerKey for your own application. service = build(serviceName='calendar', version='v3', http=http,
from oauth2client.client import flow_from_clientsecrets from oauth2client.file import Storage from oauth2client.tools import run EMAIL="*****@*****.**" #change this # Path to the client_secret.json file downloaded from the Developer Console CLIENT_SECRET_FILE = '/usr/share/adafruit/webide/repositories/my-pi-projects/Doorbell/client_secret_935106472194-ntvvnbqtgcpnd2qu7akrk6g8tu225br4.apps.googleusercontent.com.json' # Check https://developers.google.com/gmail/api/auth/scopes for all available scopes OAUTH_SCOPE = 'https://www.googleapis.com/auth/gmail.compose' # Location of the credentials storage file STORAGE = Storage('gmail.storage') # Start the OAuth flow to retrieve credentials flow = flow_from_clientsecrets(CLIENT_SECRET_FILE, scope=OAUTH_SCOPE) http = httplib2.Http() # Try to retrieve credentials from storage or run the flow to generate them credentials = STORAGE.get() if credentials is None or credentials.invalid: credentials = run(flow, STORAGE, http=http) # Authorize the httplib2.Http object with our credentials http = credentials.authorize(http) # Build the Gmail service from discovery gmail_service = build('gmail', 'v1', http=http)
# todo: better date handling return day + "T00:00:00.000", day + "T23:59:00.000" if __name__ == '__main__': FLOW = OAuth2WebServerFlow( client_id=client_id, client_secret=client_secret, scope='https://www.googleapis.com/auth/calendar', user_agent='calendar/v3') # If the Credentials don't exist or are invalid, run through the native client # flow. The Storage object will ensure that if successful the good # Credentials will get written back to a file. storage = Storage('calendar.dat') credentials = storage.get() if credentials is None or credentials.invalid: credentials = run(FLOW, storage) http = httplib2.Http() http = credentials.authorize(http) # Visit the Google Developers Console # to get a developerKey for your own application. service = build(serviceName='calendar', version='v3', http=http, developerKey=developerKey) with open(sys.argv[1], "r+") as input_csv_file:
from googleapiclient import discovery import httplib2 from oauth2client import tools, client from oauth2client.file import Storage from oauth2client.client import AccessTokenRefreshError, OAuth2WebServerFlow import simplejson as json import os CLIENT_SECRET_FILE = 'client_secret.json' scope = 'https://www.googleapis.com/auth/spreadsheets' try: storage = Storage('sheets.storage') flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, scope) flow.user_agent = "Sheetspread" flow.params['access_type'] = 'offline' credentials = storage.get() if credentials is None or credentials.invalid: print('hi') credentials = tools.run_flow(flow, storage) except: credentials = client.OAuth2Credentials( os.environ.get("access_token"), os.environ.get("client_id"), os.environ.get("client_secret"), os.environ.get("refresh_token"), os.environ.get("token_expiry"), os.environ.get("token_uri"), "Sheetspread",
def test_non_existent_file_storage(self): s = Storage(FILENAME) credentials = s.get() self.assertEquals(None, credentials)
def prepare_credentials(self): storage = Storage(TOKEN_FILE_NAME) credentials = storage.get() if credentials is None or credentials.invalid: credentials = False return credentials
def get_credentials(self, fake_user): """Using the fake user name as a key, retrieve the credentials.""" storage = Storage('credentials-%s.dat' % (fake_user)) return storage.get()
Created on Tue Mar 10 16:00:21 2020 @author: Steven.Nguyen """ import gspread from oauth2client.service_account import ServiceAccountCredentials import httplib2 from oauth2client.client import flow_from_clientsecrets from oauth2client.file import Storage from oauth2client.tools import run_flow CLIENT_SECRET = 'N:\Temp\Steven Nguyen\pumpscores\client_secret.json' SCOPE = 'https://www.googleapis.com/auth/spreadsheets' STORAGE = Storage('credentials.storage') # Start the OAuth flow to retrieve credentials def authorize_credentials(): # Fetch credentials from storage credentials = STORAGE.get() # If the credentials doesn't exist in the storage location then run the flow if credentials is None or credentials.invalid: flow = flow_from_clientsecrets(CLIENT_SECRET, scope=SCOPE) http = httplib2.Http() credentials = run_flow(flow, STORAGE, http=http) return credentials creds = authorize_credentials() client = gspread.authorize(creds) spreadsheeturl = 'https://docs.google.com/spreadsheets/d/1ug9O5fZo-ZhZaNa_yaKLS_eJEBMcv9yscMwGqjcD1-0/edit#gid=0'
def read_token(self): return Storage(self.oauth_token_file)
def emailList(user, email_numb=5): response_list = [] def batchResponse(request_id, response, exception): if exception is not None: response_list.append(exception) return 0 else: response_list.append(response) return 1 file = str(user) + '_goog.txt' storage = Storage(file) credentials = storage.get() http_auth = credentials.authorize(httplib2.Http()) service2 = discovery.build('gmail', 'v1', http_auth) results = service2.users().messages().list( userId='me', q='[ in:inbox -category:{social promotions forums} ]', maxResults=email_numb).execute()['messages'] batch_request = service2.new_batch_http_request() for result in results: batch_request.add(service2.users().messages().get(userId='me', id=str(result['id']), format='metadata'), callback=batchResponse) batch_request.execute() message_list = [] for response in response_list: headers = response['payload']['headers'] subject = '' fromuser = '' datesent = '' for item in headers: if item["name"] == 'Subject': subject = item["value"] if item["name"] == 'From': fromuser = item["value"] if item["name"] == 'Date': datesent = item["value"] string1 = '' string2 = '' for c in subject: if c in letters: string1 = string1 + c else: string1 = string1 + '(?)' for c in fromuser: if c in letters: string2 = string2 + c else: string2 = string2 + '(?)' message_list.append({ 'Subject': string1, 'From': string2, 'Date': datesent }) return message_list
# the Web Server Flow, but it can also handle the flow for native # applications # The client_id and client_secret can be found in Google Developers Console FLOW = OAuth2WebServerFlow( client_id='YOUR_CLIENT_ID', client_secret='YOUR_CLIENT_SECRET', scope='https://www.googleapis.com/auth/calendar', user_agent='YOUR_APPLICATION_NAME/YOUR_APPLICATION_VERSION') # To disable the local server feature, uncomment the following line: # FLAGS.auth_local_webserver = False # If the Credentials don't exist or are invalid, run through the native client # flow. The Storage object will ensure that if successful the good # Credentials will get written back to a file. storage = Storage('credentials.dat') credentials = storage.get() if credentials is None or credentials.invalid == True: credentials = run(FLOW, storage) # Create an httplib2.Http object to handle our HTTP requests and authorize it # with our good Credentials. http = httplib2.Http() http = credentials.authorize(http) # Build a service object for interacting with the API. Visit # the Google Developers Console # to get a developerKey for your own application. service = build(serviceName='calendar', version='v3', http=http,
# applications # The client_id and client_secret are copied from the API Access tab on # the Google APIs Console FLOW = OAuth2WebServerFlow( client_id='YOUR_CLIENT_ID', client_secret='YOUR_CLIENT_SECRET', scope='https://www.googleapis.com/auth/tasks', user_agent='TODO/0.1') # To disable the local server feature, uncomment the following line: # FLAGS.auth_local_webserver = False # If the Credentials don't exist or are invalid, run through the native client # flow. The Storage object will ensure that if successful the good # Credentials will get written back to a file. storage = Storage('todo.dat') credentials = storage.get() if credentials is None or credentials.invalid == True: credentials = run(FLOW, storage) # Create an httplib2.Http object to handle our HTTP requests and authorize it # with our good Credentials. http = httplib2.Http() http = credentials.authorize(http) # Build a service object for interacting with the API. Visit # the Google APIs Console # to get a developerKey for your own application. service = build(serviceName='tasks', version='v1', http=http, developerKey='YOUR_DEVELOPERKEY')
def GetDataSourceId(googleClient, dataSource, googleauthfile): projectNumber = Storage(googleauthfile).get().client_id.split('-')[0] return ':'.join( (dataSource['type'], dataSource['dataType']['name'], projectNumber, dataSource['device']['manufacturer'], dataSource['device']['model'], dataSource['device']['uid']))
def save_credentials(self, fake_user, credentials): """Using the fake user name as a key, save the credentials.""" storage = Storage('credentials-%s.dat' % (fake_user)) storage.put(credentials)
def add_to_playlist(): # The CLIENT_SECRETS_FILE variable specifies the name of a file that contains # the OAuth 2.0 information for this application, including its client_id and # client_secret. You can acquire an OAuth 2.0 client ID and client secret from # the Google Developers Console at # https://console.developers.google.com/. # Please ensure that you have enabled the YouTube Data API for your project. # For more information about using OAuth2 to access the YouTube Data API, see: # https://developers.google.com/youtube/v3/guides/authentication # For more information about the client_secrets.json file format, see: # https://developers.google.com/api-client-library/python/guide/aaa_client_secrets CLIENT_SECRETS_FILE = "client_secret_903221304600-cqh20m4v1fitiu8u9okgrh2k27t0is67.apps.googleusercontent.com.json" # This variable defines a message to display if the CLIENT_SECRETS_FILE is # missing. MISSING_CLIENT_SECRETS_MESSAGE = """ WARNING: Please configure OAuth 2.0 To make this sample run you will need to populate the client_secrets.json file found at: %s with information from the Developers Console https://console.developers.google.com/ For more information about the client_secrets.json file format, please visit: https://developers.google.com/api-client-library/python/guide/aaa_client_secrets """ % os.path.abspath(os.path.join(os.path.dirname(__file__), CLIENT_SECRETS_FILE)) # This OAuth 2.0 access scope allows for full read/write access to the # authenticated user's account. YOUTUBE_READ_WRITE_SCOPE = "https://www.googleapis.com/auth/youtube" YOUTUBE_API_SERVICE_NAME = "youtube" YOUTUBE_API_VERSION = "v3" flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, message=MISSING_CLIENT_SECRETS_MESSAGE, scope=YOUTUBE_READ_WRITE_SCOPE) storage = Storage("%s-oauth2.json" % sys.argv[0]) credentials = storage.get() if credentials is None or credentials.invalid: flags = argparser.parse_args() credentials = run_flow(flow, storage, flags) youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, http=credentials.authorize(httplib2.Http())) add_video_request = youtube.playlistItems().insert( part="snippet", body={ 'snippet': { 'playlistId': globals.YOUTUBE_PLAYLIST, 'resourceId': { 'kind': 'youtube#video', 'videoId': video_id[0].strip("()") } #'position': 0 } } ).execute()
def GetGoogleClient(): credentials = Storage('google.json').get() http = credentials.authorize(httplib2.Http()) client = build('fitness', 'v1', http=http) return client
def has_credentials(user): credential_path = GoogleCredentials.get_credential_path(str(user)) if os.path.exists(credential_path): credentials = Storage(credential_path).get() return credentials and not credentials.invalid return False
from __future__ import print_function import httplib2 import os from oauth2client import client from oauth2client.file import Storage from oauth2client.tools import run_flow STORAGE = Storage('.credentials/credentials.storage') class auth: def __init__(self, SCOPES, CLIENT_SECRET_FILE, APPLICATION_NAME): self.SCOPES = SCOPES self.CLIENT_SECRET_FILE = CLIENT_SECRET_FILE self.APPLICATION_NAME = APPLICATION_NAME def get_credentials(self): cwd_dir = os.getcwd() credential_dir = os.path.join(cwd_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'credentials.storage') store = Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(self.CLIENT_SECRET_FILE, self.SCOPES) flow.user_agent = self.APPLICATION_NAME http = httplib2.Http() credentials = run_flow(flow, STORAGE, http=http) return credentials
from oauth2client.client import OAuth2WebServerFlow from oauth2client.tools import run # Initial setup keys = json.load(open("secrets.json")) client_id = keys["web"]["client_id"] client_secret = keys["web"]["client_secret"] scope = {'https://www.googleapis.com/auth/devstorage.full_control', 'https://www.googleapis.com/auth/devstorage.read_only', 'https://www.googleapis.com/auth/devstorage.read_write', 'https://www.googleapis.com/auth/prediction'} flow = OAuth2WebServerFlow(client_id, client_secret, scope) storage = Storage("credentials.dat") credentials = storage.get() if credentials is None or credentials.invalid: credentials = run(flow, storage) http = credentials.authorize(httplib2.Http()) service = build("prediction", "v1.6", http=http) class HostedModel(object): Hosted_model_id = 40204645227 def predict(self, model_id, csv_instances): body = { input: { "csvInstance": csv_instances }
def load_credentials(credentials_location): storage = Storage(credentials_location) credentials = storage.get() check(credentials and not credentials.invalid, 'missing/invalid credentials...try running idc_auth.py') return credentials
import os from core.fetch import fetch import logging import argparse # configure command line parameters parser = argparse.ArgumentParser( description='Google Cloud Platform Security Tool') group = parser.add_mutually_exclusive_group(required=True) group.add_argument('--project-name', '-p-name', help='Project name to scan') group.add_argument('--project-id', '-p-id', help='Project id to scan') group.add_argument('--organization', '-o', help='Organization id to scan') group.add_argument('--folder-id', '-f-id', help='Folder id to scan') args = parser.parse_args() storage = Storage('creds.data') logging.basicConfig(filename="log.txt") logging.getLogger().setLevel(logging.ERROR) # Silence some errors logging.getLogger('googleapiclient.discovery_cache').setLevel(logging.ERROR) try: os.remove("projects.json") except: pass db = TinyDB('projects.json') def list_projects(project_or_org, specifier): service = discovery.build('cloudresourcemanager',
def prepare_credentials(): storage = Storage(TOKEN_FILE_NAME) credentials = storage.get() if credentials is None or credentials.invalid: credentials = run(FLOW, storage) return credentials
def get_outh_credentials(client_secret_file, credential_dir=None, outh_nonlocal=False): """Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. :param client_secret_file: path to outh2 client secret file :param credential_dir: path to directory where tokens should be stored 'global' if you want to store in system-wide location None if you want to store in current script directory :param outh_nonlocal: if the authorization should be done in another computer, this will provide a url which when run will ask for credentials :return Credentials, the obtained credential. """ lflags = flags if credential_dir == 'global': home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) elif not credential_dir: credential_dir = os.getcwd() else: pass # verify credentials directory if not os.path.isdir(credential_dir): raise IOError(2, "Credential directory does not exist.", credential_dir) credential_path = os.path.join(credential_dir, 'sheets.googleapis.com-python.json') # check if refresh token file is passed with warnings.catch_warnings(): warnings.simplefilter("ignore") try: store = Storage(client_secret_file) credentials = store.get() except KeyError: credentials = None # else try to get credentials from storage if not credentials or credentials.invalid: try: with warnings.catch_warnings(): warnings.simplefilter("ignore") store = Storage(credential_path) credentials = store.get() except KeyError: credentials = None # else get the credentials from flow if not credentials or credentials.invalid: # verify client secret file if not os.path.isfile(client_secret_file): raise IOError(2, "Client secret file does not exist.", client_secret_file) # execute flow flow = client.flow_from_clientsecrets(client_secret_file, SCOPES) flow.user_agent = 'pygsheets' if lflags: lflags.noauth_local_webserver = outh_nonlocal credentials = tools.run_flow(flow, store, lflags) else: # Needed only for compatibility with Python 2.6 credentials = tools.run(flow, store) print('Storing credentials to ' + credential_path) return credentials
# https://console.developers.google.com. click credentials. create oauth2 ID drive_info = json.load(open("/home/huilichen/.google_drive_info.json")) CLIENT_ID = drive_info["CLIENT_ID"] CLIENT_SECRET = drive_info["CLIENT_SECRET"] OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive' REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob' OUT_PATH = os.path.join(os.path.dirname(__file__), 'rosbag_inputs') CREDS_FILE = os.path.join(os.path.dirname(__file__), 'credentials.json') print(OUT_PATH) if not os.path.exists(OUT_PATH): os.makedirs(OUT_PATH) storage = Storage(CREDS_FILE) credentials = storage.get() if credentials is None: # Run through the OAuth flow and retrieve credentials flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI) authorize_url = flow.step1_get_authorize_url() print('Go to the following link in your browser: ' + authorize_url) code = raw_input('Enter verification code: ').strip() #code ="4/AACrsLsy4yJ1wbQSaneHl2dlSGklb8n8GDAnSwYJJHUdTizNX5UtKFw" credentials = flow.step2_exchange(code) storage.put(credentials) print("credential part is done!") # Create an httplib2.Http object and authorize it with our credentials
class WPConfig: def __init__(self): self.ids = WPConfig.json_file_to_dic(WPConfig.CONF_JSON) # constants CLIENT_SECRETS_FILE = 'client_secrets.json' WP_BODY_FILE = 'wp_post_body.json' CONF_JSON = 'WPConfig.json' # oauth credentials storage tool CREDENTIALS_FILE = 'credentials-foobar.dat' storage = Storage(CREDENTIALS_FILE) WP_LOG_HEAD = "::::::: WhatsPlaying Event Log :::::::\nStart: " + str(time.time()) + '\n:::::::::::::::::::::::::::::::::::::::::::::::::::\n' # get_timestamp() -- returns string def get_timestamp(): return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(time.time())) def storeOauthCredentials(credentials): WPConfig.storage.put(credentials) #default method to authenticate with Google BloggerAPI ###FIX: make workable for other services in addition to Blogger def get_authenticated_service(self): # Authenticate and construct service. service, flags = sample_tools.init( [], 'blogger', 'v3', __doc__, __file__, scope=self.ids['scope']) return (service,flags) #methods to store an retrieve json and rotate body file def saveWPBodyToJson(dic): fn = WPConfig.WP_BODY_FILE WPConfig.dic_to_json_file(dic,fn) def dic_to_json_file(dic, fn): js = json.dumps(dic,indent=4, sort_keys=True) fp = open(fn, 'w') # write to json file fp.write(js) # close the connection fp.close() def renameWPdata(): stm = str(time.time()) newFile = WPConfig.WP_BODY_FILE r_fname = str('credentials-foobar' + stm + '.dat') os.rename(newFile,r_fname) def readWPBodyFromJson(fn=WP_BODY_FILE): return WPConfig.json_file_to_dic(fn) def json_file_to_dic(fn): with open(fn) as js: dic = json.load(js) js.close() return dic def loadClientSecrets(fname=CLIENT_SECRETS_FILE): with open(fname) as auth_json: d = json.load(auth_json) auth_json.close() return d['installed']
def main(argv): parser = argparse.ArgumentParser(parents=[tools.argparser]) subparsers = parser.add_subparsers(help='sub command') #------------------------------------------------------------------------- # LIST / SEARCH #------------------------------------------------------------------------- parser_list = subparsers.add_parser( 'list', help='Returns the rules in the access control list for the calendar') parser_list.add_argument('calendarId', help='calendear id') parser_list.add_argument('--maxResults', type=int, help='Acceptable values are 1 to 250') parser_list.add_argument('-v', '--verbose', action='store_true', help='show updated user data') parser_list.add_argument('--json', action='store_true', help='output in JSON') parser_list.add_argument('--jsonPretty', action='store_true', help='output in pretty JSON') #------------------------------------------------------------------------- # GET #------------------------------------------------------------------------- parser_get = subparsers.add_parser('get', help='Returns an access control rule') parser_get.add_argument('calendarId', help='calendar id') parser_get.add_argument('ruleId', help='rule id') parser_get.add_argument('--json', action='store_true', help='output in JSON') parser_get.add_argument('--jsonPretty', action='store_true', help='output in pretty JSON') #------------------------------------------------------------------------- # INSERT #------------------------------------------------------------------------- parser_insert = subparsers.add_parser( 'insert', help='Creates an access control rule') parser_insert.add_argument('calendarId', help='calendar id') parser_insert.add_argument( 'role', choices=['none', 'freeBusyReader', 'reader', 'writer', 'owner']) parser_insert.add_argument('type', choices=['default', 'user', 'group', 'domain']) parser_insert.add_argument('--value', help='email address or domain name') parser_insert.add_argument('-v', '--verbose', action='store_true', help='show created user data') parser_insert.add_argument('--json', action='store_true', help='output in JSON') parser_insert.add_argument('--jsonPretty', action='store_true', help='output in pretty JSON') #------------------------------------------------------------------------- # PATCH #------------------------------------------------------------------------- parser_patch = subparsers.add_parser('patch', help='Updates an access control rule') parser_patch.add_argument('calendarId', help='calendar id') parser_patch.add_argument('ruleId', help='rule id') parser_patch.add_argument( 'role', choices=['none', 'freeBusyReader', 'reader', 'writer', 'owner']) parser_patch.add_argument('type', choices=['default', 'user', 'group', 'domain']) parser_patch.add_argument('--value', help='email address or domain name') parser_patch.add_argument('-v', '--verbose', action='store_true', help='show updated user data') parser_patch.add_argument('--json', action='store_true', help='output in JSON') parser_patch.add_argument('--jsonPretty', action='store_true', help='output in pretty JSON') #------------------------------------------------------------------------- # DELETE #------------------------------------------------------------------------- parser_delete = subparsers.add_parser( 'delete', help='Deletes an access control rule') parser_delete.add_argument('calendarId', help='calendar id') parser_delete.add_argument('ruleId', help='rule id') args = parser.parse_args(argv[1:]) FLOW = flow_from_clientsecrets(CLIENT_SECRETS, scope=SCOPES, message=MISSING_CLIENT_SECRETS_MESSAGE) storage = Storage(CREDENTIALS_PATH) credentials = storage.get() if credentials is None or credentials.invalid: print 'invalid credentials' # Save the credentials in storage to be used in subsequent runs. credentials = tools.run_flow(FLOW, storage, args) # Create an httplib2.Http object to handle our HTTP requests and authorize it # with our good Credentials. http = httplib2.Http() http = credentials.authorize(http) service = build('calendar', 'v3', http=http) sv = service.acl() command = argv[1] if command == 'list': acls = [] pageToken = None params = {} params['calendarId'] = args.calendarId while True: if args.maxResults: params['maxResults'] = args.maxResults if pageToken: params['pageToken'] = pageToken r = sv.list(**params).execute() if r.has_key('items'): if args.jsonPretty or args.json: for acl in r['items']: acls.append(acl) else: show_resource_list(r['items'], args.verbose) if r.has_key('nextPageToken'): pageToken = r['nextPageToken'] else: break if args.jsonPretty: if len(acls) == 1: print to_pretty_json(acls[0]) else: print to_pretty_json(acls) elif args.json: if len(acls) == 1: print to_json(acls[0]) else: print to_json(acls) elif command == 'get': r = sv.get(calendarId=args.calendarId, ruleId=args.ruleId).execute() if args.jsonPretty: print to_pretty_json(r) elif args.json: print to_json(r) else: show_resource(r) elif command == 'insert': body = {'role': args.role, 'scope': {'type': args.type}} if args.type != 'default': if args.value is None: print '--value is required' sys.exit(1) body['scope']['value'] = args.value r = sv.insert(calendarId=args.calendarId, body=body).execute() if args.verbose: if args.jsonPretty: print to_pretty_json(r) elif args.json: print to_json(r) else: show_resource(r) elif command == 'patch': body = {'role': args.role, 'scope': {'type': args.type}} if args.type != 'default': if args.value is None: print '--value is required' sys.exit(1) body['scope']['value'] = args.value r = sv.patch(calendarId=args.calendarId, ruleId=args.ruleId, body=body).execute() if args.verbose: if args.jsonPretty: print to_pretty_json(r) elif args.json: print to_json(r) else: show_resource(r) elif command == 'delete': r = sv.delete(calendarId=args.calendarId, ruleId=args.ruleId).execute() else: print "unknown command '%s'" % command return
import sys from oauth2client.tools import argparser, run_flow from oauth2client.file import Storage from oauth2client.client import flow_from_clientsecrets from Statsdash.Youtube import config CLIENT_SECRETS_FILE = config.CLIENT_SECRETS_FILE YOUTUBE_SCOPES = [ "https://www.googleapis.com/auth/youtube.readonly", "https://www.googleapis.com/auth/yt-analytics.readonly", "https://www.googleapis.com/auth/youtubepartner" ] flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope=" ".join(YOUTUBE_SCOPES), redirect_uri='http://localhost:8080') storage = Storage("youtube-oauth2.json") credentials = run_flow(flow, storage)
# Google API Access requires a browser-based authentication step to create # the stored authorization .dat file. Forcign noauth_local_webserver to True # allows for authentication from an environment without a browser, such as EC2. flags.noauth_local_webserver = True # Initialize the OAuth2 authorization flow. # The string urn:ietf:wg:oauth:2.0:oob is for non-web-based applications. # The prompt='consent' Retrieves the refresh token. flow_scope = 'https://www.googleapis.com/auth/business.manage' flow = flow_from_clientsecrets(CLIENT_SECRET, scope=flow_scope, redirect_uri='urn:ietf:wg:oauth:2.0:oob', prompt='consent') # Specify the storage path for the .dat authentication file storage = Storage(AUTHORIZATION) credentials = storage.get() # Refresh the access token if it expired if credentials is not None and credentials.access_token_expired: try: h = httplib2.Http() credentials.refresh(h) except Exception: pass # Acquire credentials in a command-line application if credentials is None or credentials.invalid: credentials = tools.run_flow(flow, storage, flags) # Apply credential headers to all requests made by an httplib2.Http instance