示例#1
0
def handle_position_request(service, action):
    LIBRARY = get_library()
    MPDCLIENT = get_client()

    print "Position"

    MPDCLIENT.connect()
    status = MPDCLIENT.status()
    if not "songid" in status:
      MPDCLIENT.disconnect()
      getattr(action, "return")()
      return
    songinfo = MPDCLIENT.playlistid(status['songid'])
    MPDCLIENT.disconnect()
    
    w = GUPnPAV.GUPnPDIDLLiteWriter.new("English")   
    song = LIBRARY.songs_by_file.get(songinfo[0]['file'], None)

    song_id = "0"
    if song:
      song.writeself(w)
      song_id = str(song.id)
    
    action.set_values(["Track", "TrackMetaData", "TrackURI"],
                      [song_id, w.get_string(), getattr(song, "url", "")])

    action.set_value("TrackDuration",
                     int_to_time(status.get("time", "0:0").split(":")[1]))
    
    curtime = int_to_time(status.get("time", "0:0").split(":")[0])
    action.set_value("RelTime", curtime)
    action.set_value("AbsTime", curtime)
    
    getattr(action, "return")()
示例#2
0
def connection_manager(uuid, request, protocol):
    """Accept a new request from a unique ID from the protocol.
    Send a remote signal followed by a get_client.
    Return a tuple of success, client dict.

    """
    # Send off....
    pipe_send("init", uuid, request)
    # get_client
    ok, client = get_client(uuid, request)

    if ok is False:
        print("Client failure", uuid)
        pipe_send("client_failure", uuid, vars(client))
        return False, client

    cache = MEM.get(uuid, None)
    if cache is None:
        log('New uuid', uuid)
        cache = {}
    else:
        cache['cache_load'] = True

    cache['entry_client'] = client
    cache['protocol'] = protocol

    log(f'!! connection_manager Cache connection: {uuid}')
    pipe_send("client", uuid, client)
    MEM[uuid] = cache
    return True, client
示例#3
0
 def _get_client(self):
     random_server = random.randint(0, len(self.context['servers']) - 1)
     topic, server_name = self.context['servers'][random_server]
     client = cl.get_client()
     client = client.prepare(timeout=30, topic=topic,
                             server=server_name)
     return client
示例#4
0
文件: upload.py 项目: Naveengnn/one
def upload(path, remote_path=''):
  '''upload a file with the directory path "path"'''
  if (user.is_user_signed_in()):
    remote_path = sanitize_path(remote_path)
    full_path_expansion = get_path_expansion(path)
    file_name = os.path.basename(full_path_expansion)
    if (os.path.isfile(full_path_expansion)):
        
      client = c.get_client() 
      if (check_existance(file_name, remote_path, client)):
        logger.die('File with name "' + file_name + '" already exists')
      else:
        try:
          client.upload_file(full_path_expansion, 'mf:' + remote_path + '/')
          #updated_hash = get_hash(full_path_expansion, client)
          #xattr.setxattr(f, 'hash', binascii.a2b_qp(updated_hash))
          logger.log('File "' + file_name + '" has been succesfully uploaded.')
        except ResourceNotFoundError:
          Logger.die('Path "' + remote_path + '" not found.')
        except requests.exceptions.RequestException:
          logger.die('Network error, please check network status and try again')

    elif (os.path.isdir(full_path_expansion)):
      logger.die('File, "' + full_path_expansion + '", is a directory')
    else:
      logger.die('No such file or directory')
  else:
    user.get_auth()
示例#5
0
    def __iter__(self):
        client = get_client()

        # make our first request
        data = client.make_request(self.url)

        while is_api_collection(data):
            # iterate through the data objects
            for obj in data['objects']:
                # act as a generator
                if isinstance(self.type, type(Object)):
                    # if self.type is an Object then return it
                    # instantiated with the data from the api call
                    yield self.type(data=obj)
                else:
                    # otherwise just return the data itself
                    yield obj

            if 'meta' in data and 'next' in data['meta'] and \
                    data['meta']['next'] is not None:
                # fetch the next set of objects
                data = client.make_request(data['meta']['next'], has_base=True)
            else:
                # we've reached the end of the object listing
                # signal to the while loop
                data = None
示例#6
0
    def __init__(self, data=None, filter=None, url=None):
        invalid = ObjectException("Not a valid object")

        if url or filter:
            client = get_client()
        if url:
            data = client.make_request(url, has_base=True)
        elif filter:
            # since we're filtering we're going to get back
            # a collection instead of a single object
            data = client.make_request(self.__class__.make_url(filter))

            if not is_api_collection(data):
                raise invalid

            if data['meta']['total_count'] != 1:
                raise ObjectException("Too many objects returned")

            # now that we know it's valid set the data reference
            # to the first object
            data = data['objects'][0]

        if not is_api_object(data):
            raise invalid

        self.data = data
