示例#1
0
def logout():
    import requests
    from os import remove
    global credentials
    requests.post(
        'https://accounts.google.com/o/oauth2/revoke',
        params={'token': credentials.token},
        headers={'content-type': 'application/x-www-form-urlencoded'})
    try:
        remove('credentials.pickle')
    except:
        pass
    credentials = None
示例#2
0
def createVolSMB():
    id_token1 = get_token()
    # Get all volumes from all regions
    # Construct GET request

    createvolumeURL = server + "/v2/projects/" + str(project_number) + "/locations/" + location + "/Volumes/"
    payload = "{\n  \"name\": \"prabu-smb\",\n  \"region\": \"us-central1\",\n  \"creationToken\": \"prabu-smb\",\n  \"serviceLevel\": \"medium\",\n  \"network\": \"projects/779740114201/global/networks/ncv-vpc\",\n  \"quotaInBytes\": 1099511627776,\n  \"snapReserve\": 20,\n  \"protocolTypes\": [\n    \"CIFS\"\n  ],\n  \"smbShareSettings\": [\n    \"continuously_available\"\n  ],\n  \"jobs\": [\n    {}\n  ],\n  \"labels\": [\n    \"api\"\n  ]\n}\n\n\n"
    headers = {
        'accept': "application/json",
        'Content-Type': "application/json",
        'Authorization': "Bearer " + id_token1.decode('utf-8'),
        'cache-control': "no-cache",
    }
    # POST request to create the volume
    response = requests.post(createvolumeURL, payload, headers=headers)
    # Sleep for 20 seconds to wait for the creation of the volume
    time.sleep(20)
    r_dict = response.json()
    # print("Response to POST request: " + response.text)
    # Get volume attributes
    # To get the values from the dictionary, you have read the dictionary one by one.
    # fetch the response first
    fetchvalue = (r_dict.get('response'))
    # fetch all the values from the response
    fetchvolumeID = fetchvalue.get('AnyValue')
    # fetch the volume ID from the values
    volumeID = fetchvolumeID.get('volumeId')
    # fetch the service level from the values
    serviceLevel = fetchvolumeID.get('serviceLevel')
    # fetch the class of the protocol types
    ProtocolList = fetchvolumeID.get('protocolTypes')
    # fetch the protocol type
    protocolType = ProtocolList[0]
    # Print the values
    print("\tvolumeID: " + volumeID + ", serviceLevel: " + serviceLevel + ", ProtocolType: " + protocolType)
def createVol():
    id_token1 = get_token()
    # Get all volumes from all regions
    # Construct GET request

    createvolumeURL = server + "/v2/projects/" + str(
        project_number) + "/locations/" + location + "/Volumes/"
    payload = "{\n   \"name\": \"AutomatedVolume6\",\n   \"creationToken\": \"ACV6\",\n   \"region\": \"us-central1\",\n   \"serviceLevel\": \"basic\",\n   \"quotaInBytes\": 1100000000000,\n   \"kerberosEnabled\": \"true\",\n   \"network\": \"projects/779740114201/global/networks/ncv-vpc\",\n   \"protocolTypes\": [\"NFSv4\"],\n   \"exportPolicy\": {\n      \"rules\": [\n         {\n            \"access\": \"ReadWrite\",\n            \"allowedClients\": \"0.0.0.0/0\",\n            \"hasRootAccess\": true,\n            \"nfsv3\": {\n               \"checked\": false\n            },\n            \"nfsv4\": {\n               \"checked\": true\n            },\n            \"kerberos5ReadOnly\": false,\n\t        \"kerberos5ReadWrite\": false,\n\t        \"kerberos5iReadOnly\": false,\n\t        \"kerberos5iReadWrite\": false,\n\t        \"kerberos5pReadOnly\": false,\n\t        \"kerberos5pReadWrite\": false\n         }\n      ]\n   }\n}"
    headers = {
        'accept': "application/json",
        'Content-Type': "application/json",
        'Authorization': "Bearer " + id_token1.decode('utf-8'),
        'cache-control': "no-cache",
    }
    # POST request to create the volume
    response = requests.post(createvolumeURL, payload, headers=headers)
    # Sleep for 20 seconds to wait for the creation of the volume
    time.sleep(20)
    r_dict = response.json()
    # print("Response to POST request: " + response.text)
    # Get volume attributes
    # To get the values from the dictionary, you have read the dictionary one by one.
    # fetch the response first
    fetchvalue = (r_dict.get('response'))
    # fetch all the values from the response
    fetchvolumeID = fetchvalue.get('AnyValue')
    # fetch the volume ID from the values
    volumeID = fetchvolumeID.get('volumeId')
    # fetch the service level from the values
    serviceLevel = fetchvolumeID.get('serviceLevel')
    # Print the values
    print("\tvolumeID: " + volumeID + ", serviceLevel: " + serviceLevel)
示例#4
0
def oauth2callback():

    time.sleep(.5)  # without this it gives errors about 30% of the time

    if 'code' not in flask.request.args:
        auth_uri = (
            'https://accounts.google.com/o/oauth2/v2/auth?response_type=code'
            '&client_id={}&redirect_uri={}&scope={}&state={}').format(
                CLIENT_ID, REDIRECT_URI, SCOPES, flask.session['oauth_state'])
        return flask.redirect(auth_uri)
    else:
        # Validate state
        if flask.request.args.get('state') != flask.session['oauth_state']:
            return flask.jsonify('Invalid state parameter.'), 401

        auth_code = flask.request.args.get('code')
        data = {
            'code': auth_code,
            'client_id': CLIENT_ID,
            'client_secret': CLIENT_SECRET,
            'redirect_uri': REDIRECT_URI,
            'grant_type': 'authorization_code'
        }
        r = requests.post('https://oauth2.googleapis.com/token', data=data)
        flask.session['credentials'] = r.text
        return flask.redirect(flask.url_for('userinfo'))
