Beispiel #1
0
def food_record(account_id, food_id, servings):
    with get_db_cursor(commit=True) as cur:
        cur.execute('''
                    INSERT INTO food_history(account_id, food_id, food_servings)
                    VALUES (%s, %s, %s)
                    ''', (account_id, food_id, servings))
    return success_response()
Beispiel #2
0
def writeToDB():
	i = 10
	while i > 0:
		first_name = first_names_list[randint(0, len(first_names_list)-1)]
		last_name = last_names_list[randint(0, len(last_names_list)-1)]
		email = first_name + last_name + str(randint(1, 999999)) + '@' + 'gmail.com'
		min_price = min_price_list[randint(0, len(min_price_list)-1)]
		max_price = max_price_list[randint(0, len(max_price_list)-1)]

	
		user = User.objects.create_user(username=email, first_name=first_name, last_name=last_name, email=email, password='******')
				
		values = {'class_year': year_list[randint(0, len(year_list)-1)],
            'major': major_list[randint(0, len(major_list)-1)],
            'min_price' : min_price_list[randint(0, len(min_price_list)-1)],
            'max_price' : max_price_list[randint(0, len(max_price_list)-1)],
            'gender' : gender_list[randint(0, len(gender_list)-1)],
            'smoking' : smoking_list[randint(0,1)],
            'birthday': birthday_list[randint(0, len(birthday_list)-1)],
            'cleanliness': randint(1, 5),
            'location': location_list[randint(0, len(location_list)-1)]
        }

		request = PostRequestMock('POST', json.dumps(values), user)	
		response = api.handle_survey(request)


		i -= 1

	return utils.success_response()
Beispiel #3
0
def post_review(request):
	post_obj = json.loads(request.body)
	title, description, safety, rating, building_id = None, None, None, None, None
	user = request.user
	if 'title' in post_obj:
		title = post_obj['title']
	if 'description' in post_obj:
		description = post_obj['description']
	if 'safety' in post_obj:
		safety = post_obj['safety']
	if 'rating' in post_obj:
		rating = post_obj['rating']
	if 'building_id' in post_obj:
		building_id = post_obj['building_id']
	errors = check_post_review_errors(title, description, safety, rating, building_id, user)
	if len(errors) > 0:
		return utils.makeGenericErrorResponse(errors)
	building = models.Building.objects.get(id=building_id)
	num_reviews = models.Review.objects.filter(building=building_id).count()
	review = models.Review(title=title, description=description, safety=safety, rating=rating, user=user, building=building)
	review.save()
	building.average_rating = (building.average_rating * num_reviews + review.rating) / float(num_reviews+1)
	building.save()
	review_dict = get_review_dict_from_obj(review)
	return utils.success_response({'status': 1, 'review': review_dict, 'new_rating': building.average_rating})
Beispiel #4
0
def clear_all_housing_data(request):
	models.HousingPost.objects.all().delete()
	models.Building.objects.all().delete()
	models.Location.objects.all().delete()
	models.Address.objects.all().delete()
	resp_data = {"status" : 1}
	return utils.success_response()
Beispiel #5
0
def account_profile(account_id):
    with get_db_cursor(commit=True) as cur:
        cur.execute('''
                    SELECT json_build_object(
                            'first_name', first_name,
                            'last_name', last_name,
                            'height', height,
                            'weight', weight,
                            'sex', sex,
                            'dob', dob,
                            'email', email,
                            'diabetes_type', diabetes_type,
                            'high_blood_pressure', high_blood_pressure,
                            'pregnant', pregnant,
                            'insulin_tdd', insulin_tdd,
                            'background_dose', background_dose,
                            'pre_meal_target', pre_meal_target,
                            'post_meal_target', post_meal_target,
                            'basal_corr_factor', basal_corr_factor,
                            'bolus_corr_factor', bolus_corr_factor,
                            'grams_carb_per_unit', grams_carb_per_unit)::JSONB
                    AS response
                    FROM accounts
                    WHERE account_id = %s
                    ''', (account_id,))
        account = cur.fetchone()['response']
        if account is None:
            raise InvalidUsage('There are no accounts with '
                               'the provided id.',
                               'account_not_found')
        return success_response({'data': account})
Beispiel #6
0
def readings_blood_sugar(account_id, reading):
    with get_db_cursor(commit=True) as cur:
        cur.execute('''
                    INSERT INTO readings(account_id, reading)
                    VALUES (%s, %s)
                    ''', (account_id, reading))
    return success_response()
