예제 #1
0
    def testRemoveLocationByName(self):
        test_location_name = 'test_location'
        db.session.add(Location(name=test_location_name))
        db.session.commit()

        assert Location.getLocationByName(test_location_name) is not None
        Location.removeLocationByName(test_location_name)
        db.session.commit()
        assert Location.getLocationByName(test_location_name) is None
예제 #2
0
    def migrate_locations(self):
        print cformat("%{white!}migrating locations")
        default_location_name = self.zodb_root["DefaultRoomBookingLocation"]
        custom_attributes_dict = self.rb_root["CustomAttributesList"]

        for old_location in self.zodb_root["RoomBookingLocationList"]:
            # create location
            l = Location(
                name=convert_to_unicode(old_location.friendlyName),
                is_default=(old_location.friendlyName == default_location_name),
            )

            print cformat("- %{cyan}{}").format(l.name)

            # add aspects
            for old_aspect in old_location._aspects.values():
                a = Aspect(
                    name=convert_to_unicode(old_aspect.name),
                    center_latitude=old_aspect.centerLatitude,
                    center_longitude=old_aspect.centerLongitude,
                    zoom_level=old_aspect.zoomLevel,
                    top_left_latitude=old_aspect.topLeftLatitude,
                    top_left_longitude=old_aspect.topLeftLongitude,
                    bottom_right_latitude=old_aspect.bottomRightLatitude,
                    bottom_right_longitude=old_aspect.bottomRightLongitude,
                )

                print cformat("  %{blue!}Aspect:%{reset} {}").format(a.name)

                l.aspects.append(a)
                if old_aspect.defaultOnStartup:
                    l.default_aspect = a

            # add custom attributes
            for ca in custom_attributes_dict.get(l.name, []):
                if ca["type"] != "str":
                    raise RuntimeError("Non-str custom attributes are unsupported: {}".format(ca))
                attr_name = attribute_map.get(ca["name"], ca["name"])
                attr = RoomAttribute(
                    name=attr_name.replace(" ", "-").lower(),
                    title=attr_name,
                    type=ca["type"],
                    is_required=ca["required"],
                    is_hidden=ca["hidden"],
                )
                l.attributes.append(attr)
                print cformat("  %{blue!}Attribute:%{reset} {}").format(attr.title)

            # add new created location
            db.session.add(l)
            print
            print
        db.session.commit()
예제 #3
0
    def migrate_locations(self):
        print cformat('%{white!}migrating locations')
        default_location_name = self.zodb_root['DefaultRoomBookingLocation']
        custom_attributes_dict = self.rb_root['CustomAttributesList']

        for old_location in self.zodb_root['RoomBookingLocationList']:
            # create location
            l = Location(
                name=convert_to_unicode(old_location.friendlyName),
                is_default=(
                    old_location.friendlyName == default_location_name))

            print cformat('- %{cyan}{}').format(l.name)

            # add aspects
            for old_aspect in old_location._aspects.values():
                a = Aspect(
                    name=convert_to_unicode(old_aspect.name),
                    center_latitude=old_aspect.centerLatitude,
                    center_longitude=old_aspect.centerLongitude,
                    zoom_level=old_aspect.zoomLevel,
                    top_left_latitude=old_aspect.topLeftLatitude,
                    top_left_longitude=old_aspect.topLeftLongitude,
                    bottom_right_latitude=old_aspect.bottomRightLatitude,
                    bottom_right_longitude=old_aspect.bottomRightLongitude)

                print cformat('  %{blue!}Aspect:%{reset} {}').format(a.name)

                l.aspects.append(a)
                if old_aspect.defaultOnStartup:
                    l.default_aspect = a

            # add custom attributes
            for ca in custom_attributes_dict.get(l.name, []):
                if ca['type'] != 'str':
                    raise RuntimeError(
                        'Non-str custom attributes are unsupported: {}'.format(
                            ca))
                attr_name = attribute_map.get(ca['name'], ca['name'])
                attr = RoomAttribute(name=attr_name.replace(' ', '-').lower(),
                                     title=attr_name,
                                     type=ca['type'],
                                     is_required=ca['required'],
                                     is_hidden=ca['hidden'])
                l.attributes.append(attr)
                print cformat('  %{blue!}Attribute:%{reset} {}').format(
                    attr.title)

            # add new created location
            db.session.add(l)
            print
            print
        db.session.commit()
def migrate_locations(main_root, rb_root):
    print cformat('%{white!}migrating locations')
    default_location_name = main_root['DefaultRoomBookingLocation']
    custom_attributes_dict = rb_root['CustomAttributesList']

    for old_location in main_root['RoomBookingLocationList']:
        # create location
        l = Location(
            name=convert_to_unicode(old_location.friendlyName),
            is_default=(old_location.friendlyName == default_location_name)
        )

        print cformat('- %{cyan}{}').format(l.name)

        # add aspects
        for old_aspect in old_location._aspects.values():
            a = Aspect(
                name=convert_to_unicode(old_aspect.name),
                center_latitude=old_aspect.centerLatitude,
                center_longitude=old_aspect.centerLongitude,
                zoom_level=old_aspect.zoomLevel,
                top_left_latitude=old_aspect.topLeftLatitude,
                top_left_longitude=old_aspect.topLeftLongitude,
                bottom_right_latitude=old_aspect.bottomRightLatitude,
                bottom_right_longitude=old_aspect.bottomRightLongitude
            )

            print cformat('  %{blue!}Aspect:%{reset} {}').format(a.name)

            l.aspects.append(a)
            if old_aspect.defaultOnStartup:
                l.default_aspect = a

        # add custom attributes
        for ca in custom_attributes_dict.get(l.name, []):
            if ca['type'] != 'str':
                raise RuntimeError('Non-str custom attributes are unsupported: {}'.format(ca))
            attr_name = attribute_map.get(ca['name'], ca['name'])
            attr = RoomAttribute(name=attr_name.replace(' ', '-').lower(), title=attr_name, type=ca['type'],
                                 is_required=ca['required'], is_hidden=ca['hidden'])
            l.attributes.append(attr)
            print cformat('  %{blue!}Attribute:%{reset} {}').format(attr.title)

        # add new created location
        db.session.add(l)
        print
        print
    db.session.commit()