示例#5
0
def sms_glucose_alert(to, username, glucose):
    global client
    # We send our sms using the messages api not the sms api
    response = requests.post(
        'https://api.nexmo.com/v0.1/messages',
        auth=HTTPBasicAuth(os.getenv("NEXMO_API_KEY"),
                           os.getenv("NEXMO_API_SECRET")),
        headers={
            "Content-Type": "application/json",
            "Accept": "application/json"
        },
        json={
            "from": {
                "type": "sms",
                "number": os.getenv("NEXMO_NUMBER"),
            },
            "to": {
                "type": "sms",
                "number": to
            },
            "message": {
                "content": {
                    "type": "text",
                    "text": "Alert {username} Blood Glucose is {glucose}".format(username=username, glucose=glucose)
                }
            }
        }
    ).json()

    if "message_uuid" in response:
        return True
    else:
        return False
def createADJoin():
    id_token1 = get_token()
    # Construct POST request
    # Create AD Join
    createADJoinURL = server + "/v2/projects/" + str(
        project_number
    ) + "/locations/" + location + "/Storage/" + "/ActiveDirectory/"
    payload = "{\n    \"username\": \"[email protected]\",\n    \"password\": \"Password123..!\",\n    \"domain\": \"cloud.dom\",\n    \"DNS\": \"10.3.1.16\",\n    \"netBIOS\": \"cloudier\",\n    \"organizationalUnit\": \"CN=Computers\",\n    \"site\": \"Default-First-Site-Name\",\n    \"kdcIP\": \"10.3.1.16\",\n    \"adName\": \"2BOVAEKB44B\",\n    \"ldapSigning\": false,\n    \"region\": \"us-east1\",\n    \"securityOperators\": [\n        \"test\"\n    ],\n    \"backupOperators\": [\n        \"backupOperators1\"\n    ]\n}"
    headers = {
        'accept': "application/json",
        'Content-Type': "application/json",
        'Authorization': "Bearer " + id_token1.decode('utf-8'),
        'cache-control': "no-cache",
    }
    # POST request to create the volume
    response = requests.post(createADJoinURL, payload, headers=headers)
    # Sleep for 20 seconds to wait for the creation of the volume
    time.sleep(20)
    r_dict = response.json()
    # Get AD attributes
    # fetch the DNS details
    DNSServer = (r_dict.get('DNS'))
    # fetch the KPC IP address
    kdcIP = (r_dict.get('kdcIP'))
    # fetch the Domain Name
    domain = (r_dict.get('domain'))
    # fetch the KPC IP address
    UUID = (r_dict.get('UUID'))
    # Print the values
    print("\tAD connection details \tDNSServer: " + DNSServer + ", domain: " +
          domain + ", kdcIP: " + kdcIP + ", UUID: " + UUID)
    backupOperators = (r_dict.get('backupOperators'))
    for backupOperatorsName in backupOperators:
        # get updated backup operators
        print(backupOperatorsName)
示例#7
0
def callback():
    # Get authorization code Google sent back to you
    code = request.args.get("code")

    # Find out what URL to hit to get tokens that allow you to ask for
    # things on behalf of a user
    google_provider_cfg = get_google_provider_cfg()
    token_endpoint = google_provider_cfg["token_endpoint"]

    # Prepare and send request to get tokens! Yay tokens!
    token_url, headers, body = client.prepare_token_request(
        token_endpoint,
        authorization_response=request.url,
        redirect_url=request.base_url,
        code=code,
    )
    token_response = requests.post(
        token_url,
        headers=headers,
        data=body,
        auth=(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET),
    )

    # Parse the tokens!
    client.parse_request_body_response(json.dumps(token_response.json()))

    # Now that we have tokens (yay) let's find and hit URL
    # from Google that gives you user's profile information,
    # including their Google Profile Image and Email
    userinfo_endpoint = google_provider_cfg["userinfo_endpoint"]
    uri, headers, body = client.add_token(userinfo_endpoint)
    userinfo_response = requests.get(uri, headers=headers, data=body)

    # We want to make sure their email is verified.
    # The user authenticated with Google, authorized our
    # app, and now we've verified their email through Google!
    if userinfo_response.json().get("email_verified"):
        unique_id = userinfo_response.json()["sub"]
        users_email = userinfo_response.json()["email"]
    else:
        return "User email not available or not verified by Google.", 400

    # Create a user in our db with the information provided
    # by Google

    # Create a user in our db with the information provided
    # by Google
    user = User(id_=users_email)

    # Doesn't exist? Add to database of suspicious people
    if not User.get(users_email):
        User.suspicious(users_email)
        print("User doesn't exist")

    # Begin user session by logging the user in
    login_user(user)

    # Send user back to homepage
    return redirect(url_for("index"))
示例#8
0
def POST(url, headers, data=None, params=None):
    '''post_url will use the requests library to post to a url
    '''
    if data is not None:
        return requests.post(url,
                             headers=headers,
                             data=json.dumps(data))
    return requests.get(url, headers=headers)
示例#9
0
 def send_cancel_request(self, job_name: str):
     if not job_name:
         return
     creds, _ = google.auth.default(
         scopes=['https://www.googleapis.com/auth/cloud-platform'])
     if not creds.valid:
         creds.refresh(google.auth.transport.requests.Request())
     headers = {
         'Content-type': 'application/json',
         'Authorization': 'Bearer ' + creds.token,
     }
     # Vertex AI cancel APIs:
     # https://cloud.google.com/vertex-ai/docs/reference/rest/v1/projects.locations.hyperparameterTuningJobs/cancel
     # https://cloud.google.com/vertex-ai/docs/reference/rest/v1/projects.locations.customJobs/cancel
     # https://cloud.google.com/vertex-ai/docs/reference/rest/v1/projects.locations.batchPredictionJobs/cancel
     requests.post(url=f'{self.job_uri_prefix}{job_name}:cancel',
                   data='',
                   headers=headers)
