Ejemplo n.º 1
0
 def _getAnswer(self):
     result = {}
     locationNames = map(lambda l: l.friendlyName, Location.allLocations)
     for loc in locationNames:
         for room in CrossLocationQueries.getRooms(location=loc):
             result[loc + ":" + room.name] = loc + ":" + room.name
     return sorted(result)
Ejemplo n.º 2
0
    def rebuildRoomReservationsIndex():
        from MaKaC.common.db import DBMgr
        from MaKaC.rb_location import CrossLocationDB
        from MaKaC.rb_room import RoomBase
        from MaKaC.plugins.RoomBooking.default.dalManager import DALManager
        from BTrees.OOBTree import OOBTree

        DBMgr.getInstance().startRequest()
        CrossLocationDB.connect()
        root = DALManager.root

        resvEx = ReservationBase()
        resvEx.isConfirmed = None
        allResvs = CrossLocationQueries.getReservations( resvExample = resvEx )
        print "There are " + str( len( allResvs ) ) + " resvs and pre-resvs to index..."
        c = 0
        
        root[_ROOM_RESERVATIONS_INDEX] = OOBTree()
        print "Room => Reservations Index branch created"
        
        for resv in allResvs:
            roomReservationsIndexBTree = root[_ROOM_RESERVATIONS_INDEX]
            resvs = roomReservationsIndexBTree.get( resv.room.id )
            if resvs == None:
                resvs = [] # New list of reservations for this room
                roomReservationsIndexBTree.insert( resv.room.id, resvs )
            resvs.append( resv )
            roomReservationsIndexBTree[resv.room.id] = resvs
            c += 1
            if c % 100 == 0:
                print c
        
        CrossLocationDB.commit()
        CrossLocationDB.disconnect()
        DBMgr.getInstance().endRequest()
Ejemplo n.º 3
0
 def _getAnswer( self ):
     result = {}
     locationNames = map(lambda l: l.friendlyName, Location.allLocations);
     for loc in locationNames:
         for room in CrossLocationQueries.getRooms( location = loc ):
             result[loc +":" +room.name] = loc +":" +room.name;
     return sorted(result)
Ejemplo n.º 4
0
    def _getParams(self):
        super(BookRoomHook, self)._getParams()

        username = get_query_parameter(self._queryParams, ['username'])
        booked_for = AuthenticatorMgr().getAvatarByLogin(username).values()

        if not booked_for:
            raise HTTPAPIError('Username does not exist.')

        self._params = {
            'roomid': get_query_parameter(self._queryParams, ['roomid']),
            'location': get_query_parameter(self._queryParams, ['location']),
            'username': username,
            'reason': get_query_parameter(self._queryParams, ['reason']),
            'userBookedFor': booked_for[0],
            'from': self._fromDT,
            'to': self._toDT
            }

        # calculate missing arguments
        missing = list(name for (name, value) in (self._params.iteritems()) if not value)

        if missing:
            raise HTTPAPIError('Argument(s) missing: {0}'.format(', '.join(missing)), apache.HTTP_BAD_REQUEST)

        self._room = CrossLocationQueries.getRooms(location=self._params['location'], roomID=int(self._params['roomid']))
Ejemplo n.º 5
0
 def _checkParams(self):
     LoggedOnlyService._checkParams(self)
     self._user = self.getAW().getUser()
     self._roomID = int(self._params.get("roomID", ""))
     self._roomLocation = self._params.get("roomLocation",
                                           "").replace("+", " ")
     self._room = CrossLocationQueries.getRooms(roomID=self._roomID,
                                                location=self._roomLocation)
Ejemplo n.º 6
0
    def _getAnswer(self):
        p = ReservationBase()
        p.startDT = self._startDT
        p.endDT = self._endDT
        p.repeatability = self._repeatability

        rooms = CrossLocationQueries.getRooms(location=self._location, resvExample=p, available=True)

        return [room.id for room in rooms]
Ejemplo n.º 7
0
    def _getAnswer(self):

        res = []
        minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
        if minfo.getRoomBookingModuleActive():
            if Location.parse(self._location):
                for room in CrossLocationQueries.getRooms(location=self._location, allFast=True):
                        res.append((room.name, room.getFullName()))
        return res
Ejemplo n.º 8
0
    def _getAnswer(self):

        res = {}
        minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
        if minfo.getRoomBookingModuleActive():
            if Location.parse(self._location):
                for room in CrossLocationQueries.getRooms(location=self._location):
                    res[room.name] = room.name
        return sorted(res)
Ejemplo n.º 9
0
    def _getAnswer( self ):

        res = []

        if Location.parse( self._location ):
            for room in CrossLocationQueries.getRooms( location = self._location ):
                res.append((room.name, room.getFullName()))

        return res
Ejemplo n.º 10
0
    def _getAnswer(self):

        res = {}
        minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
        if minfo.getRoomBookingModuleActive():
            if Location.parse(self._location):
                for room in CrossLocationQueries.getRooms(
                        location=self._location):
                    res[room.name] = room.name
        return sorted(res)
Ejemplo n.º 11
0
    def _getAnswer( self ):

        if not Location.parse( self._location ):
            return {}

        res = {}
        for room in CrossLocationQueries.getRooms( location = self._location ):
            res[room.name] = room.name

        return sorted(res)
Ejemplo n.º 12
0
    def _getAnswer(self):

        res = []
        minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
        if minfo.getRoomBookingModuleActive():
            if Location.parse(self._location):
                for room in CrossLocationQueries.getRooms(
                        location=self._location):
                    res.append((room.name, room.getFullName()))
        return res
Ejemplo n.º 13
0
    def _getAnswer(self):

        if not Location.parse(self._location):
            return {}

        res = {}
        for room in CrossLocationQueries.getRooms(location=self._location):
            res[room.name] = room.name

        return sorted(res)
