Пример #1
0
def updateNews():
    log.info('Starting \'News\' widget update...')
    try:
        news_key = os.environ['NEWS_KEY']
        news_url = f'http://newsapi.org/v2/top-headlines?country=us&apiKey={news_key}'
        response = requests.get(news_url)
        response.raise_for_status()
        data = response.json()
    except Exception as e:
        log.error('Failed to update \'News\' widget.', exc_info=True)
        return
    articles = data.get('articles')
    if not articles:
        return
    new_articles = []
    for i, article in enumerate(articles):
        if i >= MAX_POSTS:
            break
        if not article:
            continue
        title = article.get('title')
        title = re.sub(r'-\s*[^-]+$', '', title).strip()
        source = article.get('source')
        if source:
            source = source.get('name')
            # source = re.sub(r'\.com.*$', '', source).strip()

        url = article.get('url')
        new_articles.append({'title': title, 'source': source, 'url': url})


    with app.app_context():
        news_widget = None
        try:
            news_widget = Widget.query.filter_by(alias_name='news').first()
            if not news_widget:
                log.critical('News widget not found')
                return
        except Exception as e:
            log.error('Error retrieving News Widget', exc_info=True)
            return
        try:
            db.session.query(CustomPost).filter(CustomPost.widget_id==news_widget.id).delete()
            for a in new_articles:
                article_post = CustomPost(content=a['title'], custom_author=a['source'], url=a['url'], widget=news_widget)
                db.session.add(article_post)
            news_widget.active = True
            db.session.commit()

        except Exception as e:
            db.session.rollback()
            log.error('Error updating News Widget')
            try:
                news_widget.active = False
                db.session.commit()
            except Exception as e:
                db.session.rollback()
                log.error('Error updating News Widget active status')
    log.info('Exiting \'News\' widget update.')
Пример #2
0
def addSubscription(current_user,
                    widget_id,
                    grid_location=default_widget_location):
    """
    Subscribe User current_user to widget with primary_key = widget_id.
    Set initial grid_location.

    Parameters
    ----------
    current_user : User
    widget_id : int
    grid_location : dict

    Returns
    -------
    None

    """
    # validate widget_id
    try:
        widget_id = int(widget_id)
    except:
        log.critical(
            f'{current_user} attempted to subscribe with non-int widget_id.')
        raise Exception(f'{error_msg_global}')

    widget = Widget.query.get(widget_id)
    if not widget:
        log.error(
            f'{current_user} attempted to subscribe to non-existing widget with id = \"{widget_id}\".'
        )
        raise Exception(f'{error_msg_global}')
    if widget in current_user.widgets:
        log.info(
            f'{current_user} attempted to re-subscribe to existing {widget}.')
        raise Exception(
            f'{error_msg_global} You are already subscribed to {widget.name}.')

    try:
        new_subscription = Subscription(user=current_user,
                                        widget_id=widget_id,
                                        grid_location=grid_location)
        db.session.add(new_subscription)
        db.session.commit()
        log.info(f'{current_user} subscribed to {widget}.')

    except Exception as e:
        db.session.rollback()
        log.warning(f'Failed to subscribe {current_user} to {widget}.',
                    exc_info=True)
        raise Exception(error_msg_global)
Пример #3
0
def updateCOVIDReport():
    log.info('Starting \'COVID\' widget update...')

    covid_url = 'https://pomber.github.io/covid19/timeseries.json'

    try:
        response = requests.get(covid_url)
        response.raise_for_status()
        data = response.json()
    except Exception as e:
        log.error('Failed to update \'COVID\' widget.', exc_info=True)
        return

    country_data = data[country]
    today_confirmed = country_data[-1]['confirmed']
    yesterday_confirmed = country_data[-2]['confirmed']
    today_deaths = country_data[-1]['deaths']
    yesterday_deaths = country_data[-2]['deaths']

    post = f'Since yesterday, the US has witnessed an increase in total confirmed cases by {today_confirmed-yesterday_confirmed:n}, and an increase in total deaths by {today_deaths-yesterday_deaths:n}.'

    with app.app_context():
        covid_widget = None
        try:
            covid_widget = Widget.query.filter_by(alias_name='covid').first()
            if not covid_widget:
                log.critical('COVID widget not found')
                return
        except Exception as e:
            log.error('Error retrieving COVID widget', exc_info=True)
            return
        try:
            db.session.query(CustomPost).filter(
                CustomPost.widget_id == covid_widget.id).delete()
            covid_post = CustomPost(content=post,
                                    custom_author="Johns Hopkins CSSE",
                                    widget=covid_widget)
            db.session.add(covid_post)
            covid_widget.active = True
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            log.error('Error updating COVID widget')
            try:
                covid_widget.active = False
                db.session.commit()
            except Exception as e:
                db.session.rollback()
                log.error('Error updating COVID widget active status')
    log.info('Exiting \'COVID\' widget update.')
Пример #4
0
def getUser(netid):
    """
    User associated with provided `netid`. If netid does not exist in
    database, creates a new User, and subscribes new User to `welcome` Widget.

    Parameters
    ----------
    netid : str

    Returns
    -------
    User
        User associated with `netid`.

    """
    user = User.query.filter_by(netid=netid).first()
    if not user:
        log.info(
            f'User with netid = \"{netid}\" does not exist. Creating User...')
        user = user_utils.createUser(netid)
        if user:
            log.info(f'Subscribing {user} to Welcome widget...')
            try:
                addSubscription(user,
                                1,
                                grid_location={
                                    'x': 2,
                                    'y': 0,
                                    'width': 8,
                                    'height': 3,
                                    'minWidth': 8,
                                    'minHeight': 3
                                })
            except:
                log.critical(
                    f'Failed to subscribe new user {user} to Welcome widget.',
                    exc_info=True)

    return user