Beispiel #7
0
def food_search(query, results=10):
    with get_db_cursor(commit=True) as cur:
        cur.execute('''
                    SELECT food_search(%s, %s) AS response
                    ''', (query, results))
        res = cur.fetchone()['response']
    return success_response({'data': res})
Beispiel #8
0
def readings_insulin(account_id, units):
    with get_db_cursor(commit=True) as cur:
        cur.execute('''
                    INSERT INTO doses(account_id, dose_units)
                    VALUES (%s, %s)
                    ''', (account_id, units))
    return success_response()
Beispiel #9
0
def food_retrieve(food_id):
    with get_db_cursor(commit=True) as cur:
        cur.execute('''
                    SELECT get_food_item(%s) AS response
                    ''', (food_id,))
        res = cur.fetchone()['response']
    return success_response({'data': res})
Beispiel #10
0
def post_survey(request):
	#TODO: Handle image upload of user profile picture
	post_obj = json.loads(request.body)
	class_year, major, min_price, max_price, gender, smoking, birthday, cleanliness, location = None, None, None, None, None, None, None, None, None
	user = request.user
	user_picture = None #TODO: change this
	if 'class_year' in post_obj:
		class_year = post_obj['class_year']
	if 'major' in post_obj:
		major = post_obj['major']
	if 'min_price' in post_obj:
		min_price = post_obj['min_price']
	if 'max_price' in post_obj:
		max_price = post_obj['max_price']
	if 'gender' in post_obj:
		gender = post_obj['gender']
	if 'smoking' in post_obj:
		smoking = post_obj['smoking']
	if 'birthday' in post_obj:
		birthday = post_obj['birthday']
	if 'cleanliness' in post_obj:
		cleanliness = post_obj['cleanliness']
	if 'location' in post_obj:
		location = post_obj['location']
	errors = check_post_survey_errors(user, class_year, major, min_price, max_price, gender, smoking, birthday, cleanliness, location)
	if len(errors) != 0:
		return utils.error_response(errors)
	models.SurveyInfo.objects.filter(user=user).delete()
	survey_data = models.SurveyInfo(user=user, user_picture=user_picture, class_year=class_year, major=major, min_price=min_price,
		max_price=max_price, gender=gender, smoking=smoking, birthday=birthday, cleanliness=cleanliness, location=location)
	survey_data.save()
	return utils.success_response()
Beispiel #11
0
def delete_testing_accounts(request):
	try:
		testing_users = User.objects.filter(email=TESTING_EMAIL)
		for u in testing_users:
			u.delete()
		return utils.success_response()
	except Exception, e:
		return utils.error_response(e)
Beispiel #12
0
def food_calculate(account_id, food_id, servings):
    with get_db_cursor(commit=True) as cur:
        cur.execute('''
                    SELECT round(food_insulin_units_required(%s, %s, %s))::INTEGER
                    AS response
                    ''', (account_id, food_id, servings))
        res = cur.fetchone()['response']
    return success_response({'data': {'units': res}})
Beispiel #13
0
def account_email_available(email):
    with get_db_cursor(commit=True) as cur:
        cur.execute('''
                    SELECT email FROM accounts WHERE email = lower(%s)
                    ''', (email,))
        res = cur.fetchone()
        if res is not None:
            raise InvalidUsage('Email not available.',
                               'email_not_available')
    return success_response({'data': {'available': email}})
Beispiel #14
0
def history_meals(account_id):
    with get_db_cursor(commit=True) as cur:
        cur.execute('''
                    SELECT json_agg(summarize_food_history(food_history))::jsonb AS response
                    FROM food_history
                    WHERE account_id = %s
                    AND food_timestamp >= (now() - interval '31 day');
                    ''', (account_id,))
        res = cur.fetchone()['response']
    return success_response({'data': res})
Beispiel #15
0
def history_blood_sugar(account_id):
    with get_db_cursor(commit=True) as cur:
        cur.execute('''
                    SELECT json_agg(summarize_readings(readings))::jsonb AS response
                    FROM readings
                    WHERE account_id = %s
                    AND reading_timestamp >= (now() - interval '31 day');
                    ''', (account_id,))
        res = cur.fetchone()['response']
    return success_response({'data': res})
Beispiel #16
0
def upload():
    body = json.loads(request.data)
    image_data = body.get("image")
    bucket_name = body.get("bucket")
    if image_data is None:
        return failure_response("No base64 URL to be found!")
    img_url = upload_image_helper(image_data, bucket_name)
    if img_url is None:
        return failure_response("Could not upload image!")
    return success_response(img_url, 201)