Ejemplo n.º 14
0
def changeCreator(oldUser, newUser):
    dbi = DBMgr.getInstance()

    dbi.startRequest()
    Factory.getDALManager().connect()

    # check if the users exist
    if AvatarHolder().getById(oldUser) is None:
        print "There is no user with id %s" % oldUser
        return
    if AvatarHolder().getById(newUser) is None:
        print "There is no user with id %s" % newUser
        return

    resvEx = ReservationBase()
    resvEx.createdBy = oldUser

    allResv4OldUser = CrossLocationQueries.getReservations(resvExample=resvEx)

    if allResv4OldUser == []:
        print "No reservations for user %s" % oldUser
        return

    # resvs = ReservationBase.getReservations()
    # allResv4OldUser = [x for x in allResv if x.createdBy == oldUser]

    if type(allResv4OldUser) is not list:
        allResv4OldUser = [allResv4OldUser]

    # Modify reservations
    for r in allResv4OldUser:
        r.createdBy = newUser
        #print r.createdBy, r.id

    # Update index
    userReservationsIndexBTree = Reservation.getUserReservationsIndexRoot()

    newUserResvs = userReservationsIndexBTree.get(newUser)
    if newUserResvs == None:
        newUserResvs = []  # New list of reservations for this room
        userReservationsIndexBTree.insert(newUser, newUserResvs)
    newUserResvs.extend(allResv4OldUser)
    userReservationsIndexBTree[newUser] = newUserResvs[:]

    if userReservationsIndexBTree.has_key(oldUser):
        userReservationsIndexBTree.pop(oldUser)

    userReservationsIndexBTree._p_changed = 1

    # close DB connection
    Factory.getDALManager().commit()
    Factory.getDALManager().disconnect()
    dbi.endRequest()
    print "%s reservations have moved from creator %s to creator %s" % (
        len(allResv4OldUser), oldUser, newUser)
Ejemplo n.º 15
0
 def _getAnswer( self ):
     minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
     result = {}
     if minfo.getRoomBookingModuleActive():
         locationNames = map(lambda l: l.friendlyName, Location.allLocations)
         for loc in locationNames:
             roomEx = Factory.newRoom()
             roomEx.isActive = self._isActive
             for room in CrossLocationQueries.getRooms( location = loc, roomExample=roomEx ):
                 result[str(room.guid)] = "%s: %s" % (loc, room.getFullName())
     return result
Ejemplo n.º 16
0
    def _getAnswer(self):
        p = ReservationBase()
        p.startDT = self._startDT
        p.endDT = self._endDT
        p.repeatability = self._repeatability

        rooms = CrossLocationQueries.getRooms(location=self._location,
                                              resvExample=p,
                                              available=True)

        return [room.id for room in rooms]
Ejemplo n.º 17
0
def changeCreator(oldUser, newUser):
    dbi = DBMgr.getInstance()

    dbi.startRequest()
    Factory.getDALManager().connect()

    # check if the users exist
    if AvatarHolder().getById(oldUser) is None:
        print "There is no user with id %s"%oldUser
        return
    if AvatarHolder().getById(newUser) is None:
        print "There is no user with id %s"%newUser
        return

    resvEx = ReservationBase()
    resvEx.createdBy = oldUser

    allResv4OldUser = CrossLocationQueries.getReservations( resvExample = resvEx)

    if allResv4OldUser == []:
        print "No reservations for user %s"%oldUser
        return

    # resvs = ReservationBase.getReservations()
    # allResv4OldUser = [x for x in allResv if x.createdBy == oldUser]

    if type(allResv4OldUser) is not list:
        allResv4OldUser = [allResv4OldUser]

    # Modify reservations
    for r in allResv4OldUser:
        r.createdBy = newUser
        #print r.createdBy, r.id

    # Update index
    userReservationsIndexBTree = Reservation.getUserReservationsIndexRoot()

    newUserResvs = userReservationsIndexBTree.get( newUser )
    if newUserResvs == None:
        newUserResvs = [] # New list of reservations for this room
        userReservationsIndexBTree.insert( newUser, newUserResvs )
    newUserResvs.extend( allResv4OldUser )
    userReservationsIndexBTree[newUser] = newUserResvs[:]

    if userReservationsIndexBTree.has_key(oldUser):
        userReservationsIndexBTree.pop(oldUser)

    userReservationsIndexBTree._p_changed = 1

    # close DB connection
    Factory.getDALManager().commit()
    Factory.getDALManager().disconnect()
    dbi.endRequest()
    print "%s reservations have moved from creator %s to creator %s" % (len(allResv4OldUser), oldUser, newUser)
Ejemplo n.º 18
0
 def _getAnswer( self ):
     minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
     if minfo.getRoomBookingModuleActive():
         result = {}
         locationNames = map(lambda l: l.friendlyName, Location.allLocations);
         for loc in locationNames:
             for room in CrossLocationQueries.getRooms( location = loc ):
                 result[loc +":" +room.name] = loc +":" +room.name;
         return sorted(result)
     else:
         return []
Ejemplo n.º 19
0
 def getMapURL(self, roomName):
     if re.match("[0-9]+-([0-9]+|R)-[0-9]+", roomName):
         return "%s%s"%(self.getBaseMapURL(), roomName[:roomName.find('-')])
     else:
         minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
         if minfo.getRoomBookingModuleActive():
             rooms = CrossLocationQueries.getRooms(roomName = roomName)
             rooms = [r for r in rooms if r is not None]
             if rooms and rooms[0]:
                 return "%s%s"%(self.getBaseMapURL(), str(rooms[0].building))
     return ""
