Exemple #1
0
def inlinequery(bot, update):

    print("New query started")
    query = update.inline_query.query
    results = list()
    types = ['Track', 'Artist', 'Album', 'Playlist']

    auth_token = auth.get_auth_token()

    # if empty query, return blank results to prevent unnecessary Spotify API calls
    if is_empty_query(query):
        return results
    else:
        # each new value will show up in the response to the user
        for _type in types:
            response = search(query, _type.lower(), auth_token)
            if response is not None:
                results.append(
                    build_inline_query_result_article(_type, response))

    # if there are no results, tell user
    if check_no_results(results):
        results.append(
            InlineQueryResultArticle(
                id=uuid4(),
                title="No results found",
                input_message_content=InputTextMessageContent(
                    "No results found")))

    update.inline_query.answer(results)
def get_headers():
    return {
        'authorization': 'Bearer %s' % get_auth_token(),
        'user-agent':
        'Telecine_iOS/2.5.10 (br.com.telecineplay; build:37; iOS 14.1.0) Alamofire/5.2.2',
        'x-device': 'Mobile-iOS',
        'x-version': '2.5.10'
    }
Exemple #3
0
def submit_for_recognition(audio_file_uri, api_key):
    auth_token = auth.get_auth_token()
    response = requests.post(_LONG_RUNNING_RECOGNIZE_URI,
                             json=_build_request_payload(audio_file_uri),
                             headers={'Authorization': 'Bearer ' + auth_token})

    if response.status_code != http.HTTPStatus.OK:
        raise RecognizerException(response.json()['error'])
    return response.json()
Exemple #4
0
def spotify_token_callback():
    flask.session.clear()

    code = flask.request.args.get('code')
    res = auth.get_auth_token(code)
    flask.session["toke"] = res.json().get("access_token")

    print(flask.session["toke"])
    return flask.redirect(flask.url_for("app_dashboard.join_or_host"))
Exemple #5
0
    def login():
        login_data = request.get_json(cache=False)
        email = login_data['email']
        passwd = login_data['password']

        u = User.query.filter_by(email=email).first()
        if u and u.is_active and verify_password(passwd, u.password):
            login_user(u)
            return dict(user=u.to_dict(), token=get_auth_token(u))
        return abort(401)
Exemple #6
0
def test_get_auth_token_raises(monkeypatch):
    """
    it raises AuthorizationException if authorization fails
    """
    import subprocess

    @dataclass
    class MockCompletedProcess:
        returncode: int
        stdout: bytes
        stderr: bytes

    monkeypatch.setattr(
            subprocess,
            'run',
            lambda args, capture_output: MockCompletedProcess(1, b'', b'failed to authenticate')
            )
    with pytest.raises(auth.AuthorizationException) as excinfo:
        auth.get_auth_token()

    assert 'failed to authenticate' in str(excinfo.value)
def _get_resource_group_name(resource_group_name):
    ctx.logger.info("In _get_resource_group_name looking for {0}".format(resource_group_name))
    credentials = 'Bearer ' + auth.get_auth_token()
    ctx.logger.info("In _get_resource_group_name credentials is {0}".format(credentials))
    headers, location, subscription_id = auth.get_credentials()
    list_resource_group_url = constants.azure_url+'/subscriptions/'+subscription_id+'/resourcegroups?api-version='+constants.api_version_resource_group
    response_get_resource_group = requests.get(url=list_resource_group_url, headers=headers)
    ctx.logger.info("response_get_resource_group.text {0} ".format(response_get_resource_group.text))
    if resource_group_name in response_get_resource_group.text:
        return True
    else:
        return False
Exemple #8
0
    def GET(self):
        query = web.input()
        if 'code' in query:
            token = auth.get_auth_token(client_id, client_secret,
                                        query['code'])

            if token is None:
                return 'Login failed - no access token received.'

            session.token = token
            raise web.seeother('/')  # redirect users back to the editor
        else:
            return 'Login failed - no auth. code received.'
Exemple #9
0
def recognition_request_status(operation_name):
    auth_token = auth.get_auth_token()
    response = requests.get(
        _RECOGNIZE_STATUS_URI.format(operation_name=operation_name),
        headers={'Authorization': 'Bearer ' + auth_token})

    if response.status_code != http.HTTPStatus.OK:
        raise RecognizerException(response.json()['error'])
    data = response.json()
    return RecognitionResults(data['name'],
                              data['metadata']['progressPercent'],
                              parse(data['metadata']['startTime']),
                              parse(data['metadata']['lastUpdateTime']),
                              _transcript_from_response(data.get('response')))
Exemple #10
0
def login():
    """
    Login route. Provide the credentials (email/password).

    :return:
    """
    user_name = request.form['username']
    password = request.form['password']

    user = {'id': user_name, 'password': password}

    token = get_auth_token(user)
    _USER_REPO.session.commit()
    if token[0] != 200:
        return json.dumps(token[1]).encode('utf-8'), 401, {
            'ContentType': 'application/json'
        }
    return jsonify({'access_token': token[1].decode("utf-8")})