Beispiel #17
0
def stats_insulin(account_id):
    with get_db_cursor(commit=True) as cur:
        cur.execute('''
                    SELECT json_agg(summarize_doses(doses))::jsonb AS response
                    FROM doses
                    WHERE account_id = %s
                    AND dose_timestamp >= (now() - interval '48 hour');
                    ''', (account_id,))
        res = cur.fetchone()['response']
    return success_response({'data': res})
Beispiel #18
0
def remove():
    body = json.loads(request.data)
    image_url = body.get("image_url")
    bucket_name = body.get("bucket")
    if image_url is None or image_url == "":
        return failure_response("No URL to be found!")
    res = remove_image_helper(image_url, bucket_name)
    if not res:
        return failure_response("Image does not exist!")
    elif res != 204:
        return failure_response("Could not delete image!")
    return success_response("Image successfully deleted!")
Beispiel #19
0
def login_account(request):
	account_json = json.loads(request.body)
	user = authenticate(username=account_json['email'], password=account_json['password'])
	if user is not None:
		if user.is_active:
			login(request, user)
			print user, "logged in."
			return utils.success_response()
		else:
			return utils.error_response("Your account has been disabled. Check your email for details")
	else:
		return utils.error_response("Your account does not exist!")
Beispiel #20
0
def account_login():
    req = get_request_data()
    with get_db_cursor(commit=True) as cur:
        cur.execute('''
                    SELECT account_id
                    FROM accounts
                    WHERE email = %(email)s
                    AND password = %(password)s
                    ''', req)
        res = cur.fetchone()
        if res is None:
            raise InvalidUsage('Email not found or password invalid.',
                               'email_or_password_invalid')
        else:
            account_id = res['account_id']

        return success_response({'data': {'account_id': account_id}})
Beispiel #21
0
def get_search_results(request):
	obj = request.GET
	order_by = obj.get('order_by')
	min_price = obj.get('min_price')
	max_price = obj.get('max_price')
	num_bedrooms = obj.get('num_bedrooms')
	num_bathrooms = obj.get('num_bathrooms')
	results = models.HousingPost.objects.filter(bedrooms=num_bedrooms).filter(bathrooms = num_bathrooms).filter(price__lt=max_price).filter(price__gt=min_price).order_by(order_by)	# TODO: check for empty fields
	housing_output = []
	for result in results:
		user = result.user
		address = result.address
		building = result.building
		img_path = None
		images = models.PostImage.objects.filter(housing_post=result)
		if images.count() > 0:
			img_path = '../uploads/' + str(images[0].image)
		data = {'id' : result.id,
				'username' : user.username,
				'first_name': user.first_name,
				'last_name': user.last_name,
				'title': result.title,
				'description': result.description,
				'price': result.price,
				'num_people': result.num_people,
				'bedrooms': result.bedrooms,
				'bathrooms': result.bathrooms,
				'line_address1': address.line_address1,
				'line_address2': address.line_address2,
				'city': address.city,
				'zip_code': address.zip_code,
				'average_rating': building.average_rating,
				'longitude' : building.location.longitude,
				'latitude': building.location.latitude,
				'property_name': building.property_name,
				'last_updated': result.last_updated,
				'start_date': str(result.start_date), #TODO: might need to be fixed
				'end_date': str(result.end_date), #TODO: might need to be fixed
				'img_path': img_path
				}
		housing_output.append(data)
	return utils.success_response({"status": 1, "results": housing_output})