示例#7
0
def set_mpd_uri(service, action, uri):
    MPDCLIENT = get_client()
    LIBRARY = get_library()

    print "Playing %s" % uri
    match = re.search("/file\/(.*)$", uri)
    if not match:
        action.return_error(0, "Invalid URI")
        
    itemid = int(match.groups()[0])
    
    song = LIBRARY.get_by_id(itemid)

    if not isinstance(song, MPDSong):
        action.return_error()
        return
    
    MPDCLIENT.connect()
    songdata = MPDCLIENT.playlistfind('file', song.file)
    
    if songdata:        
        # If the song is in the current playlist move to it and play it
        MPDCLIENT.seek(songdata[0]['pos'], 0)
    else:
        # Else add it to the playlist then play it
        MPDCLIENT.add(song.file)
        songdata = MPDCLIENT.playlistfind('file', song.file)
        if not songdata:
            action.return_error()
            return
        MPDCLIENT.seek(songdata[0]['pos'], 0)

    MPDCLIENT.disconnect()
    getattr(action, "return")()
示例#8
0
 def wrapper(service, action):
     MPDCLIENT = get_client()
     print function_name
     MPDCLIENT.connect()
     getattr(MPDCLIENT, function_name.lower())(*args)
     MPDCLIENT.disconnect()
     getattr(action, "return")()
示例#9
0
文件: download.py 项目: cdpetty/one
def download(file_path):
  '''Download the file by name of "file_path"'''
  if (user.is_user_signed_in()):
    client = c.get_client()
    filename = os.path.basename(file_path)
    file_path = sanitize_path(file_path)
    if (os.path.isfile(filename) or os.path.isdir(filename)):
      logger.die('File or dir with name "' + filename + '" in current directory')
    else:
      existance = check_existance(file_path, client)
      if (existance[0]):
        try:
          client.download_file("mf:" + file_path , '.')
          file_info = existance[1]
          xattr.setxattr(filename, 'hash', binascii.a2b_qp(file_info['hash']))
          logger.log('File "' + filename + '" downloaded successfully.')
        except NotAFolderError:
          logger.die('Path "' + remote_path + '" not found on MediaFire')
        except ResourceNotFoundError:
          logger.die('Path "' + remote_path + '" not found on MediaFire.')
        except requests.exceptions.RequestException:
          logger.die('Network error, please check network status and try again')

      else:
        logger.log('File path and name "' + file_path + '" does not exist.')
  else:
    user.get_auth()
示例#10
0
    def __iter__(self):
        client = get_client()

        # make our first request
        data = client.make_request(self.url)

        while is_api_collection(data):
            # iterate through the data objects
            for obj in data['objects']:
                # act as a generator
                if isinstance(self.type, type(Object)):
                    # if self.type is an Object then return it
                    # instantiated with the data from the api call
                    yield self.type(data=obj)
                else:
                    # otherwise just return the data itself
                    yield obj

            if 'meta' in data and 'next' in data['meta'] and \
                    data['meta']['next'] is not None:
                # fetch the next set of objects
                data = client.make_request(data['meta']['next'], has_base=True)
            else:
                # we've reached the end of the object listing
                # signal to the while loop
                data = None
def create_implicit_grant_access_token(uid, client_id, redirect_uri, scope=None):
    user = get_user(uid)
    client = get_client(client_id)
    db = DB()
    try:

        # the only authentication here is to check the
        # redirect_uri is the same as the one stored
        # for the registered client
        if client.redirect_uri == redirect_uri:
            token = AccessToken(client.id, user.id, scope=scope)
            while db.contains(token.code):
                token = AccessToken(client.id, user.id, scope=scope)
            db.put(token.code, token)
            db.commit()

            return token.code
        else:
            logging.warn(
                "".join([str(client_id), " uri of ", str(client.redirect_uri), " does not match ", str(redirect_uri)])
            )

    except Exception, e:
        logging.error("".join(["create_implicit_grant_access_token: ", str(e)]))
        db.abort()
示例#12
0
def get_token(client_id, client_secret, code):
    '''
    This function should get any type of token
    since the code is unique and should only
    return the type of token that was created
    in create_[...]_token
    '''
    db = DB()
    try:
        if db.contains(code):
            token = db.get(code)
            client = get_client(token.client)
            if (not token.expire or token.expire + \
                token.created > time()) and \
                client.id == client_id and \
                client.secret == client_secret:
            
                return token
            else:
                logging.warn('get_token: Did not authenticate')
        else:
            logging.warn(''.join(['get_token: code ', str(code), ' is not in database']))
    except Exception, e:
        logging.error(''.join(['get_token(',
                               str(client_id),
                               ',',
                               str(client_secret),
                               ',',
                               str(code),
                               '): ',
                               str(e)]))
def create_access_token_from_user_pass(client_id, client_secret, user_id, password, scope):
    client = None
    if client_id != None:
        client = get_client(client_id)
    else:
        # create a client object from username and password
        client = Client(user_id, user_id, password, None)
        # make client_secret equal the password
        # saving me from having to change anything below
        client_secret = password

    user = get_user(user_id)

    db = DB()

    try:
        if client != None and user != None and client.secret == client_secret and user.password == password:
            token = AccessToken(client.id, user.id, scope=scope)
            while db.contains(token.code):
                token = AccessToken(client.id, user.id, scope=scope)

            db.put(token.code, token)
            db.commit()

            return token.code
    except Exception, e:
        logging.error("".join(["create_access_token_from_user_pass: ", str(e)]))
        db.abort()
