Example #1
0
 def log_out_user(user_id):
     try:
         r = requests.post(API_HOST + f'/admin/users/{user_id}/log_out',
                           params=AUTH_PARAMS,
                           timeout=TIMEOUT)
         raise_for_status(r)
     except requests.exceptions.RequestException as e:
         return {'exception': str(e)}
     return r.json()
Example #2
0
    def update_video_meta(t):
        if video_meta_synced(t.video):
            return

        url = t.video['url']
        path = download_file(url,
                             os.path.join(os.sep, 'tmp',
                                          url.split('/')[-1]))

        name_part = f'de {t.pretty_recipients(3, "y")} ' if t.recipients else ''
        locality = t.action.locality
        site_url = f'{os.getenv("CUSTOM_SITE_URL")}/proyectos/{t.action.id}?_mn=testimonial&_ms={t.id}'
        meta = {
            'snippet': {
                'categoryId': '29',  # nonprofits and activism
                'description':
                f'Testimonio de un proyecto de {t.action.action_label()} en {locality.name}, {locality.state_name}, realizado por {t.action.organization.name}.\n\n{site_url}',
                'title':
                f'Testimonio {name_part}en {locality.name}'[:
                                                            100],  # max title length is 100 chars
            },
            'status': {
                'privacyStatus': 'public'
            },
        }
        params = {'part': 'snippet,status', 'uploadType': 'resumable'}

        token = YoutubeAccessToken.objects.get(token_type='Bearer')
        headers = {'Authorization': 'Bearer {}'.format(token.access_token)}

        r = requests.post(
            'https://www.googleapis.com/upload/youtube/v3/videos',
            json=meta,
            headers=headers,
            params=params)
        raise_for_status(r)

        with open(path, 'rb') as data:
            r = requests.post(r.headers['location'],
                              headers=headers,
                              data=data)
            raise_for_status(r)

        data = r.json()
        t.video['synced'] = True
        t.video['youtube_response_data'] = data
        t.video['youtube_video_id'] = data['id']
        try:
            t.video['url_thumbnail'] = data['snippet']['thumbnails']['high'][
                'url']
        except:
            pass
        t.save()
Example #3
0
def get_user_ids(exclude_emails=None):
    r = requests.get(API_HOST + '/admin/users.json',
                     params={
                         **AUTH_PARAMS,
                         **{
                             'show_emails': 'true'
                         }
                     },
                     timeout=TIMEOUT)
    raise_for_status(r)
    exclude_emails = exclude_emails or []
    return [
        user['id'] for user in r.json() if user['email'] not in exclude_emails
    ]
Example #4
0
def get_recent_form_submissions(form_id, past_days=1):
    date = datetime.today() - timedelta(days=past_days)
    r = requests.get(
        API_HOST + f'/data/{form_id}',
        params={
            'query':
            '{"_submission_time": {"$gte": "' + date.strftime('%Y-%m-%d') +
            '"}}'
        },
        auth=TokenAuth('Token', AUTH_TOKEN),
        timeout=TIMEOUT,
    )
    raise_for_status(r)
    return r.json()
Example #5
0
def sync_landing_page_data() -> None:
    data_file_path = '/tmp/landing_data.json.gz'
    r = requests.get('https://api.brigada.mx/api/landing/')
    raise_for_status(r)

    with gzip.open(data_file_path, 'wb') as f:
        f.write(bytes(json.dumps(r.json()), 'utf-8'))

    s3 = get_s3_client()
    with open(data_file_path, 'rb') as data:
        s3.upload_fileobj(data,
                          'brigada.mx',
                          'landing_data.json',
                          ExtraArgs={
                              'ACL': 'public-read',
                              'CacheControl': 'max-age=43200',
                              'ContentType': 'application/json',
                              'ContentEncoding': 'gzip',
                          })
Example #6
0
    def get(self, request, *args, **kwargs):
        action_fields = 'id,locality,organization,donations,action_type,budget,target,unit_of_measurement,preview'
        action_query = f'?level__gte=2&has_start_date=true&ordering=-start_date&page_size=100&fields={action_fields}'
        opportunities_query = '?transparency_level__gte=2&ordering=-created&page_size=100'

        paths = [
            ('metrics', '/landing_metrics/'),
            ('localities', '/localities_with_actions/?page_size=10000'),
            ('opportunities',
             f'/volunteer_opportunities_cached/{opportunities_query}'),
            ('actions', f'/actions_cached/{action_query}'),
        ]
        data = {}

        for key, path in paths:
            r = requests.get(f'{os.getenv("CUSTOM_API_URL")}{path}')
            raise_for_status(r)
            data[key] = r.json()
        return Response(data, status=200)
Example #7
0
def refresh_youtube_access_token():
    r = requests.post('https://www.googleapis.com/oauth2/v4/token',
                      data={
                          'client_id':
                          os.getenv('CUSTOM_GOOGLE_OAUTH_CLIENT_ID'),
                          'client_secret':
                          os.getenv('CUSTOM_GOOGLE_OAUTH_CLIENT_SECRET'),
                          'refresh_token':
                          os.getenv('CUSTOM_GOOGLE_OAUTH_REFRESH_TOKEN'),
                          'grant_type':
                          'refresh_token'
                      })
    raise_for_status(r)
    data = r.json()

    try:
        token = YoutubeAccessToken.objects.get(token_type='Bearer')
    except YoutubeAccessToken.DoesNotExist:
        token = YoutubeAccessToken()
    token.access_token = data['access_token']
    token.expires_in = data['expires_in']
    token.token_type = 'Bearer'
    token.save()
Example #8
0
def get_form_ids():
    r = requests.get(API_HOST + '/data',
                     auth=TokenAuth('Token', AUTH_TOKEN),
                     timeout=TIMEOUT)
    raise_for_status(r)
    return [form['id'] for form in r.json()]