def createVol():
    id_token1 = get_token()
    # Get all volumes from all regions
    # Construct GET request

    createvolumeURL = server + "/v2/projects/" + str(
        project_number) + "/locations/" + location + "/Volumes/"
    payload = {
        "name": "AutomatedVolume3",
        "creationToken": "ACV3",
        "region": "us-east1",
        "zone": "us-east1-b",
        "serviceLevel": "basic",
        "quotaInBytes": 1099511627776,
        "usedBytes": 78606279278,
        "snapshotPolicy": {
            "dailySchedule": {
                "hour": 1,
                "minute": 10,
                "snapshotsToKeep": 5
            }
        },
        "storageClass": "software",
        "network":
        "projects/123456789/global/networks/ncv-vpc",  # Replace with your VPC instead of ncv-vpc and the project number instead of 123456789
        "protocolTypes": ["NFSv3"]
    }
    headers = {
        'accept': "application/json",
        'Content-Type': "application/json",
        'Authorization': "Bearer " + id_token1.decode('utf-8'),
        'cache-control': "no-cache",
    }
    # POST request to create the volume
    response = requests.post(createvolumeURL,
                             json.dumps(payload),
                             headers=headers)
    # Sleep for 20 seconds to wait for the creation of the volume
    time.sleep(20)
    print(response)
    r_dict = response.json()
    # print("Response to POST request: " + response.text)
    # Get volume attributes
    # To get the values from the dictionary, you have read the dictionary one by one.
    # fetch the response first
    fetchvalue = (r_dict.get('response'))
    # fetch all the values from the response
    fetchvolumeID = fetchvalue.get('AnyValue')
    # fetch the volume ID from the values
    volumeID = fetchvolumeID.get('volumeId')
    # fetch the service level from the values
    serviceLevel = fetchvolumeID.get('serviceLevel')
    # Print the values
    print("\tvolumeID: " + volumeID + ", serviceLevel: " + serviceLevel)
def generate_access_token(bucket_name):
    token_broker_url = os.environ.get(
        'TOKEN_BROKER_URL', 'Specified environment variable is not set.')
    credentials, project = auth.default()
    auth_req = google.auth.transport.requests.Request()
    id_token = google.oauth2.id_token.fetch_id_token(auth_req,
                                                     token_broker_url)
    param = {'access-type': 'write', 'access-bucket': f'{bucket_name}'}
    function_headers = {'Authorization': f'bearer {id_token}'}
    function_response = requests.post(token_broker_url,
                                      headers=function_headers,
                                      json=param)
    return json.loads(function_response.content)
示例#12
0
 def revoke_access(self):
     if not self.credentials:
         raise EmptyCredentialsError
     revoke = requests.post(
         "https://accounts.google.com/o/oauth2/revoke",
         params={"token": self.credentials["token"]},
         headers={"content-type": "application/x-www-form-urlencoded"},
     )
     if not revoke.status_code == 200:
         raise RequestError
     self.credentials = None
     for drive in self.user.drives:
         drive.delete()
     self.save()
示例#13
0
def callback():
    # Get authorization code Google sent back to you
    code = request.args.get("code")

    google_provider_cfg = get_google_provider_cfg()
    token_endpoint = google_provider_cfg["token_endpoint"]

    token_url, headers, body = client.prepare_token_request(
        token_endpoint,
        authorization_response=request.url,
        redirect_url=request.base_url,
        code=code)

    token_response = requests.post(
        token_url,
        headers=headers,
        data=body,
        auth=(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET),
    )

    client.parse_request_body_response(json.dumps(token_response.json()))

    userinfo_endpoint = google_provider_cfg["userinfo_endpoint"]
    uri, headers, body = client.add_token(userinfo_endpoint)
    userinfo_response = requests.get(uri, headers=headers, data=body)

    if userinfo_response.json().get("email_verified"):
        google_uid = userinfo_response.json()["sub"]
        users_email = userinfo_response.json()["email"]
        users_name = userinfo_response.json()["given_name"]
    else:
        return "User email not available or not verified by Google.", 400

    user = User(google_id=google_uid, first_name=users_name, email=users_email)

    # If user does not exist in db, create and add them to it
    if not db.session.query(
            exists().where(User.google_id == google_uid)).scalar():
        db.session.add(user)
        db.session.commit()
    else:
        user = db.session.query(User).filter_by(google_id=google_uid).first()

    # Begin user session by logging the user in

    login_user(user)

    # Send user back to homepage
    return redirect(url_for("home"))
示例#14
0
def authenticate(username, password):
    for pair in pairs:
        if compare_digest(username, pair["client_id"]) and compare_digest(
                password, pair["client_secret"]):
            return {"user": pair["client"], "metered": False, "calls": 0}
    auth_req = google.auth.transport.requests.Request()
    id_token = google.oauth2.id_token.fetch_id_token(auth_req, service_url)
    response = requests.post(service_url,
                             json={
                                 "client_id": username,
                                 "client_secret": password
                             },
                             headers={'Authorization': 'Bearer ' + id_token})
    if response.status_code == 200:
        return json.loads(response.text)
    return False