Ejemplo n.º 20
0
    def search(self, location, name):

        Factory.getDALManager().connect()
        rooms = CrossLocationQueries.getRooms(location=location)

        def _search_rooms(name):
            return (room for room in rooms if name in room.getFullName())

        for obj in self._process(_search_rooms(name)):
            yield obj
        Factory.getDALManager().rollback()
        Factory.getDALManager().disconnect()
Ejemplo n.º 21
0
 def _getAnswer(self):
     minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
     if minfo.getRoomBookingModuleActive():
         result = {}
         locationNames = map(lambda l: l.friendlyName,
                             Location.allLocations)
         for loc in locationNames:
             for room in CrossLocationQueries.getRooms(location=loc):
                 result[loc + ":" + room.name] = loc + ":" + room.name
         return sorted(result)
     else:
         return []
Ejemplo n.º 22
0
 def getMapURL(self, roomName):
     groupdict = self.applyRegularExpressions(roomName)
     if groupdict:
         return self.getBaseMapURL().format(**groupdict)
     minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
     if minfo.getRoomBookingModuleActive():
         rooms = CrossLocationQueries.getRooms(roomName = roomName)
         rooms = [r for r in rooms if r is not None]
         if rooms and rooms[0]:
             if all(field in self.getBaseMapURL() for field in ['{building}','{floor}','{roomNr}']):
                 return self.getBaseMapURL().format(**{'building': str(rooms[0].building),'floor': rooms[0].floor,'roomNr': rooms[0].roomNr})
     return ""
Ejemplo n.º 23
0
 def getMapURL(self, roomName):
     groupdict = self.applyRegularExpressions(roomName)
     if groupdict:
         return self.getBaseMapURL().format(**groupdict)
     minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
     if minfo.getRoomBookingModuleActive():
         rooms = CrossLocationQueries.getRooms(roomName = roomName)
         rooms = [r for r in rooms if r is not None]
         if rooms and rooms[0]:
             if all(field in self.getBaseMapURL() for field in ['{building}','{floor}','{roomNr}']):
                 return self.getBaseMapURL().format(**{'building': str(rooms[0].building),'floor': rooms[0].floor,'roomNr': rooms[0].roomNr})
     return ""
Ejemplo n.º 24
0
    def room(self, location, idlist):

        Factory.getDALManager().connect()
        rooms = CrossLocationQueries.getRooms(location=location)

        def _iterate_rooms(objIds):
            objIds = map(int, objIds)
            return (room for room in rooms if room.id in objIds)

        for obj in self._process(_iterate_rooms(idlist)):
            yield obj
        Factory.getDALManager().rollback()
        Factory.getDALManager().disconnect()
Ejemplo n.º 25
0
 def _getAnswer(self):
     minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
     result = {}
     if minfo.getRoomBookingModuleActive():
         locationNames = map(lambda l: l.friendlyName,
                             Location.allLocations)
         for loc in locationNames:
             roomEx = Factory.newRoom()
             roomEx.isActive = self._isActive
             for room in CrossLocationQueries.getRooms(location=loc,
                                                       roomExample=roomEx):
                 result[str(
                     room.guid)] = "%s: %s" % (loc, room.getFullName())
     return result
Ejemplo n.º 26
0
    def getAverageOccupation(**kwargs):
        """
        FINAL (not intented to be overriden)
        Returns float <0, 1> representing how often - on the avarage - 
        the rooms are booked during the working hours. (1 == all the time, 0 == never).
        """

        name = kwargs.get('location',
                          Location.getDefaultLocation().friendlyName)

        # Get active, publically reservable rooms
        from MaKaC.rb_factory import Factory
        roomEx = Factory.newRoom()
        roomEx.isActive = True
        roomEx.isReservable = True

        rooms = CrossLocationQueries.getRooms(roomExample=roomEx,
                                              location=name)

        # Find collisions with last month period
        from MaKaC.rb_reservation import ReservationBase, RepeatabilityEnum
        resvEx = ReservationBase()
        now = datetime.now()
        resvEx.endDT = datetime(now.year, now.month, now.day, 17, 30)
        resvEx.startDT = resvEx.endDT - timedelta(
            30, 9 * 3600)  # - 30 days and 9 hours
        resvEx.repeatability = RepeatabilityEnum.daily
        collisions = resvEx.getCollisions(rooms=rooms)

        totalWorkingDays = 0
        weekends = 0
        for day in iterdays(resvEx.startDT, resvEx.endDT):
            if day.weekday() in [5, 6]:  # Skip Saturday and Sunday
                weekends += 1
                continue
            # if c.startDT is CERN Holiday: continue
            totalWorkingDays += 1

        booked = timedelta(0)
        for c in collisions:
            if c.startDT.weekday() in [5, 6]:  # Skip Saturday and Sunday
                continue
            # if c.startDT is CERN Holiday: continue
            booked = booked + (c.endDT - c.startDT)
        totalBookableTime = totalWorkingDays * 9 * len(rooms)  # Hours
        bookedTime = booked.days * 24 + 1.0 * booked.seconds / 3600  # Hours
        if totalBookableTime > 0:
            return bookedTime / totalBookableTime
        else:
            return 0  # Error (no rooms in db)
def listResv4User(user):
    dbi = DBMgr.getInstance()

    dbi.startRequest()
    Factory.getDALManager().connect()

    resvEx = ReservationBase()
    resvEx.createdBy = user

    allResv = CrossLocationQueries.getReservations( resvExample = resvEx)
    print "User %s has %s resevations created by him/her"%(user, len(allResv))

    Factory.getDALManager().disconnect()
    dbi.endRequest()
