Beispiel #1
0
    def post(self, name):
        bot = auth_util.get_bot(flask.request)

        service = Service.get(name, parent=bot.key)
        Service.clear_credentials(service)
        ds_util.client.put(service)
        return WrapEntity(service)
Beispiel #2
0
def _withings_trainerroad(request, user_key, measure):
    params = task_util.get_payload(request)
    user_key = params['user_key']
    measure = params['measure']
    logging.info('ProcessMeasure: withings_trainerroad: %s %s', user_key,
                 measure)

    trainerroad_service = Service.get('trainerroad', parent=user_key)
    if not Service.has_credentials(trainerroad_service,
                                   required_key='password'):
        logging.debug('ProcessMeasure: Trainerroad not connected')
        return responses.OK

    if not measure.get('weight'):
        logging.debug('ProcessMeasure: Skipping non-weight measure.')
        return responses.OK

    try:
        client = trainerroad_create_client(trainerroad_service)
        with client:
            client.weight = measure['weight']
    except Exception:
        logging.exception('ProcessMeasure: Failed: %s', measure)
        return responses.OK_SYNC_EXCEPTION
    return responses.OK
Beispiel #3
0
 def post(self, name):
     user = auth_util.get_user(flask.request)
     connect_userpass = api.payload
     service = Service.get(name, parent=user.key)
     Service.update_credentials_userpass(service, connect_userpass)
     ds_util.client.put(service)
     return WrapEntity(service)
Beispiel #4
0
    def refresh_callback(new_credentials):
        """Updates credentials.

        Params:
            new_credentials: withings_api.Credentials2
        """
        logging.debug('Withings creds refresh for: %s', service.key)
        creds_dict = create_creds_dict(new_credentials)
        Service.update_credentials(service, creds_dict)
Beispiel #5
0
 def post(self):
     user = auth_util.get_user(flask.request)
     backfill = api.payload
     source = Service.get(backfill['source'], parent=user.key)
     dest = Service.get(backfill['dest'], parent=user.key)
     start = datetime.datetime.fromisoformat(backfill.get('start'))
     end = datetime.datetime.fromisoformat(backfill.get('end'))
     task_util.xsync_tasks_backfill(source.key, dest.key, start, end)
     # TODO: pre-check there are credentials.
     return backfill
Beispiel #6
0
    def get(self):
        user = auth_util.get_user(flask.request)
        strava = Service.get('strava', parent=user.key)
        strava_connected = Service.has_credentials(strava)
        athlete = Athlete.get_private(strava.key)

        return dict(
            user=WrapEntity(user),
            athlete=WrapEntity(athlete),
            signup_complete=strava_connected,
        )
Beispiel #7
0
def _oauth(request: flask.Request, user: Entity, dest: str):
    code = request.args.get('code')
    service = Service.get(SERVICE_NAME, parent=user.key)
    client = stravalib.client.Client()
    creds = client.exchange_code_for_token(
        client_id=config.strava_creds['client_id'],
        client_secret=config.strava_creds['client_secret'],
        code=code,
    )
    Service.update_credentials(service, dict(creds))
    task_util.sync_service(service)
    return flask.redirect(config.devserver_url + dest)
Beispiel #8
0
def redirect(user):
    service = Service.get(SERVICE_NAME, parent=user.key)

    code = flask.request.args.get('code')
    dest = flask.request.args.get('dest', '')

    auth = create_auth(callback_uri=get_callback_uri(dest))

    creds_dict = create_creds_dict(auth.get_credentials(code))
    Service.update_credentials(service, creds_dict)

    task_util.sync_service(service)

    return flask.redirect(config.devserver_url + dest)
Beispiel #9
0
 def _refresh_access_token(self):
     if self._service['credentials'].get('refresh_token') is None:
         logging.warning(
             'Cannot refresh_access_token for %s, no refresh_token',
             self._service.key,
         )
         return False
     new_credentials = self._client.refresh_access_token(
         client_id=config.strava_creds['client_id'],
         client_secret=config.strava_creds['client_secret'],
         refresh_token=self._service['credentials']['refresh_token'],
     )
     Service.update_credentials(self._service, dict(new_credentials))
     self._client.access_token = self._service['credentials'][
         'access_token']
     return True
Beispiel #10
0
 def post(self, name):
     user = auth_util.get_user(flask.request)
     new_service = api.payload
     existing_service = Service.get(name, parent=user.key)
     existing_service.update(new_service)
     ds_util.client.put(existing_service)
     return WrapEntity(existing_service)
Beispiel #11
0
    def post(self, name):
        bot = auth_util.get_bot(flask.request)

        force = api.payload.get('force', False)
        service = Service.get(name, parent=bot.key)
        task_util.sync_service(service, force=force)
        return WrapEntity(service)
