Example #1
0
def receive_events(request):
    json_body = request.json_body
    parsed_events_set = EventsSetSchema().loads(json_body)
    if len(parsed_events_set.errors.keys()) > 0:
        raise HTTPBadRequest()
    last_update_ts = int(parsed_events_set.data['stop'])

    events = []
    if 'data' in parsed_events_set.data:
        events = parsed_events_set.data['data']

    events_to_insert = []
    for event in events:
        existed = DBSession.query(exists().where(Event.event_id==event.event_id)).scalar()
        exists_in_inserted_list = any(ev.event_id == event.event_id for ev in events_to_insert)
        if not existed and not exists_in_inserted_list:
            events_to_insert.append(event)

    with transaction.manager:
        Meta.filter_by(key=LAST_UPDATE_KEY).update({
            'value': last_update_ts
        })
        for event in events_to_insert:
            DBSession.add(event)
    return response_ok(dict(
        count=len(events),
        start=parsed_events_set.data['start'],
        stop=parsed_events_set.data['stop'],
        lastUpdateTs=last_update_ts
    ))
Example #2
0
def get_last_update(request):
    try:
        last_update = Meta.filter_by(key=LAST_UPDATE_KEY).one()
    except NoResultFound:
        from datetime import datetime, timedelta
        import calendar
        prevent_date = datetime.utcnow() - timedelta(days=1)
        prevent_date_utc_ts = calendar.timegm(prevent_date.utctimetuple())
        with transaction.manager:
            last_update = Meta(key=LAST_UPDATE_KEY, value=prevent_date_utc_ts)
            DBSession.add(last_update)
        last_update = Meta.filter_by(key=LAST_UPDATE_KEY).one()
    return int(last_update.value)
Example #3
0
def pull_messages_from_email(trailcam):
    email_connection = trailcam.email_connection

    current_request = pyramid.threadlocal.get_current_request()

    request_json_data = {
        'ngw': {
            'unique_id': get_ngw_unique_id(current_request),
            'name': get_ngw_instance_name(current_request),
            'url': current_request.application_url
        },
        'email': {
            'address': email_connection.email
        },
        'messages': {
            'regex': trailcam.filter
        }
    }

    trailcam_email_service_url = get_trailcam_service_endpoint_url(
        current_request, 'messages')
    response = requests.get(trailcam_email_service_url, json=request_json_data)

    status_code = response.status_code
    if status_code == 500:
        raise ValidationError(
            _('The email is not registered on NextGIS Email System. Try later, please.'
              ))
    elif status_code != 200:
        raise ValidationError(
            _('NextGIS Email System is unavailable. Try later, please.'))

    messages_info = response.json()

    from nextgisweb_trailcam.model import Trailcam, TrailcamItem
    session = DBSession()

    trailcam = session.query(Trailcam).get(trailcam.id)
    for message_info in messages_info:
        new_trailcam_item = TrailcamItem()
        email_message_info = message_info['message']
        new_trailcam_item.email_uid = email_message_info['uid']
        new_trailcam_item.date_received = dateutil.parser.parse(
            email_message_info['received'])
        new_trailcam_item.name = email_message_info['subject']
        new_trailcam_item.message_body = email_message_info['body']

        new_trailcam_item.file_name = email_message_info['image_name']
        image_file_info = write_image(
            current_request, unicode.encode(email_message_info['image']),
            new_trailcam_item.file_name)

        new_trailcam_item.file_path = image_file_info['file_path']
        new_trailcam_item.file_path_thumbnail = image_file_info[
            'file_path_thumbnail']
        new_trailcam_item.file_size = image_file_info['file_size']

        extra = message_info['extra']
        if 'month' in extra and 'day' in extra and 'hour' in extra and 'minutes' in extra:
            datetime_original = datetime.datetime(2017, int(extra['month']),
                                                  int(extra['day']),
                                                  int(extra['hour']),
                                                  int(extra['minutes']))
        new_trailcam_item.date_original = datetime_original

        new_trailcam_item.trailcam = trailcam
        session.add(new_trailcam_item)

    transaction.commit()
    session.close()

    return {'count': len(messages_info)}