示例#15
0
def refreshToken(client_id, client_secret, refresh_token):
    params = {
        "grant_type": "refresh_token",
        "client_id": client_id,
        "client_secret": client_secret,
        "refresh_token": refresh_token
    }

    authorization_url = "https://www.googleapis.com/oauth2/v4/token"

    r = requests.post(authorization_url, data=params)

    if r.ok:
        return r.json()['access_token']
    else:
        return None
示例#16
0
def sms_request_glucose_level(args, glucose):
    global client

    args = ast.literal_eval(json.dumps(args))

    # Parse incoming values
    keyword = args['keyword'][0]
    to = args["msisdn"][0]
    response = None

    if keyword == "NIGHTSCOUT":
        # "msg" stores the response to be sent\
        msg = "Hey, the latest blood glucose level entry: {glucose}".format(
            glucose=glucose)

        response = requests.post('https://api.nexmo.com/v0.1/messages',
                                 auth=HTTPBasicAuth(
                                     os.getenv("NEXMO_API_KEY"),
                                     os.getenv("NEXMO_API_SECRET")),
                                 headers={
                                     "Content-Type": "application/json",
                                     "Accept": "application/json"
                                 },
                                 json={
                                     "from": {
                                         "type": "sms",
                                         "number": os.getenv('NEXMO_NUMBER')
                                     },
                                     "to": {
                                         "type": "sms",
                                         "number": to
                                     },
                                     "message": {
                                         "content": {
                                             "type": "text",
                                             "text": msg
                                         }
                                     }
                                 }).json()

    if response is not None and "message_uuid" in response:
        return True
    else:
        return False
示例#17
0
def handle_nightscout_failed_pings(to, api_url, username):
    global client
    global nightscout_failed_pings
    if to not in nightscout_failed_pings:
        nightscout_failed_pings[to] = 1
    else:
        nightscout_failed_pings[to] += 1
    # print('Intent: {0} for {1}'.format(nightscout_failed_pings[to],to))
    if nightscout_failed_pings[to] == int(os.getenv("NEXMO_FAILED_PING_SMS")):
        response = requests.post(
            'https://api.nexmo.com/v0.1/messages',
            auth=HTTPBasicAuth(os.getenv("NEXMO_API_KEY"),
                               os.getenv("NEXMO_API_SECRET")),
            headers={
                "Content-Type": "application/json",
                "Accept": "application/json"
            },
            json={
                "from": {
                    "type": "sms",
                    "number": os.getenv("NEXMO_NUMBER"),
                },
                "to": {
                    "type": "sms",
                    "number": to
                },
                "message": {
                    "content": {
                        "type":
                        "text",
                        "text":
                        "Dear {0} the nexmo api url: {1} is not responding, please check the service"
                        .format(username, api_url)
                    }
                }
            }).json()

        # Reset the variable
        nightscout_failed_pings[to] = 0

        if "message_uuid" in response:
            return True
    return False
示例#18
0
def bkpVol():
    id_token1 = get_token()
    # Get all volumes from all regions
    # Construct GET request

    createBKP = stagingserver + "/v2/projects/" + str(
        project_number
    ) + "/locations/" + location + "/Volumes/" + volumeID + "/Backups"
    payload = {
        "region": "us-east1",
        "serviceLevel": "basic",
        "quotaInBytes": 1100000000000,
        "network":
        "projects/779740114201/global/networks/cvs-staging",  # Replace with your VPC instead of ncv-vpc and the project number instead of 123456789
        "protocolTypes": ["NFSv3"]
    }
    headers = {
        'accept': "application/json",
        'Content-Type': "application/json",
        'Authorization': "Bearer " + id_token1.decode('utf-8'),
        'cache-control': "no-cache",
    }
    # POST request to create the volume
    response = requests.post(createvolumeURL,
                             json.dumps(payload),
                             headers=headers)
    # Sleep for 20 seconds to wait for the creation of the volume
    time.sleep(20)
    r_dict = response.json()
    # print("Response to POST request: " + response.text)
    # Get volume attributes
    # To get the values from the dictionary, you have read the dictionary one by one.
    # fetch the response first
    fetchvalue = (r_dict.get('response'))
    # fetch all the values from the response
    fetchvolumeID = fetchvalue.get('AnyValue')
    # fetch the volume ID from the values
    volumeID = fetchvolumeID.get('volumeId')
    # fetch the service level from the values
    serviceLevel = fetchvolumeID.get('serviceLevel')
    # Print the values
    print("\tvolumeID: " + volumeID + ", serviceLevel: " + serviceLevel)
示例#19
0
def start_transcode(event, context):

    bucket_name_input = event['bucket']
    object_name_input = event['name']
    file_name = os.path.split(object_name_input)[1]
    file_name_wo_extension = os.path.splitext(file_name)[0]

    cred = compute_engine.credentials.Credentials()

    auth_req = google.auth.transport.requests.Request()
    cred.refresh(auth_req)
    #print(cred.token)

    api_url = "https://transcoder.googleapis.com/v1beta1/projects/{}/locations/{}/jobs".format(PROJECT_ID, PROJECT_LOCATION)

    headers = {
        "Authorization": "Bearer {}".format(cred.token),
        "Content-Type": "application/json"
    }

    test = "gs://{}/{}".format(bucket_name_input, object_name_input)
    print("Bucket: {}, inputUri: {}\n".format(bucket_name_input, test))

    data = {
        "inputUri": "gs://{}/{}".format(bucket_name_input, object_name_input),
        "outputUri": "{}/{}/".format(DEST_LOCATION, file_name_wo_extension),
        "templateId": "{}".format(TEMPLATE_ID)
    }

    req = requests.Request('POST',api_url,headers=headers,json=data)
    prepared = req.prepare()
    pretty_print_POST(prepared)

    response = requests.post(url = api_url, headers=headers, json = data)

    if not response.ok or "error" in response.text:
        logging.error(RuntimeError(response.text))
        exit_abort()

    response_json = response.json()
    print("New job started - Job Name: {}".format(response_json['name']))