示例#14
0
def run():
    pid = os.getpid()
    msg = str(pid)
    parser = argparse.ArgumentParser(description='Run Server on PORT')
    parser.add_argument('-P',
                        metavar='P',
                        type=int,
                        nargs='+',
                        help='an integer for gRPC Server port')
    args = parser.parse_args()
    if args and args.P:
        port = args.P[-1]
        jobset.message('START', 'Run hello on port %s' % port, do_newline=True)
        c = get_client()
        start = time.time()
        tt = int(total / cpu_count)
        for i in range(tt):
            r = c.hello(msg)
            assert msg in str(r)
        end = time.time()
        diff = end - start
        qps = total / diff
        jobset.message('SUCCESS',
                       'Done hello total=%s, '
                       'time diff=%s, qps=%s' % (total, diff, qps),
                       do_newline=True)
示例#15
0
def download(file_path):
    '''Download the file by name of "file_path"'''
    if (user.is_user_signed_in()):
        client = c.get_client()
        filename = os.path.basename(file_path)
        file_path = sanitize_path(file_path)
        if (os.path.isfile(filename) or os.path.isdir(filename)):
            logger.die('File or dir with name "' + filename +
                       '" in current directory')
        else:
            existance = check_existance(file_path, client)
            if (existance[0]):
                try:
                    client.download_file("mf:" + file_path, '.')
                    file_info = existance[1]
                    xattr.setxattr(filename, 'hash',
                                   binascii.a2b_qp(file_info['hash']))
                    logger.log('File "' + filename +
                               '" downloaded successfully.')
                except NotAFolderError:
                    logger.die('Path "' + remote_path +
                               '" not found on MediaFire')
                except ResourceNotFoundError:
                    logger.die('Path "' + remote_path +
                               '" not found on MediaFire.')
                except requests.exceptions.RequestException:
                    logger.die(
                        'Network error, please check network status and try again'
                    )

            else:
                logger.log('File path and name "' + file_path +
                           '" does not exist.')
    else:
        user.get_auth()
示例#16
0
def update_association(user_id, client_id, refresh_token_str):
    client = get_client(client_id)
    user = get_user(user_id)
    logging.warn('update_associations 1: ' + str(refresh_token_str))
    refresh_token = get_token(client_id, client.secret, refresh_token_str)
    #always check to see if it is confidential or not.
    #it shouldn't be if it's using update_association, but you never know
    #and it's good to have a log message to possible alert the admin that
    #this is going on.
    if client.type.lower() != 'confidential':
        raise ConfidentailError('Client ' + client_id + \
                                ' is not a confidentail client')

    db = DB()
    try:
        key = 'client_association_' + str(user.id)
        if db.contains(key):
            association = db.get(key)
            if client.id in association.clients:
                logging.warn('update_associations 2: ' + str(association.clients[client.id]))
                old_refresh = get_token(client.id, client.secret, association.clients[client.id])
                delete_token(old_refresh.access_token)
                delete_token(old_refresh.code)
                association.clients[client.id] = refresh_token.code
                logging.warn('update_associations 3: ' + str(refresh_token.code) + ', ' + str(association.clients[client.id]))
                db.update(key, association)
                db.commit()
    #except Exception, e:
    #    logging.error('update_associations: ' + str(e))
    #    db.abort()
    finally:
        db.close()

    return False
示例#17
0
def get_token(client_id, client_secret, code):
    """
    This function should get any type of token
    since the code is unique and should only
    return the type of token that was created
    in create_[...]_token
    """
    db = DB()
    try:
        if db.contains(code):
            token = db.get(code)
            client = get_client(token.client)
            if (
                (not token.expire or token.expire + token.created > time())
                and client.id == client_id
                and client.secret == client_secret
            ):

                return token
            else:
                logging.warn("get_token: Did not authenticate")
        else:
            logging.warn("".join(["get_token: code ", str(code), " is not in database"]))
    except Exception, e:
        logging.error("".join(["get_token(", str(client_id), ",", str(client_secret), ",", str(code), "): ", str(e)]))
示例#18
0
    def __init__(self, data=None, filter=None, url=None):
        invalid = ObjectException("Not a valid object")

        if url or filter:
            client = get_client()
        if url:
            data = client.make_request(url, has_base=True)
        elif filter:
            # since we're filtering we're going to get back
            # a collection instead of a single object
            data = client.make_request(self.__class__.make_url(filter))

            if not is_api_collection(data):
                raise invalid

            if data['meta']['total_count'] != 1:
                raise ObjectException("Too many objects returned")

            # now that we know it's valid set the data reference
            # to the first object
            data = data['objects'][0]

        if not is_api_object(data):
            raise invalid

        self.data = data
示例#19
0
文件: user.py 项目: Naveengnn/one
def check_existance(email, password):
  try:
    client = c.get_client(email, password) 
    return (True, client)
  except (MediaFire.api.MediaFireApiError):
    return (False, None)
  except requests.exceptions.RequestException:
    logger.die('Network error, please check network status and try again')