Ejemplo n.º 28
0
    def getVars(self):
        vars = WJSBase.getVars( self )

        roomsWithH323IP = []

        if self._conf:

            vars["ConferenceId"] = self._conf.getId()

            # Code to get a list of H.323 Videoconference-able rooms
            # by querying Indico's RB database
            location = self._conf.getLocation()

            if location and location.getName():
                locationName = location.getName()

                # TODO: get list of room from a plugin option instead of querying the RB DB everytime
                try:
                    minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
                    if minfo.getRoomBookingModuleActive():
                        Logger.get("CERNMCU").info("Connecting with Room Booking DB to get the list of all rooms with a H323 IP")
                        CrossLocationDB.connect()
                        Logger.get("CERNMCU").info("Connection successful")

                        attName = getCERNMCUOptionValueByName("H323_IP_att_name")

                        try:
                            returnedRooms = CrossLocationQueries.getRooms( location = locationName,
                                                                           customAtts = [{"name":attName, "allowEmpty":False,
                                                                                          "filter": (lambda ip: validIP(ip))}] )
                            if not isinstance(returnedRooms, list):
                                if returnedRooms:
                                    returnedRooms = [returnedRooms]
                                else:
                                    returnedRooms = []

                            for room in returnedRooms:
                                roomsWithH323IP.append(RoomWithH323(locationName, room.getFullName(), room.customAtts[attName]))

                        except AttributeError:
                            #CrossLocationQueries.getRooms fails because it does not handle location names that are not in the DB
                            pass
                        except Exception, e:
                            Logger.get("CERNMCU").warning("Location: " + locationName + "Problem with CrossLocationQueries when retrieving the list of all rooms with a H323 IP: " + str(e))

                except MaKaCError, e:
                    Logger.get("CERNMCU").warning("Location: " + locationName + "MaKaCError when retrieving the list of all rooms with a H323 IP: " + e.getMsg())
                except Exception, e:
                    Logger.get("CERNMCU").warning("Location: " + locationName + "Exception when retrieving the list of all rooms with a H323 IP: " + str(e))
Ejemplo n.º 29
0
    def getRoomsByExampleDemo():
        Test.dalManager.connect()

        roomEx = Factory.newRoom()

        roomEx.building = 513
        roomEx.capacity = 20

        rooms = CrossLocationQueries.getRooms( roomExample = roomEx )

        for room in rooms:
            print "============================="
            print room

        Test.dalManager.disconnect()
Ejemplo n.º 30
0
 def getLinkRoomIp(cls, linkVideo):
     if linkVideo is None:
         return ""
     location = linkVideo.getLocation()
     room = linkVideo.getRoom()
     roomIp = ""
     if location and room and location.getName() and room.getName() and location.getName().strip() and room.getName().strip():
         minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
         if minfo.getRoomBookingModuleActive():
             CrossLocationDB.connect()
             try:
                 roomInfo = CrossLocationQueries.getRooms( location = location.getName(), roomName = room.getName())
                 roomIp = roomInfo.customAtts["H323 IP"]
             except Exception, e:
                 Logger.get("Vidyo").warning("Location: " + location.getName() + "Problem with CrossLocationQueries when retrieving the list of all rooms with a H323 IP: " + str(e))
Ejemplo n.º 31
0
def runRoomDayIndexInit(dbi, withRBDB, prevVersion):
    """
    Initializing room+day => reservation index.
    """
    if not withRBDB:
        return

    root = DALManager().getRoot()
    if not root.has_key('RoomDayReservationsIndex'):
        root['RoomDayReservationsIndex'] = OOBTree()
        for i, resv in enumerate(CrossLocationQueries.getReservations()):
            resv._addToRoomDayReservationsIndex()
            if i % 1000 == 0:
                DALManager.commit()
        DALManager.commit()
Ejemplo n.º 32
0
 def getLinkRoomIp(cls, linkVideo, ipAttName="H323 IP"):
     if linkVideo is None:
         return ""
     location = linkVideo.getLocation()
     room = linkVideo.getRoom()
     roomIp = ""
     if location and room and location.getName() and room.getName() and location.getName().strip() and room.getName().strip():
         minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
         if minfo.getRoomBookingModuleActive():
             CrossLocationDB.connect()
             try:
                 roomInfo = CrossLocationQueries.getRooms( location = location.getName(), roomName = room.getName())
                 roomIp = roomInfo.customAtts[ipAttName]
             except Exception, e:
                 Logger.get("Vidyo").warning("Location: '%s' - Problem with CrossLocationQueries: '%s'" % (location.getName(), str(e)))
Ejemplo n.º 33
0
    def getRoomsByExampleDemo():
        Test.dalManager.connect()

        roomEx = Factory.newRoom()

        roomEx.building = 513
        roomEx.capacity = 20

        rooms = CrossLocationQueries.getRooms( roomExample = roomEx )

        for room in rooms:
            print "============================="
            print room

        Test.dalManager.disconnect()
Ejemplo n.º 34
0
def runRoomDayIndexInit(dbi, withRBDB, prevVersion):
    """
    Initializing room+day => reservation index.
    """
    if not withRBDB:
        return

    root = DALManager().getRoot()
    if not root.has_key('RoomDayReservationsIndex'):
        root['RoomDayReservationsIndex'] = OOBTree()
        for i, resv in enumerate(CrossLocationQueries.getReservations()):
            resv._addToRoomDayReservationsIndex()
            if i % 1000 == 0:
                DALManager.commit()
        DALManager.commit()
Ejemplo n.º 35
0
def runReservationNotificationMigration(dbi, withRBDB, prevVersion):
    """
    Migrate the reservation notification system.
    """
    if not withRBDB:
        return

    # Delete old start end notification data
    for i, resv in enumerate(CrossLocationQueries.getReservations()):
        if hasattr(resv, '_startEndNotification'):
            resv._startEndNotification = None
        if i % 1000 == 0:
            DALManager.commit()
    # Create start notification task
    Client().enqueue(RoomReservationTask(rrule.HOURLY, byminute=0, bysecond=0))
    DALManager.commit()
