Exemplo n.º 1
0
    def iter_start_time(start, end, repetition):
        from indico.modules.rb.models.reservations import RepeatFrequency

        repeat_frequency, repeat_interval = repetition

        if repeat_frequency == RepeatFrequency.NEVER:
            return [start]

        elif repeat_frequency == RepeatFrequency.DAY:
            if repeat_interval != 1:
                raise IndicoError('Unsupported interval')
            return rrule.rrule(rrule.DAILY, dtstart=start, until=end)

        elif repeat_frequency == RepeatFrequency.WEEK:
            if repeat_interval <= 0:
                raise IndicoError('Unsupported interval')
            return rrule.rrule(rrule.WEEKLY, dtstart=start, until=end, interval=repeat_interval)

        elif repeat_frequency == RepeatFrequency.MONTH:
            if repeat_interval == 0:
                raise IndicoError('Unsupported interval')
            position = int(ceil(start.day / 7.0))
            if position == 5:
                # The fifth weekday of the month will always be the last one
                position = -1
            return rrule.rrule(rrule.MONTHLY, dtstart=start, until=end, byweekday=start.weekday(),
                               bysetpos=position, interval=repeat_interval)

        raise IndicoError(f'Unexpected frequency {repeat_frequency}')
Exemplo n.º 2
0
 def _process_args(self):
     self._room = Room.get(request.view_args['roomID'])
     self._occupancy_period = request.args.get('period', 'pastmonth')
     self._end = date.today()
     if self._occupancy_period == 'pastmonth':
         self._end = self._end - relativedelta(days=1)
         self._start = self._end - relativedelta(days=29)
     elif self._occupancy_period == 'thisyear':
         self._start = date(self._end.year, 1, 1)
     elif self._occupancy_period == 'sinceever':
         oldest = db.session.query(func.min(
             Reservation.start_dt)).filter_by(
                 room_id=self._room.id).scalar()
         self._start = oldest.date() if oldest else self._end
     else:
         match = re.match(r'(\d{4})(?:-(\d{2}))?', self._occupancy_period)
         if match is None:
             raise IndicoError(u'Invalid period specified')
         year = int(match.group(1))
         month = int(match.group(2)) if match.group(2) else None
         if month:
             try:
                 self._start = date(year, month, 1)
             except ValueError:
                 raise IndicoError(u'Invalid year or month specified')
             self._end = self._start + relativedelta(months=1)
             self._occupancy_period = '{:d}-{:02d}'.format(year, month)
         else:
             try:
                 self._start = date(year, 1, 1)
             except ValueError:
                 raise IndicoError(u'Invalid year specified')
             self._end = self._start + relativedelta(years=1)
             self._occupancy_period = str(year)
Exemplo n.º 3
0
    def _process_args(self):
        id_ = request.view_args['event_vc_room_id']
        self.event_vc_room = VCRoomEventAssociation.find_one(id=id_)
        if not self.event_vc_room:
            raise NotFound(_("Event VC Room not found for id {id}").format(id=id_))

        if not self.event_vc_room.link_object:
            raise IndicoError(_("Event VC Room ({id}) is not linked to anything").format(id=id_))

        event_id = int(request.view_args['confId'])
        event = self.event_vc_room.link_object.event
        if not event:
            raise IndicoError(_("Event VC Room ({id}) does not have an event").format(id=id_))

        if event.id != event_id:
            raise IndicoError(_("Event VC Room ({id}) does not have an event with the id {conf.id}")
                              .format(id=id_, conf=event))

        room = self.event_vc_room.link_object.room if self.event_vc_room.link_object else None
        if not room:
            raise IndicoError(_("Event VC Room ({id}) is not linked to an event with a room").format(id=id_))

        self.room_name = room.generate_name()
        self.room_special_name = room.name

        if not self.room_name:
            raise IndicoError(_("Event VC Room ({id}) is not linked to an event with a valid room").format(id=id_))

        if not self.room_special_name:
            self.room_special_name = self.room_name
Exemplo n.º 4
0
 def _process_select_period(self):
     form = self._make_select_period_form()
     if form.is_submitted():
         # Errors in here are only caused by users messing with the submitted data so it's not
         # worth making the code more complex to show the errors nicely on the originating page.
         # Doing so would be very hard anyway as we don't keep all data necessary to show step 2
         # when it's not a step 1 form submission.
         if not form.validate():
             raise IndicoError('<br>'.join(form.error_list))
         room = Room.get(form.room_id.data)
         if not room:
             raise IndicoError('Invalid room')
         # Show step 3 page
         confirm_form_defaults = FormDefaults(form.data)
         return self._show_confirm(room, form, self._step, confirm_form_defaults)