示例#20
0
def get_code():
    client = get_client(client_id=CLIENT_ID, secret=SECRET, redirect_uri=REDIRECT_URI,
                        scope=SCOPE, response_type=RESPONSE_TYPE)
    code = request.args.get('code')
    client.get_tokens(code=code)
    print(code)
    if client.token_loaded:
        return redirect('/contact_list')
示例#21
0
 def _get_client(self, *args, **kwargs):
     api = client.get_client(self.reference_name).api
     if not api:
         log.info('No reference found: {0}'.format(self.reference_name))
         raise NoReference(self.reference_name)
     if 'uuid' in kwargs:
         return getattr(api, kwargs['resource_name'])(kwargs['uuid'])
     else:
         return getattr(api, kwargs['resource_name'])
示例#22
0
def get_files(path):
    try:
        client = c.get_client()
        contents = client.get_folder_contents_iter('mf:' + path)
        return list(contents)
    except ResourceNotFoundError:
        logger.die('Path: "' + path + '" does not exist')
    except requests.exceptions.RequestException:
        logger.die('Network error, please check network status and try again')
示例#23
0
 def client(self, *args, **kwargs):
     api = client.get_client(self.reference_name).api
     if not api:
         log.info('No reference found: {0}'.format(self.reference_name))
         raise NoReference(self.reference_name)
     if 'uuid' in kwargs:
         return getattr(api, kwargs['resource_name'])(kwargs['uuid'])
     else:
         return getattr(api, kwargs['resource_name'])
示例#24
0
文件: list.py 项目: cdpetty/one
def get_files(path):
  try:
    client = c.get_client()
    contents = client.get_folder_contents_iter('mf:' + path)
    return list(contents)
  except ResourceNotFoundError:
    logger.die('Path: "' + path + '" does not exist')
  except requests.exceptions.RequestException:
    logger.die('Network error, please check network status and try again')
示例#25
0
def index():

    client = get_client(client_id=CLIENT_ID, secret=SECRET, redirect_uri=REDIRECT_URI,
                            scope=SCOPE, response_type=RESPONSE_TYPE)
    if client.token_loaded:
        return redirect('/contact_list')

    auth_url = client.generate_auth_url()
    print("Auth Url",auth_url)
    return redirect(auth_url, code=302)
示例#26
0
def handle_seek_request(service, action):
    MPDCLIENT = get_client()

    seek_time = action.get_value('Target', GObject.TYPE_STRING)
    MPDCLIENT.connect()
    status = MPDCLIENT.status()
    print "Seek id: %s, time: %s" % (status["song"], seek_time)
    MPDCLIENT.seek(status["song"], time_to_int(seek_time))
    MPDCLIENT.disconnect()

    getattr(action, "return")()
示例#27
0
文件: share.py 项目: Naveengnn/one
def get_existance(filename):
    client = c.get_client()
    try:
        contents = client.get_folder_contents_iter('mf:/one_storage/')
        for item in contents:
            if type(item) is File:
                if item['filename'] == filename:
                    return (True, item)
        return (False, None)
    except requests.exceptions.RequestException:
        logger.die('Network error, please check network status and try again')
示例#28
0
文件: share.py 项目: cdpetty/one
def get_existance(filename):
  client = c.get_client()
  try:
    contents = client.get_folder_contents_iter('mf:/one_storage/')
    for item in contents:
      if type(item) is File:
        if item['filename'] == filename:
          return (True, item)
    return (False, None)
  except requests.exceptions.RequestException:
    logger.die('Network error, please check network status and try again')
示例#29
0
def contact_list():
    """Show contact lists"""

    client = get_client(client_id=CLIENT_ID, secret=SECRET, redirect_uri=REDIRECT_URI,
                        scope=SCOPE, response_type=RESPONSE_TYPE)

    if not client.token_loaded:
        return redirect('/')

    res = client.get_contact_list()
    return json.dumps(res)
示例#30
0
def get_auth_code(client_id, client_secret, code):
    db = DB()
    try:
        if db.contains(code):
            auth_code = deepcopy(db.get(code))
            client = get_client(auth_code.client)
            if auth_code.expire + auth_code.created > time() and \
                   client.id == client_id and \
                   client.secret == client_secret:
                return auth_code
    except Exception, e:
        logging.error(''.join(['get_auth_code: ', str(e)]))
