def addRoom(self, groupId, roomName, buildingName): checkData(locals()) group = Group(buildingName = buildingName, id = groupId) group.retrieve() from app.backend.model.room import Room room = Room(buildingName = buildingName, roomName = roomName) room.retrieve() if group.crossRoomsValidation: print "\t\t\t\t\t\t\t\tTODO (" + self.__class__.__name__ + ":" + sys._getframe().f_code.co_name + ") This part of the method as not been tested" # In this case we have to check that the room doesn't belong to another CrossRoomValidatioGroup from app.backend.model.building import Building building = Building(buildingName = buildingName) building.retrieve() crvgList = building.getCrossRoomValidationGroups(roomName = roomName, validationCategories = group.crossRoomsValidationCategories) if len(crvgList) > 0: raise WrongBuildingGroupRipartitionError("A room can belong to only one cross validation group per category. Room " + str(roomName) + " in already in group " + str(crvgList[0])) group.addRoom(room) return room.getDict()
def deleteRule(self, ruleId, buildingName, roomName, editorUuid): checkData(locals()) room = Room(buildingName = buildingName, roomName = roomName) room.retrieve() from app.backend.model.rule import Rule rule = Rule(id = ruleId) rule.retrieve() from app.backend.model.user import User editor = User(uuid = editorUuid) editor.retrieve() author = User(uuid = rule.authorUuid) author.retrieve() # If this room is not related to a room, I cannot modify it from this method if not rule.roomName: raise UserCredentialError("You cannot modify this group related rule.") # If this rule is not about this building if rule.buildingName != buildingName: raise UserCredentialError("You cannot modify the rule of another building.") if author.uuid != editor.uuid: if not rule.groupId and not rule.getRoom().roomName in list(r.roomName for r in editor.getRooms()): raise UserCredentialError("You cannot modify a rule of a room you do not own.") #if rule.getRoom() not in editor.getRooms(): # raise UserCredentialError("You cannot modify a rule of a room you do not own.") if rule.groupId: from app.backend.model.group import Group group = Group(buildingName = buildingName, id = groupId) group.retrieve() if not group: raise UserCredentialError("You cannot delete a rule of a room you do not own.") if not group.crossRoomsValidation: raise UserCredentialError("You cannot delete a rule you do not own.") if not group.id in list(g.id for g in editor.getGroups()): raise UserCredentialError("You cannot delete a rule belonging to a group you do not own.") if not rule.getRoom().roomName in list(r.roomName for r in group.getRooms()): raise UserCredentialError("You cannot delete a rule belonging to room that does not belongs to a group you do not own.") if editor.level < rule.getPriority(): raise UserCredentialError("You cannot modify this rule since it has a too high priority for your user level") room.deleteRule(rule) return {}
def getRooms(self, groupId, buildingName): checkData(locals()) group = Group(buildingName = buildingName, id = groupId) group.retrieve() roomList = [] for room in group.getRooms(): roomList.append(room.getDict()) return {"rooms" : roomList}
def getRules(self, groupId, buildingName): checkData(locals()) group = Group(buildingName = buildingName, id = groupId) group.retrieve() ruleList = group.getRules() response = [] for rule in ruleList: response.append(rule.getDict()) return {"rules" : response}
def deleteRule(self, ruleId, buildingName, groupId): checkData(locals()) group = Group(buildingName = buildingName, id = groupId) group.retrieve() from app.backend.model.rule import Rule rule = Rule(id = ruleId) rule.retrieve() group.deleteRule(rule) return {}
def isCrossRoomsValidationGroup(self, groupId, buildingName, crossRoomsValidationCategory = None): checkData(locals()) group = Group(buildingName = buildingName, id = groupId) group.retrieve() if group.crossRoomsValidation: if crossRoomsValidationCategory: if crossRoomsValidationCategory in group.crossRoomsValidationCategories: return True else: return False else: return True else: return False
def getCrossRoomValidationGroups(self, roomName = None, validationCategories = None): print "\t\t\t\t\t\t\t\tTODO (" + self.__class__.__name__ + ":" + sys._getframe().f_code.co_name + ") : non yet tested" from app.backend.model.group import Group query = "SELECT id FROM groups WHERE building_name = '@@building_name@@' AND cross_rooms_validation = '1';" database = Database() database.open() query = self.__replaceSqlQueryToken(query) queryResult = database.executeReadQuery(query) database.close() groupList = [] for groupRecord in queryResult: group = Group(id = groupRecord[0], buildingName = self.buildingName) group.retrieve() if validationCategories: queriedValidationCategories = set(validationCategories) groupValidationCategories = set(group.crossRoomsValidationCategories) if queriedValidationCategories.issubset(groupValidationCategories): groupList.append(group) else: groupList.append(group) if not roomName and not validationCategories: return groupList if roomName: filteredGroupList = [] for group in groupList: for room in group.getRooms(): if room.roomName == roomName: filteredGroupList.append(group) return filteredGroupList raise UnknownError()
def getGroups(self): print "\t\t\t\t\t\t\t\tTODO (" + self.__class__.__name__ + ":" + sys._getframe().f_code.co_name + ") : non yet tested" from app.backend.model.group import Group query = "SELECT id FROM groups WHERE building_name = '@@building_name@@';" database = Database() database.open() query = self.__replaceSqlQueryToken(query) queryResult = database.executeReadQuery(query) database.close() groupList = [] for groupRecord in queryResult: group = Group(id = groupRecord[0], buildingName = self.buildingName) group.retrieve() groupList.append(group) return groupList
def getGroups(self): from app.backend.model.group import Group database = Database() database.open() query = "SELECT * FROM rooms_groups WHERE room_name = '@@room_name@@' AND building_name = '@@building_name@@';" query = self.__replaceSqlQueryToken(query) queryResult = database.executeReadQuery(query) database.close() groupList = [] for record in queryResult: groupId = record[0] buildingName = record[1] group = Group(id = groupId, buildingName = buildingName) group.retrieve() groupList.append(group) return groupList
def deleteGroup(self, buildingName, groupId): checkData(locals()) print "\t\t\t\t\t\t\t\tTODO (" + self.__class__.__name__ + ":" + sys._getframe().f_code.co_name + ") not yet tested" from app.backend.model.group import Group group = Group(buildingName = buildingName, id = groupId) roomList = group.getRooms() ruleList = group.getRules() for room in roomList: group.deleteRoom(room) for rule in ruleList: rule.delete() group.delete() return {}
def editRule(self, ruleId, priority, buildingName, roomName, editorUuid, groupId, ruleBody = None, antecedent = None, consequent = None, enabled = True): checkData(locals()) if not ruleBody: if not antecedent: raise MissingInputDataError("") if not consequent: raise MissingInputDataError("") if ruleBody and antecedent: raise TooManyInputParametersError("") if ruleBody and consequent: raise TooManyInputParametersError("") from app.backend.model.rule import Rule oldRule = Rule(id = ruleId) oldRule.retrieve() from app.backend.model.user import User author = User(uuid = oldRule.authorUuid) author.retrieve() editor = User(uuid = editorUuid) editor.retrieve() writePermission = False errorMessage = "" # If this room is not related to a room, I cannot modify it from this method if not oldRule.roomName: raise UserCredentialError("You cannot modify this group related rule.") # If this rule is not about this building if oldRule.buildingName != buildingName: raise UserCredentialError("You cannot modify the rule of another building.") if author.uuid != editor.uuid: if not groupId and not oldRule.getRoom().roomName in list(r.roomName for r in editor.getRooms()): raise UserCredentialError("You cannot modify a rule of a room you do not own.") #if oldRule.getRoom() not in editor.getRooms(): # raise UserCredentialError("You cannot modify a rule of a room you do not own.") if groupId: from app.backend.model.group import Group group = Group(buildingName = buildingName, id = groupId) group.retrieve() if not group: raise UserCredentialError("You cannot modify a rule of a room you do not own.") if not group.crossRoomsValidation: raise UserCredentialError("You cannot modify a rule you do not own.") if not group.id in list(g.id for g in editor.getGroups()): raise UserCredentialError("You cannot modify a rule belonging to a group you do not own.") if not oldRule.getRoom().roomName in list(r.roomName for r in group.getRooms()): raise UserCredentialError("You cannot modify a rule belonging to room that does not belongs to a group you do not own.") if editor.level < oldRule.getPriority(): raise UserCredentialError("You cannot modify this rule since it has a too high priority for your user level") authorUuid = editorUuid result = self.__addOrModifyRule(ruleId = ruleId, priority = priority, buildingName = buildingName, roomName = roomName, authorUuid = authorUuid, ruleBody = ruleBody, antecedent = antecedent, consequent = consequent, enabled = enabled) from app.backend.controller.notificationsManager import NotificationsManager notifications = NotificationsManager() messageSubject = "Rule modified in building " + str(buildingName) + " room " + str(roomName) messageText = "The user " + str(editor.username) + " edited (or tried to edit) the rule <<" + str(oldRule.getFullRepresentation()) + ">>. The new rule is <<" + str(ruleBody) + ">>" notifications.sendNotification(buildingName = buildingName, roomName = roomName, messageSubject = messageSubject, messageText = messageText) return result
def sendNotification(self, userUuid = None, buildingName = None, groupId = None, roomName = None, messageSubject = None, messageText = None): checkData(locals()) if not messageSubject: raise NewNotificationMissingInputError("messageSubject is mandatory to send a new notification") if not messageText: raise NewNotificationMissingInputError("messageText is mandatory to send a new notification") if not userUuid and not buildingName: raise NewNotificationMissingInputError("You have to specify at least one recipient to send a new notification") if buildingName and not roomName and not groupId: raise NewNotificationMissingInputError("You cannot send a notification to an entire building. You have to specify at least a room or a group.") if not buildingName and not roomName and not groupId: raise NewNotificationMissingInputError("You have to specify at least one recipient to send a new notification.") recipientUuidList = [] if userUuid: recipientUuidList.append(userUuid) if buildingName and roomName: from app.backend.model.room import Room room = Room(buildingName = buildingName, roomName = roomName) room.retrieve() for user in room.getUsers(): recipientUuidList.append(user.uuid) # managing rooms insid a cross validation group for group in room.getGroups(): if group.crossRoomsValidation: for gRoom in group.getRooms(): for user in gRoom.getUsers(): recipientUuidList.append(user.uuid) if buildingName and groupId: from app.backend.model.group import Group from app.backend.model.room import Room group = Group(buildingName = buildingName, id = groupId) group.retrieve() for room in group.getRooms(): for user in room.getUsers(): recipientUuidList.append(user.uuid) # Removing duplicate Id recipientUuidList = list(set(recipientUuidList)) for recipientUuid in recipientUuidList: notification = Notification(recipientUuid = recipientUuid, messageSubject = messageSubject, messageText = messageText) notification.store() return {}
def test0(self): from app.backend.commons.database import Database from app.backend.model.building import Building from app.backend.model.group import Group from app.backend.model.room import Room from app.backend.model.user import User from app.backend.model.rule import Rule print "Starting test..." print "Cleaning database..." database = Database() database.open() database.executeWriteQuery("TRUNCATE TABLE buildings") database.executeWriteQuery("TRUNCATE TABLE groups") database.executeWriteQuery("TRUNCATE TABLE rooms") database.executeWriteQuery("TRUNCATE TABLE users") database.executeWriteQuery("TRUNCATE TABLE users_rooms") database.executeWriteQuery("TRUNCATE TABLE rooms_groups") database.executeWriteQuery("TRUNCATE TABLE rules") database.close() print "Testing model..." building = Building(buildingName = "CSE", label = "Computer Science", description = "This is a nice place") building.store() building = Building(buildingName = "CSE", label = "Computer Science", description = "This is a great place") building.store() building = Building(buildingName = "CSE") building.retrieve() print building group = Group(buildingName = "CSE", description = "Questo gruppo eheh") group.store() print group group = Group(id=1, buildingName = "CSE") group.retrieve() print group group = Group(id=1, buildingName = "CSE", description = "we ciao ciao") group.store() group = Group(id=1, buildingName = "CSE") group.retrieve() print group room = Room(roomName = "200", buildingName = "CSE", description = "Bella 3333") room.store() room = Room(roomName = "200", buildingName = "CSE") room.retrieve() print room print "room.getBuilding() test" print room.getBuilding() user = User(username = "******", email = "*****@*****.**", password = "******", personName = "Alessandro Nacci", level = 10) user.store() room.addUser(user) print "user.getRooms() test" for room in user.getRooms(): print room print "group.addRoom(room) test" group.addRoom(room) print group print "User test 1" user = User(username = "******") user.retrieve() print user print "User test 2" user = User(username = "******", password="******") user.retrieve() print user print "User test 3" user = User(uuid = 1) user.retrieve() print user rule = Rule(priority = 1, category = "ELECTRICT222", buildingName = "CSE", groupId = 1, roomName = "200", authorUuid = 1, antecedent = "the ligjt is on", consequent = "turn off the light", enabled = 1, deleted = 0) rule.store() rule = Rule(id = 1) rule.retrieve() print rule print rule.getBuilding() print rule.getGroup() print rule.getAuthor() print "test group.getRules()" ruleList = group.getRules() for r in ruleList: print r print "test room.getRules()" ruleList = room.getRules() for r in ruleList: print r print "test room.getRules(author)" ruleList = room.getRules(author = user, includeGroupsRules = None) for r in ruleList: print r print "test room.getRules(includeGroupsRules)" ruleList = room.getRules(includeGroupsRules = True) for r in ruleList: print r print "test user.getCreatedRules()" ruleList = user.getCreatedRules() for r in ruleList: print r group.deleteRoom(room) room.deleteUser(user) rule.delete() user.delete() group.delete() building.delete() room.delete() user = User(username = "******") user.retrieve()
def getGroup(self): from app.backend.model.group import Group group = Group(id = self.groupId, buildingName = self.buildingName) group.retrieve() return group
def getInfo(self, groupId, buildingName): checkData(locals()) group = Group(buildingName = buildingName, id = groupId) group.retrieve() return group.getDict()
def __addOrModifyRule(self, priority = None, buildingName = None, groupId = None, authorUuid = None, ruleBody = None, ruleId = None): checkData(locals()) import time,datetime startTimeMilliseconds = long((time.time() + 0.5) * 1000) try: antecedent = ruleBody.split("then")[0].replace("if ", "").strip() consequent = ruleBody.split("then")[1].strip() except Exception as e: raise NotWellFormedRuleError("There is a syntax error in the rule you are trying to save") from app.backend.controller.actionManager import ActionManager actionManager = ActionManager() category = actionManager.getAction(consequent).category from app.backend.model.user import User author = User(uuid = authorUuid) author.retrieve() if int(str(priority)) < 0 or int(str(priority)) > author.getMaxGroupPriority(): raise RulePriorityError("You can specify rules for groups with a priority value between 0 and " + str(author.getMaxRoomPriority()) + ". You inserted " + str(priority)) from app.backend.model.rule import Rule from app.backend.model.group import Group if not ruleId: rule = Rule(priority = priority, category = category, buildingName = buildingName, groupId = groupId, authorUuid = authorUuid, antecedent = antecedent, consequent = consequent, enabled = True) else: rule = Rule(id = ruleId) rule.retrieve() author = rule.getAuthor() rule.antecedent = antecedent rule.consequent = consequent rule.authorUuid = authorUuid editor = rule.getAuthor() if editor.level < rule.getPriority(): raise UserCredentialError("You cannot modify this rule since it has a too high priority for your user level") group = Group(buildingName = buildingName, id = groupId) group.retrieve() if not ruleId and not rule.checkIfUnique(): raise DuplicatedRuleError("The submitted rule is already been saved for the considered group.") # excludedRuleId is needed to ignore the rule that the user want to edit excludedRuleId = ruleId if ruleId else None ruleCheckErrorList = [] groupRoomList = group.getRooms() for room in groupRoomList: groupRules = group.getRules(excludedRuleId = excludedRuleId) # Checking that a priority is unique over the same category for r in groupRules: if str(r.category) == str(category) and int(r.getPriority()) == int(priority): raise AlredyAssignedPriorityError("In group " + str(groupId) + " the priority " + str(priority) + " has alredy been assigned to another rule with the same category!") temporaryRuleSet = [] temporaryRuleSet.extend(room.getRules(author = False, includeGroupsRules = True, excludedRuleId = False, excludeCrossRoomValidationRules = True)) temporaryRuleSet.extend(groupRules) temporaryRuleSet.append(rule) from app.backend.controller.rulesetChecker import RulesetChecker rulesetChecker = RulesetChecker(temporaryRuleSet) ruleCheckErrorList.extend(rulesetChecker.check()) if len(ruleCheckErrorList) == 0: if ruleId: #if i'm in edit mode rule.id = ruleId rule.setPriority(priority) # Disabling rules in all the groups rooms since they have to be validated again for room in groupRoomList: from app.backend.controller.notificationsManager import NotificationsManager notifications = NotificationsManager() messageSubject = "Group " + str(groupId) + " changed your room " + str(room.roomName) + " policy." messageText = "Some rules in group " + str(groupId) + " have been changed." notifications.sendNotification(buildingName = buildingName, roomName = room.roomName, messageSubject = messageSubject, messageText = messageText) #for r in room.getRules(includeGroupsRules = False, excludeCrossRoomValidationRules = True): # r.disable() from app.backend.commons.console import flash endTimeMilliseconds = long((time.time() + 0.5) * 1000) opTimeMilliseconds = endTimeMilliseconds - startTimeMilliseconds flash("GroupsRuleVerification [SUCCESS]: groupId = " + str(groupId) +" #rules=" + str(len(temporaryRuleSet)) + " - opTimeMilliseconds:" + str(opTimeMilliseconds)) return group.addRule(rule).getDict() else: from app.backend.commons.console import flash logMessage = "authorUuid = " + str(authorUuid) + ", " logMessage += "buildingName = " + str(buildingName) + ", " logMessage += "gropuId = " + str(groupId) + ", " logMessage += "ruleSetDescr = " + str(temporaryRuleSet) + ", " logMessage += "newRule = " + str(rule) flash("RuleValidationError: " + logMessage) endTimeMilliseconds = long((time.time() + 0.5) * 1000) opTimeMilliseconds = endTimeMilliseconds - startTimeMilliseconds flash("GroupsRuleVerification [FAILED]: groupId = " + str(groupId) +" #rules=" + str(len(temporaryRuleSet)) + " - opTimeMilliseconds:" + str(opTimeMilliseconds)) raise RuleValidationError(ruleCheckErrorList + " Error in room " + room.roomName)