예제 #5
0
 def wrapper(*args, **kw):
     location_name = getattr(request, request_attribute).get(parameter_name, None)
     location = Location.find_first(name=location_name)
     if not location:
         raise NotFound(_('There is no location named: {0}').format(location_name))
     setattr(args[0], attribute_name, location)
     return f(*args, **kw)
예제 #6
0
 def process_formdata(self, valuelist):
     super(IndicoLocationField, self).process_formdata(valuelist)
     self.data['room'] = Room.get(int(self.data['room_id'])) if self.data.get('room_id') else None
     self.data['venue'] = (Location.get(int(self.data['venue_id']), is_deleted=False)
                           if self.data.get('venue_id')
                           else None)
     self.data['source'] = self.object_data.get('source') if self.object_data else None
def main(main_uri, rb_uri, sqla_uri, photo_path, drop, merged_avatars):
    update_session_options(db)  # get rid of the zope transaction extension
    main_root, rb_root, app = setup(main_uri, rb_uri, sqla_uri)
    global tz
    try:
        tz = pytz.timezone(main_root['MaKaCInfo']['main'].getTimezone())
    except KeyError:
        tz = pytz.utc

    start = time.clock()
    with app.app_context():
        if drop:
            print cformat('%{yellow!}*** DANGER')
            print cformat('%{yellow!}***%{reset} '
                          '%{red!}ALL DATA%{reset} in your database %{yellow!}{!r}%{reset} will be '
                          '%{red!}PERMANENTLY ERASED%{reset}!').format(db.engine.url)
            if raw_input(cformat('%{yellow!}***%{reset} To confirm this, enter %{yellow!}YES%{reset}: ')) != 'YES':
                print 'Aborting'
                sys.exit(1)
            delete_all_tables(db)
        stamp()
        db.create_all()
        if Location.find().count():
            # Usually there's no good reason to migrate with data in the DB. However, during development one might
            # comment out some migration tasks and run the migration anyway.
            print cformat('%{yellow!}*** WARNING')
            print cformat('%{yellow!}***%{reset} Your database is not empty, migration will most likely fail!')
            if raw_input(cformat('%{yellow!}***%{reset} To confirm this, enter %{yellow!}YES%{reset}: ')) != 'YES':
                print 'Aborting'
                sys.exit(1)
        migrate(main_root, rb_root, photo_path, merged_avatars)
    print 'migration took {} seconds'.format((time.clock() - start))
예제 #8
0
    def testClone(self):
        original = Location.getDefaultLocation()
        cloned = utils.clone(Location, original)

        assert cloned.id != original.id
        assert cloned.name == original.name
        assert cloned.default_aspect.id == original.default_aspect.id
예제 #9
0
 def get_location_data(params):
     location_data = json.loads(params['location_data'])
     if location_data.get('room_id'):
         location_data['room'] = Room.get_one(location_data['room_id'])
     if location_data.get('venue_id'):
         location_data['venue'] = Location.get_one(location_data['venue_id'])
     return location_data
예제 #10
0
 def _process_POST(self, name, room_name_format, map_url_template):
     loc = Location(name=name,
                    room_name_format=room_name_format,
                    map_url_template=(map_url_template or ''))
     db.session.add(loc)
     db.session.flush()
     return self._jsonify_one(loc), 201
예제 #11
0
 def _process_args(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_one(name=location_name)
예제 #12
0
    def export_reservation(self, aw):
        locations = Location.find_all(Location.name.in_(self._locations))
        if not locations:
            return

        for room_id, reservation in _export_reservations(self, False, True):
            yield reservation
예제 #13
0
파일: locations.py 프로젝트: NIIF/indico
 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))
예제 #14
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))
예제 #15
0
    def export_reservation(self, user):
        locations = Location.find_all(Location.name.in_(self._locations))
        if not locations:
            return

        for room_id, reservation in _export_reservations(self, False, True):
            yield reservation
예제 #16
0
파일: locations.py 프로젝트: NIIF/indico
 def _checkParams(self):
     self._locationName = request.form.get('newLocationName').strip()
     if not self._locationName:
         raise FormValuesError(_('Location name may not be empty'))
     if '/' in self._locationName:
         raise FormValuesError(_('Location name may not contain slashes'))
     if Location.find_first(name=self._locationName):
         raise FormValuesError(_('Location "{0}" already exists').format(self._locationName))
예제 #17
0
def get_location(building):
    location = Location.query.filter(Location.name == "Area {}".format(building), ~Location.is_deleted).first()
    if not location:
        location = Location(name="Area {}".format(building))
        print(cformat("%{green!}+%{reset} Adding new location for building {}").format(building))
        db.session.add(location)
        db.session.flush()
    return location
예제 #18
0
 def _process_args(self):
     self._locationName = request.form.get('newLocationName').strip()
     if not self._locationName:
         raise BadRequest(_('Location name may not be empty'))
     if '/' in self._locationName:
         raise BadRequest(_('Location name may not contain slashes'))
     if Location.find_first(name=self._locationName):
         raise BadRequest(_('Location "{0}" already exists').format(self._locationName))
예제 #19
0
 def _checkParams(self):
     self._locationName = request.form.get('newLocationName').strip()
     if not self._locationName:
         raise FormValuesError(_('Location name may not be empty'))
     if '/' in self._locationName:
         raise FormValuesError(_('Location name may not contain slashes'))
     if Location.find_first(name=self._locationName):
         raise FormValuesError(_('Location "{0}" already exists').format(self._locationName))
 def __init__(self, db_name, logger):
     self.db_name = db_name
     self._logger = logger
     try:
         self._location = Location.find_one(name='CERN')
     except NoResultFound:
         self._logger.exception("Synchronization failed: Location CERN not found in Indico DB")
         raise
예제 #21
0
 def get_location_data(params):
     location_data = json.loads(params['location_data'])
     if location_data.get('room_id'):
         location_data['room'] = Room.get_one(location_data['room_id'])
     if location_data.get('venue_id'):
         location_data['venue'] = Location.get_one(
             location_data['venue_id'])
     return location_data
