Example #1
0
File: api.py Project: OmeGak/indico
    def _getParams(self):
        super(BookRoomHook, self)._getParams()
        self._fromDT = utc_to_server(self._fromDT.astimezone(pytz.utc)).replace(tzinfo=None) if self._fromDT else None
        self._toDT = utc_to_server(self._toDT.astimezone(pytz.utc)).replace(tzinfo=None) if self._toDT else None
        if not self._fromDT or not self._toDT or self._fromDT.date() != self._toDT.date():
            raise HTTPAPIError('from/to must be on the same day')
        elif self._fromDT >= self._toDT:
            raise HTTPAPIError('to must be after from')
        elif self._fromDT < datetime.now():
            raise HTTPAPIError('You cannot make bookings in the past')

        username = get_query_parameter(self._queryParams, 'username')
        if not username:
            raise HTTPAPIError('No username provided')
        users = User.find_all(~User.is_deleted, Identity.identifier == username)
        if not users:
            raise HTTPAPIError('Username does not exist')
        elif len(users) != 1:
            raise HTTPAPIError('Ambiguous username ({} users found)'.format(len(users)))
        user = users[0]

        self._params = {
            'room_id': get_query_parameter(self._queryParams, 'roomid'),
            'reason': get_query_parameter(self._queryParams, 'reason'),
            'booked_for': user,
            'from': self._fromDT,
            'to': self._toDT
        }
        missing = [key for key, val in self._params.iteritems() if not val]
        if missing:
            raise HTTPAPIError('Required params missing: {}'.format(', '.join(missing)))
        self._room = Room.get(self._params['room_id'])
        if not self._room:
            raise HTTPAPIError('A room with this ID does not exist')
Example #2
0
    def _getParams(self):
        super(BookRoomHook, self)._getParams()
        self._fromDT = utc_to_server(self._fromDT.astimezone(pytz.utc)).replace(tzinfo=None) if self._fromDT else None
        self._toDT = utc_to_server(self._toDT.astimezone(pytz.utc)).replace(tzinfo=None) if self._toDT else None
        if not self._fromDT or not self._toDT or self._fromDT.date() != self._toDT.date():
            raise HTTPAPIError('from/to must be on the same day')
        elif self._fromDT >= self._toDT:
            raise HTTPAPIError('to must be after from')
        elif self._fromDT < datetime.now():
            raise HTTPAPIError('You cannot make bookings in the past')

        username = get_query_parameter(self._queryParams, 'username')
        avatars = username and filter(None, AuthenticatorMgr().getAvatarByLogin(username).itervalues())
        if not avatars:
            raise HTTPAPIError('Username does not exist')
        elif len(avatars) != 1:
            raise HTTPAPIError('Ambiguous username ({} users found)'.format(len(avatars)))
        avatar = avatars[0]

        self._params = {
            'room_id': get_query_parameter(self._queryParams, 'roomid'),
            'reason': get_query_parameter(self._queryParams, 'reason'),
            'booked_for': avatar,
            'from': self._fromDT,
            'to': self._toDT
        }
        missing = [key for key, val in self._params.iteritems() if not val]
        if missing:
            raise HTTPAPIError('Required params missing: {}'.format(', '.join(missing)))
        self._room = Room.get(self._params['room_id'])
        if not self._room:
            raise HTTPAPIError('A room with this ID does not exist')
Example #3
0
    def _getParams(self):
        super(BookRoomHook, self)._getParams()
        self._fromDT = utc_to_server(self._fromDT.astimezone(pytz.utc)).replace(tzinfo=None) if self._fromDT else None
        self._toDT = utc_to_server(self._toDT.astimezone(pytz.utc)).replace(tzinfo=None) if self._toDT else None
        if not self._fromDT or not self._toDT or self._fromDT.date() != self._toDT.date():
            raise HTTPAPIError('from/to must be on the same day')
        elif self._fromDT >= self._toDT:
            raise HTTPAPIError('to must be after from')
        elif self._fromDT < datetime.now():
            raise HTTPAPIError('You cannot make bookings in the past')

        username = get_query_parameter(self._queryParams, 'username')
        if not username:
            raise HTTPAPIError('No username provided')
        users = User.query.join(User.identities).filter(~User.is_deleted, Identity.identifier == username).all()
        if not users:
            raise HTTPAPIError('Username does not exist')
        elif len(users) != 1:
            raise HTTPAPIError('Ambiguous username ({} users found)'.format(len(users)))
        user = users[0]

        self._params = {
            'room_id': get_query_parameter(self._queryParams, 'roomid'),
            'reason': get_query_parameter(self._queryParams, 'reason'),
            'booked_for': user,
            'from': self._fromDT,
            'to': self._toDT
        }
        missing = [key for key, val in self._params.iteritems() if not val]
        if missing:
            raise HTTPAPIError('Required params missing: {}'.format(', '.join(missing)))
        self._room = Room.get(self._params['room_id'])
        if not self._room:
            raise HTTPAPIError('A room with this ID does not exist')