Exemplo n.º 5
0
 def _process(self):
     if self._reservation.find_overlapping().filter(Reservation.is_accepted).count():
         raise IndicoError("This reservation couldn't be accepted due to conflicts with other reservations")
     if self._reservation.is_pending:
         self._reservation.accept(session.user)
         flash(_(u'Booking accepted'), 'success')
     self._redirect(self._get_success_url())
Exemplo n.º 6
0
 def _checkParams(self, params):
     RHConferenceModifBase._checkParams(self, params)
     try:
         self.event_id = int(self._conf.id)
     except ValueError:
         raise IndicoError(_('This page is not available for legacy events.'))
     self.event = self._conf
Exemplo n.º 7
0
    def to_serializable(self, attr='__public__', converters=None):
        serializable = {}
        if converters is None:
            converters = {}
        for k in getattr(self, attr):
            try:
                if isinstance(k, tuple):
                    k, name = k
                else:
                    k, name = k, k

                v = getattr(self, k)
                if callable(
                        v
                ):  # to make it generic, we can get rid of it by properties
                    v = v()
                if isinstance(v, Serializer):
                    v = v.to_serializable()
                elif isinstance(v, list):
                    v = [e.to_serializable() for e in v]
                elif isinstance(v, dict):
                    v = dict((k, vv.to_serializable(
                    ) if isinstance(vv, Serializer) else vv)
                             for k, vv in v.iteritems())
                if type(v) in converters:
                    v = converters[type(v)](v)
                serializable[name] = v
            except Exception:
                msg = 'Could not retrieve {}.{}.'.format(
                    self.__class__.__name__, k)
                Logger.get('Serializer{}'.format(
                    self.__class__.__name__)).exception(msg)
                raise IndicoError(msg)
        return serializable
Exemplo n.º 8
0
 def _checkProtection(self):
     RHRoomBookingCreateModifyBlockingBase._checkProtection(self)
     if not self._doProcess:  # we are not logged in
         return
     if not self._blocking.can_be_modified(self._getUser()):
         raise IndicoError(
             _("You are not authorized to modify this blocking."))
Exemplo n.º 9
0
 def _checkParams(self):
     self._with_kpi = request.args.get('withKPI', type=bool)
     self._actionSucceeded = request.args.get('actionSucceeded', default=False, type=bool)
     location_name = request.view_args.get('locationId')
     self._location = Location.find_first(name=location_name)
     if not self._location:
         raise IndicoError('Unknown Location: {0}'.format(location_name))
Exemplo n.º 10
0
        def wrapper(*args, **kw):
            for e in list(args) + kw.values():
                if isinstance(e, Exception):
                    exception = e
                    break
            else:
                raise IndicoError(
                    'Wrong usage of jsonify_error: No error found in params')

            tb = ''
            if logging_level != 'exception' and not isinstance(
                    exception, no_tb_exceptions):
                tb = traceback.format_exc()
            logger_fn = getattr(Logger.get(logger_name), logging_level)
            logger_fn(
                logger_message
                if logger_message else 'Request finished: {} ({})\n{}'.
                format(exception.__class__.__name__, exception, tb).rstrip())

            # allow e.g. NoReportError to specify a status code without possibly
            # breaking old code that expects it with a 200 code.
            # new variable name since python2 doesn't have `nonlocal`...
            used_status = getattr(exception, 'http_status_code', status)
            if request.is_xhr or request.headers.get(
                    'Content-Type') == 'application/json':
                if log_sentry:
                    sentry_log_exception()
                return create_json_error_answer(exception, status=used_status)
            else:
                args[0]._responseUtil.status = used_status
                return f(*args, **kw)
Exemplo n.º 11
0
    def _process_args(self):
        id_ = request.view_args['event_vc_room_id']
        self.event_vc_room = self.get_event_vc_room(id_)

        event_id = request.view_args['event_id']
        event = self.event_vc_room.link_object.event
        if not event:
            raise IndicoError(_("Event VC Room ({id}) does not have an event").format(id=id_))
        if event.id != event_id:
            raise IndicoError(_("Event VC Room ({id}) does not have an event with the id {conf.id}")
                              .format(id=id_, conf=event))

        self.room = self.event_vc_room.link_object.room if self.event_vc_room.link_object else None
        if not self.room:
            raise IndicoError(_("Event VC Room ({id}) is not linked to an event with a room").format(id=id_))
        if not self.room.name:
            raise IndicoError(_("Event VC Room ({id}) is not linked to an event with a valid room").format(id=id_))
Exemplo n.º 12
0
 def _process_args(self):
     self._blocking = Blocking.get(request.view_args['blocking_id'])
     if self._blocking is None:
         raise IndicoError('A blocking with this ID does not exist.')
     defaults = FormDefaults(self._blocking, attrs={'reason'},
                             principals=self._blocking.allowed,
                             blocked_rooms=[br.room_id for br in self._blocking.blocked_rooms])
     self._form = BlockingForm(obj=defaults)
     self._form._blocking = self._blocking