Beispiel #22
0
def make_housing_post(request):
# try:
	housing_json = json.loads(request.body)
	errors = check_errors_post_housing(request.user, housing_json)
	if len(errors) != 0:
		return utils.error_response(errors)
	#TODO: Handle image uploads in post
	#TODO: format address info with Google Maps API
	line1 = housing_json['line1']
	line2 = housing_json['line2']
	city = housing_json['city']
	zip_code = housing_json['zip_code']
	property_name = housing_json['property_name']
	longitude = 0.0
	latitude = 0.0
	address_dict = googleParse(line1 + ' ' + line2 + ' ' + city + ' ' + zip_code)
	if address_dict['status'] == -1:
		return utils.error_response(["Address could not be parsed"])
	line1, line2, city, zip_code = address_dict['line1'], address_dict['line2'], address_dict['city'], address_dict['zipcode']
	longitude, latitude = address_dict['longitude'], address_dict['latitude']
	if models.Address.objects.filter(line_address1=line1).filter(zip_code=zip_code).filter(is_building=True).count() == 0:
		building = create_building(line1, line2, city, zip_code, property_name, longitude, latitude)
	else:
		building = models.Address.objects.filter(zip_code=zip_code).filter(is_building=True).get(line_address1=line1).building
	address = models.Address(is_building=False, line_address1=line1, line_address2=line2, city=city, zip_code=zip_code)
	address.save()
	housing_post = models.HousingPost(
							user = request.user, #TODO Figure out how to test with cookies
							title=housing_json['title'],
							description=housing_json['description'],
							price = housing_json['price'],
							num_people=housing_json['num_people'],
							bedrooms=housing_json['bedrooms'],
							bathrooms=housing_json['bathrooms'],
							address=address,
							building=building,
							last_updated=datetime.datetime.now(),
							start_date=housing_json['start_date'],
							end_date=housing_json['end_date'])
	housing_post.save()
	return utils.success_response({'postId' : housing_post.id})
Beispiel #23
0
def make_account(request):
	account_json = json.loads(request.body)
	if is_account(account_json):
		try:
			user = User.objects.get(email=account_json['email'])
			return utils.error_response('Account with email: '
								  + account_json['email'] + ' already exists.')
		except User.DoesNotExist, e:
			errors = check_errors_account(account_json)
			if len(errors) == 0:
				user = create_user(account_json)
				user.save()
				logged_in_user = authenticate(username=account_json['email'],
											  password=account_json['password'])
				print logged_in_user
				login(request, logged_in_user)
				return utils.success_response()
			else:
				return utils.error_response(errors)
		except Exception, e:
			return utils.error_response(e)
Beispiel #24
0
def account_signup():
    req = get_request_data()
    with get_db_cursor(commit=True) as cur:
        cur.execute('''
                    SELECT
                    account_signup(%(first_name)s, %(last_name)s,
                                   %(height)s, %(weight)s,
                                   %(sex)s, %(dob)s,
                                   %(email)s, %(password)s,
                                   %(diabetes_type)s,
                                   %(high_blood_pressure)s,
                                   %(pregnant)s,
                                   %(insulin_tdd)s,
                                   %(background_dose)s,
                                   %(pre_meal_target)s,
                                   %(post_meal_target)s)
                    AS response
                    ''', req)
        res = cur.fetchone()['response']
        if not res['success']:
            raise InvalidUsage(res['message'], res['status'])
    return success_response({'data': {'account_id': res['account_id']}})
Beispiel #25
0
				
			# review_post.save()
			# print 'building id: ' + str(models.HousingPost.objects.get(id=housing_post_response['postId']).building.id)

			params = {'title': review_adj[randint(0, len(review_adj)-1)] + ' ' + noun_list[randint(0, len(noun_list)-1)],
	            'description' : lorem_ipsum,
	            'safety' : safety,
	            'rating' : rating,
	            'bedrooms' : bedrooms,
	            'bathrooms' : bathrooms,
	            'building_id': models.HousingPost.objects.get(id=json.loads(housing_post_response.content)['postId']).building.id
		        }
			review_request = PostRequestMock('POST', json.dumps(params), user)
			api.handle_review(review_request)

	return utils.success_response()

def create_building(line1, line2, city, zip_code, property_name, longitude, latitude):
	address = models.Address(is_building=True, line_address1=line1, city=city, zip_code=zip_code)
	address.save()
	location = models.Location(longitude=longitude, latitude=latitude)
	location.save()
	building = models.Building(average_rating=0, property_name=property_name, address=address, location=location)
	building.save()
	return building


def makeBetterAddress(address):
	result = address
	if address.find('#') != -1:
		result = result.replace('#', 'Apt.')
Beispiel #26
0
def hello_world():
    return success_response("Hello World!")
Beispiel #27
0
def getValidReviewResponse(reviews_obj):
	review_list = get_reviews_list(reviews_obj)
	reviews_json = {'status' : 1, 'reviews': review_list}
	return utils.success_response(reviews_json)