예제 #22
0
파일: locations.py 프로젝트: qroques/indico
 def _process_args(self):
     self._locationName = request.form.get('newLocationName').strip()
     if not self._locationName:
         raise BadRequest(_('Location name may not be empty'))
     if '/' in self._locationName:
         raise BadRequest(_('Location name may not contain slashes'))
     if Location.find_first(name=self._locationName):
         raise BadRequest(_('Location "{0}" already exists').format(self._locationName))
예제 #23
0
 def wrapper(*args, **kw):
     location_name = getattr(request,
                             request_attribute).get(parameter_name, None)
     location = Location.find_first(name=location_name)
     if not location:
         raise NotFound(
             _('There is no location named: {0}').format(location_name))
     setattr(args[0], attribute_name, location)
     return f(*args, **kw)
예제 #24
0
파일: location.py 프로젝트: imfht/flaskapps
 def process_formdata(self, valuelist):
     from indico.modules.rb.models.locations import Location
     from indico.modules.rb.models.rooms import Room
     super().process_formdata(valuelist)
     self.data['room'] = Room.get(int(self.data['room_id'])) if self.data.get('room_id') else None
     self.data['venue'] = (Location.get(int(self.data['venue_id']), is_deleted=False)
                           if self.data.get('venue_id')
                           else None)
     self.data['source'] = self.object_data.get('source') if self.object_data else None
예제 #25
0
 def _checkParams(self):
     try:
         location = Location.find_one(name=self._params['location'])
     except NoResultFound:
         raise ServiceError(
             'ERR-RB0',
             'Invalid location name: {0}.'.format(self._params['location']))
     self._rooms = sorted(location.rooms,
                          key=lambda r: natural_sort_key(r.full_name))
예제 #26
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)
예제 #27
0
    def export_roomName(self, aw):
        loc = Location.find_first(name=self._location)
        if loc is None:
            return

        search_str = '%{}%'.format(self._room_name)
        rooms_data = Room.get_with_data('vc_equipment', 'non_vc_equipment',
                                        filters=[Room.location_id == loc.id, Room.name.ilike(search_str)])
        for result in rooms_data:
            yield _serializable_room(result)
예제 #28
0
파일: decorators.py 프로젝트: florv/indico
    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)
예제 #29
0
    def _process_args(self):
        name = request.view_args.get('locationId')
        self._location = Location.find_one(name=name)
        self._new_attr = None
        attr_title = request.form.get('newCustomAttributeName', default='').strip()
        if attr_title:
            attr_name = attr_title.replace(' ', '-').lower()
            if RoomAttribute.query.filter_by(name=attr_name).first():
                raise BadRequest(_('There is already an attribute named: {0}').format(attr_name))

            self._new_attr = RoomAttribute(name=attr_name, title=attr_title,
                                           is_hidden=request.form.get('newCustomAttributeIsHidden') == 'on')
예제 #30
0
def populate_db():
    """Populate DB with fun stuff"""

    # set tileserver URL
    rb_settings.set(
        'tileserver_url',
        'https://indico-maps.web.cern.ch/styles/cern/{z}/{x}/{y}.png')

    location = Location(name="CERN")
    owner = User.get(0)

    for area in MAP_AREAS:
        map_area = MapArea(name=area[0],
                           top_left_latitude=area[1],
                           top_left_longitude=area[2],
                           bottom_right_latitude=area[3],
                           bottom_right_longitude=area[4])
        db.session.add(map_area)

    for name in shower_names:
        # split name in parts
        building, floor, number = ROOM_RE.match(name).groups()
        # random number of showers, since we don't have time
        # to figure out what it really is
        num_showers = random.choice([2, 3, 4])
        file_name = './photos/{}.png'.format(name.replace('/', '_'))
        photo_data = None

        # Check if there's a photo in './photos/xxxx' and use it
        if os.path.exists(file_name):
            with open(file_name, 'r') as f:
                photo_data = f.read()
        else:
            print cformat("%{yellow}!%{reset} Photo for {} not found!").format(
                name)

        for num_shower in range(num_showers):
            room = Room(building=building,
                        floor=floor,
                        number=number,
                        verbose_name="Shower {}".format(num_shower + 1),
                        location=location,
                        division='CERN',
                        owner=owner,
                        capacity=1)
            if photo_data:
                room.photo = Photo(data=photo_data)
            if building in GEO_INFO:
                room.latitude, room.longitude = GEO_INFO[building]
            db.session.add(room)

    db.session.commit()
예제 #31
0
파일: api.py 프로젝트: vincentroman/indico
    def export_roomName(self, user):
        loc = Location.find_first(name=self._location)
        if loc is None:
            return

        search_str = '%{}%'.format(self._room_name)
        rooms_data = Room.get_with_data(filters=[
            Room.location_id == loc.id,
            or_(Room.name.ilike(search_str), Room.verbose_name.ilike(
                search_str))
        ])

        for result in rooms_data:
            yield _serializable_room(result)
예제 #32
0
파일: api.py 프로젝트: mic4ael/indico
    def export_roomName(self, user):
        loc = Location.find_first(name=self._location)
        if loc is None:
            return

        search_str = '%{}%'.format(self._room_name)
        rooms_data = Room.get_with_data(
            filters=[
                Room.location_id == loc.id,
                or_(Room.name.ilike(search_str),
                    Room.verbose_name.ilike(search_str))
            ])

        for result in rooms_data:
            yield _serializable_room(result)
예제 #33
0
    def export_roomName(self, aw):
        loc = Location.find_first(name=self._location)
        if loc is None:
            return

        search_str = '%{}%'.format(self._room_name)
        rooms_data = Room.get_with_data(
            'vc_equipment', 'non_vc_equipment', filters=[
                Room.location_id == loc.id,
                or_((Room.building + '-' + Room.floor + '-' + Room.number).ilike(search_str),
                    Room.name.ilike(search_str))
            ])

        for result in rooms_data:
            yield _serializable_room(result)
예제 #34
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')
예제 #35
0
파일: locations.py 프로젝트: NIIF/indico
    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')