Exemplo n.º 13
0
 def _process(self):
     try:
         room_event_assocs = VCRoomEventAssociation.find_for_event(self._conf, include_hidden=True,
                                                                   include_deleted=True).all()
     except ValueError:
         raise IndicoError(_('This page is not available for legacy events.'))
     event_vc_rooms = [event_vc_room for event_vc_room in room_event_assocs if event_vc_room.vc_room.plugin]
     return WPVCManageEvent.render_template('manage_event.html', self._conf, event=self._conf,
                                            event_vc_rooms=event_vc_rooms, plugins=get_vc_plugins().values())
Exemplo n.º 14
0
 def get_event_vc_room(self, id_):
     event_vc_room = VCRoomEventAssociation.query.get(id_)
     if not event_vc_room:
         raise NotFound(_("Event VC Room not found for id {id}").format(id=id_))
     if not event_vc_room.link_object:
         raise IndicoError(
             _("Event VC Room ({id}) is not linked to anything").format(id=id_)
         )
     return event_vc_room
Exemplo n.º 15
0
    def wrapper(*args, **kw):
        if not args:
            raise IndicoError(_('Wrong usage of location decorator'))

        location_name = getattr(request, request_attribute).get(parameter_name, None)
        location = Location.find_first(name=location_name)
        if not location:
            raise NotFoundError(_('There is no location named: {0}').format(location_name))
        setattr(args[0], attribute_name, location)
        return f(*args, **kw)
Exemplo n.º 16
0
 def _process_confirm(self):
     # The form needs the room to create the equipment list, so we need to get it "manually"...
     room = Room.get(int(request.form['room_id']))
     form = self._make_confirm_form(room)
     if not room.can_be_booked(session.user) and not room.can_be_prebooked(session.user):
         raise IndicoError('You cannot book this room')
     if form.validate_on_submit():
         return self._create_booking_response(form, room)
     # There was an error in the form
     return self._show_confirm(room, form)
Exemplo n.º 17
0
 def check_bookable_hours(self, start_time, end_time, user=None, quiet=False):
     if user and (user.isRBAdmin() or self.is_owned_by(user)):
         return True
     bookable_hours = self.bookable_hours.all()
     if not bookable_hours:
         return True
     for bt in bookable_hours:
         if bt.fits_period(start_time, end_time):
             return True
     if quiet:
         return False
     raise IndicoError('Room cannot be booked at this time')
Exemplo n.º 18
0
def check_config(quiet=False):
    """Checks if all required config options are set

    :param quiet: if True, return the result as a bool, otherwise
                  raise `IndicoError` if any setting is missing
    """
    from indico_chat.plugin import ChatPlugin
    settings = ChatPlugin.settings.get_all()
    missing = not all(settings[x] for x in ('server', 'muc_server', 'bot_jid', 'bot_password'))
    if missing and not quiet:
        raise IndicoError(_('Chat plugin is not configured properly'))
    return not missing
Exemplo n.º 19
0
 def check_advance_days(self, end_date, user=None, quiet=False):
     if not self.max_advance_days:
         return True
     if user and (user.isRBAdmin() or self.is_owned_by(user)):
         return True
     advance_days = (end_date - date.today()).days
     ok = advance_days < self.max_advance_days
     if quiet or ok:
         return ok
     else:
         msg = _('You cannot book this room more than {} days in advance')
         raise IndicoError(msg.format(self.max_advance_days))
Exemplo n.º 20
0
 def _checkParams(self):
     self._room = Room.get(request.view_args['roomID'])
     self._occupancy_period = request.args.get('period', 'pastmonth')
     self._end = date.today()
     if self._occupancy_period == 'pastmonth':
         self._start = self._end - relativedelta(months=1)
     elif self._occupancy_period == 'thisyear':
         self._start = date(self._end.year, 1, 1)
     elif self._occupancy_period == 'sinceever':
         self._start = Reservation.query.with_entities(
             func.min(Reservation.start_dt)).one()[0].date()
     else:
         raise IndicoError('Invalid period specified')
    def iter_start_time(start, end, repetition):
        from indico.modules.rb.models.reservations import RepeatFrequency

        repeat_frequency, repeat_interval = repetition

        if repeat_frequency == RepeatFrequency.NEVER:
            return [start]

        if repeat_frequency == RepeatFrequency.DAY:
            if repeat_interval == 1:
                return rrule.rrule(rrule.DAILY, dtstart=start, until=end)
            else:
                raise IndicoError('Unsuported interval')

        elif repeat_frequency == RepeatFrequency.WEEK:
            if 0 < repeat_interval < 4:
                return rrule.rrule(rrule.WEEKLY,
                                   dtstart=start,
                                   until=end,
                                   interval=repeat_interval)
            else:
                raise IndicoError('Unsupported interval')

        elif repeat_frequency == RepeatFrequency.MONTH:
            if repeat_interval == 1:
                position = start.day // 7 + 1
                if position == 5:
                    # The fifth weekday of the month will always be the last one
                    position = -1
                return rrule.rrule(rrule.MONTHLY,
                                   dtstart=start,
                                   until=end,
                                   byweekday=start.weekday(),
                                   bysetpos=position)
            else:
                raise IndicoError(
                    'Unsupported interval {}'.format(repeat_interval))

        raise IndicoError('Unexpected frequency {}'.format(repeat_frequency))