Exemple #11
0
def test_get_auth_token(monkeypatch):
    """
    it returns the authorization token string
    """
    import subprocess

    @dataclass
    class MockCompletedProcess:
        returncode: int
        stdout: bytes
        stderr: bytes

    monkeypatch.setattr(
            subprocess,
            'run',
            lambda args, capture_output: MockCompletedProcess(0, b'gdstwe7354', b'')
            )
    token = auth.get_auth_token()
    assert token =='gdstwe7354'
Exemple #12
0
def get_track_dict(track_id):
    response = requests.get(
        TRACK_URL + track_id,
        headers={'Authorization': 'Bearer %s' % get_auth_token()})
    return response.json()
Exemple #13
0
 def authorize(self, ticket):
     result = auth.get_auth_token(self.api_key, ticket)
     try:
         self.auth_token = result['response']['auth_token']['value']
     except:
         raise Exception("[Error] Authorizing failed.")
 def setUp(self):
     self.auth_token = get_auth_token("*****@*****.**", "dnbdirect123")
    def student_view(self, context=None, request=None):
        cr = CrequestMiddleware.get_request()
        if not self.runtime.user_is_staff and cr is not None:
            user_service = self.runtime.service(self, 'user')
            xb_user = user_service.get_current_user()
            username = xb_user.opt_attrs.get('edx-platform.username')
            if username is None:
                log.debug(u'[JupyterNotebook Xblock] : User not found in student_view')

            # get the course details
            course_unit_name = str(self.course_unit)
            resource = str(self.file_noteBook)

            token = csrf.get_token(cr)
            sessionid = cr.session.session_key

            cookie_data_string = cr.COOKIES.get(settings.SESSION_COOKIE_NAME)
            host = cr.META['HTTP_HOST']

            authorization_grant = get_authorization_grant(token, sessionid, host)

            # Get a token from Sifu
            sifu_domain = self.get_config('sifu_domain')
            sifu_token = None
            # it looks like these might be single use tokens
            cr.session['sifu_token'] = None
            try:
                sifu_token = cr.session['sifu_token']
            except:
                cr.session['sifu_token'] = None

            if sifu_token is None:
                sifu_token = get_auth_token(authorization_grant, username, sifu_domain)
                cr.session['sifu_token'] = sifu_token
                cr.session.save()
                cr.session.modified = True

            #check if user notebook & base notebook exists
            if not self.user_notebook_exists(username, course_unit_name, resource, sifu_token, sifu_domain):
                log.debug(u'[JupyterNotebook Xblock] : User notebook does not exist.')
                # check the base file exists
                if not self.base_file_exists(course_unit_name, resource, sifu_token, sifu_domain):
                    log.debug(u'[JupyterNotebook Xblock] : The course unit base notebook does not exist.')
                    # create the base file
                    self.create_base_file(course_unit_name, resource, sifu_token, sifu_domain, host)
                # create user notebook assuming the base file exists
                if not self.create_user_notebook(username, course_unit_name, resource, sifu_token, sifu_domain):
                    log.debug(u'[JupyterNotebook Xblock] : Could create {}\'s notebook'.format(username))

            context = {
                "sifu_token": sifu_token,
                'sifu_url': 'http://%s:3334/v1/api/set-cookie/' % sifu_domain,
                'self': self,
                'user_is_staff': self.runtime.user_is_staff,
                'current_url_resource': self.get_current_url_resource(username, course_unit_name, resource, sifu_token, sifu_domain, host),
            }
        else:
            context = {
                'self': self,
                'user_is_staff': self.runtime.user_is_staff,
                'current_url_resource': None,
            }
        template = self.render_template("static/html/jupyternotebook_xblock.html", context)
        frag = Fragment(template)
        frag.add_css(self.resource_string("static/css/jupyternotebook_xblock.css"))
        frag.add_javascript(self.resource_string("static/js/src/jupyternotebook_xblock.js"))
        frag.initialize_js('JupyterNotebookXBlock')
        return frag
Exemple #16
0
url_upload = 'https://sync.admicro.vn/api2/repos/{0}/upload-link/'.format(repo_id)


def upload(token, upload_file, upload_dir):
    headers = {
        'Authorization': 'Token {token}'.format(token=token)
    }
    # get upload link
    upload_link = requests.get(url_upload, headers=headers).json()

    # upload
    upload_data = {
        'filename': upload_file[upload_file.rfind('/') + 1:],
        'parent_dir': upload_dir
    }
    response = requests.post(
        upload_link,
        data=upload_data,
        files={'file': open(upload_file, 'rb')},
        headers=headers
    )

    print('Upload result: ', response)


if __name__ == "__main__":
    token = get_auth_token()

    upload(token, '/storage/gender_cls/celeb_ntt/dnb-facerecognition-aivivn/datasets/aligned.tar',
           '/DataSet/celeb_ntt/')