Ejemplo n.º 36
0
def runReservationNotificationMigration(dbi, withRBDB, prevVersion):
    """
    Migrate the reservation notification system.
    """
    if not withRBDB:
        return

    # Delete old start end notification data
    for i, resv in enumerate(CrossLocationQueries.getReservations()):
        if hasattr(resv, '_startEndNotification'):
            resv._startEndNotification = None
        if i % 1000 == 0:
            DALManager.commit()
    # Create start notification task
    Client().enqueue(RoomReservationTask(rrule.HOURLY, byminute=0, bysecond=0))
    DALManager.commit()
Ejemplo n.º 37
0
    def getAverageOccupation( **kwargs ):
        """
        FINAL (not intented to be overriden)
        Returns float <0, 1> representing how often - on the avarage -
        the rooms are booked during the working hours. (1 == all the time, 0 == never).
        """

        name = kwargs.get( 'location', Location.getDefaultLocation().friendlyName )

        # Get active, publically reservable rooms
        from MaKaC.rb_factory import Factory
        roomEx = Factory.newRoom()
        roomEx.isActive = True
        roomEx.isReservable = True

        rooms = CrossLocationQueries.getRooms( roomExample = roomEx, location = name )

        # Find collisions with last month period
        from MaKaC.rb_reservation import ReservationBase, RepeatabilityEnum
        resvEx = ReservationBase()
        now = datetime.now()
        resvEx.endDT = datetime( now.year, now.month, now.day, 17, 30 )
        resvEx.startDT = resvEx.endDT - timedelta( 30, 9 * 3600 ) # - 30 days and 9 hours
        resvEx.repeatability = RepeatabilityEnum.daily
        collisions = resvEx.getCollisions( rooms = rooms )

        totalWorkingDays = 0
        weekends = 0
        for day in iterdays( resvEx.startDT, resvEx.endDT ):
            if day.weekday() in [5,6]: # Skip Saturday and Sunday
                weekends += 1
                continue
            # if c.startDT is CERN Holiday: continue
            totalWorkingDays += 1

        booked = timedelta( 0 )
        for c in collisions:
            if c.startDT.weekday() in [5,6]: # Skip Saturday and Sunday
                continue
            # if c.startDT is CERN Holiday: continue
            booked = booked + ( c.endDT - c.startDT )
        totalBookableTime = totalWorkingDays * 9 * len( rooms ) # Hours
        bookedTime = booked.days * 24 + 1.0 * booked.seconds / 3600 # Hours
        if totalBookableTime > 0:
            return bookedTime / totalBookableTime
        else:
            return 0 # Error (no rooms in db)
Ejemplo n.º 38
0
    def getVars(self):
        vars = WJSBase.getVars( self )

        roomsWithH323IP = []

        if self._conf:
            
            # Code to get a list of H.323 Videoconference-able rooms
            # by querying Indico's RB database
            location = self._conf.getLocation()

            if location and location.getName():
                locationName = location.getName()

                # TODO: get list of room from a plugin option instead of querying the RB DB everytime
                try:
                    minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
                    if minfo.getRoomBookingModuleActive():
                        Logger.get("CERNMCU").info("Connecting with Room Booking DB to get the list of all rooms with a H323 IP")
                        CrossLocationDB.connect()
                        Logger.get("CERNMCU").info("Connection successful")

                        attName = getCERNMCUOptionValueByName("H323_IP_att_name")

                        try:
                            returnedRooms = CrossLocationQueries.getRooms( location = locationName,
                                                                           customAtts = [{"name":attName, "allowEmpty":False,
                                                                                          "filter": (lambda ip: validIP(ip))}] )
                            if not isinstance(returnedRooms, list):
                                if returnedRooms:
                                    returnedRooms = [returnedRooms]
                                else:
                                    returnedRooms = []
    
                            for room in returnedRooms:
                                roomsWithH323IP.append(RoomWithH323(locationName, room._getName(), room.customAtts[attName]))
                                
                        except AttributeError:
                            #CrossLocationQueries.getRooms fails because it does not handle location names that are not in the DB
                            pass
                        except Exception, e:
                            Logger.get("CERNMCU").warning("Location: " + locationName + "Problem with CrossLocationQueries when retrieving the list of all rooms with a H323 IP: " + str(e))

                except MaKaCError, e:
                    Logger.get("CERNMCU").warning("Location: " + locationName + "MaKaCError when retrieving the list of all rooms with a H323 IP: " + e.getMsg())
                except Exception, e:
                    Logger.get("CERNMCU").warning("Location: " + locationName + "Exception when retrieving the list of all rooms with a H323 IP: " + str(e))
Ejemplo n.º 39
0
    def play():
        from MaKaC.rb_location import CrossLocationDB
        from MaKaC.rb_room import RoomBase
        from MaKaC.common.db import DBMgr

        DBMgr.getInstance().startRequest()
        CrossLocationDB.connect()

        roomEx = RoomBase()
        roomEx.isActive = False
        rooms = CrossLocationQueries.getRooms( roomExample = roomEx )
        for r in rooms:
            print r
            
        CrossLocationDB.commit()
        CrossLocationDB.disconnect()
        DBMgr.getInstance().endRequest()
Ejemplo n.º 40
0
 def getTotalSurfaceAndCapacity( **kwargs ):
     """
     FINAL (not intented to be overriden)
     Returns (total_surface, total_capacity) of all Active rooms.
     """
     name = kwargs.get( 'location', Location.getDefaultLocation().friendlyName )
     location = Location.parse(name)
     roomEx = location.factory.newRoom()
     roomEx.isActive = True
     roomEx.isReservable = True
     rooms = CrossLocationQueries.getRooms( roomExample = roomEx, location = name )
     totalSurface, totalCapacity = 0, 0
     for r in rooms:
         if r.surfaceArea:
             totalSurface += r.surfaceArea
         if r.capacity:
             totalCapacity += r.capacity
     return ( totalSurface, totalCapacity )