예제 #36
0
    def export_room(self, user):
        loc = Location.find_first(name=self._location)
        if loc is None:
            return

        # Retrieve rooms
        rooms_data = list(Room.get_with_data(filters=[Room.id.in_(self._ids), Room.location_id == loc.id]))

        # Retrieve reservations
        reservations = None
        if self._detail == 'reservations':
            reservations = OrderedMultiDict(_export_reservations(self, True, False, [
                Reservation.room_id.in_(x['room'].id for x in rooms_data)
            ]))

        for result in rooms_data:
            yield _serializable_room(result, reservations)
예제 #37
0
파일: api.py 프로젝트: mic4ael/indico
    def export_room(self, user):
        loc = Location.find_first(name=self._location)
        if loc is None:
            return

        # Retrieve rooms
        rooms_data = list(Room.get_with_data(filters=[Room.id.in_(self._ids), Room.location_id == loc.id]))

        # Retrieve reservations
        reservations = None
        if self._detail == 'reservations':
            reservations = OrderedMultiDict(_export_reservations(self, True, False, [
                Reservation.room_id.in_(x['room'].id for x in rooms_data)
            ]))

        for result in rooms_data:
            yield _serializable_room(result, reservations)
예제 #38
0
 def _checkParams(self):
     self._location = Location.find_first(name=self._param('location'))
     aspect_data = self._param('aspect')
     try:
         zoom_level = int(aspect_data.get('zoom_level', '0'))
     except ValueError:
         zoom_level = 0
     self._aspect = Aspect(
         name=aspect_data.get('name', ''),
         center_latitude=aspect_data.get('center_latitude', ''),
         center_longitude=aspect_data.get('center_longitude', ''),
         zoom_level=zoom_level,
         top_left_latitude=aspect_data.get('top_left_latitude', ''),
         top_left_longitude=aspect_data.get('top_left_longitude', ''),
         bottom_right_latitude=aspect_data.get('bottom_right_latitude', ''),
         bottom_right_longitude=aspect_data.get('bottom_right_longitude',
                                                ''))
     self._default_on_startup = aspect_data.get('DefaultOnStartup', False)
예제 #39
0
파일: aspects.py 프로젝트: NIIF/indico
 def _checkParams(self):
     self._location = Location.find_first(name=self._param('location'))
     aspect_data = self._param('aspect')
     try:
         zoom_level = int(aspect_data.get('zoom_level', '0'))
     except ValueError:
         zoom_level = 0
     self._aspect = Aspect(
         name=aspect_data.get('name', ''),
         center_latitude=aspect_data.get('center_latitude', ''),
         center_longitude=aspect_data.get('center_longitude', ''),
         zoom_level=zoom_level,
         top_left_latitude=aspect_data.get('top_left_latitude', ''),
         top_left_longitude=aspect_data.get('top_left_longitude', ''),
         bottom_right_latitude=aspect_data.get('bottom_right_latitude', ''),
         bottom_right_longitude=aspect_data.get('bottom_right_longitude', '')
     )
     self._default_on_startup = aspect_data.get('DefaultOnStartup', False)
예제 #40
0
    def testSetDefaultLocation(self):
        if len(LOCATIONS) < 2:
            raise RuntimeWarning('Not enough locations for tis test,'
                                 ' there should be at least 2 locations')
        else:
            old_default = Location.getDefaultLocation()
            name = None
            for l, loc in self.iterLocations():
                if not loc.is_default:
                    Location.setDefaultLocation(loc)
                    db.session.commit()
                    name = l['name']
                    self.assertTrue(loc.is_default)
                    break
            assert name == Location.getDefaultLocation().name

            # revert change to decrease dependency between tests
            Location.setDefaultLocation(old_default)
            db.session.commit()
예제 #41
0
파일: locations.py 프로젝트: NIIF/indico
 def _process(self):
     return WPRoomBookingAdmin(self, locations=Location.find_all()).display()
예제 #42
0
파일: locations.py 프로젝트: NIIF/indico
 def _checkParams(self, param):
     self._eq = request.form.get(param)
     name = request.view_args.get('locationId')
     self._location = Location.find_first(name=name)
     if not self._location:
         raise IndicoError(_('Unknown Location: {0}').format(name))
예제 #43
0
 def _process_args(self):
     self._location = Location.get(int(request.form['location_id']))
     if not self._location:
         raise NotFound(u'No such location')
예제 #44
0
파일: locations.py 프로젝트: NIIF/indico
 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._attr = request.args.get('removeCustomAttributeName', '')
예제 #45
0
 def _process_args(self):
     id_ = request.view_args.get('location_id')
     self.location = Location.get_one(
         id_, is_deleted=False) if id_ is not None else None
예제 #46
0
 def has_data(self):
     return bool(Location.find().count())
예제 #47
0
파일: rooms.py 프로젝트: NIIF/indico
 def _checkParams(self):
     try:
         location = Location.find_one(name=self._params['location'])
     except NoResultFound:
         raise ServiceError('ERR-RB0', 'Invalid location name: {0}.'.format(self._params['location']))
     self._rooms = sorted(location.rooms, key=lambda r: natural_sort_key(r.full_name))
예제 #48
0
파일: locations.py 프로젝트: NIIF/indico
 def _process(self):
     is_default = Location.find().count() == 0
     db.session.add(Location(name=self._locationName, is_default=is_default))
     flash(_(u'Location added'), 'success')
     self._redirect(urlHandlers.UHRoomBookingAdmin.getURL())
예제 #49
0
 def has_data(self):
     return bool(Location.find().count())
예제 #50
0
 def _checkParams(self):
     self._location = Location.find_first(name=self._param('location'))
예제 #51
0
파일: aspects.py 프로젝트: NIIF/indico
 def _checkParams(self):
     self._location = Location.find_first(name=self._param('location'))
예제 #52
0
파일: locations.py 프로젝트: NIIF/indico
 def _checkParams(self):
     self._location = Location.get(int(request.form['location_id']))
     if not self._location:
         raise NoReportError(u'No such location')