Exemple #17
0
def get_playlist_dict(username, playlist_id):
    response = requests.get(
        PLAYLIST_URL + username + '/playlists/' + playlist_id + '/tracks',
        headers={'Authorization': 'Bearer %s' % get_auth_token()})
    return response.json()
Exemple #18
0
 def authorize(self, ticket):
     result = auth.get_auth_token(self.api_key, ticket)
     try:
         self.auth_token = result['response']['auth_token']['value']
     except:
         raise Exception("[Error] Authorizing failed.")
    def student_view(self, context=None, request=None):
        cr = CrequestMiddleware.get_request()
        if not self.runtime.user_is_staff and cr is not None:
            user_service = self.runtime.service(self, 'user')
            xb_user = user_service.get_current_user()
            username = xb_user.opt_attrs.get('edx-platform.username')
            if username is None:
                log.debug(
                    u'[JupyterNotebook Xblock] : User not found in student_view'
                )

            # get the course details
            course_unit_name = str(self.course_unit)
            resource = str(self.file_noteBook)

            token = csrf.get_token(cr)
            sessionid = cr.session.session_key

            cookie_data_string = cr.COOKIES.get(settings.SESSION_COOKIE_NAME)
            host = cr.META['HTTP_HOST']

            authorization_grant = get_authorization_grant(
                token, sessionid, host)

            # Get a token from Sifu
            sifu_domain = self.get_config('sifu_domain')
            sifu_token = None
            # it looks like these might be single use tokens
            cr.session['sifu_token'] = None
            try:
                sifu_token = cr.session['sifu_token']
            except:
                cr.session['sifu_token'] = None

            if sifu_token is None:
                sifu_token = get_auth_token(authorization_grant, username,
                                            sifu_domain)
                cr.session['sifu_token'] = sifu_token
                cr.session.save()
                cr.session.modified = True

            #check if user notebook & base notebook exists
            if not self.user_notebook_exists(username, course_unit_name,
                                             resource, sifu_token,
                                             sifu_domain):
                log.debug(
                    u'[JupyterNotebook Xblock] : User notebook does not exist.'
                )
                # check the base file exists
                if not self.base_file_exists(course_unit_name, resource,
                                             sifu_token, sifu_domain):
                    log.debug(
                        u'[JupyterNotebook Xblock] : The course unit base notebook does not exist.'
                    )
                    # create the base file
                    self.create_base_file(course_unit_name, resource,
                                          sifu_token, sifu_domain, host)
                # create user notebook assuming the base file exists
                if not self.create_user_notebook(username, course_unit_name,
                                                 resource, sifu_token,
                                                 sifu_domain):
                    log.debug(
                        u'[JupyterNotebook Xblock] : Could create {}\'s notebook'
                        .format(username))

            context = {
                "sifu_token":
                sifu_token,
                'sifu_url':
                'http://%s:3334/v1/api/set-cookie/' % sifu_domain,
                'self':
                self,
                'user_is_staff':
                self.runtime.user_is_staff,
                'current_url_resource':
                self.get_current_url_resource(username, course_unit_name,
                                              resource, sifu_token,
                                              sifu_domain, host),
            }
        else:
            context = {
                'self': self,
                'user_is_staff': self.runtime.user_is_staff,
                'current_url_resource': None,
            }
        template = self.render_template(
            "static/html/jupyternotebook_xblock.html", context)
        frag = Fragment(template)
        frag.add_css(
            self.resource_string("static/css/jupyternotebook_xblock.css"))
        frag.add_javascript(
            self.resource_string("static/js/src/jupyternotebook_xblock.js"))
        frag.initialize_js('JupyterNotebookXBlock')
        return frag
Exemple #20
0
current_time = datetime.now().strftime("%H:%M:%S")

# Optional: lift to env files.

parser = argparse.ArgumentParser(
    description='DSC job management for Databricks')
parser.add_argument('--params',
                    type=str,
                    help='your Databricks and Azure parameter file',
                    default='params.json')
args = parser.parse_args()

configuration = json.load(open(args.params))

auth_token = auth.get_auth_token(configuration)
databricks_uri = configuration['databricks_uri'] + "/api/2.0/%s"

# Settings for jinja2
tplenv = Environment(loader=PackageLoader('job', 'templates'))
tplenv.filters['jsonify'] = json.dumps

# Settings for request/urllib3
head = {
    'Authorization': 'Bearer ' + auth_token["access_token"],
    'Content-Type': 'application/json'
}


# Get something from Databricks, parse to JSON if asked
def get_db(action, returnJson=False):
Exemple #21
0
 def setUp(self):
     self.auth_token = get_auth_token("*****@*****.**", "dnbdirect123")
     self.matches = self.read_matches()
Exemple #22
0
def get_artist_dict(artist_id):
    response = requests.get(
        ALBUM_URL + artist_id,
        headers={'Authorization': 'Bearer %s' % get_auth_token()})
    return response.json()