Пример #5
0
def createUser(netid):
    """
    Create a new user with `netid`. Populate account info if `netid`
    associated with an undergraduate student.

    Parameters
    ----------
    netid : str

    Returns
    -------
    User
        New User associated with `netid`.

    """
    new_user = None
    undergrad_profile = getUndergraduate(netid)
    if undergrad_profile:
        new_user = User(netid=netid,
                        email=undergrad_profile.get('email'),
                        first_name=undergrad_profile.get('first_name'),
                        last_name=undergrad_profile.get('last_name'),
                        class_year=undergrad_profile.get('class_year'))
    else:
        new_user = User(netid=netid)

    try:
        db.session.add(new_user)
        db.session.commit()
        log.info(f'New {new_user} created!')
        return new_user
    except Exception as e:
        db.session.rollback()
        msg = f'Failed to create user account with netid = \"{netid}\"'
        log.critical(msg, exc_info=True)
        return None
Пример #6
0
def updateNews():
    log.info('Starting \'Princeton News\' widget update...')
    MAX_POSTS = None
    try:
        with app.app_context():
            princeton_news_widget = Widget.query.filter_by(
                alias_name='princeton_news').first()
            if not princeton_news_widget:
                log.critical(
                    'Princeton News Widget not found when attempting to update'
                )
            MAX_POSTS = princeton_news_widget.post_limit
    except Exception as e:
        return

    news_posts = None
    try:
        feed = feedparser.parse(princeton_news_url)
        if not feed:
            return
        news_posts_count = min(len(feed.entries), MAX_POSTS)
        if not news_posts_count:
            return

        news_posts = [None] * news_posts_count
        for i, post in enumerate(feed.entries):
            if i == news_posts_count:
                break
            title = post.title
            if not title:
                continue
            author = post.author
            if not author:
                author = 'Office of Communications'
            if post.published_parsed:
                date_published = datetime(*post.published_parsed[:6])
            url = post.link
            news_posts[i] = {
                'title': title,
                'author': author,
                'date_published': date_published,
                'url': url
            }

    except Exception as e:
        log.error('Error retrieving new posts for Princeton News widget')
        return
    with app.app_context():
        try:
            princeton_news_widget = Widget.query.filter_by(
                alias_name='princeton_news').first()
            db.session.query(CustomPost).filter(
                CustomPost.widget_id == princeton_news_widget.id).delete()
            for post in news_posts:
                news_post = CustomPost(content=post['title'],
                                       custom_author=post['author'],
                                       url=post['url'],
                                       create_dttm=post['date_published'],
                                       widget=princeton_news_widget)
                db.session.add(news_post)
            princeton_news_widget.active = True
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            log.error('Error updating daily poem post.', exc_info=True)
            try:
                princeton_news_widget.active = False
                db.session.commit()
            except Exception as e:
                db.session.rollback()
    log.info('Exiting \'Princeton News\' widget update.')
Пример #7
0
def updateCalendar():
    log.info('Starting \'Academic Calendar\' widget update...')
    url = "https://registrar.princeton.edu/feeds/events/ical.ics"

    try:
        response = requests.get(url)
        response.raise_for_status()
        c = Calendar(response.text)
    except requests.exceptions.HTTPError as err:
        log.error("Error updating academic calendar widget", exc_info=True)
        return
    info = []
    for event in c.events:
        info.append({
            'event_name': event.name,
            'start_month': date_extraction(str(event.begin))[0],
            'start_day': date_extraction(str(event.begin))[1],
            'start_year': date_extraction(str(event.begin))[2]
        })

    sorted_info = sorted(info,
                         key=itemgetter('start_year', 'start_month',
                                        'start_day'))
    current_month = datetime.datetime.today().month
    current_day = datetime.datetime.today().day
    current_year = datetime.datetime.today().year
    i = 0

    for s in sorted_info:
        if s['start_year'] >= current_year:
            break
        i += 1

    j = i
    while sorted_info[j]['start_month'] < current_month:
        j += 1

    m = j
    while sorted_info[m]['start_day'] < current_day:
        m += 1

    k = m
    next_ten_events = []
    while k < 10 + m:
        next_ten_events.append(sorted_info[k])
        if k + 1 > len(sorted_info): break
        k += 1

    with app.app_context():
        pton_calendar = None
        try:
            pton_calendar = Widget.query.filter_by(
                alias_name='pton_calendar').first()
            if not pton_calendar:
                log.critical('Pton Calendar Widget not found')
                return
        except Exception:
            log.error('Error retrieving pton calendar widget', exc_info=True)

        try:
            db.session.query(CustomPost).filter(
                CustomPost.widget_id == pton_calendar.id).delete()
            t = len(next_ten_events) - 1
            while t >= 0:
                e = next_ten_events[t]
                content_string = str(e['event_name'])
                day = str(e['start_day'])

                if len(day) == 1:
                    day = "0" + day

                author_string = str(e['start_month']) + "/" + day + "/" + str(
                    e['start_year'])
                calendar_event = CustomPost(content=content_string,
                                            custom_author=author_string,
                                            widget=pton_calendar)
                db.session.add(calendar_event)
                t -= 1
            pton_calendar.active = True
            db.session.commit()

        except Exception as e:
            db.session.rollback()
            log.error('Error updating Pton Calendar Widget')
            log.error(e)
            try:
                pton_calendar.active = False
                db.session.commit()
            except Exception as e:
                db.session.rollback()
                log.error('Error updating Pton Calendar Widget active status')
    log.info('Exiting \'Academic Calendar\' widget update.')