Example #4
0
 def _getParams(self):
     super()._getParams()
     self._fromDT = utc_to_server(self._fromDT.astimezone(
         pytz.utc)).replace(tzinfo=None) if self._fromDT else None
     self._toDT = utc_to_server(self._toDT.astimezone(pytz.utc)).replace(
         tzinfo=None) if self._toDT else None
     self._occurrences = _yesno(
         get_query_parameter(self._queryParams, ['occ', 'occurrences'],
                             'no'))
Example #5
0
 def _process(self):
     q = (ReservationOccurrence.query.filter(
         ReservationOccurrence.start_dt > utc_to_server(now_utc()),
         db.or_(Reservation.booked_for_user == session.user,
                Reservation.created_by_user == session.user)).join(
                    Reservation).order_by(
                        ReservationOccurrence.start_dt.asc()).limit(5))
     return jsonify(reservation_occurrences_schema.dump(q).data)
Example #6
0
def _get_category_score(user, categ, attended_events, debug=False):
    if debug:
        print(repr(categ))
    # We care about events in the whole timespan where the user attended some events.
    # However, this might result in some missed events e.g. if the user was not working for
    # a year and then returned. So we throw away old blocks (or rather adjust the start time
    # to the start time of the newest block)
    first_event_date = attended_events[0].start_dt.replace(hour=0, minute=0)
    last_event_date = attended_events[-1].start_dt.replace(hour=0, minute=0) + timedelta(days=1)
    blocks = _get_blocks(_query_categ_events(categ, first_event_date, last_event_date), attended_events)
    for a, b in window(blocks):
        # More than 3 months between blocks? Ignore the old block!
        if b[0].start_dt - a[-1].start_dt > timedelta(weeks=12):
            first_event_date = b[0].start_dt.replace(hour=0, minute=0)

    # Favorite categories get a higher base score
    score = int(categ in user.favorite_categories)
    if debug:
        print('{0:+.3f} - initial'.format(score))
    # Attendance percentage goes to the score directly. If the attendance is high chances are good that the user
    # is either very interested in whatever goes on in the category or it's something he has to attend regularily.
    total = _query_categ_events(categ, first_event_date, last_event_date).count()
    if total:
        attended_block_event_count = sum(1 for e in attended_events if e.start_dt >= first_event_date)
        score += attended_block_event_count / total
    if debug:
        print('{0:+.3f} - attendance'.format(score))
    # If there are lots/few unattended events after the last attended one we also update the score with that
    total_after = _query_categ_events(categ, last_event_date + timedelta(days=1), None).count()
    if total_after < total * 0.05:
        score += 0.25
    elif total_after > total * 0.25:
        score -= 0.5
    if debug:
        print('{0:+.3f} - unattended new events'.format(score))
    # Lower the score based on how long ago the last attended event was if there are no future events
    # We start applying this modifier only if the event has been more than 40 days in the past to avoid
    # it from happening in case of monthly events that are not created early enough.
    days_since_last_event = (date.today() - last_event_date.date()).days
    if days_since_last_event > 40:
        score -= 0.025 * days_since_last_event
    if debug:
        print('{0:+.3f} - days since last event'.format(score))
    # For events in the future however we raise the score
    now_local = utc_to_server(now_utc())
    attending_future = (_query_categ_events(categ, now_local, last_event_date)
                        .filter(Event.id.in_(e.id for e in attended_events))
                        .all())
    if attending_future:
        score += 0.25 * len(attending_future)
        if debug:
            print('{0:+.3f} - future event count'.format(score))
        days_to_future_event = (attending_future[0].start_dt.date() - date.today()).days
        score += max(0.1, -(max(0, days_to_future_event - 2) / 4) ** (1 / 3) + 2.5)
        if debug:
            print('{0:+.3f} - days to next future event'.format(score))
    return score