示例#31
0
文件: shell.py 项目: xinni-ge/eclcli
    def main(self, argv):
        parsed = self.parse_args(argv)
        if parsed == 0:
            return 0
        api_version, args = parsed

        # Short-circuit and deal with help command right away.
        if args.func == self.do_help:
            self.do_help(args)
            return 0
        elif args.func == self.do_bash_completion:
            self.do_bash_completion(args)
            return 0

        if not ((self.auth_plugin.opts.get('token')
                 or self.auth_plugin.opts.get('auth_token'))
                and self.auth_plugin.opts['endpoint']):
            if not self.auth_plugin.opts['username']:
                raise exc.CommandError("You must provide a username via "
                                       "either --os-username or via "
                                       "env[OS_USERNAME]")

            if not self.auth_plugin.opts['password']:
                raise exc.CommandError("You must provide a password via "
                                       "either --os-password or via "
                                       "env[OS_PASSWORD]")

            if self.no_project_and_domain_set(args):
                # steer users towards Keystone V3 API
                raise exc.CommandError("You must provide a project_id via "
                                       "either --os-project-id or via "
                                       "env[OS_PROJECT_ID] and "
                                       "a domain_name via either "
                                       "--os-user-domain-name or via "
                                       "env[OS_USER_DOMAIN_NAME] or "
                                       "a domain_id via either "
                                       "--os-user-domain-id or via "
                                       "env[OS_USER_DOMAIN_ID]")

            if not self.auth_plugin.opts['auth_url']:
                raise exc.CommandError("You must provide an auth url via "
                                       "either --os-auth-url or via "
                                       "env[OS_AUTH_URL]")

        client_kwargs = vars(args)
        client_kwargs.update(self.auth_plugin.opts)
        client_kwargs['auth_plugin'] = self.auth_plugin
        client = monitoringclient.get_client(api_version, **client_kwargs)
        # call whatever callback was selected
        try:
            args.func(client, args)
        except exc.HTTPUnauthorized:
            raise exc.CommandError("Invalid OpenStack Identity credentials.")
示例#32
0
def get_volume(service, action):
    MPDCLIENT = get_client()
    
    MPDCLIENT.connect()

    status = MPDCLIENT.status()
    action.set_value("CurrentVolume", str(status.get('volume', '0')))
    MPDCLIENT.disconnect()

    print "Get Volume %s" % status.get('volume', 0)

    getattr(action, "return")()
示例#33
0
文件: diff.py 项目: Naveengnn/one
def get_hash(mf_path):
    try:
        client = c.get_client()
        path = os.path.dirname(mf_path)
        if path == '/':
            path = ''
        contents = client.get_folder_contents_iter('mf:' + path + '/')
        for item in contents:
            if type(item) is File:
                if (item['filename'] == os.path.basename(mf_path)):
                    return item['hash']
        return ''
    except requests.exceptions.RequestException:
        logger.die('Network error, please check network status and try again')
示例#34
0
def setup_mpd():
    global CON_ID, MPDCLIENT, HOST, PORT
    CON_ID = {'host':HOST, 'port':PORT}

    client.MPDCLIENT = MPDClient(CON_ID)
    
    import server
    library.LIBRARY = MPDLibrary(client.get_client(),
                                 CON_ID, server.get_context(),
                                 MUSIC_PATH)

    library.LIBRARY.start_updating()
    
    print "Scheduling MPD Database refresh every 60 seconds..."
示例#35
0
文件: diff.py 项目: cdpetty/one
def get_hash(mf_path):
  try:
    client = c.get_client()  
    path = os.path.dirname(mf_path)
    if path == '/':
      path = ''
    contents = client.get_folder_contents_iter('mf:' + path + '/')
    for item in contents:
      if type(item) is File:
        if (item['filename'] == os.path.basename(mf_path)):
          return item['hash']
    return ''
  except requests.exceptions.RequestException:
    logger.die('Network error, please check network status and try again')
def mqtt_client(ctx: Context, project_id: str, cloud_region: str,
                registry_id: str, device_id: str, private_key_file: str,
                algorithm: str, mqtt_bridge_hostname: str,
                mqtt_bridge_port: int, ca_certs: str):
    password = create_jwt(project_id, private_key_file, algorithm)
    client = get_client(project_id, cloud_region, registry_id, device_id,
                        password, mqtt_bridge_hostname, mqtt_bridge_port,
                        ca_certs)

    time.sleep(2)

    # Ensure that ctx.obj exists and is a dict
    ctx.ensure_object(dict)
    ctx.obj[CLIENT] = client
    ctx.obj[DEVICE_ID] = device_id
示例#37
0
def set_volume(service, action):
    MPDCLIENT = get_client()
    volume = action.get_value("DesiredVolume", GObject.TYPE_INT)
    print "Set Volume", volume

    try:    
      MPDCLIENT.connect()
      MPDCLIENT.setvol(volume)
      MPDCLIENT.disconnect()
    except:
      MPDCLIENT.disconnect()
      action.return_error(32, "Couldn't set volume (possible that MPD is paused?)")
      return

    getattr(action, "return")()
示例#38
0
async def callback_handler(request):
    '''endpoint for redirection following successful sign in'''
    await check_state(request)

    if 'code' not in request.query:
        raise web.HTTPBadRequest(text='must provide code')

    oidc_client = client.get_client(request)
    id_token = await oidc_client.exchange_auth_code(request)
    if id_token:
        session = await get_session(request)
        session['id_token'] = id_token
        rd = request.query['rd']
        return web.HTTPFound(rd)
    return web.HTTPUnauthorized(text='bad token exchange')