예제 #53
0
파일: vars_js.py 프로젝트: NIIF/indico
def generate_global_file(config):
    locations = Location.find_all() if config.getIsRoomBookingActive() else []
    location_names = {loc.name: loc.name for loc in locations}
    default_location = next((loc.name for loc in locations if loc.is_default), None)
    ext_auths = [(auth.id, auth.name) for auth in AuthenticatorMgr().getList() if auth.id != 'Local']
    file_type_icons = dict((k.lower(), v[2]) for k, v in config.getFileTypes().iteritems())
    material_types = dict((evt_type, [(m, m.title()) for m in MaterialFactoryRegistry._allowedMaterials[evt_type]])
                          for evt_type in ['meeting', 'simple_event', 'conference', 'category'])

    indico_vars = {
        'FileTypeIcons': file_type_icons,

        'Urls': {
            'ImagesBase': config.getImagesBaseURL(),
            'SecureImagesBase': config.getImagesBaseSecureURL(),

            'Login': urlHandlers.UHSignIn.getURL().js_router,
            'Favourites': urlHandlers.UHUserBaskets.getURL(_ignore_static=True).js_router,

            'ConferenceDisplay': urlHandlers.UHConferenceDisplay.getURL(_ignore_static=True).js_router,
            'ContributionDisplay': urlHandlers.UHContributionDisplay.getURL(_ignore_static=True).js_router,
            'SessionDisplay': urlHandlers.UHSessionDisplay.getURL(_ignore_static=True).js_router,

            'ContribToXML': urlHandlers.UHContribToXML.getURL(_ignore_static=True).js_router,
            'ContribToPDF': urlHandlers.UHContribToPDF.getURL(_ignore_static=True).js_router,

            'ConfTimeTablePDF': urlHandlers.UHConfTimeTablePDF.getURL(_ignore_static=True).js_router,
            'ConfTimeTableCustomPDF': urlHandlers.UHConfTimeTableCustomizePDF.getURL(_ignore_static=True).js_router,

            'SessionModification': urlHandlers.UHSessionModification.getURL(_ignore_static=True).js_router,
            'ContributionModification': urlHandlers.UHContributionModification.getURL(_ignore_static=True).js_router,
            'SessionProtection': urlHandlers.UHSessionModifAC.getURL(_ignore_static=True).js_router,
            'ContributionProtection': urlHandlers.UHContribModifAC.getURL(_ignore_static=True).js_router,

            'Reschedule': urlHandlers.UHConfModifReschedule.getURL(_ignore_static=True).js_router,
            'SlotCalc': urlHandlers.UHSessionModSlotCalc.getURL(_ignore_static=True).js_router,
            'FitSessionSlot': urlHandlers.UHSessionFitSlot.getURL(_ignore_static=True).js_router,

            'UploadAction': {
                'subcontribution': urlHandlers.UHSubContribModifAddMaterials.getURL(_ignore_static=True).js_router,
                'contribution': urlHandlers.UHContribModifAddMaterials.getURL(_ignore_static=True).js_router,
                'session': urlHandlers.UHSessionModifAddMaterials.getURL(_ignore_static=True).js_router,
                'conference': urlHandlers.UHConfModifAddMaterials.getURL(_ignore_static=True).js_router,
                'category': urlHandlers.UHCategoryAddMaterial.getURL(_ignore_static=True).js_router
            },

            'RoomBookingBookRoom': url_rule_to_js('rooms.room_book'),
            'RoomBookingBook': url_rule_to_js('rooms.book'),
            'RoomBookingDetails': urlHandlers.UHRoomBookingRoomDetails.getURL(_ignore_static=True).js_router,
            'RoomBookingCloneBooking': url_rule_to_js('rooms.roomBooking-cloneBooking'),
            'ConfModifSchedule': urlHandlers.UHConfModifSchedule.getURL(_ignore_static=True).js_router,
            'SubcontrModif': urlHandlers.UHContribModifSubCont.getURL(_ignore_static=True).js_router,
            'AuthorDisplay': urlHandlers.UHContribAuthorDisplay.getURL(_ignore_static=True).js_router,
            'AuthorEmail': urlHandlers.UHConferenceEmail.getURL(_ignore_static=True).js_router
        },

        'Data': {
            'MaterialTypes': material_types,
            'WeekDays': ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
            'DefaultLocation': default_location,
            'Locations': location_names
        },

        'Security': {
            'allowedTags': ','.join(security_tools.allowedTags),
            'allowedAttributes': ','.join(security_tools.allowedAttrs),
            'allowedCssProperties': ','.join(security_tools.allowedCssProperties),
            'allowedProtocols': ','.join(security_tools.allowedProtocols),
            'urlProperties': ','.join(security_tools.urlProperties),
            'sanitizationLevel': config.getSanitizationLevel()
        },

        'Settings': {
            'ExtAuthenticators': ext_auths,
            'RoomBookingModuleActive': config.getIsRoomBookingActive()
        },

        'FileRestrictions': {
            'MaxUploadFilesTotalSize': config.getMaxUploadFilesTotalSize(),
            'MaxUploadFileSize': config.getMaxUploadFileSize()
        },

        'PDFConversion': {
            'AvailablePDFConversions': fileConverter.CDSConvFileConverter.getAvailableConversions(),
            'HasFileConverter': config.hasFileConverter()
        }
    }

    return render_template('assets/vars_globals.js', indico_vars=indico_vars, config=config, url_handlers=urlHandlers)