Exemplo n.º 22
0
 def _process(self):
     res = AsyncResult(request.view_args['task_id'])
     try:
         download_url = res.get(5, propagate=False)
     except TimeoutError:
         return jsonify(download_url=None)
     try:
         if res.successful():
             return jsonify(download_url=download_url)
         else:
             raise IndicoError(_('Material package generation failed'))
     finally:
         res.forget()
Exemplo n.º 23
0
    def wrapper(*args, **kw):
        try:
            location = getattr(args[0], location_attribute_name)
        except (AttributeError, IndexError):
            raise IndicoError(_('Wrong usage of room decorator'))

        room_id = getattr(request, request_attribute).get(parameter_name, None)
        try:
            room = Room.query.with_parent(location).filter_by(id=room_id).one()
        except NoResultFound:
            raise NotFoundError(_("There is no room at '{1}' with id: {0}").format(room_id, location.name))
        setattr(args[0], attribute_name, room)
        return f(*args, **kw)
Exemplo n.º 24
0
    def _checkParams(self):
        name = request.view_args.get('locationId')
        self._location = Location.find_first(name=name)
        if not self._location:
            raise IndicoError(_('Unknown Location: {0}').format(name))

        self._new_attr = None
        attr_title = request.form.get('newCustomAttributeName', default='').strip()
        if attr_title:
            attr_name = attr_title.replace(' ', '-').lower()
            if self._location.get_attribute_by_name(attr_name):
                raise FormValuesError(_('There is already an attribute named: {0}').format(attr_name))

            self._new_attr = RoomAttribute(name=attr_name, title=attr_title, type='str',
                                           is_required=request.form.get('newCustomAttributeIsRequired') == 'on',
                                           is_hidden=request.form.get('newCustomAttributeIsHidden') == 'on')
Exemplo n.º 25
0
        def wrapper(*args, **kw):
            for e in list(args) + kw.values():
                if isinstance(e, Exception):
                    exception = e
                    break
            else:
                raise IndicoError('Wrong usage of jsonify_error: No error found in params')

            tb = traceback.format_exc() if logging_level != 'exception' else ''
            getattr(Logger.get(logger_name), logging_level)(
                logger_message if logger_message else
                'Request {0} finished with {1}: {2}\n{3}'.format(
                    request, exception.__class__.__name__, exception, tb
                ).rstrip())

            if request.is_xhr or request.headers.get('Content-Type') == 'application/json':
                return create_json_error_answer(exception)
            else:
                return f(*args, **kw)
Exemplo n.º 26
0
    def _process(self):
        if self.chatroom.custom_server:
            return jsonify(result='')

        config = get_room_config(self.chatroom.jid)
        if config is None:
            if not room_exists(self.chatroom.jid):
                return jsonify(result='not-found')
            raise IndicoError(_('Unexpected result from Jabber server'))

        changed = False
        for key, value in config.iteritems():
            if getattr(self.chatroom, key) != value:
                changed = True
                setattr(self.chatroom, key, value)

        if changed:
            self.event.log(EventLogRealm.management, EventLogKind.change, 'Chat',
                           'Chatroom updated during refresh: {}'.format(self.chatroom.name), session.user)

        return jsonify(result='changed' if changed else '')
Exemplo n.º 27
0
 def _checkProtection(self):
     RHRoomBookingBase._checkProtection(self)
     if not self._reservation.can_be_cancelled(session.user):
         raise IndicoError("You are not authorized to perform this action")
Exemplo n.º 28
0
 def _check_access(self):
     RHRoomBookingBase._check_access(self)
     if not self._block.can_be_deleted(session.user):
         raise IndicoError('You are not authorized to delete this blocking.')
Exemplo n.º 29
0
 def _process_args(self):
     self._blocking = Blocking.get(request.view_args['blocking_id'])
     if not self._blocking:
         raise IndicoError('A blocking with this ID does not exist.')
Exemplo n.º 30
0
 def _checkParams(self):
     resv_id = request.view_args.get('resvID')
     self._reservation = Reservation.get(request.view_args['resvID'])
     if not self._reservation:
         raise IndicoError('No booking with id: {}'.format(resv_id))