示例#39
0
async def auth_handler(request):
    '''endpoint for nginx.ingress.kubernetes.io/auth-url. nginx makes a request
    here, if it gets 401 or 403 it redirects to the signin handler, otherwise
    we should give 200 and the response to the original url will proceed.

    '''
    oidc_client = client.get_client(request)

    id_token = await oidc_client.get_id_token(request)

    if id_token:
        headers = {'X-Auth-ID': json.dumps(oidc_client.profile_data(id_token))}
        return web.Response(text='OK', headers=headers)

    return web.HTTPUnauthorized()
示例#40
0
    def __init__(self,
                 namespace=None,
                 name="light0",
                 bw_entity="light.ent",
                 bw_agent=None):
        if namespace is None:
            namespace = os.environ.get('NAMESPACE')
        if namespace is None:
            raise Exception("Need to provide a namespace or set NAMESPACE")

        self._url = namespace + "/s.light/" + name + "/i.boolean/slot/state"

        # init light bulb
        img_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                "images")
        img_light_on_path = os.path.join(img_path, "light_on.png")
        img_light_off_path = os.path.join(img_path, "light_off.png")
        self._img_light_on = open(img_light_on_path, "rb").read()
        self._img_light_off = open(img_light_off_path, "rb").read()
        self._light = widgets.Image(
            value=self._img_light_off,
            format='png',
            width=75,
            height=120,
        )

        text_layout = widgets.Layout(width="500px", height='100px')
        self._text = widgets.Textarea(
            value='',
            description='Event Log:',
            disabled=False,
            layout=text_layout,
        )

        # init a box widget
        items = (self._light, self._text)
        box_layout = widgets.Layout(
            display='flex',
            flex_flow='row',
            align_items='center',
            border='none',
            width='100%',
        )
        self._box = widgets.Box(children=items, layout=box_layout)

        # init WAVE client
        self._bw_client = get_client(agent=bw_agent, entity=bw_entity)
        self._bw_client.subscribe(self._url, self._callback)
示例#41
0
文件: delete.py 项目: cdpetty/one
def delete(file_path):
  '''Deletes file with name "filename" from
  MediaFire account.'''
  if (user.is_user_signed_in()):
    client = c.get_client()
    file_path = sanitize_path(file_path)
    if (check_existance(file_path, client)):
      try: 
        client.delete_file('mf:' + file_path)
        logger.log('File "' + os.path.basename(file_path) + '" successfully deleted.')
      except requests.exceptions.RequestException:
        logger.die('Network error, please check network status and try again')
    else:
      logger.die('File with path and name "' + file_path + '" does not exist.')
  else:
    user.get_auth()
示例#42
0
async def signin_handler(request):
    '''endpoint for nginx.ingress.kubernetes.io/auth_signin nginx redirects us here
    if the original auth_request gave something other than 200

    '''
    oidc_client = client.get_client(request)

    redirect = oidc_client.redirect_uri(request)

    state = secrets.token_urlsafe()
    session = await get_session(request)
    session['state'] = state
    redirect_url = oidc_client.signin_url.update_query(state=state,
                                                       redirect_uri=redirect)

    return web.HTTPFound(redirect_url)
示例#43
0
def campaigns():

    #bJnLIM4IhJbNrdJYeojJjatuBhFA
    #ouOXMZAArBobj4FA078EPPi9elZd4ieyNAEm6meQjj

    client = get_client(client_id=CLIENT_ID,
                        secret=SECRET,
                        redirect_uri=REDIRECT_URI,
                        scope=SCOPE,
                        response_type=RESPONSE_TYPE)

    if not client.token_loaded:
        return redirect('/')

    res = client.get_campaigns()
    return json.dumps(res)
def create_access_token_from_code(auth_code):
    client = get_client(auth_code.client)
    user = get_user(auth_code.user)

    db = DB()
    try:
        token = AccessToken(client.id, user.id, scope=auth_code.scope)
        while db.contains(token.code):
            token = AccessToken(client.id, user.id, scope=auth_code.scope)
        db.put(token.code, token)

        db.commit()

        return token.code
    except Exception, e:
        logging.error("".join(["create_access_token_from_code: ", str(e)]))
        db.abort()
def create_refresh_token_from_user_pass(client_id,
                                        client_secret,
                                        user_id,
                                        password,
                                        scope,
                                        access_token):
    try:
        client = None
        if client_id != None:
            client = get_client(client_id)
        else:
            #not using client credentials do just create
            #a client object from user credentials
            client = Client(user_id, user_id, password, None)
            #make client_secret equal password
            client_secret = password
            
        user = get_user(user_id)
        if client != None and \
               user != None and \
               client.secret == client_secret and \
               user.password == password:
            db = DB()
            try:
                token = RefreshToken(access_token.code,
                                     client.id,
                                     user.id,
                                     scope=scope)
                while db.contains(token.code):
                    token = RefreshToken(access_token.code,
                                         client.id,
                                         user.id,
                                         scope=scope)
                db.put(token.code, token)
                
                db.commit()

                return token.code
            except Exception, e:
                logging.error(''.join(['create_refresh_token_from_user_pass: ',
                                       str(e)]))
                db.abort()
            finally:
                db.close()