Ejemplo n.º 41
0
def pluginOptionsRoomGUIDs(dbi, withRBDB, prevVersion):
    """
    Modifying Room GUIDs
    """
    if not withRBDB:
        return

    ph = PluginsHolder()
    for pluginName, roomsOpt in [('WebcastRequest', 'webcastCapableRooms'),
                                 ('RecordingRequest', 'recordingCapableRooms')]:
        opt = ph.getPluginType('Collaboration').getPlugin(pluginName).getOption(roomsOpt)
        newValue = []
        for name in opt.getValue():
            loc, name = name.split(':')
            room = CrossLocationQueries.getRooms(location=loc, roomName=name)
            if room:
                newValue.append(str(room.guid))
        opt.setValue(newValue)
Ejemplo n.º 42
0
def pluginOptionsRoomGUIDs(dbi, withRBDB, prevVersion):
    """
    Modifying Room GUIDs
    """
    if not withRBDB:
        return

    ph = PluginsHolder()
    for pluginName, roomsOpt in [('WebcastRequest', 'webcastCapableRooms'),
                                 ('RecordingRequest', 'recordingCapableRooms')]:
        opt = ph.getPluginType('Collaboration').getPlugin(pluginName).getOption(roomsOpt)
        newValue = []
        for name in opt.getValue():
            loc, name = name.split(':')
            room = CrossLocationQueries.getRooms(location=loc, roomName=name)
            if room:
                newValue.append(str(room.guid))
        opt.setValue(newValue)
Ejemplo n.º 43
0
 def getTotalSurfaceAndCapacity( **kwargs ):
     """
     FINAL (not intented to be overriden)
     Returns (total_surface, total_capacity) of all Active rooms.
     """
     name = kwargs.get( 'location', Location.getDefaultLocation().friendlyName )
     location = Location.parse(name)
     roomEx = location.factory.newRoom()
     roomEx.isActive = True
     roomEx.isReservable = True
     rooms = CrossLocationQueries.getRooms( roomExample = roomEx, location = name )
     totalSurface, totalCapacity = 0, 0
     for r in rooms:
         if r.surfaceArea:
             totalSurface += r.surfaceArea
         if r.capacity:
             totalCapacity += r.capacity
     return ( totalSurface, totalCapacity )
Ejemplo n.º 44
0
    def getAverageOccupation(**kwargs):
        """
        FINAL (not intented to be overriden)
        Returns float <0, 1> representing how often - on the avarage -
        the rooms are booked during the working hours. (1 == all the time, 0 == never).
        """

        name = kwargs.get("location", Location.getDefaultLocation().friendlyName)

        # Get active, publically reservable rooms
        from MaKaC.rb_factory import Factory

        roomEx = Factory.newRoom()
        roomEx.isActive = True
        roomEx.isReservable = True

        rooms = CrossLocationQueries.getRooms(roomExample=roomEx, location=name)

        # Find collisions with last month period
        from MaKaC.rb_reservation import ReservationBase, RepeatabilityEnum

        resvEx = ReservationBase()
        resvEx.endDT = datetime.combine(date.today(), time(17, 30))
        resvEx.startDT = resvEx.endDT.replace(hour=8) - timedelta(days=30)
        resvEx.repeatability = RepeatabilityEnum.daily
        collisions = resvEx.getCollisions(rooms=rooms)

        totalWorkingDays = sum(1 for day in iterdays(resvEx.startDT, resvEx.endDT) if day.weekday() not in (5, 6))
        booked = timedelta()
        for c in collisions:
            if c.startDT.weekday() in (5, 6):  # skip Saturday and Sunday
                continue
            booked += c.endDT - c.startDT
        totalBookableTime = totalWorkingDays * 9 * len(rooms)  # Hours
        bookedTime = (booked.days * 86400 + booked.seconds) / 3600.0
        if totalBookableTime > 0:
            return bookedTime / totalBookableTime
        else:
            return 0
Ejemplo n.º 45
0
    def reservation(self, locList):

        Factory.getDALManager().connect()

        resvEx = ReservationBase()
        resvEx.startDT = self._fromDT
        resvEx.endDT = self._toDT

        locList = filter(lambda loc: Location.parse(loc) is not None, locList)

        if self._fromDT or self._toDT:
            daysParam = (day.date() for day in rrule.rrule(rrule.DAILY, dtstart=self._fromDT, until=self._toDT))
        else:
            # slow!
            daysParam = None

        for loc in sorted(locList):
            resvs = CrossLocationQueries.getReservations(location=loc, resvExample=resvEx, days=daysParam)
            for obj in self._process(resvs, filter=self._resvFilter):
                yield obj

        Factory.getDALManager().disconnect()
Ejemplo n.º 46
0
    def initialize(self, dbi=None):
        # empty tree
        self.clear()

        for room in set(CrossLocationQueries.getRooms()):
            self.index_obj(room.guid)