Beispiel #12
0
 def get(self):
     bot = auth_util.get_bot(flask.request)
     service = Service.get('slack', parent=bot.key)
     query = ds_util.client.query(kind='SlackWorkspace',
                                  ancestor=service.key)
     workspaces = [e for e in query.fetch()]
     return {'service': WrapEntity(service), 'workspaces': workspaces}
Beispiel #13
0
    def get(self, club_id):
        bot = auth_util.get_bot(flask.request)

        service = Service.get('strava', parent=bot.key)
        club = StravaClubWorker(club_id, service).sync_club()

        return WrapEntity(club)
Beispiel #14
0
    def get(self):
        bot = auth_util.get_bot(flask.request)

        service = Service.get('strava', parent=bot.key)
        club_query = ds_util.client.query(kind='Club', ancestor=service.key)

        return [WrapEntity(club) for club in club_query.fetch()]
Beispiel #15
0
 def get(self):
     user = auth_util.get_user(flask.request)
     service = Service.get('strava', parent=user.key)
     segments_query = ds_util.client.query(
         kind='Segment', ancestor=service.key, order=['-id']
     )
     segments = [WrapEntity(a) for a in segments_query.fetch()]
     return segments
Beispiel #16
0
    def get(self, club_id):
        bot = auth_util.get_bot(flask.request)

        service = Service.get('strava', parent=bot.key)
        club = Club.get(club_id, parent=service.key)
        if club is not None:
            ds_util.client.delete(club.key)

        return None
Beispiel #17
0
def redirect(user):
    service = Service.get(SERVICE_NAME, parent=user.key)

    code = flask.request.args.get('code')
    dest = flask.request.args.get('dest', '')

    auth_client = fitbit.FitbitOauth2Client(
        client_id=config.fitbit_creds['client_id'],
        client_secret=config.fitbit_creds['client_secret'],
        redirect_uri=get_redirect_uri(dest),
    )
    creds = auth_client.fetch_access_token(code)

    Service.update_credentials(service, creds)

    task_util.sync_service(service)

    return flask.redirect(config.devserver_url + dest)
Beispiel #18
0
def _oauth(user: Entity, dest: str, redirect_uri: str):
    """Step 2. Stores credentials."""
    service = Service.get(SERVICE_NAME, parent=user.key)

    state = flask.session['state']
    flow = google_auth_oauthlib.flow.Flow.from_client_config(
        config.gcp_web_creds, scopes=SCOPES, state=state)
    flow.redirect_uri = redirect_uri

    authorization_response = flask.request.url
    logging.debug('auth_response: %s', authorization_response)
    flow.fetch_token(authorization_response=authorization_response)
    creds = _credentials_to_dict(flow.credentials)
    logging.debug('creds: %s', creds)

    Service.update_credentials(service, creds)

    task_util.sync_service(Service.get(SERVICE_NAME, parent=user.key))
    return flask.redirect(config.devserver_url + dest)
Beispiel #19
0
def _create_slack_client_for_team(team_id):
    slack_service = Service.get('slack', parent=Bot.key())
    installation_store = DatastoreInstallationStore(ds_util.client,
                                                    parent=slack_service.key)
    slack_bot = installation_store.find_bot(
        enterprise_id=None,
        team_id=team_id,
        is_enterprise_install=False,
    )
    return WebClient(slack_bot.bot_token)
Beispiel #20
0
def sync_task():
    services_query = ds_util.client.query(kind='Service')
    services_query.add_filter('sync_enabled', '=', True)
    services_query.add_filter('syncing', '=', False)
    services = [
        service for service in services_query.fetch()
        if Service.has_credentials(service)
    ]
    task_util.sync_services(services)
    return responses.OK
Beispiel #21
0
    def do():
        for service in services:
            if service['sync_state'].get('syncing') and force:
                logging.debug('Forcing sync finished: %s', service.key)
                Service.set_sync_finished(service, error='Forced sync')

            if service['sync_state'].get('syncing'):
                logging.debug('Not enqueuing sync for %s; already started.',
                              service.key)
                continue
            Service.set_sync_enqueued(service)
            task = {
                'entity': _params_entity(service_key=service.key),
                'relative_uri':
                '/services/%s/tasks/sync' % (service.key.name, ),
                'service': 'backend',
            }
            _queue_task(**task)
            logging.debug('Added: %s', task)
Beispiel #22
0
 def get(self):
     user = auth_util.get_user(flask.request)
     service = Service.get('strava', parent=user.key)
     segments_arg = get_arg('segments')
     segments = []
     for segment_id in segments_arg:
         entity = ds_util.client.get(
             ds_util.client.key('Segment', segment_id, parent=service.key)
         )
         segments.append(WrapEntity(entity))
     return segments