示例#46
0
文件: delete.py 项目: Naveengnn/one
def delete(file_path):
    '''Deletes file with name "filename" from
  MediaFire account.'''
    if (user.is_user_signed_in()):
        client = c.get_client()
        file_path = sanitize_path(file_path)
        if (check_existance(file_path, client)):
            try:
                client.delete_file('mf:' + file_path)
                logger.log('File "' + os.path.basename(file_path) +
                           '" successfully deleted.')
            except requests.exceptions.RequestException:
                logger.die(
                    'Network error, please check network status and try again')
        else:
            logger.die('File with path and name "' + file_path +
                       '" does not exist.')
    else:
        user.get_auth()
示例#47
0
def associate_client_with_user(user_id, client_id, refresh_token_str):
    """
    Adds client to list of authorised clients who can access the users resources on a long term basis
    """
    client = get_client(client_id)
    user = get_user(user_id)
    refresh_token = get_token(client.id, client.secret, refresh_token_str)
    ## before going further, see if client is confidential or not.
    ## If confidential then it is assumed to be able to keep the
    ## username and password secret from itself.  If this is the
    ## case then it's allowed to continue, else throw a
    ## ConfindentialError.
    if client.type.lower() != 'confidential':
        client_id = refresh_token.client
        raise ConfidentailError('Client ' + client_id + \
                                ' is not a confidentail client')
    

    
    db = DB()
    try:
        key = 'client_association_' + str(user.id)
        if db.contains(key):
            association = db.get(key)
            if client.id not in association.clients:
                association.clients[client.id] = refresh_token.code
                db.update(key, association)
            else:
                raise AssociationExistsWarning(''.join(['Client ',
                                                        str(client.id),
                                                        ' is already associated with ',
                                                        str(user.id)]))
        else:
            association = Association(user.id)
            association.clients[client.id] = refresh_token.code
            db.put(key, association)
            
        db.commit()
    except Exception, e:
        logging.error(''.join(['associate_client_with_user: ', str(e)]))
        raise e
        db.abort()
示例#48
0
    def __init__(self,
                 namespace=None,
                 name="switch0",
                 bw_entity="switch.ent",
                 bw_agent=None):
        if namespace is None:
            namespace = os.environ.get('NAMESPACE')
        if namespace is None:
            raise Exception("Need to provide a namespace or set NAMESPACE")

        self._url = namespace + "/s.switch/" + name + "/i.boolean/signal/state"

        # init switch
        self._switch = widgets.ToggleButtons(
            options=['Turn On', 'Turn Off'],
            disabled=False,
            button_style='',
            tooltips=['Turn on the light', 'Turn off the light'])
        self._switch.value = "Turn Off"
        self._switch.observe(self._switch_on_click, 'value')

        text_layout = widgets.Layout(width="500px", height='100px')
        self._text = widgets.Textarea(
            value='',
            description='Event Log:',
            disabled=False,
            layout=text_layout,
        )

        # init a box widget
        items = (self._switch, self._text)
        box_layout = widgets.Layout(
            display='flex',
            flex_flow='row',
            align_items='center',
            border='none',
            width='100%',
        )
        self._box = widgets.Box(children=items, layout=box_layout)

        # init WAVE client
        self._switch_bw_client = get_client(agent=bw_agent, entity=bw_entity)
示例#49
0
def create_auth_code(client_id, uid, scope=None):
    client = get_client(client_id)
    user = get_user(uid)
    db = DB()
    try:
        auth_code = AuthCode(client.id, user.id, scope=scope)
        while db.contains(auth_code.code):
            token = AccessToken(client.id,
                                user.id,
                                scope=scope)
        db.put(auth_code.code, auth_code)
        db.commit()
        code = auth_code.code
        
        return code
    
    except Exception, e:
        logging.error(''.join(['create_auth_code: ', str(e)]))
        db.abort()
        raise e
示例#50
0
def handle_state_request(service, action):
    MPDCLIENT = get_client()
    LIBRARY = get_library()
    print "Status"
    
    MPDCLIENT.connect()
    status = MPDCLIENT.status()
    MPDCLIENT.disconnect()

    if status and status['state'] == "pause":
        state = "PAUSED_PLAYBACK"
    elif status and status['state'] == "play":
        state = "PLAYING"
    else:
        state = "STOPPED"

    action.set_value("CurrentTransportState", state)
    action.set_value("CurrentTransportStatus", "OK")
    action.set_value("CurrentSpeed", "1")
    
    getattr(action, "return")()
示例#51
0
def set_http_uri(service, action, uri):
    """
    This is a bit tricker.  We need to download the file from the local network
    (hopefully its quick), add the file to MPD (the file has to be 100% downloaded first)
    then add the file to the playlist and seek to it.

    1) Download file
    2) Add file to DB
    3) Load file to local library
    4) Generate an MPD uri and then call set_mpd_uri
    """
    LIBRARY = get_library()
    MPDCLIENT = get_client()
    from server import get_context, MUSIC_PATH
    CONTEXT = get_context()

    path = uri.replace("http:/", "")
    filename = os.path.basename(path)

    if not "." in filename:
        filename += ".mp3" # assume mp3 for now
    
    os.system("wget %s -O %s/%s" % (uri, MUSIC_PATH, filename))
    
    LIBRARY.connect()
    MPDCLIENT.update(filename)
    
    songdata = MPDCLIENT.find('file', filename)
    if not songdata:
        action.return_error(0, "Couldn't add file to MPD database")
        return
    
    song_id = LIBRARY.register_song(LIBRARY.song_from_dict(songdata[0]))

    LIBRARY.disconnect()
    set_mpd_uri(service, action, "http://%s:%s/file/%s" % (
        CONTEXT.get_host_ip(),
        CONTEXT.get_port(),
        song_id)
                )