Ejemplo n.º 47
0
 def getObject(self):
     """
     """
     if self.__resvID:
         from MaKaC.rb_location import CrossLocationQueries, Location
         obj = CrossLocationQueries.getReservations(
             resvID=self.__resvID, location=self.__location)
         return obj
     if self.__roomID:
         from MaKaC.rb_location import CrossLocationQueries, Location
         obj = CrossLocationQueries.getRooms(roomID=self.__roomID,
                                             location=self.__location)
         return obj
     if self.__categId:
         if not conference.CategoryManager().hasKey(self.__categId):
             raise errors.NoReportError(
                 _("There is no category with id '%s', or it has been deleted"
                   ) % self.__categId)
         obj = conference.CategoryManager().getById(self.__categId)
         if self.__materialId:
             obj = obj.getMaterialById(self.__materialId)
         if self.__resId:
             obj = obj.getResourceById(self.__resId)
         return obj
     if not self.__confId:
         return None
     obj = conference.ConferenceHolder().getById(self.__confId)
     if obj == None:
         raise errors.NoReportError(
             "The event you are trying to access does not exist or has been deleted"
         )
     fr = materialFactories.ConfMFRegistry
     if self.__notifTplId:
         obj = obj.getAbstractMgr().getNotificationTplById(
             self.__notifTplId)
         return obj
     if self.__alarmId:
         obj = obj.getAlarmById(self.__alarmId)
         return obj
     if self.__trackId:
         obj = obj.getTrackById(self.__trackId)
         return obj
     if self.__menuLinkId:
         obj = obj.getDisplayMgr().getMenu().getLinkById(self.__menuLinkId)
         return obj
     if self.__contribTypeId:
         obj = obj.getContribTypeById(self.__contribTypeId)
         return obj
     if self.__abstractId:
         obj = obj.getAbstractMgr().getAbstractById(self.__abstractId)
         if obj == None:
             raise errors.NoReportError(
                 "The abstract you are trying to access does not exist or has been deleted"
             )
         if self.__resId:
             return obj.getAttachmentById(self.__resId)
     if self.__registrantId:
         obj = obj.getRegistrantById(self.__registrantId)
         if obj == None:
             raise errors.NoReportError(
                 "The registrant you are trying to access does not exist or has been deleted"
             )
         if self.__resId:
             return obj.getAttachmentById(self.__resId)
     if self.__sessionId:
         obj = obj.getSessionById(self.__sessionId)
         fr = materialFactories.SessionMFRegistry
         if obj == None:
             raise errors.NoReportError(
                 "The session you are trying to access does not exist or has been deleted"
             )
     if self.__slotId:
         obj = obj.getSlotById(self.__slotId)
     if self.__contribId:
         obj = obj.getContributionById(self.__contribId)
         fr = materialFactories.ContribMFRegistry
         if obj == None:
             raise errors.NoReportError(
                 "The contribution you are trying to access does not exist or has been deleted"
             )
     if self.__reviewId:
         #obj must be a Contribution
         obj = obj.getReviewManager().getReviewById(self.__reviewId)
         if obj == None:
             raise errors.NoReportError(
                 "The review you are tring to access does not exist or has been deleted"
             )
     if self.__subContribId and self.__contribId:
         obj = obj.getSubContributionById(self.__subContribId)
         fr = materialFactories.ContribMFRegistry
         if obj == None:
             raise errors.NoReportError(
                 "The subcontribution you are trying to access does not exist or has been deleted"
             )
     if not self.__materialId:
         return obj
     #first we check if it refers to a special type of material
     mat = None
     f = fr.getById(self.__materialId)
     if f:
         mat = f.get(obj)
     if not mat:
         mat = obj.getMaterialById(self.__materialId)
     if not self.__resId:
         return mat
     return mat.getResourceById(self.__resId)
Ejemplo n.º 48
0
    def getObject(self):
        """
        """
        if self.__resvID:
            from MaKaC.rb_location import CrossLocationQueries, Location

            obj = CrossLocationQueries.getReservations(resvID=self.__resvID, location=self.__location)
            return obj
        if self.__roomID:
            from MaKaC.rb_location import CrossLocationQueries, Location

            obj = CrossLocationQueries.getRooms(roomID=self.__roomID, location=self.__location)
            return obj
        if self.__categId:
            if not conference.CategoryManager().hasKey(self.__categId):
                raise errors.NoReportError(
                    _("There is no category with id '%s', or it has been deleted") % self.__categId
                )
            obj = conference.CategoryManager().getById(self.__categId)
            if self.__materialId:
                obj = obj.getMaterialById(self.__materialId)
            if self.__resId:
                obj = obj.getResourceById(self.__resId)
            return obj
        if not self.__confId:
            return None
        obj = conference.ConferenceHolder().getById(self.__confId)
        if obj == None:
            raise errors.NoReportError("The event you are trying to access does not exist or has been deleted")
        fr = materialFactories.ConfMFRegistry
        if self.__notifTplId:
            obj = obj.getAbstractMgr().getNotificationTplById(self.__notifTplId)
            return obj
        if self.__alarmId:
            obj = obj.getAlarmById(self.__alarmId)
            return obj
        if self.__trackId:
            obj = obj.getTrackById(self.__trackId)
            return obj
        if self.__menuLinkId:
            obj = obj.getDisplayMgr().getMenu().getLinkById(self.__menuLinkId)
            return obj
        if self.__contribTypeId:
            obj = obj.getContribTypeById(self.__contribTypeId)
            return obj
        if self.__abstractId:
            obj = obj.getAbstractMgr().getAbstractById(self.__abstractId)
            if obj == None:
                raise errors.NoReportError("The abstract you are trying to access does not exist or has been deleted")
            if self.__resId:
                return obj.getAttachmentById(self.__resId)
        if self.__registrantId:
            obj = obj.getRegistrantById(self.__registrantId)
            if obj == None:
                raise errors.NoReportError("The registrant you are trying to access does not exist or has been deleted")
            if self.__resId:
                return obj.getAttachmentById(self.__resId)
        if self.__sessionId:
            obj = obj.getSessionById(self.__sessionId)
            fr = materialFactories.SessionMFRegistry
            if obj == None:
                raise errors.NoReportError("The session you are trying to access does not exist or has been deleted")
        if self.__slotId:
            obj = obj.getSlotById(self.__slotId)
        if self.__contribId:
            obj = obj.getContributionById(self.__contribId)
            fr = materialFactories.ContribMFRegistry
            if obj == None:
                raise errors.NoReportError(
                    "The contribution you are trying to access does not exist or has been deleted"
                )
        if self.__reviewId:
            # obj must be a Contribution
            obj = obj.getReviewManager().getReviewById(self.__reviewId)
            if obj == None:
                raise errors.NoReportError("The review you are tring to access does not exist or has been deleted")
        if self.__subContribId and self.__contribId:
            obj = obj.getSubContributionById(self.__subContribId)
            fr = materialFactories.ContribMFRegistry
            if obj == None:
                raise errors.NoReportError(
                    "The subcontribution you are trying to access does not exist or has been deleted"
                )
        if not self.__materialId:
            return obj
        # first we check if it refers to a special type of material
        mat = None
        f = fr.getById(self.__materialId)
        if f:
            mat = f.get(obj)
        if not mat:
            mat = obj.getMaterialById(self.__materialId)
        if not self.__resId:
            return mat
        return mat.getResourceById(self.__resId)