예제 #54
0
    def migrate_rooms(self):
        eq = defaultdict(set)
        vc = defaultdict(set)
        for old_room_id, old_room in self.rb_root['Rooms'].iteritems():
            eq[old_room._locationName].update(
                e for e in old_room._equipment.split('`') if e)
            vc[old_room._locationName].update(
                e for e in getattr(old_room, 'avaibleVC', []) if e)

        print cformat('%{white!}migrating equipment')
        for name, eqs in eq.iteritems():
            l = Location.find_first(name=name)

            if l is None:
                print cformat('%{yellow!}*** WARNING')
                print cformat(
                    "%{{yellow!}}***%{{reset}} Location '{}' does not exist. Skipped equipment: {}"
                    .format(name, eqs))
                continue

            l.equipment_types.extend(EquipmentType(name=x) for x in eqs)
            print cformat('- [%{cyan}{}%{reset}] {}').format(name, eqs)
            db.session.add(l)
        db.session.commit()
        print

        print cformat('%{white!}migrating vc equipment')
        for name, vcs in vc.iteritems():
            l = Location.find_first(name=name)

            if l is None:
                print cformat('%{yellow!}*** WARNING')
                print cformat(
                    "%{{yellow!}}***%{{reset}} Location '{}' does not exist. Skipped VC equipment: {}"
                    .format(name, vcs))
                continue

            pvc = l.get_equipment_by_name('Video conference')
            for vc_name in vcs:
                req = EquipmentType(name=vc_name)
                req.parent = pvc
                l.equipment_types.append(req)
                print cformat('- [%{cyan}{}%{reset}] {}').format(
                    name, req.name)
            db.session.add(l)
        db.session.commit()
        print

        print cformat('%{white!}migrating rooms')

        for old_room_id, old_room in self.rb_root['Rooms'].iteritems():
            l = Location.find_first(name=old_room._locationName)

            if l is None:
                print cformat('%{yellow!}*** WARNING')
                print cformat(
                    "%{{yellow!}}***%{{reset}} Location '{}' does not exist. Skipped room '{}'"
                    .format(old_room._locationName, old_room.id))
                continue

            r = Room(
                id=old_room_id,
                name=convert_to_unicode((old_room._name or '').strip()
                                        or generate_name(old_room)),
                site=convert_to_unicode(old_room.site),
                division=convert_to_unicode(old_room.division),
                building=convert_to_unicode(old_room.building),
                floor=convert_to_unicode(old_room.floor),
                number=convert_to_unicode(old_room.roomNr),
                notification_before_days=((
                    old_room.resvStartNotificationBefore or None) if getattr(
                        old_room, 'resvStartNotification', False) else None),
                notification_for_responsible=getattr(
                    old_room, 'resvNotificationToResponsible', False),
                notification_for_assistance=getattr(
                    old_room, 'resvNotificationAssistance', False),
                reservations_need_confirmation=old_room.resvsNeedConfirmation,
                telephone=convert_to_unicode(
                    getattr(old_room, 'telephone', None)),
                key_location=convert_to_unicode(
                    getattr(old_room, 'whereIsKey', None)),
                capacity=getattr(old_room, 'capacity', None),
                surface_area=getattr(old_room, 'surfaceArea', None),
                latitude=getattr(old_room, 'latitude', None),
                longitude=getattr(old_room, 'longitude', None),
                comments=convert_to_unicode(getattr(old_room, 'comments',
                                                    None)),
                owner_id=self.merged_avatars.get(old_room.responsibleId,
                                                 old_room.responsibleId),
                is_active=old_room.isActive,
                is_reservable=old_room.isReservable,
                max_advance_days=int(old_room.maxAdvanceDays) if getattr(
                    old_room, 'maxAdvanceDays', None) else None)

            print cformat(
                '- [%{cyan}{}%{reset}] %{grey!}{:4}%{reset}  %{green!}{}%{reset}'
            ).format(l.name, r.id, r.name)

            for old_bookable_time in getattr(old_room, '_dailyBookablePeriods',
                                             []):
                r.bookable_hours.append(
                    BookableHours(start_time=old_bookable_time._startTime,
                                  end_time=old_bookable_time._endTime))
                print cformat('  %{blue!}Bookable:%{reset} {}').format(
                    r.bookable_hours[-1])

            for old_nonbookable_date in getattr(old_room, '_nonBookableDates',
                                                []):
                r.nonbookable_periods.append(
                    NonBookablePeriod(start_dt=old_nonbookable_date._startDate,
                                      end_dt=old_nonbookable_date._endDate))
                print cformat('  %{blue!}Nonbookable:%{reset} {}').format(
                    r.nonbookable_periods[-1])

            if self.photo_path:
                try:
                    with open(
                            os.path.join(
                                self.photo_path, 'large_photos',
                                get_canonical_name_of(old_room) + '.jpg'),
                            'rb') as f:
                        large_photo = f.read()
                except Exception:
                    large_photo = None

                try:
                    with open(
                            os.path.join(
                                self.photo_path, 'small_photos',
                                get_canonical_name_of(old_room) + '.jpg'),
                            'rb') as f:
                        small_photo = f.read()
                except Exception:
                    small_photo = None

                if large_photo and small_photo:
                    r.photo = Photo(data=large_photo, thumbnail=small_photo)
                    print cformat('  %{blue!}Photos')

            new_eq = []
            for old_equipment in ifilter(
                    None,
                    old_room._equipment.split('`') + old_room.avaibleVC):
                room_eq = l.get_equipment_by_name(old_equipment)
                new_eq.append(room_eq)
                r.available_equipment.append(room_eq)
            if new_eq:
                print cformat('  %{blue!}Equipment:%{reset} {}').format(
                    ', '.join(sorted(x.name for x in new_eq)))

            for attr_name, value in getattr(old_room, 'customAtts',
                                            {}).iteritems():
                value = convert_to_unicode(value)
                if not value or ('Simba' in attr_name
                                 and value == u'Error: unknown mailing list'):
                    continue
                attr_name = attribute_map.get(attr_name,
                                              attr_name).replace(' ',
                                                                 '-').lower()
                ca = l.get_attribute_by_name(attr_name)
                if not ca:
                    print cformat(
                        '  %{blue!}Attribute:%{reset} {} %{red!}not found'
                    ).format(attr_name)
                    continue
                attr = RoomAttributeAssociation()
                attr.value = value
                attr.attribute = ca
                r.attributes.append(attr)
                print cformat('  %{blue!}Attribute:%{reset} {} = {}').format(
                    attr.attribute.title, attr.value)

            l.rooms.append(r)
            db.session.add(l)
            print
        db.session.commit()