Beispiel #28
0
def account_signup():
    req = get_request_data()
    facebook_user_id = None

    if 'facebook_auth_token' in req:
        try:
            fb = requests.get('https://graph.facebook.com/debug_token',
                              params={
                                  'input_token':
                                  req['facebook_auth_token'],
                                  'access_token':
                                  current_app.config['FB_ACCESS_TOKEN']
                              }).json()

            if 'error' in fb:
                error_msg = fb['error']['message']
                error_type = fb['error']['type']
                current_app.logger.error('{}: {}'.format(
                    error_type, error_msg))
                raise InvalidUsage(error_msg, error_type)

            if not fb['data']['is_valid']:
                raise InvalidUsage('Invalid Facebook login session.',
                                   'invalid_facebook_login')

            facebook_user_id = fb['data']['user_id']

            fb = requests.get(
                'https://graph.facebook.com/v2.5/me?access_token={}'
                '&fields=email'.format(req['facebook_auth_token'])).json()

            if 'email' not in fb:
                raise InvalidUsage('Email from Facebook account is required',
                                   'facebook_email_required')

            req['email'] = fb['email']

        except RequestException as e:
            current_app.logger.error(e)
            raise InvalidUsage(
                'Error contacting Facebook for '
                'authorization verification.', 'facebook_communication_error')

    req['password_hash'] = generate_password_hash(req['password'])
    req['facebook_user_id'] = facebook_user_id

    fields = [
        'account_type', 'username', 'first_name', 'last_name', 'company_name',
        'email', 'phone_number', 'bio', 'latitude', 'longitude'
    ]

    for f in fields:
        if f not in req:
            req[f] = None

    # Set these fields to empty string if not present
    # Because they cannot be saved as NULL in database
    # TODO probably better to make fields empty by default in DB
    for f in ['first_name', 'last_name', 'company_name']:
        if not req[f]:
            req[f] = ''

    with db.get_db_cursor(commit=True) as cur:
        cur.execute(
            '''
                    SELECT
                    account_signup (%(account_type)s, %(username)s, %(password_hash)s,
                                    %(first_name)s, %(last_name)s, %(company_name)s,
                                    %(email)s, %(phone_number)s,
                                    %(bio)s, %(latitude)s, %(longitude)s,
                                    %(facebook_user_id)s)
                    AS response
                    ''', req)
        res = cur.fetchone()['response']
        if not res['success']:
            raise InvalidUsage(res['message'], res['status'])
        cur.execute(
            '''
                    SELECT row_to_json(accounts) as account_info
                    FROM accounts
                    WHERE account_id = %(account_id)s
                    ''', res)
        account = cur.fetchone()['account_info']

        # Send confirm email and SMS pin
        send_registration_email.delay(account)
        send_cell_phone_sms.delay(account)

        # Slack notif
        send_notif.delay(title='New Signup',
                         first_name=account['first_name'],
                         email=account['email'],
                         username=account['username'],
                         facebook_user_id=account['facebook_user_id'])

        errors = []
        if 'facebook_auth_token' in req:
            try:
                remote = (requests.get(
                    'https://graph.facebook.com/v2.5/me'
                    '?access_token={}&fields=cover'.format(
                        req['facebook_auth_token'])).json())['cover']['source']
                img = requests.get(remote)
                image_id = account_upload_and_resize_image(
                    cur, BytesIO(img.content), 'cover.jpg',
                    account['account_uuid'], 'cover', 'Facebook cover photo.',
                    'Retreived {}.'.format(
                        datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
                cur.execute(
                    '''
                            UPDATE accounts
                            SET cover_photo_id=%s
                            WHERE account_uuid=%s
                            ''', (image_id, account['account_uuid']))
            except Exception:
                current_app.logger.exception(
                    "Error retreiving cover photo from Facebook")
                errors.append('Error retreiving cover photo from Facebook.')
            try:
                img = requests.get(
                    'http://graph.facebook.com/v2.5/{}/picture?type=large'.
                    format(facebook_user_id))
                image_id = account_upload_and_resize_image(
                    cur, BytesIO(img.content), 'profile.jpg',
                    account['account_uuid'], 'profile',
                    'Facebook profile photo.', 'Retreived {}.'.format(
                        datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
                cur.execute(
                    '''
                            UPDATE accounts
                            SET profile_photo_id=%s
                            WHERE account_uuid=%s
                            ''', (image_id, account['account_uuid']))
            except Exception:
                current_app.logger.exception(
                    "Error retreiving profile photo from Facebook")
                errors.append('Error retreiving profile photo from Facebook.')
    resp = success_response(
        {'data': {
            'account_uuid': account['account_uuid']
        }})
    if len(errors) > 0:
        resp['errors'] = errors
    return resp