예제 #1
0
def get_client(config):
    client = RestConnectClient(
        data_get(config, 'auth.auth_scope'),
        data_get(config, 'auth.api_key'),
        host=data_get(config, 'api.host', helpsocial.API_HOST),
        ssl=data_get(config, 'api.ssl'),
        request_hooks=[RequestPrinter()],
        response_hooks=[ResponsePrinter()]
    )

    if data_get(config, 'social.user_token') is not None:
        client.set_user_token(data_get(config, 'social.user_token'))
        return client
    if data_get(config, 'auth.user_token') is not None:
        client.set_user_token(data_get(config, 'auth.user_token'))
        return client

    username = data_get(config, 'social.username')
    if username is None:
        username = input('username: '******'social.password')
    if password is None:
        password = getpass.getpass('password: '******'value')
    client.set_user_token(user_token)
    return client
예제 #2
0
def json_stream(stream, config_path, ttl=None, **kwargs):
    """Demo reading from a json stream. Each json entity is
    printed to the console using a `ConsolePrintWorker`. The demo can
    be completed killed issuing a keyboard interrupt or any other
    kill sig.

    :type stream: string
    :param stream:

    :type config_path: string
    :param config_path:

    :type ttl: int
    :param ttl: the stream time to live, after which it will disconnect automatically
    """

    config = read_config(config_path)
    dispatcher = Dispatcher(ConsolePrintWorker())
    user_token = data_get(config, 'auth.user_token', authenticate(config))
    client = StreamingConnectClient(data_get(config, 'auth.auth_scope'),
                                    data_get(config, 'auth.api_key'),
                                    dispatcher,
                                    user_token=user_token,
                                    host=data_get(config, 'api.host'),
                                    ssl=data_get(config, 'api.ssl'),
                                    request_hooks=[RequestPrinter()],
                                    response_hooks=[StreamResponsePrinter()])

    def default_stream(*args, **kwargs):
        raise RuntimeError('Invalid stream option.')

    streams = {
        'activity': activity_stream,
        'conversation': conversation_stream,
        'events': event_stream,
    }

    try:
        stream = streams.get(stream, default_stream)
        start = time()
        stream(client, async=True, **kwargs)

        forever = ttl < 0
        while client.is_alive():
            if not forever and time() > (start + ttl):
                break
    except ApiException:
        pass
    except KeyboardInterrupt:
        pass
    finally:
        # Tell the client to stop the underlying
        # stream thread.
        client.shutdown()
예제 #3
0
def authorize_sse_stream(config_path):
    """Demo the retrieval of a SSE Stream authorization code.

    :type config_path: string
    :param config_path:
    """

    config = read_config(config_path)
    user_token = authenticate(config)

    client = RestConnectClient(data_get(config, 'auth.auth_scope'),
                               data_get(config, 'auth.api_key'),
                               user_token=user_token,
                               request_hooks=[RequestPrinter()],
                               response_hooks=[ResponsePrinter()])

    authorization = client.get_sse_authorization()
    print('\n\nRetrieved authorization token for user.')
    print('Authorization: ' + authorization)
예제 #4
0
def single(conversation_id, config_path):
    config = read_config(config_path)

    client = RestConnectClient(
        data_get(config, 'auth.auth_scope'),
        data_get(config, 'auth.api_key'),
        host=data_get(config, 'api.host'),
        ssl=data_get(config, 'api.ssl'),
        request_hooks=[RequestPrinter()],
        response_hooks=[ResponsePrinter()]
    )

    manager = Manager()
    manager.add_worker(Worker(client,
                              data_get(config, 'launch_conversation.spa_url'),
                              data_get(config, 'launch_conversation.user_token')))

    manager.queue(conversation_id)

    manager.start()
    while manager.has_pending():
        sleep(1)
    manager.stop()