예제 #55
0
    def migrate_rooms(self):
        eq = defaultdict(set)
        vc = defaultdict(set)
        for old_room_id, old_room in self.rb_root["Rooms"].iteritems():
            eq[old_room._locationName].update(e for e in old_room._equipment.split("`") if e)
            vc[old_room._locationName].update(e for e in getattr(old_room, "avaibleVC", []) if e)

        print cformat("%{white!}migrating equipment")
        for name, eqs in eq.iteritems():
            l = Location.find_first(name=name)

            if l is None:
                print cformat("%{yellow!}*** WARNING")
                print cformat(
                    "%{{yellow!}}***%{{reset}} Location '{}' does not exist. Skipped equipment: {}".format(name, eqs)
                )
                continue

            l.equipment_types.extend(EquipmentType(name=x) for x in eqs)
            print cformat("- [%{cyan}{}%{reset}] {}").format(name, eqs)
            db.session.add(l)
        db.session.commit()
        print

        print cformat("%{white!}migrating vc equipment")
        for name, vcs in vc.iteritems():
            l = Location.find_first(name=name)

            if l is None:
                print cformat("%{yellow!}*** WARNING")
                print cformat(
                    "%{{yellow!}}***%{{reset}} Location '{}' does not exist. Skipped VC equipment: {}".format(name, vcs)
                )
                continue

            pvc = l.get_equipment_by_name("Video conference")
            for vc_name in vcs:
                req = EquipmentType(name=vc_name)
                req.parent = pvc
                l.equipment_types.append(req)
                print cformat("- [%{cyan}{}%{reset}] {}").format(name, req.name)
            db.session.add(l)
        db.session.commit()
        print

        print cformat("%{white!}migrating rooms")

        for old_room_id, old_room in self.rb_root["Rooms"].iteritems():
            l = Location.find_first(name=old_room._locationName)

            if l is None:
                print cformat("%{yellow!}*** WARNING")
                print cformat(
                    "%{{yellow!}}***%{{reset}} Location '{}' does not exist. Skipped room '{}'".format(
                        old_room._locationName, old_room.id
                    )
                )
                continue

            r = Room(
                id=old_room_id,
                name=convert_to_unicode((old_room._name or "").strip() or generate_name(old_room)),
                site=convert_to_unicode(old_room.site),
                division=convert_to_unicode(old_room.division),
                building=convert_to_unicode(old_room.building),
                floor=convert_to_unicode(old_room.floor),
                number=convert_to_unicode(old_room.roomNr),
                notification_before_days=(
                    (old_room.resvStartNotificationBefore or None)
                    if getattr(old_room, "resvStartNotification", False)
                    else None
                ),
                notification_for_responsible=getattr(old_room, "resvNotificationToResponsible", False),
                notification_for_assistance=getattr(old_room, "resvNotificationAssistance", False),
                reservations_need_confirmation=old_room.resvsNeedConfirmation,
                telephone=convert_to_unicode(getattr(old_room, "telephone", None)),
                key_location=convert_to_unicode(getattr(old_room, "whereIsKey", None)),
                capacity=getattr(old_room, "capacity", None),
                surface_area=getattr(old_room, "surfaceArea", None),
                latitude=getattr(old_room, "latitude", None),
                longitude=getattr(old_room, "longitude", None),
                comments=convert_to_unicode(getattr(old_room, "comments", None)),
                owner_id=self.merged_avatars.get(old_room.responsibleId, old_room.responsibleId),
                is_active=old_room.isActive,
                is_reservable=old_room.isReservable,
                max_advance_days=int(old_room.maxAdvanceDays) if getattr(old_room, "maxAdvanceDays", None) else None,
            )

            print cformat("- [%{cyan}{}%{reset}] %{grey!}{:4}%{reset}  %{green!}{}%{reset}").format(
                l.name, r.id, r.name
            )

            for old_bookable_time in getattr(old_room, "_dailyBookablePeriods", []):
                r.bookable_hours.append(
                    BookableHours(start_time=old_bookable_time._startTime, end_time=old_bookable_time._endTime)
                )
                print cformat("  %{blue!}Bookable:%{reset} {}").format(r.bookable_hours[-1])

            for old_nonbookable_date in getattr(old_room, "_nonBookableDates", []):
                r.nonbookable_periods.append(
                    NonBookablePeriod(start_dt=old_nonbookable_date._startDate, end_dt=old_nonbookable_date._endDate)
                )
                print cformat("  %{blue!}Nonbookable:%{reset} {}").format(r.nonbookable_periods[-1])

            if self.photo_path:
                try:
                    with open(
                        os.path.join(self.photo_path, "large_photos", get_canonical_name_of(old_room) + ".jpg"), "rb"
                    ) as f:
                        large_photo = f.read()
                except Exception:
                    large_photo = None

                try:
                    with open(
                        os.path.join(self.photo_path, "small_photos", get_canonical_name_of(old_room) + ".jpg"), "rb"
                    ) as f:
                        small_photo = f.read()
                except Exception:
                    small_photo = None

                if large_photo and small_photo:
                    r.photo = Photo(data=large_photo, thumbnail=small_photo)
                    print cformat("  %{blue!}Photos")

            new_eq = []
            for old_equipment in ifilter(None, old_room._equipment.split("`") + old_room.avaibleVC):
                room_eq = l.get_equipment_by_name(old_equipment)
                new_eq.append(room_eq)
                r.available_equipment.append(room_eq)
            if new_eq:
                print cformat("  %{blue!}Equipment:%{reset} {}").format(", ".join(sorted(x.name for x in new_eq)))

            for attr_name, value in getattr(old_room, "customAtts", {}).iteritems():
                value = convert_to_unicode(value)
                if not value or ("Simba" in attr_name and value == u"Error: unknown mailing list"):
                    continue
                attr_name = attribute_map.get(attr_name, attr_name).replace(" ", "-").lower()
                ca = l.get_attribute_by_name(attr_name)
                if not ca:
                    print cformat("  %{blue!}Attribute:%{reset} {} %{red!}not found").format(attr_name)
                    continue
                attr = RoomAttributeAssociation()
                attr.value = value
                attr.attribute = ca
                r.attributes.append(attr)
                print cformat("  %{blue!}Attribute:%{reset} {} = {}").format(attr.attribute.title, attr.value)

            l.rooms.append(r)
            db.session.add(l)
            print
        db.session.commit()