示例#20
0
def handle_nightscout_failed_update(to, api_url, username):
    global client
    global nightscout_failed_update_wait_mark
    if to not in nightscout_failed_update_wait_mark:
        nightscout_failed_update_wait_mark[to] = 1
    else:
        nightscout_failed_update_wait_mark[to] += 1

    if nightscout_failed_update_wait_mark[to] == 1:
        response = requests.post(
            'https://api.nexmo.com/v0.1/messages',
            auth=HTTPBasicAuth(os.getenv("NEXMO_API_KEY"),
                               os.getenv("NEXMO_API_SECRET")),
            headers={
                "Content-Type": "application/json",
                "Accept": "application/json"
            },
            json={
                "from": {
                    "type": "sms",
                    "number": os.getenv("NEXMO_NUMBER"),
                },
                "to": {
                    "type": "sms",
                    "number": to
                },
                "message": {
                    "content": {
                        "type":
                        "text",
                        "text":
                        "Dear {0} the nightscout api is not retrieving updated entries, please check your device or your service to solve any issues"
                        .format(username)
                    }
                }
            }).json()
    elif nightscout_failed_update_wait_mark[to] == int(
            os.getenv("WAIT_AFTER_SMS_MARK")):
        nightscout_failed_update_wait_mark[to] = 0
示例#21
0
def authenticate(username, password):
    if correct(username, password, watchdog_client_id, watchdog_client_secret):
        return {"user": "******", "metered": False, "calls": 0}
    elif correct(username, password, explore_client_id, explore_client_secret):
        return {"user": "******", "metered": False, "calls": 0}
    elif correct(username, password, calc_client_id, calc_client_secret):
        return {"user": "******", "metered": False, "calls": 0}
    else:
        auth_req = google.auth.transport.requests.Request()
        id_token = google.oauth2.id_token.fetch_id_token(auth_req, service_url)
        response = requests.post(
            service_url,
            json={
                "client_id": username,
                "client_secret": password
            },
            headers={'Authorization': 'Bearer ' + id_token})
        if response.status_code == 200:
            return json.loads(response.text)
        else:
            return False
    return False
示例#22
0
def call_stt_api(
        gcs_uri: str, config_object: dict,
        credentials: google.auth.credentials.Credentials) -> Optional[Any]:
    """Sends HTTP Post Request to Speech-to-Text API

    Args:
        gcs_uri: String holding URI where audio file is stored in GCS.
        config_object: Object holding config information for
        credentials: Object holding Oauth2 token for default App Engine account

    Returns:
        String holding name of operation in STT API Queue
    """

    audio_object = {'uri': gcs_uri}
    endpoint = 'https://speech.googleapis.com/v1/speech:longrunningrecognize'
    body = json.dumps({'config': config_object, 'audio': audio_object})
    token = credentials.token
    headers = {
        'Authorization': f'Bearer {token}',
        'Content-Type': 'application/json; charset=utf-8'
    }
    logging.info(f'Body: {body}')
    operation_name = None
    try:
        response = requests.post(endpoint, data=body, headers=headers)
        logging.info(f'Response: {response}')
        response_json = response.json()
        logging.info(f'Response json: {response_json}')
        response.raise_for_status()
        if 'name' in response_json:
            operation_name = response_json['name']
    except HTTPError as http_err:
        logging.error(f'HTTP error occurred: {http_err}')
        raise Exception
    except Exception as err:
        logging.error(f'Python Exception occurred: {err}')
    return operation_name
def make_post_request_to_ai_platform(
        uri: str,
        request_body: Dict[str, Any],
        credentials: Optional[google.auth.credentials.Credentials] = None,
        timeout_ms: int = constants.DEFAULT_TIMEOUT):
    """Makes a post request to AI Platform.

  Args:
    uri: URI of the model resource.
    request_body: A dict for the request body
    credentials: The OAuth2.0 credentials to use for GCP services.
    timeout_ms: Timeout for each service call to the api (in milliseconds).

  Returns:
    Request results in json format.
  """
    headers = _get_request_header(credentials)

    r = requests.post(uri,
                      headers=headers,
                      json=request_body,
                      timeout=timeout_ms)
    return _handle_ai_platform_response(uri, r)
示例#24
0
def callback():
    # Get authorization code Google sent back to you
    code = request.args.get("code")
    google_provider_cfg = get_google_provider_cfg()
    token_endpoint = google_provider_cfg["token_endpoint"]
    token_url = "https://accounts.google.com/o/oauth2/token"
    refresh_url = token_url
    client = WebApplicationClient(GOOGLE_CLIENT_ID)
    token_url, headers, body = client.prepare_token_request(
        token_endpoint,
        authorization_response=request.url,
        redirect_url=request.base_url,
        code=code)
    token_response = requests.post(
        token_url,
        headers=headers,
        data=body,
        auth=(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET),
    )
    client.parse_request_body_response(json.dumps(token_response.json()))
    userinfo_endpoint = google_provider_cfg["userinfo_endpoint"]
    uri, headers, body = client.add_token(userinfo_endpoint)
    userinfo_response = requests.get(uri, headers=headers, data=body)
    if userinfo_response.json().get("email_verified"):
        unique_id = userinfo_response.json()["sub"]
        users_email = userinfo_response.json()["email"]
        users_name = userinfo_response.json()["given_name"]
    else:
        return "User email not available or not verified by Google.", 400

    employee = Employee.query.filter_by(email=users_email).first()
    login_user(employee)
    if employee.email == '*****@*****.**':
        employee.is_admin = 1
        return redirect(url_for("home.admin_dashboard"))
    else:
        return redirect(url_for("home.dashboard"))
