<commit_before>from flask import request, jsonify
from server import app, sqldb
from os import getenv
from .models import User, DiningPreference, LaundryPreference, HomeCell, Event, Account, StudySpacesBooking
from .calendar3year import pull_todays_calendar
from sqlalchemy import func, and_
from .news import fetch_frontpage_article
from .account import get_todays_courses, get_courses_in_N_days
from .studyspaces import get_reservations
from penn.base import APIError
import json
import pytz
import datetime

utc = pytz.timezone('UTC')
eastern = pytz.timezone('US/Eastern')


@app.route('/homepage', methods=['GET'])
def get_homepage():
    # Find user in database
    try:
        user = User.get_or_create()
    except ValueError as e:
        response = jsonify({'err': [str(e)]})
        response.status_code = 400
        return response

    try:
        account = Account.get_account()
    except ValueError:
        account = None

    if account and account.email and user.email is None:
        user.email = account.email
        sqldb.session.commit()

    cells = []

    sessionid = request.args.get("sessionid")
    reservations_cell = get_reservations_cell(user, sessionid)
    if reservations_cell:
        cells.append(reservations_cell)

    if account and account.is_student():
        courses = get_courses_cell(account)
        if courses is not None:
            cells.append(courses)

    laundry = get_top_laundry_cell(user)
    dining = get_dining_cell(user)
    gsr_locations = get_gsr_locations_cell(user, account)
    cells.extend([dining, laundry, gsr_locations])

    calendar = get_university_event_cell()
    if calendar is not None:
        cells.append(calendar)

    news = get_news_cell()
    if news is not None:
        cells.append(news)

    cells.sort(key=lambda x: x.weight, reverse=True)

    response = jsonify({"cells": [x.getCell() for x in cells]})
    response.status_code = 200
    return response


def get_dining_cell(user):
    # returns a dining cell
    preferences = sqldb.session.query(DiningPreference.venue_id).filter_by(user_id=user.id)
    venue_ids = [x.venue_id for x in preferences]
    defaults_ids = [593, 1442, 636]
    if len(venue_ids) == 0:
        venue_ids = defaults_ids
    elif len(venue_ids) == 1:
        venue_ids.extend(defaults_ids)
        venue_ids = list(set(venue_ids))[:3]

    info = {"venues": venue_ids}
    return HomeCell("dining", info, 100)


def get_laundry_cells(user):
    # returns a list of laundry cells
    preferences = LaundryPreference.query.filter_by(user_id=user.id)
    room_ids = [x.room_id for x in preferences]

    # If the user has no preferences, select Bishop White
    if not room_ids:
        room_ids.append(0)

    return [HomeCell("laundry", {"room_id": x}) for x in room_ids]


def get_top_laundry_cell(user):
    # returns user's top laundry cell
    top_preference = LaundryPreference.query.filter_by(user_id=user.id).first()
    # If no top choice, select bishop white
    if top_preference:
        return HomeCell("laundry", {"room_id": top_preference.room_id}, 5)
    return HomeCell("laundry", {"room_id": 0}, 5)


def get_gsr_locations_cell(user, account):
    # returns a gsr cell with list of locations
    # if student is a Wharton student, show at the top
    top_gsrs_query = sqldb.session.query(StudySpacesBooking.lid) \
                                  .filter(and_(StudySpacesBooking.user == user.id, StudySpacesBooking.lid.isnot(None))) \
                                  .group_by(StudySpacesBooking.lid) \
                                  .order_by(func.count(StudySpacesBooking.lid).desc()) \
                                  .limit(2) \
                                  .all()
    preferences = [x for (x,) in top_gsrs_query]

    showHuntsman = account is None or account.email is None or "wharton" in account.email
    if showHuntsman:
        default_gids = [1, 1086]
        weighting = 300
    else:
        default_gids = [1086, 2587]
        weighting = 10

    # Remove duplicates while retaining relative ordering
    def f7(seq):
        seen = set()
        seen_add = seen.add
        return [x for x in seq if not (x in seen or seen_add(x))]

    gids = f7(preferences + default_gids)[:2]
    return HomeCell("gsr-locations", gids, weighting)


def get_university_event_cell():
    # returns a university notification cell
    calendar = pull_todays_calendar()
    if calendar:
        return HomeCell("calendar", calendar, 40)
    else:
        return None