Ejemplo n.º 49
0
    if len(roomIDs) > 10:
        return "One can only export 10 rooms at most"

    #################### process ###################
    rooms = []
    for roomID in roomIDs:
        roomEx = Factory.newRoom()
        roomEx.id = roomID
        rooms.append(roomEx)

    resvEx = Factory.newReservation()
    resvEx.isCancelled = False
    resvEx.isRejected = False
    resvEx.startDT = datetime(sd.year, sd.month, sd.day, 0, 0)
    resvEx.endDT = datetime(ed.year, ed.month, ed.day, 23, 59)
    resvs = CrossLocationQueries.getReservations(location="CERN", resvExample=resvEx, rooms=rooms)
    collisions = []
    for resv in resvs:
        for p in resv.splitToPeriods(endDT=resvEx.endDT, startDT=resvEx.startDT):
            collisions.append(Collision( ( p.startDT, p.endDT ), resv ))

    of = params.get("of", "csv")
    if of == "xml":
        result = createXML(collisions, req)
    else:
        result = createCSV(collisions, req)

    Factory.getDALManager().disconnect()
    DBMgr.getInstance().endRequest()

    return result
Ejemplo n.º 50
0
    def getVars(self):
        vars = WJSBase.getVars( self )

        vars["MinStartDate"] = formatDateTime(self._conf.getAdjustedStartDate())
        vars["MaxEndDate"] = formatDateTime(self._conf.getAdjustedEndDate())

        # Code to retrieve the event's location and room in order to include the event's room
        # as an initial participant
        location = self._conf.getLocation()
        room = self._conf.getRoom()
        if location and room and location.getName() and room.getName() and location.getName().strip() and room.getName().strip():
            locationName = location.getName()
            roomName = room.getName()
            
            vars["IncludeInitialRoom"] = True
            vars["IPRetrievalResult"] = -1 # 0 = OK, 1 = room without H323 IP, 2 = room with invalid H323 IP, 3 = connection to RB problem, 4 = another unknown problem 
            vars["InitialRoomName"] = roomName
            if self._conf.getLocation():
                vars["InitialRoomInstitution"] = locationName
            else:
                vars["InitialRoomInstitution"] = ""

            # TODO: get IP of room from a plugin option instead of querying RB DB every time
            try:
                minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
                if minfo.getRoomBookingModuleActive():
                    Logger.get("CERNMCU").info("Connecting with Room Booking DB to get a room's H323 IP")
                    CrossLocationDB.connect()
                    Logger.get("CERNMCU").info("Connection successful")

                    attName = getCERNMCUOptionValueByName("H323_IP_att_name")

                    try:
                        returnedRooms = CrossLocationQueries.getRooms( location = locationName, roomName = roomName )
    
                        if isinstance(returnedRooms, list):
                            if len(returnedRooms) == 0:
                                returnedRoom = None
                            else:
                                returnedRoom = returnedRooms[0]
                        else:
                            returnedRoom = returnedRooms
    
                        if (returnedRoom != None) and (attName in returnedRoom.customAtts):
    
                            initialRoomIp = returnedRoom.customAtts[attName]
                            if (initialRoomIp.strip() == ""):
                                vars["IPRetrievalResult"] = 1
                            elif not validIP(initialRoomIp):
                                vars["IPRetrievalResult"] = 2
                            else:
                                vars["IPRetrievalResult"] = 0
    
                        else:
                            initialRoomIp = "IP not defined for this room."
                            vars["IPRetrievalResult"] = 2
                            
                    except AttributeError:
                        #CrossLocationQueries.getRooms fails because it does not handle location names that are not in the DB
                        initialRoomIp = "Please enter IP"
                        vars["IPRetrievalResult"] = 1
                    except Exception, e:
                        initialRoomIp = "IP not found."
                        vars["IPRetrievalResult"] = 4
                        Logger.get("CERNMCU").warning("Location: " + locationName + "Problem with CrossLocationQueries when retrieving the list of all rooms with a H323 IP: " + str(e))
                else:
                    initialRoomIp = "Please enter IP"
                    vars["IPRetrievalResult"] = 3
                    Logger.get("CERNMCU").info("Tried to retrieve a room's H323 IP, but Room Booking module was not active.")
Ejemplo n.º 51
0
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Indico;if not, see <http://www.gnu.org/licenses/>.

from MaKaC.common.db import DBMgr
from MaKaC.rb_factory import Factory
from MaKaC.rb_location import CrossLocationQueries

DBMgr.getInstance().startRequest()
Factory.getDALManager().connect()

idontknow = "I don't know"

rooms = CrossLocationQueries.getRooms( allFast = True )
for room in rooms:
    print "[%s][%s] %s"%(room.id, room.needsAVCSetup,room.getAvailableVC())
    if room.needsAVCSetup:
        if not idontknow in room.getAvailableVC():
            room.avaibleVC.append(idontknow)
            room.update()


Factory.getDALManager().commit()
Factory.getDALManager().disconnect()
DBMgr.getInstance().endRequest()



DBMgr.getInstance().startRequest()