示例#25
0
    def get_token(api_key: str, email: str, password: str) -> Tuple[str, Tuple[str, str]]:
        """
        Authenticate against firebase and get token & refresh.
        Args:
            api_key (str): The firebase API key.
            email (str): The user email.
            password (str): The user password.

        Returns:
            The user ID and the ID / refresh tokens.
        """
        payload = {
            'email': email,
            'password': password,
            'returnSecureToken': True
        }

        response = requests.post(FIREBASE_AUTH_URL.format(API_KEY=api_key), json=payload)
        data = response.json()

        user_id = data['localId']
        id_token = data['idToken']
        refresh_token = data['refreshToken']
        return user_id, (id_token, refresh_token)
示例#26
0
_HOST = " https://api.endpoints.YOUR_PROJECT.cloud.goog"

idt = "IAP_ISSUED_TOKEN_HERE"
print 'id_token: ' + idt

id = 7777

print '-------------- list'
response = requests.get(_HOST + '/todos',
                        headers={'Authorization': 'Bearer ' + idt})
print response.text

print '-------------- put'
body = {'id': id, 'task': 'some task'}
response = requests.post(_HOST + '/todos',
                         headers={'Authorization': 'Bearer ' + idt},
                         json=body)
print response.text

print '-------------- list'
response = requests.get(_HOST + '/todos',
                        headers={'Authorization': 'Bearer ' + idt})
print response.text

print '-------------- get'
response = requests.get(_HOST + '/todos/' + str(id),
                        headers={'Authorization': 'Bearer ' + idt})
print response.text