Beispiel #23
0
    def test_process_event_task_no_credentials(
        self, ds_util_client_get_mock, ds_util_client_put_mock, withings_worker_mock
    ):

        service = Entity(ds_util.client.key('Service', 'withings'))
        Service._set_defaults(service)
        _setup_service_get_put(
            service, ds_util_client_get_mock, ds_util_client_put_mock
        )

        event_entity = Entity(
            ds_util.client.key('SubscriptionEvent', parent=service.key)
        )

        r = self.client.post(
            '/tasks/event',
            data=task_util.task_body_for_test(event=event_entity),
        )
        responses.assertResponse(self, responses.OK_NO_CREDENTIALS, r)
        withings_worker_mock.assert_not_called()
Beispiel #24
0
 def get(self):
     user = auth_util.get_user(flask.request)
     service = Service.get('strava', parent=user.key)
     activities_query = ds_util.client.query(
         kind='Activity', ancestor=service.key, order=['-start_date']
     )
     one_year_ago = datetime.datetime.now(
         datetime.timezone.utc
     ) - datetime.timedelta(days=365)
     activities_query.add_filter('start_date', '>', one_year_ago)
     return [WrapEntity(a) for a in activities_query.fetch(limit=20)]
Beispiel #25
0
    def get(self):
        bot = auth_util.get_bot(flask.request)

        user_entities = [bot]
        user_entities += ds_util.client.query(kind='User').fetch()
        users = []
        for user_entity in user_entities:
            users.append({
                'user':
                WrapEntity(user_entity),
                'google':
                Service.get('google', parent=user_entity.key),
                'strava':
                Service.get('strava', parent=user_entity.key),
                'withings':
                Service.get('withings', parent=user_entity.key),
                'fitbit':
                Service.get('fitbit', parent=user_entity.key),
            })

        return users
Beispiel #26
0
    def get(self, club_id):
        club_id = int(club_id)
        auth_util.get_user(flask.request)

        bot_strava = Service.get('strava', parent=Bot.key())
        club = Club.get(club_id, parent=bot_strava.key)

        # Find the user's club reference.
        if club is None:
            flask.abort(404)

        return WrapEntity(club)
Beispiel #27
0
    def test_process_event_task_valid_strava(
        self, ds_util_client_get_mock, ds_util_client_put_mock, strava_worker_mock
    ):

        service = Entity(ds_util.client.key('Service', 'strava'))
        Service._set_defaults(service)
        service['credentials'] = {'refresh_token': 'validrefreshtoken'}
        _setup_service_get_put(
            service, ds_util_client_get_mock, ds_util_client_put_mock
        )

        event_entity = Entity(
            ds_util.client.key('SubscriptionEvent', parent=service.key)
        )

        r = self.client.post(
            '/tasks/event',
            data=task_util.task_body_for_test(event=event_entity),
        )
        responses.assertResponse(self, responses.OK, r)
        strava_worker_mock.assert_called_once()
Beispiel #28
0
def _create_slack_client(event):
    slack_service = Service.get('slack', parent=Bot.key())
    installation_store = DatastoreInstallationStore(ds_util.client,
                                                    parent=slack_service.key)
    slack_bot = installation_store.find_bot(
        enterprise_id=event.get('authorizations',
                                [{}])[0].get('enterprise_id'),
        team_id=event.get('authorizations', [{}])[0].get('team_id'),
        is_enterprise_install=event.get('authorizations',
                                        [{}])[0].get('is_enterprise_install'),
    )
    return WebClient(slack_bot.bot_token)
Beispiel #29
0
def _create_unfurls(event):
    strava = Service.get('strava', parent=Bot.key())
    strava_client = ClientWrapper(strava)

    unfurls = {}
    for link in event['event']['links']:
        alt_url = _resolve_rewrite_link(link)
        unfurl = _unfurl(strava_client, link, alt_url)
        if unfurl:
            unfurls[link['url']] = unfurl
    logging.warning(f'_create_unfurls: {unfurls}')
    return unfurls
Beispiel #30
0
def sync():
    logging.debug('Syncing: google')
    payload = task_util.get_payload(flask.request)

    service = ds_util.client.get(payload['service_key'])
    if not Service.has_credentials(service):
        Service.set_sync_finished(service, error='No credentials')
        return responses.OK_NO_CREDENTIALS

    try:
        Service.set_sync_started(service)
        client = create_gmail_client(service)
        sync_helper.do(Worker(service, client), work_key=service.key)
        Service.set_sync_finished(service)
        return responses.OK
    except SyncException as e:
        Service.set_sync_finished(service, error=str(e))
        return responses.OK_SYNC_EXCEPTION