예제 #5
0
def sse_stream(config_path,
               authorization=None,
               ttl=None,
               last_event_id=None,
               event_types=None):
    """Demo reading from a stream of server sent events. The events
    are printed to the console using a `ConsolePrintWorker`. The demo can
    be completed killed issuing a keyboard interrupt or any other
    kill sig.

    :type config_path: string
    :param config_path:

    :type authorization: string
    :param authorization: SSE authorization token.

    :type ttl: int
    :param ttl: the stream time to live, after which it will disconnect automatically

    :type last_event_id: int
    :param last_event_id: Last event processed

    :type event_types: list
    :param event_types: event types to stream.
    """

    config = read_config(config_path)
    dispatcher = Dispatcher(ConsolePrintWorker())
    user_token = data_get(config, 'auth.user_token', authenticate(config))

    client = StreamingConnectClient(data_get(config, 'auth.auth_scope'),
                                    data_get(config, 'auth.api_key'),
                                    dispatcher,
                                    user_token=user_token,
                                    host=data_get(config, 'api.host'),
                                    ssl=data_get(config, 'api.ssl'),
                                    request_hooks=[RequestPrinter()],
                                    response_hooks=[StreamResponsePrinter()])

    params = {'last_event_id': last_event_id, 'event_types': event_types}

    try:
        if authorization is None:
            authorization = RestConnectClient(
                data_get(config, 'auth.auth_scope'),
                data_get(config, 'auth.api_key'),
                user_token=user_token).get_sse_authorization()

        start = time()
        client.sse(authorization, params=params, async=True)

        forever = ttl < 0
        while client.is_alive():
            if not forever and time() > (start + ttl):
                break
    except ApiException:
        pass
    except KeyboardInterrupt:
        # We ignore the keyboard interrupt - The user sent it,
        # and knows they sent it
        pass
    finally:
        # Tell the client to stop the underlying
        # stream thread.
        client.shutdown()
예제 #6
0
config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                           '.config.ini')

if not os.path.exists(config_path):
    print("File '.config.ini' seems to not exist.")
    exit(-1)

parser = configparser.ConfigParser()
if not parser.read(config_path):
    print('Failed to read config file.')
    exit(-1)

client = RestConnectClient(parser.get('account', 'scope'),
                           parser.get('account', 'key'),
                           request_hooks=[RequestPrinter()])

if parser.get('account', 'user_token', fallback=None) is not None:
    client.set_user_token(parser.get('account', 'user_token'))
else:
    username = parser.get('account', 'username')
    password = parser.get('account', 'password')
    user_token = data_get(client.authenticate(username, password), 'value')
    client.set_user_token(user_token)

query = {
    'managed': True
    # 'accessible': True
    # 'network': 'twitter'
}
예제 #7
0
파일: auth.py 프로젝트: sp4ceb4r/py-client
def main(username, config=None):
    if not os.path.exists(config):
        raise IOError('{} does not exist.', config)

    # read the configuration file
    # it doesn't have to json, you just have
    # to be able to parse it.
    with open(config, 'r') as file_:
        config = json.load(file_)

    # create an instance of the RestConnectionClient
    # using the application authentication
    # parameters.
    #
    # We're also add a request and response hook
    # so that we can echo the raw request and
    # response data to the console.
    #
    # The host, version, and ssl options are not required
    # and default to helpsocial.API_HOST, helpsocial.API_VERSION, and True.
    client = RestConnectClient(
        data_get(config, 'auth.auth_scope'),
        data_get(config, 'auth.api_key'),
        host=data_get(config, 'api.host'),
        ssl=data_get(config, 'api.ssl'),
        request_hooks=[RequestPrinter()],
        response_hooks=[ResponsePrinter()]
    )

    # Request the password for the user
    # but don't show it (because it's a password)
    # though we are printing the request/response bodies so ...
    password = getpass.getpass('Password for {}: '.format(username))

    print('\n\n')

    try:
        # Create our request body as a dictionary
        # The helpsocial will handle serializing the
        # dictionary to the proper json.
        body = {
            'username': username,
            'password': password
        }

        # Call the helpsocial.post method directly
        # passing the path to the authentication resource ('tokens'),
        # the authentication provider,
        # and the json body.
        #
        # In the short hand helpers methods, such as helpsocial.authenticate
        # the helpsocial will handle setting up the default authentication.
        # The default authentication may still be overridden using
        # the auth parameter.
        response = client.post('tokens',
                               json=body,
                               auth=ApplicationAuth(
                                   data_get(config, 'auth.auth_scope'),
                                   data_get(config, 'auth.api_key')
                               ))

        # Retrieve the user's authentication token
        # from the json response.
        value = data_get(response.json(), 'data.token.value')

        print('\n\nPulled user authentication token'
              'from data.token.value.')
        print('TOKEN: {}'.format(value))
    except ApiException as ex:
        print('\n\n{} - {}'.format(
            ex.__class__.__name__,
            ex.message,
        ))