示例#52
0
    def open(self, identifier):
        '''
        Handle an incoming connection. Opens up a new channel with the client
        that has this IP.

        :param identifier: Identifier
        :return: None
        '''
        self.setup()
        self.ip = self.request.remote_ip
        logging.info('Creating client for %s from %s' %
                     (self.remote_host, self.ip) + ' |' + str(self))
        self.client = client.get_client(self.ip, self.remote_host, self)
        ppdata = pprint.pformat([{
            c.ws: (c.ip, c.host)
        } for c in client.clients.values()])
        logging.info("Current clients on connection==================")
        logging.info(ppdata)
        num_channels = len(self.client.channels)
        if num_channels >= config.getint('server',
                                         'max_connections_per_client'):
            logging.warning("Connection limit for client %s reached" % self.ip)
            # Notify and close connection again
            self.id = -1
            self.send(
                'handler_unidentifiable', 'error', {
                    'msg':
                    'Maximum number of connections for this client' +
                    ' reached'
                })
            self.on_close()
            self.close()
            return
        self.id = self.client.add_channel(self)
        client_name = self.client.name
        if client_name is None:
            client_name = 'Unknown client'
        logging.info('%s from %s is now connected as websocket, channel %d' %
                     (client_name, self.ip, self.id))
示例#53
0
文件: spot.py 项目: kiriclope/binance
#!/usr/bin/env python3

import math 
import click
from client import get_client
from binance.exceptions import BinanceAPIException, BinanceOrderException 

client = get_client() 

@click.command() 
@click.argument('side') 
@click.argument('order_type') 
@click.argument('symbol') 
@click.option('--test','-t', default=False, is_flag=True) 
@click.option('--percentage', '-p', default=1, type=float) 
@click.option('--mrk_per', '-m', default=0, type=float) 

def make_order(side, order_type, symbol, test, percentage, mrk_per):
    
    if symbol.endswith('USDT'): 
        asset = symbol[:-4]
        base = 'USDT' 
    else: # BTC or BNB 
        asset = symbol[:-3]
        base = symbol[-3:]
        
    asset_balance = client.get_asset_balance(asset=asset) 
    base_balance = client.get_asset_balance(asset=base) 
    current_price = client.get_symbol_ticker(symbol=symbol)
    
    print(asset_balance)    
示例#54
0
        update_subscriptions(mqtt, payload, custom_callback)
    elif 'ot/riders/searching' in message.topic:
        print_updated_locations(payload)
    else:
        print("--------------")
        print(message.topic, ':')
        print(payload)
        print("--------------")

role_name = 'open-taxi-sls-DriversRole-1S0DSO6ZWQE9'
session_name = 'example-driver'
credentials = client.get_credentials_for_role(role_name, session_name)
client_id = credentials['client_id']
reply_topic = f'ot/replies/{client_id}'

mqtt = client.get_client(credentials)
mqtt.connect()

print('subscribing to', reply_topic)
mqtt.subscribe(reply_topic, 1, custom_callback)
time.sleep(2)

start_time = datetime.now()

path = [
    [51.509541, -0.076598],
    [51.509804, -0.088039],
    [51.511115, -0.096459],
    [51.510974, -0.107735],
    [51.509745, -0.118489],
    [51.507234, -0.126293],
示例#55
0
def shutdown_event():
    es_client = get_client()
    es_client.close()
示例#56
0
def main(reactor):
    settings = get_settings()
    client = get_client()
    return SUBCOMMANDS[settings['subparser_name']](settings, client)
示例#57
0
import googleads
import client

ga_client = client.get_client()
company_service = ga_client.GetService('CompanyService', version='v201811')


def get(name):
    if name is None:
        return None

    statement = (googleads.ad_manager.StatementBuilder().Where(
        'type = :type').WithBindVariable(
            'type',
            'ADVERTISER').Where('name = :name').WithBindVariable('name', name))

    response = company_service.getCompaniesByStatement(statement.ToStatement())
    if 'results' in response and len(response['results']):
        for advertiser in response['results']:
            return advertiser

    return None


def printOut():
    statement = (googleads.ad_manager.StatementBuilder().Where(
        'type = :type').WithBindVariable('type', 'ADVERTISER'))

    response = company_service.getCompaniesByStatement(statement.ToStatement())
    if 'results' in response and len(response['results']):
        print('Found %s Advertiser(s):' % len(response['results']))
示例#58
0
def test_touch():
    from client import get_client
    client = get_client()
    resp = client.hello('hello')
    assert 'hello' in str(resp)