Example #7
0
def _get_category_score(user, categ, attended_events, debug=False):
    if debug:
        print(repr(categ))
    # We care about events in the whole timespan where the user attended some events.
    # However, this might result in some missed events e.g. if the user was not working for
    # a year and then returned. So we throw away old blocks (or rather adjust the start time
    # to the start time of the newest block)
    first_event_date = attended_events[0].start_dt.replace(hour=0, minute=0)
    last_event_date = attended_events[-1].start_dt.replace(hour=0, minute=0) + timedelta(days=1)
    blocks = _get_blocks(_query_categ_events(categ, first_event_date, last_event_date), attended_events)
    for a, b in window(blocks):
        # More than 3 months between blocks? Ignore the old block!
        if b[0].start_dt - a[-1].start_dt > timedelta(weeks=12):
            first_event_date = b[0].start_dt.replace(hour=0, minute=0)

    # Favorite categories get a higher base score
    score = int(categ in user.favorite_categories)
    if debug:
        print('{0:+.3f} - initial'.format(score))
    # Attendance percentage goes to the score directly. If the attendance is high chances are good that the user
    # is either very interested in whatever goes on in the category or it's something he has to attend regularily.
    total = _query_categ_events(categ, first_event_date, last_event_date).count()
    if total:
        attended_block_event_count = sum(1 for e in attended_events if e.start_dt >= first_event_date)
        score += attended_block_event_count / total
    if debug:
        print('{0:+.3f} - attendance'.format(score))
    # If there are lots/few unattended events after the last attended one we also update the score with that
    total_after = _query_categ_events(categ, last_event_date + timedelta(days=1), None).count()
    if total_after < total * 0.05:
        score += 0.25
    elif total_after > total * 0.25:
        score -= 0.5
    if debug:
        print('{0:+.3f} - unattended new events'.format(score))
    # Lower the score based on how long ago the last attended event was if there are no future events
    # We start applying this modifier only if the event has been more than 40 days in the past to avoid
    # it from happening in case of monthly events that are not created early enough.
    days_since_last_event = (date.today() - last_event_date.date()).days
    if days_since_last_event > 40:
        score -= 0.025 * days_since_last_event
    if debug:
        print('{0:+.3f} - days since last event'.format(score))
    # For events in the future however we raise the score
    now_local = utc_to_server(now_utc())
    attending_future = (_query_categ_events(categ, now_local, last_event_date)
                        .filter(Event.id.in_(e.id for e in attended_events))
                        .all())
    if attending_future:
        score += 0.25 * len(attending_future)
        if debug:
            print('{0:+.3f} - future event count'.format(score))
        days_to_future_event = (attending_future[0].start_dt.date() - date.today()).days
        score += max(0.1, -(max(0, days_to_future_event - 2) / 4) ** (1 / 3) + 2.5)
        if debug:
            print('{0:+.3f} - days to next future event'.format(score))
    return score
Example #8
0
 def _process(self):
     q = (ReservationOccurrence.query
          .filter(ReservationOccurrence.start_dt > utc_to_server(now_utc()),
                  db.or_(
                      Reservation.booked_for_user == session.user,
                      Reservation.created_by_user == session.user))
          .join(Reservation)
          .order_by(ReservationOccurrence.start_dt.asc())
          .limit(5))
     return jsonify(reservation_occurrences_schema.dump(q).data)
Example #9
0
 def __init__(self, event_id, contrib_id=None, start_date=None, end_date=None, **report_params):
     self.event_id = event_id
     self.contrib_id = contrib_id
     self._init_date_range(start_date, end_date)
     self.params = {'start_date': self.start_date,
                    'end_date': self.end_date,
                    'event_id': self.event_id,
                    'contrib_id': self.contrib_id}
     self._build_report(**report_params)
     self.timestamp = utc_to_server(now_utc())
Example #10
0
 def __init__(self,
              event_id,
              contrib_id=None,
              start_date=None,
              end_date=None,
              **report_params):
     self.event_id = event_id
     self.contrib_id = contrib_id
     self._init_date_range(start_date, end_date)
     self.params = {
         'start_date': self.start_date,
         'end_date': self.end_date,
         'event_id': self.event_id,
         'contrib_id': self.contrib_id
     }
     self._build_report(**report_params)
     self.timestamp = utc_to_server(now_utc())
Example #11
0
def _format_dt(dt):
    return utc_to_server(dt.replace(second=0, microsecond=0)).replace(
        tzinfo=None).isoformat(' ') if dt else None
Example #12
0
 def _getParams(self):
     super(RoomBookingHookBase, self)._getParams()
     self._fromDT = utc_to_server(self._fromDT.astimezone(pytz.utc)).replace(tzinfo=None) if self._fromDT else None
     self._toDT = utc_to_server(self._toDT.astimezone(pytz.utc)).replace(tzinfo=None) if self._toDT else None
     self._occurrences = _yesno(get_query_parameter(self._queryParams, ['occ', 'occurrences'], 'no'))