print '-------------- delete'
response = requests.delete(_HOST + '/todos/' + str(id),
示例#27
0
def main():
    init_pubnub()
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('--credentials', type=existing_file,
                        metavar='OAUTH2_CREDENTIALS_FILE',
                        default=os.path.join(
                            os.path.expanduser('~/.config'),
                            'google-oauthlib-tool',
                            'credentials.json'
                        ),
                        help='Path to store and read OAuth2 credentials')
    parser.add_argument('--device_model_id', type=str,
                        metavar='DEVICE_MODEL_ID', required=True,
                        help='The device model ID registered with Google.')
    parser.add_argument(
        '--project_id',
        type=str,
        metavar='PROJECT_ID',
        required=False,
        help='The project ID used to register device instances.')
    parser.add_argument(
        '-v',
        '--version',
        action='version',
        version='%(prog)s ' +
        Assistant.__version_str__())

    args = parser.parse_args()
    with open(args.credentials, 'r') as f:
        credentials = google.oauth2.credentials.Credentials(token=None,
                                                            **json.load(f))
    with Assistant(credentials, args.device_model_id) as assistant:
        subprocess.Popen(["aplay", "/home/pi/GassistPi-IT/sample-audio-files/Startup.wav"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        events = assistant.start()
        print('device_model_id:', args.device_model_id + '\n' +
              'device_id:', assistant.device_id + '\n')
        if args.project_id:
            register_device(args.project_id, credentials,
                            args.device_model_id, assistant.device_id)
        for event in events:
            process_event(event, assistant.device_id)
            usrcmd=event.args
            with open('/home/pi/GassistPi-IT/src/diyHue/config.json', 'r') as config:
                 hueconfig = json.load(config)
            for i in range(1,len(hueconfig['lights'])+1):
                try:
                    if str(hueconfig['lights'][str(i)]['name']).lower() in str(usrcmd).lower():
                        assistant.stop_conversation()
                        hue_control(str(usrcmd).lower(),str(i),str(hueconfig['lights_address'][str(i)]['ip']))
                        break
                except Keyerror:
                    say('Unable to help, please check your config file')

            for num, name in enumerate(tasmota_devicelist):
                if name.lower() in str(usrcmd).lower():
                    assistant.stop_conversation()
                    tasmota_control(str(usrcmd).lower(), name.lower(),tasmota_deviceip[num])
                    break
            if 'lampadina'.lower() in str(usrcmd).lower():		
                assistant.stop_conversation()
                if 'accendi'.lower() in str(usrcmd).lower():
                    url = ''
                    r = requests.post(url, data="")
                    say("Lampadina Accesa")
                elif 'spegni'.lower() in str(usrcmd).lower():
                    url = ''
                    r = requests.post(url, data="")
                    say("Lampadina Spenta")        
            if 'magic mirror'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                try:
                    mmmcommand=str(usrcmd).lower()
                    if 'weather'.lower() in mmmcommand:
                        if 'show'.lower() in mmmcommand:
                            mmreq_one=requests.get("http://"+mmmip+":8080/remote?action=SHOW&module=module_2_currentweather")
                            mmreq_two=requests.get("http://"+mmmip+":8080/remote?action=SHOW&module=module_3_currentweather")
                        if 'hide'.lower() in mmmcommand:
                            mmreq_one=requests.get("http://"+mmmip+":8080/remote?action=HIDE&module=module_2_currentweather")
                            mmreq_two=requests.get("http://"+mmmip+":8080/remote?action=HIDE&module=module_3_currentweather")
                    if 'power off'.lower() in mmmcommand:
                        mmreq=requests.get("http://"+mmmip+":8080/remote?action=SHUTDOWN")
                    if 'reboot'.lower() in mmmcommand:
                        mmreq=requests.get("http://"+mmmip+":8080/remote?action=REBOOT")
                    if 'restart'.lower() in mmmcommand:
                        mmreq=requests.get("http://"+mmmip+":8080/remote?action=RESTART")
                    if 'display on'.lower() in mmmcommand:
                        mmreq=requests.get("http://"+mmmip+":8080/remote?action=MONITORON")
                    if 'display off'.lower() in mmmcommand:
                        mmreq=requests.get("http://"+mmmip+":8080/remote?action=MONITOROFF")
                except requests.exceptions.ConnectionError:
                    say("Magic mirror not online")
            if 'ingredients'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                ingrequest=str(usrcmd).lower()
                ingredientsidx=ingrequest.find('for')
                ingrequest=ingrequest[ingredientsidx:]
                ingrequest=ingrequest.replace('for',"",1)
                ingrequest=ingrequest.replace("'}","",1)
                ingrequest=ingrequest.strip()
                ingrequest=ingrequest.replace(" ","%20",1)
                getrecipe(ingrequest)
            if 'kickstarter'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                kickstarter_tracker(str(usrcmd).lower())
            if 'trigger'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                Action(str(usrcmd).lower())
            if 'avvia'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                os.system('pkill mpv')
                if os.path.isfile("/home/pi/GassistPi-IT/src/trackchange.py"):
                    os.system('rm /home/pi/GassistPi-IT/src/trackchange.py')
                    if 'autoplay'.lower() in str(usrcmd).lower():
                        os.system('echo "from actions import youtubeplayer\n\n" >> /home/pi/GassistPi-IT/src/trackchange.py')
                        os.system('echo "youtubeplayer()\n" >> /home/pi/GassistPi-IT/src/trackchange.py')
                        YouTube_Autoplay(str(usrcmd).lower())
                    else:
                        YouTube_No_Autoplay(str(usrcmd).lower())
                else:
                    if 'autoplay'.lower() in str(usrcmd).lower():
                        os.system('echo "from actions import youtubeplayer\n\n" >> /home/pi/GassistPi-IT/src/trackchange.py')
                        os.system('echo "youtubeplayer()\n" >> /home/pi/GassistPi-IT/src/trackchange.py')
                        YouTube_Autoplay(str(usrcmd).lower())
                    else:
                        YouTube_No_Autoplay(str(usrcmd).lower())

            if 'ferma'.lower() in str(usrcmd).lower():
                stop()
            if 'radio'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                radio(str(usrcmd).lower())
            if 'wireless'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                ESP(str(usrcmd).lower())
            if 'parcel'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                track()
            if 'news'.lower() in str(usrcmd).lower() or 'feed'.lower() in str(usrcmd).lower() or 'quote'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                feed(str(usrcmd).lower())
            if 'on kodi'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                kodiactions(str(usrcmd).lower())
            if 'chromecast'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                if 'play'.lower() in str(usrcmd).lower():
                    chromecast_play_video(str(usrcmd).lower())
                else:
                    chromecast_control(usrcmd)
            if 'pause music'.lower() in str(usrcmd).lower() or 'resume music'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                if ismpvplaying():
                    if 'pause music'.lower() in str(usrcmd).lower():
                        playstatus=os.system("echo '"+json.dumps({ "command": ["set_property", "pause", True]})+"' | socat - /tmp/mpvsocket")
                    elif 'resume music'.lower() in str(usrcmd).lower():
                        playstatus=os.system("echo '"+json.dumps({ "command": ["set_property", "pause", False]})+"' | socat - /tmp/mpvsocket")
                else:
                    say("Sorry nothing is playing right now")
            if 'music volume'.lower() in str(usrcmd).lower():
                if ismpvplaying():
                    if 'set'.lower() in str(usrcmd).lower() or 'change'.lower() in str(usrcmd).lower():
                        if 'hundred'.lower() in str(usrcmd).lower() or 'maximum' in str(usrcmd).lower():
                            settingvollevel=100
                            with open('/home/pi/.mediavolume.json', 'w') as vol:
                                json.dump(settingvollevel, vol)
                            mpvsetvol=os.system("echo '"+json.dumps({ "command": ["set_property", "volume",str(settingvollevel)]})+"' | socat - /tmp/mpvsocket")
                        elif 'zero'.lower() in str(usrcmd).lower() or 'minimum' in str(usrcmd).lower():
                            settingvollevel=0
                            with open('/home/pi/.mediavolume.json', 'w') as vol:
                                json.dump(settingvollevel, vol)
                            mpvsetvol=os.system("echo '"+json.dumps({ "command": ["set_property", "volume",str(settingvollevel)]})+"' | socat - /tmp/mpvsocket")
                        else:
                            for settingvollevel in re.findall(r"[-+]?\d*\.\d+|\d+", str(usrcmd)):
                                with open('/home/pi/.mediavolume.json', 'w') as vol:
                                    json.dump(settingvollevel, vol)
                            mpvsetvol=os.system("echo '"+json.dumps({ "command": ["set_property", "volume",str(settingvollevel)]})+"' | socat - /tmp/mpvsocket")
                    elif 'increase'.lower() in str(usrcmd).lower() or 'decrease'.lower() in str(usrcmd).lower() or 'reduce'.lower() in str(usrcmd).lower():
                        if os.path.isfile("/home/pi/.mediavolume.json"):
                            with open('/home/pi/.mediavolume.json', 'r') as vol:
                                oldvollevel = json.load(vol)
                                for oldvollevel in re.findall(r'\b\d+\b', str(oldvollevel)):
                                    oldvollevel=int(oldvollevel)
                        else:
                            mpvgetvol=subprocess.Popen([("echo '"+json.dumps({ "command": ["get_property", "volume"]})+"' | socat - /tmp/mpvsocket")],shell=True, stdout=subprocess.PIPE)
                            output=mpvgetvol.communicate()[0]
                            for oldvollevel in re.findall(r"[-+]?\d*\.\d+|\d+", str(output)):
                                oldvollevel=int(oldvollevel)

                        if 'increase'.lower() in str(usrcmd).lower():
                            if any(char.isdigit() for char in str(usrcmd)):
                                for changevollevel in re.findall(r'\b\d+\b', str(usrcmd)):
                                    changevollevel=int(changevollevel)
                            else:
                                changevollevel=10
                            newvollevel= oldvollevel+ changevollevel
                            print(newvollevel)
                            if newvollevel>100:
                                settingvollevel==100
                            elif newvollevel<0:
                                settingvollevel==0
                            else:
                                settingvollevel=newvollevel
                            with open('/home/pi/.mediavolume.json', 'w') as vol:
                                json.dump(settingvollevel, vol)
                            mpvsetvol=os.system("echo '"+json.dumps({ "command": ["set_property", "volume",str(settingvollevel)]})+"' | socat - /tmp/mpvsocket")
                        if 'decrease'.lower() in str(usrcmd).lower() or 'reduce'.lower() in str(usrcmd).lower():
                            if any(char.isdigit() for char in str(usrcmd)):
                                for changevollevel in re.findall(r'\b\d+\b', str(usrcmd)):
                                    changevollevel=int(changevollevel)
                            else:
                                changevollevel=10
                            newvollevel= oldvollevel - changevollevel
                            print(newvollevel)
                            if newvollevel>100:
                                settingvollevel==100
                            elif newvollevel<0:
                                settingvollevel==0
                            else:
                                settingvollevel=newvollevel
                            with open('/home/pi/.mediavolume.json', 'w') as vol:
                                json.dump(settingvollevel, vol)
                            mpvsetvol=os.system("echo '"+json.dumps({ "command": ["set_property", "volume",str(settingvollevel)]})+"' | socat - /tmp/mpvsocket")
                    else:
                        say("Sorry I could not help you")
                else:
                    say("Sorry nothing is playing right now")

            if 'refresh'.lower() in str(usrcmd).lower() and 'music'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                refreshlists()
            if 'google music'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                os.system('pkill mpv')
                if os.path.isfile("/home/pi/GassistPi-IT/src/trackchange.py"):
                    os.system('rm /home/pi/GassistPi-IT/src/trackchange.py')
                    gmusicselect(str(usrcmd).lower())
                else:
                    gmusicselect(str(usrcmd).lower())
示例#28
0
def publish(resource, payload):
    requests.post('http://localhost:3000/{}'.format(resource), payload)
示例#29
0
from google.oauth2 import id_token
from google.oauth2 import service_account
import json

audience = "https://www.googleapis.com/oauth2/v4/token"
additional_claims = {'target_audience': 'http://yourappspot.com'}

svc_creds = service_account.Credentials.from_service_account_file(
    '/home/srashid/gcp_misc/certs/GCPNETAppID-e65deccae47b.json')
jwt_creds = jwt.Credentials.from_signing_credentials(
    svc_creds, audience=audience, additional_claims=additional_claims)

request = google.auth.transport.requests.Request()
jwt_creds.refresh(request)
signed_jwt = jwt_creds.token

url = 'https://www.googleapis.com/oauth2/v4/token'
data = {
    'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
    'assertion': signed_jwt
}
headers = {"Content-type": "application/x-www-form-urlencoded"}
resp = requests.post(url, data=data, headers=headers)
idt = json.loads(resp.text)['id_token']
print idt

request = google.auth.transport.requests.Request()
print id_token.verify_token(idt, request)
print '--------------------------------------------------------------------------'
示例#30
0
def jobupload(pypath):
    #Create directory

    path = os.getcwd()

    os.mkdir(path + '\\Job')
    os.mkdir(path + '\\Job\\trainer')

    #Create setup

    f = open(path + "\\Job" + "\\setup.py", "x")
    f.write("""
    from setuptools import find_packages
    from setuptools import setup

    REQUIRED_PACKAGES = ['Keras==2.0.4',
                         'h5py==2.7.0',
                         'tensorflow>=2.4.1',
                         'xgboost>=1.4.1'
                         ]

    setup(
        name='trainer',
        version='0.1',
        install_requires=REQUIRED_PACKAGES,
        packages=find_packages(),
        include_package_data=True,
        description='Keras trainer application'
    )
    """)
    f.close()

    #Create __init__.py

    f = open(path + "\\Job\\trainer" + "\\__init__.py", "x")

    #Create requirements.txt

    f = open(path + "\\Job" + "\\requirements.txt", "x")
    f.write("""
    tensorflow>=1.15.*,<2
    future==0.16.0
    h5py>=2.7.0,<3.0
    Keras>=2.2.4,<3.0
    numexpr>=2.6.8,<3.0
    pandas>=0.23.4,<1.0
    """)
    f.close()

    #move the python code to the directory
    files = [pypath]
    for f in files:
        shutil.copy(f, path + "\\Job\\trainer")

    #creating the tar file
    def tardir(path, tar_name):
        with tarfile.open(tar_name, "w:gz") as tar_handle:
            for root, dirs, files in os.walk(path):
                for file in files:
                    tar_handle.add(os.path.join(root, file))
    tardir('./Job', 'Job.tar.gz')

    #send through API
    base = open(path + '/Job.tar.gz', 'rb')
    base_read = base.read()
    base_64_encode = base64.encodebytes(base_read)
    base_64_decode = base64.decodebytes(base_64_encode) 
    
    url = 'http://127.0.0.1:8000/upload_job/'
    myobj = {"file": str(base_64_decode)}
    x = requests.post(url, json=myobj)

    #delete everything
    base.close()
    shutil.rmtree(path + "\\Job")
    os.remove(path + '\\Job.tar.gz')
    

    
    print('Job submitted')