예제 #56
0
def generate_global_file(config):
    locations = Location.find_all() if config.getIsRoomBookingActive() else []
    location_names = {loc.name: loc.name for loc in locations}
    default_location = next((loc.name for loc in locations if loc.is_default), None)
    ext_auths = [{
        'name': auth.name,
        'title': auth.title,
        'supports_groups': auth.supports_groups
    } for auth in multipass.identity_providers.itervalues() if auth.supports_search]
    file_type_icons = dict((k.lower(), v[2]) for k, v in config.getFileTypes().iteritems())

    indico_vars = {
        'FileTypeIcons': file_type_icons,

        'Urls': {
            'BasePath': url_parse(config.getBaseURL()).path.rstrip('/'),
            'JsonRpcService': url_for('api.jsonrpc'),
            'ExportAPIBase': url_for('api.httpapi', prefix='export'),
            'APIBase': url_for('api.httpapi', prefix='api'),

            'ImagesBase': config.getImagesBaseURL(),
            'SecureImagesBase': config.getImagesBaseSecureURL(),

            'Login': url_for_login(),
            'Favorites': url_for('users.user_favorites'),
            'FavoriteUserAdd': url_for('users.user_favorites_users_add'),
            'FavoriteUserRemove': url_rule_to_js('users.user_favorites_user_remove'),

            'ConferenceDisplay': urlHandlers.UHConferenceDisplay.getURL(_ignore_static=True).js_router,

            'AttachmentManager': url_rule_to_js('attachments.management'),
            'ManagementAttachmentInfoColumn': url_rule_to_js('attachments.management_info_column'),

            'RoomBookingBookRoom': url_rule_to_js('rooms.room_book'),
            'RoomBookingBook': url_rule_to_js('rooms.book'),
            'RoomBookingDetails': urlHandlers.UHRoomBookingRoomDetails.getURL(_ignore_static=True).js_router,
            'RoomBookingCloneBooking': url_rule_to_js('rooms.roomBooking-cloneBooking'),

            'APIKeyCreate': url_for('api.key_create'),
            'APIKeyTogglePersistent': url_for('api.key_toggle_persistent'),
            'FontSassBundle': core_env['fonts_sass'].urls(),

            'RegistrationForm': {
                'section': {
                    'add': url_rule_to_angular('event_registration.add_section'),
                    'modify': url_rule_to_angular('event_registration.modify_section'),
                    'toggle': url_rule_to_angular('event_registration.toggle_section'),
                    'move': url_rule_to_angular('event_registration.move_section')
                },
                'field': {
                    'add': url_rule_to_angular('event_registration.add_field'),
                    'modify': url_rule_to_angular('event_registration.modify_field'),
                    'toggle': url_rule_to_angular('event_registration.toggle_field'),
                    'move': url_rule_to_angular('event_registration.move_field')
                },
                'text': {
                    'add': url_rule_to_angular('event_registration.add_text'),
                    'modify': url_rule_to_angular('event_registration.modify_text'),
                    'toggle': url_rule_to_angular('event_registration.toggle_text'),
                    'move': url_rule_to_angular('event_registration.move_text')
                }
            },

            'Timetable': {
                'management': url_rule_to_js('timetable.management'),
                'default_pdf': url_rule_to_js('timetable.export_default_pdf'),
                'pdf': url_rule_to_js('timetable.export_pdf'),
                'reschedule': url_rule_to_js('timetable.reschedule'),
                'breaks': {
                    'add': url_rule_to_js('timetable.add_break')
                },
                'contributions': {
                    'add': url_rule_to_js('timetable.add_contribution'),
                    'notScheduled': url_rule_to_js('timetable.not_scheduled'),
                    'schedule': url_rule_to_js('timetable.schedule'),
                    'protection': url_rule_to_js('contributions.manage_contrib_protection')
                },
                'sessionBlocks': {
                    'add': url_rule_to_js('timetable.add_session_block'),
                    'fit': url_rule_to_js('timetable.fit_session_block')
                },
                'sessions': {
                    'add': url_rule_to_js('timetable.add_session')
                },
                'entries': {
                    'delete': url_rule_to_js('timetable.delete_entry'),
                    'edit': url_rule_to_js('timetable.edit_entry'),
                    'editDatetime': url_rule_to_js('timetable.edit_entry_datetime'),
                    'editTime': url_rule_to_js('timetable.edit_entry_time'),
                    'move': url_rule_to_js('timetable.move_entry'),
                    'shift': url_rule_to_js('timetable.shift_entries'),
                    'info': {
                        'display': url_rule_to_js('timetable.entry_info'),
                        'manage': url_rule_to_js('timetable.entry_info_manage'),
                    },
                }
            },

            'Contributions': {
                'display_contribution': url_rule_to_js('contributions.display_contribution')
            },

            'Sessions': {
                'display_session': url_rule_to_js('sessions.display_session')
            }
        },

        'Data': {
            'WeekDays': ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
            'DefaultLocation': default_location,
            'Locations': location_names
        },

        'Security': {
            'allowedTags': ','.join(security_tools.allowedTags),
            'allowedAttributes': ','.join(security_tools.allowedAttrs),
            'allowedCssProperties': ','.join(security_tools.allowedCssProperties),
            'allowedProtocols': ','.join(security_tools.allowedProtocols),
            'urlProperties': ','.join(security_tools.urlProperties),
            'sanitizationLevel': config.getSanitizationLevel()
        },

        'Settings': {
            'ExtAuthenticators': ext_auths,
            'RoomBookingModuleActive': config.getIsRoomBookingActive()
        },

        'FileRestrictions': {
            'MaxUploadFilesTotalSize': config.getMaxUploadFilesTotalSize(),
            'MaxUploadFileSize': config.getMaxUploadFileSize()
        }
    }

    return render_template('assets/vars_globals.js', indico_vars=indico_vars, config=config, url_handlers=urlHandlers)
예제 #57
0
 def _create_location(name, **params):
     location = Location(name=name, **params)
     db.session.add(location)
     db.session.flush()
     return location
예제 #58
0
 def _process(self):
     is_default = Location.find().count() == 0
     db.session.add(Location(name=self._locationName,
                             is_default=is_default))
     flash(_(u'Location added'), 'success')
     return redirect(url_for('rooms_admin.roomBooking-admin'))