def get_news_cell():
    # returns a news cell
    article = fetch_frontpage_article()
    if article:
        return HomeCell("news", article, 50)
    else:
        return None


def get_event_cell():
    # return a event cell
    # TODO Fetch most recent, most popular, etc<commit_msg>Revert "New GSR Cell with Locations"<commit_after>from flask import request, jsonify
from server import app, sqldb
from os import getenv
from .models import User, DiningPreference, LaundryPreference, HomeCell, Event, Account
from .calendar3year import pull_todays_calendar
from sqlalchemy import func
from .news import fetch_frontpage_article
from .account import get_todays_courses, get_courses_in_N_days
from .studyspaces import get_reservations
from penn.base import APIError
import json
import pytz
import datetime

utc = pytz.timezone('UTC')
eastern = pytz.timezone('US/Eastern')


@app.route('/homepage', methods=['GET'])
def get_homepage():
    # Find user in database
    try:
        user = User.get_or_create()
    except ValueError as e:
        response = jsonify({'err': [str(e)]})
        response.status_code = 400
        return response

    try:
        account = Account.get_account()
    except ValueError:
        account = None

    if account and account.email and user.email is None:
        user.email = account.email
        sqldb.session.commit()

    cells = []

    sessionid = request.args.get("sessionid")
    reservations_cell = get_reservations_cell(user, sessionid)
    if reservations_cell:
        cells.append(reservations_cell)

    if account and account.is_student():
        courses = get_courses_cell(account)
        if courses is not None:
            cells.append(courses)

    laundry = get_top_laundry_cell(user)
    dining = get_dining_cell(user)
    gsr = get_study_spaces_cell()
    cells.extend([dining, gsr, laundry])

    calendar = get_university_event_cell()
    if calendar is not None:
        cells.append(calendar)

    news = get_news_cell()
    if news is not None:
        cells.append(news)

    cells.sort(key=lambda x: x.weight, reverse=True)

    response = jsonify({"cells": [x.getCell() for x in cells]})
    response.status_code = 200
    return response


def get_dining_cell(user):
    # returns a dining cell
    preferences = sqldb.session.query(DiningPreference.venue_id).filter_by(user_id=user.id)
    venue_ids = [x.venue_id for x in preferences]
    defaults_ids = [593, 1442, 636]
    if len(venue_ids) == 0:
        venue_ids = defaults_ids
    elif len(venue_ids) == 1:
        venue_ids.extend(defaults_ids)
        venue_ids = list(set(venue_ids))[:3]

    info = {"venues": venue_ids}
    return HomeCell("dining", info, 100)


def get_laundry_cells(user):
    # returns a list of laundry cells
    preferences = LaundryPreference.query.filter_by(user_id=user.id)
    room_ids = [x.room_id for x in preferences]

    # If the user has no preferences, select Bishop White
    if not room_ids:
        room_ids.append(0)

    return [HomeCell("laundry", {"room_id": x}) for x in room_ids]


def get_top_laundry_cell(user):
    # returns user's top laundry cell
    top_preference = LaundryPreference.query.filter_by(user_id=user.id).first()
    # If no top choice, select bishop white
    if top_preference:
        return HomeCell("laundry", {"room_id": top_preference.room_id}, 5)
    return HomeCell("laundry", {"room_id": 0}, 5)


def get_study_spaces_cell():
    # returns a study spaces cell
    return HomeCell("studyRoomBooking", None, 8)


def get_university_event_cell():
    # returns a university notification cell
    calendar = pull_todays_calendar()
    if calendar:
        return HomeCell("calendar", calendar, 40)
    else:
        return None


def get_news_cell():
    # returns a news cell
    article = fetch_frontpage_article()
    if article:
        return HomeCell("news", article, 50)
    else:
        return None


def get_event_cell():
    # return a event cell
    # TODO Fetch most recent, most popular, etc
{'fraction_non_alphanumeric': 0.09255131964809384, 'fraction_numerical': 0.00997067448680352, 'mean_word_length': 3.0794258373205743, 'pattern_counts': {'":': 10, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 5, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '67580', 'n_tokens_mistral': 2811, 'n_tokens_neox': 2644, 'n_words': 727}