Пример #1
0
    def layerrequest(self, event):
        """
        Handles new layer category requests

        :param event: LayerRequest Event with basic action types:
        * put
        * get
        * delete
        * list

        For events, there are two more actions:
        * subscribe
        * unsubscribe

        """

        hfoslog("[LM] Event: ", event, lvl=debug)

        try:
            if event.action == 'list':
                try:
                    dblist = self._generatelayerlist()
                    self.fireEvent(
                        send(
                            event.client.uuid, {
                                'component': 'layers',
                                'action': 'list',
                                'data': dblist
                            }))
                except Exception as e:
                    hfoslog("[LM] Listing error: ", e, type(e), lvl=error)
                return

        except Exception as e:
            hfoslog("[LM] Global Error: '%s' %s" % (e, type(e)), lvl=error)
Пример #2
0
    def broadcast(self, event):
        """Broadcasts an event either to all users or clients, depending on event flag"""
        try:
            if event.broadcasttype == "users":
                if len(self._users) > 0:
                    hfoslog("[CM] Broadcasting to all users:", event.content)
                    for useruuid in self._users.keys():
                        self.fireEvent(send(useruuid, event.content, sendtype="user"))
                else:
                    hfoslog("[CM] Not broadcasting, no users connected.", lvl=debug)

            elif event.broadcasttype == "clients":
                if len(self._clients) > 0:
                    hfoslog("[CM] Broadcasting to all clients: ", event.content)
                    for client in self._clients.values():
                        self.fireEvent(write(client.sock, event.content), "wsserver")
                else:
                    hfoslog("[CM] Not broadcasting, no clients connected.", lvl=debug)
            elif event.broadcasttype == "socks":
                if len(self._sockets) > 0:
                    hfoslog("[CM] Emergency?! Broadcasting to all sockets: ", event.content)
                    for sock in self._sockets:
                        self.fireEvent(write(sock, event.content), "wsserver")
                else:
                    hfoslog("[CM] Not broadcasting, no sockets connected.", lvl=debug)

        except Exception as e:
            hfoslog("[CM] Error during broadcast: ", e, type(e), lvl=critical)
Пример #3
0
 def _broadcast(self, camerapacket, camerauuid):
     try:
         for recipient in self._subscribers[camerauuid]:
             self.fireEvent(send(recipient, camerapacket, raw=True),
                            "hfosweb")
     except Exception as e:
         hfoslog("[CAM] Failed broadcast: ", e, type(e), lvl=error)
Пример #4
0
    def broadcast(self, event):
        """Broadcasts an event either to all users or clients, depending on event flag"""
        try:
            if event.broadcasttype == "users":
                if len(self._users) > 0:
                    hfoslog("[CM] Broadcasting to all users:", event.content)
                    for useruuid in self._users.keys():
                        self.fireEvent(
                            send(useruuid, event.content, sendtype="user"))
                else:
                    hfoslog("[CM] Not broadcasting, no users connected.",
                            lvl=debug)

            elif event.broadcasttype == "clients":
                if len(self._clients) > 0:
                    hfoslog("[CM] Broadcasting to all clients: ",
                            event.content)
                    for client in self._clients.values():
                        self.fireEvent(write(client.sock, event.content),
                                       "wsserver")
                else:
                    hfoslog("[CM] Not broadcasting, no clients connected.",
                            lvl=debug)
            elif event.broadcasttype == "socks":
                if len(self._sockets) > 0:
                    hfoslog("[CM] Emergency?! Broadcasting to all sockets: ",
                            event.content)
                    for sock in self._sockets:
                        self.fireEvent(write(sock, event.content), "wsserver")
                else:
                    hfoslog("[CM] Not broadcasting, no sockets connected.",
                            lvl=debug)

        except Exception as e:
            hfoslog("[CM] Error during broadcast: ", e, type(e), lvl=critical)
Пример #5
0
    def layerrequest(self, event):
        """
        Handles new layer category requests

        :param event: LayerRequest Event with basic action types:
        * put
        * get
        * delete
        * list

        For events, there are two more actions:
        * subscribe
        * unsubscribe

        """

        hfoslog("[LM] Event: ", event, lvl=debug)

        try:
            if event.action == 'list':
                try:
                    dblist = self._generatelayerlist()
                    self.fireEvent(
                        send(event.client.uuid, {'component': 'layers', 'action': 'list', 'data': dblist}))
                except Exception as e:
                    hfoslog("[LM] Listing error: ", e, type(e), lvl=error)
                return

        except Exception as e:
            hfoslog("[LM] Global Error: '%s' %s" % (e, type(e)), lvl=error)
Пример #6
0
    def _broadcast(self, mapviewpacket, mapviewuuid):

        try:
            hfoslog("[MVM] Transmitting message '%s'" % mapviewpacket)
            for recipient in self._subscribers[mapviewuuid]:
                self.fireEvent(send(recipient, mapviewpacket))
        except Exception as e:
            hfoslog("[MVM] Failed broadcast: ", e, type(e), lvl=error)
Пример #7
0
    def _broadcast(self, mapviewpacket, mapviewuuid):

        try:
            hfoslog("[MVM] Transmitting message '%s'" % mapviewpacket)
            for recipient in self._subscribers[mapviewuuid]:
                self.fireEvent(send(recipient, mapviewpacket))
        except Exception as e:
            hfoslog("[MVM] Failed broadcast: ", e, type(e), lvl=error)
Пример #8
0
    def _broadcast(self, layerupdatepacket, layeruuid):

        try:
            hfoslog("[LM] Transmitting message '%s'" % layerupdatepacket)
            for recipient in self._subscribers[layeruuid]:
                self.fireEvent(send(recipient, layerupdatepacket), "wsserver")
        except Exception as e:
            hfoslog("[LM] Failed broadcast: ", e, type(e), lvl=error)
Пример #9
0
    def _broadcast(self, layerupdatepacket, layeruuid):

        try:
            hfoslog("[LM] Transmitting message '%s'" % layerupdatepacket)
            for recipient in self._subscribers[layeruuid]:
                self.fireEvent(send(recipient, layerupdatepacket), "wsserver")
        except Exception as e:
            hfoslog("[LM] Failed broadcast: ", e, type(e), lvl=error)
Пример #10
0
    def userlogin(self, event):
        """Checks if an alert is ongoing and alerts the newly connected client, if so."""

        clientuuid = event.clientuuid

        if self.mobalert:
            alertpacket = {'component': 'alert', 'action': 'mob', 'data': True}
            self.fireEvent(send(clientuuid, alertpacket))
Пример #11
0
    def userlogin(self, event):
        """Checks if an alert is ongoing and alerts the newly connected client, if so."""

        clientuuid = event.clientuuid

        if self.mobalert:
            alertpacket = {'component': 'alert', 'action': 'mob', 'data': True}
            self.fireEvent(send(clientuuid, alertpacket))
Пример #12
0
    def schemarequest(self, event):
        """Handles schema requests.

        :param event: SchemaRequest with actions
        * Get
        * All
        """
        if event.action == "Get":
            hfoslog("[SM] Schemarequest for ", event.data, "from", event.user, lvl=info)
            if event.data in hfos.schemata.schemastore:
                response = {'component': 'schema',
                            'action': 'Get',
                            'data': self.schemata[event.data]
                            }
                self.fireEvent(send(event.client.uuid, response))
        elif event.action == "All":
            hfoslog("[SM] Schemarequest for all schemata from ", event.user, lvl=info)
            response = {'component': 'schema',
                        'action': 'All',
                        'data': hfos.schemata.schemastore}
            self.fireEvent(send(event.client.uuid, response))
Пример #13
0
    def camerarequest(self, event):
        """
        Handles new camera category requests

        :param event: CameraRequest with actions
        * subscribe
        * unsubscribe
        * update
        """

        hfoslog("[CAM] Event: '%s'" % event.__dict__)

        try:
            try:
                action = event.action
                data = event.data

                clientuuid = event.client.uuid
            except Exception as e:
                raise ValueError("[CAM] Problem during event unpacking:", e,
                                 type(e))

            if action == 'list':
                try:
                    dblist = self._generatecameralist()
                    self.fireEvent(
                        send(
                            clientuuid, {
                                'component': 'camera',
                                'action': 'list',
                                'data': dblist
                            }), "hfosweb")
                except Exception as e:
                    hfoslog("[CAM] Listing error: ", e, type(e), lvl=error)
                return
            elif action == 'get':
                return
            elif action == 'subscribe':
                # TODO: Verify everything and send a response
                if data in self._subscribers:
                    if clientuuid not in self._subscribers[data]:
                        self._subscribers[data].append(clientuuid)
                else:
                    self._subscribers[data] = [clientuuid]
                hfoslog("[CAM] Subscription registered: ", data, clientuuid)
                return
            elif action == 'unsubscribe':
                self._unsubscribe(clientuuid, data)
                return

        except Exception as e:
            hfoslog("[CAM] Global Error: '%s' %s" % (e, type(e)), lvl=error)
Пример #14
0
    def camerarequest(self, event):
        """
        Handles new camera category requests

        :param event: CameraRequest with actions
        * subscribe
        * unsubscribe
        * update
        """

        hfoslog("[CAM] Event: '%s'" % event.__dict__)

        try:
            try:
                action = event.action
                data = event.data

                clientuuid = event.client.uuid
            except Exception as e:
                raise ValueError("[CAM] Problem during event unpacking:", e, type(e))

            if action == 'list':
                try:
                    dblist = self._generatecameralist()
                    self.fireEvent(send(clientuuid, {'component': 'camera', 'action': 'list', 'data': dblist}),
                                   "hfosweb")
                except Exception as e:
                    hfoslog("[CAM] Listing error: ", e, type(e), lvl=error)
                return
            elif action == 'get':
                return
            elif action == 'subscribe':
                # TODO: Verify everything and send a response
                if data in self._subscribers:
                    if clientuuid not in self._subscribers[data]:
                        self._subscribers[data].append(clientuuid)
                else:
                    self._subscribers[data] = [clientuuid]
                hfoslog("[CAM] Subscription registered: ", data, clientuuid)
                return
            elif action == 'unsubscribe':
                self._unsubscribe(clientuuid, data)
                return

        except Exception as e:
            hfoslog("[CAM] Global Error: '%s' %s" % (e, type(e)), lvl=error)
Пример #15
0
    def wikirequest(self, event):
        """Wiki event handler for incoming events
        :param event: WikiRequest with incoming wiki pagename and pagedata
        """

        hfoslog("[WIKI] Event: '%s'" % event.__dict__)
        try:
            action = event.action
            data = event.data

            if action == "get":
                wikipage = wikipageobject.find_one({'name': data})

                if not wikipage:
                    hfoslog("[WIKI] Page not found: ", data)
                    wikipage = wikipageobject({'uuid': str(uuid4()),
                                               'name': data,
                                               })
                else:
                    hfoslog("[WIKI] Page found, delivering: ", data)

                wikipacket = {'component': 'wiki',
                              'action': 'get',
                              'data': wikipage.serializablefields()
                              }
            elif action == "put":
                if data['uuid']:
                    wikipage = wikipageobject.find_one({'uuid': data['uuid']})

                    if wikipage:
                        hfoslog("[WIKI] Updating old page.")
                        wikipage.update(data)
                    else:
                        wikipage = wikipageobject(data)
                        hfoslog("[WIKI] Storing a new page:", wikipage._fields)
                        try:
                            wikipage.validate()
                            wikipage.save()
                        except ValidationError:
                            hfoslog("[WIKI] Validation of new page failed!", data, lvl=warn)

                        hfoslog("[WIKI] Page stored. Reindexing.")
                        self._updateIndex()
                        hfoslog("[WIKI] Reindexing done.")

                    wikipacket = {'component': 'wiki',
                                  'action': 'put',
                                  'data': (True, wikipage.name),
                                  }
                else:
                    hfoslog("[WIKI] Weird request without uuid! Trying to create completely new page.", lvl=warn)
                    wikipage = wikipageobject(data)
                    wikipage.uuid = str(uuid4())
                    if wikipage.validate():
                        wikipage.save()

                    wikipacket = {'component': 'wiki',
                                  'action': 'put',
                                  'data': (True, wikipage.name),
                                  }

            else:
                hfoslog("[WIKI] Unsupported action: ", action, event, event.__dict__, lvl=warn)
                return

            try:
                self.fireEvent(send(event.client.uuid, wikipacket))
            except Exception as e:
                hfoslog("[WIKI] Transmission error before broadcast: %s" % e, lvl=error)

        except Exception as e:
            hfoslog("[WIKI] Error: '%s' %s" % (e, type(e)), lvl=error)
Пример #16
0
    def objectmanagerrequest(self, event):
        """OM event handler for incoming events
        :param event: OMRequest with incoming OM pagename and pagedata
        """

        hfoslog("[OM] Event: '%s'" % event.__dict__)
        try:
            action = event.action
            data = event.data
            schema = data['schema']

            result = None

            if action == "list":
                if schema in objectmodels.keys():
                    if 'filter' in data:
                        filter = data['filter']
                    else:
                        filter = {}

                    if 'fields' in data:
                        fields = data['fields']
                    else:
                        fields = []

                    objlist = []

                    if objectmodels[schema].count(filter) > WARNSIZE:
                        hfoslog("[OM] Getting a very long list of items for ",
                                schema,
                                lvl=warn)

                    for item in objectmodels[schema].find(filter):
                        try:
                            listitem = {'uuid': item.uuid, 'name': item.name}
                            for field in fields:
                                if field in item._fields:
                                    listitem[field] = item._fields[field]
                                else:
                                    listitem[field] = None

                            objlist.append(listitem)
                        except Exception as e:
                            hfoslog("[OM] Faulty object or field: ",
                                    item._fields,
                                    fields,
                                    lvl=error)
                    hfoslog("[OM] Generated object list: ", objlist)

                    result = {
                        'component': 'objectmanager',
                        'action': 'list',
                        'data': {
                            'schema': schema,
                            'list': objlist
                        }
                    }
                else:
                    hfoslog("[OM] List for unavailable schema requested: ",
                            schema,
                            lvl=warn)

            elif action == "get":
                uuid = data['uuid']

                obj = None

                if schema in objectmodels.keys() and uuid.upper != "CREATE":
                    obj = objectmodels[schema].find_one({'uuid': uuid})

                if not obj:
                    hfoslog("[OM] Object not found, creating: ", data)
                    obj = objectmodels[schema]({'uuid': str(uuid4())})
                else:
                    hfoslog("[OM] Object found, delivering: ", data)

                result = {
                    'component': 'objectmanager',
                    'action': 'get',
                    'data': obj.serializablefields()
                }

            elif action == "put":
                try:
                    putobj = data['obj']
                    uuid = putobj['uuid']
                except KeyError:
                    hfoslog("[OM] Put request with missing arguments!",
                            event,
                            lvl=critical)
                    return

                try:
                    if uuid != 'create':
                        obj = objectmodels[schema].find_one({'uuid': uuid})
                    else:
                        putobj['uuid'] = uuid4()
                    if obj:
                        hfoslog("[OM] Updating object:",
                                obj._fields,
                                lvl=debug)
                        obj.update(putobj)

                    else:
                        obj = objectmodels[schema](putobj)
                        hfoslog("[OM] Storing object:", obj._fields, lvl=debug)
                        try:
                            obj.validate()
                        except ValidationError:
                            hfoslog("[OM] Validation of new object failed!",
                                    data,
                                    lvl=warn)

                    obj.save()

                    hfoslog("[OM] Object stored.")

                    result = {
                        'component': 'objectmanager',
                        'action': 'put',
                        'data': (True, obj.uuid),
                    }
                except Exception as e:
                    hfoslog("[OM] Error during object storage:",
                            e,
                            type(e),
                            lvl=error)

            else:
                hfoslog("[OM] Unsupported action: ",
                        action,
                        event,
                        event.__dict__,
                        lvl=warn)
                return

            if result:
                try:
                    self.fireEvent(send(event.client.uuid, result))
                except Exception as e:
                    hfoslog("[OM] Transmission error before broadcast: %s" % e,
                            lvl=error)

        except Exception as e:
            hfoslog("[OM] Error: '%s' %s" % (e, type(e)), lvl=error)
Пример #17
0
    def remotecontrolrequest(self, event):
        """Remote control event handler for incoming events
        :param event: RemoteControlRequest with action being one of
            ['list', 'takeControl', 'leaveControl', 'controlData']
        """

        hfoslog("[RCM] Event: '%s'" % event.__dict__)
        try:
            action = event.action
            data = event.data
            username = event.user.account.username
            clientname = event.client.name
            clientuuid = event.client.uuid

            if action == 'list':
                try:
                    dblist = {
                        'controllables':
                        self._getobjectlist(controllableobject),
                        'controllers': self._getobjectlist(controllerobject)
                    }

                    self.fireEvent(
                        send(
                            clientuuid, {
                                'component': 'remotectrl',
                                'action': 'list',
                                'data': dblist
                            }))
                except Exception as e:
                    hfoslog("[RCM]: Listing error: ", e, type(e), lvl=error)
                return

            if action == "takeControl":
                hfoslog("[RCM] Client wants to remote control: ",
                        username,
                        clientname,
                        lvl=warn)
                if not self.remotecontroller:
                    hfoslog("[RCM] Success!")
                    self.remotecontroller = clientuuid
                    self.fireEvent(
                        send(
                            clientuuid, {
                                'component': 'remotectrl',
                                'action': 'takeControl',
                                'data': True
                            }))
                else:
                    hfoslog("[RCM] No, we're already being remote controlled!")
                    self.fireEvent(
                        send(
                            clientuuid, {
                                'component': 'remotectrl',
                                'action': 'takeControl',
                                'data': False
                            }))
                return
            elif action == "leaveControl":

                if self.remotecontroller == event.client.uuid:
                    hfoslog("[RCM] Client leaves control!",
                            username,
                            clientname,
                            lvl=warn)
                    self.remotecontroller = None
                    self.fireEvent(
                        send(
                            clientuuid, {
                                'component': 'remotectrl',
                                'action': 'takeControl',
                                'data': False
                            }))
                return
            elif action == "controlData":
                hfoslog("[RCM] Control data received: ", data)
                if event.client.uuid == self.remotecontroller:
                    hfoslog(
                        "[RCM] Valid data, handing on to ControlDataManager.")
                    self.fireEvent(remotecontrolupdate(data), "machineroom")
                else:
                    hfoslog("[RCM] Invalid control data update request!",
                            lvl=warn)

        except Exception as e:
            hfoslog("[RCM] Error: '%s' %s" % (e, type(e)), lvl=error)
Пример #18
0
    def authenticationrequest(self, event):
        """Handles authentication requests from clients
        :param event: AuthenticationRequest with user's credentials
        """

        hfoslog("[AUTH] Auth request for ", event.username, event.clientuuid)

        if (len(event.username) < 3) or (len(event.passhash) < 3):
            hfoslog("[AUTH] Illegal username or password received, login cancelled", lvl=warn)
            return

        useraccount = None
        clientconfig = None
        userprofile = None

        try:
            useraccount = userobject.find_one({'username': event.username})
            hfoslog("[AUTH] Account: %s" % useraccount._fields, lvl=debug)
        except Exception as e:
            hfoslog("[AUTH] No userobject due to error: ", e, type(e), lvl=error)

        if useraccount:
            hfoslog("[AUTH] User found.")

            if useraccount.passhash == event.passhash:
                hfoslog("[AUTH] Passhash matches, checking client and profile.", lvl=debug)

                requestedclientuuid = event.requestedclientuuid

                # Client requests to get an existing client configuration or has none

                clientconfig = clientconfigobject.find_one({'uuid': requestedclientuuid})

                if clientconfig:
                    hfoslog("[AUTH] Checking client configuration permissions", lvl=debug)
                    if clientconfig.useruuid != useraccount.uuid:
                        clientconfig = None
                        hfoslog("[AUTH] Unauthorized client configuration requested", lvl=warn)
                else:
                    hfoslog("[AUTH] Unknown client configuration requested: ", requestedclientuuid, event.__dict__,
                            lvl=warn)

                if not clientconfig:
                    hfoslog("[AUTH] Creating new default client configuration")
                    # Either no configuration was found or requested
                    # -> Create a new client configuration

                    clientconfig = clientconfigobject()
                    clientconfig.uuid = event.clientuuid
                    clientconfig.name = "New client"
                    clientconfig.description = "New client configuration from " + useraccount.username
                    clientconfig.useruuid = useraccount.uuid
                    # TODO: Make sure the profile is only saved if the client could store it, too
                    clientconfig.save()

                try:
                    userprofile = profileobject.find_one({'uuid': str(useraccount.uuid)})
                    hfoslog("[AUTH] Profile: ", userprofile, useraccount.uuid, lvl=debug)

                    useraccount.passhash = ""
                    self.fireEvent(
                        authentication(useraccount.username, (useraccount, userprofile, clientconfig), event.clientuuid,
                                       useraccount.uuid,
                                       event.sock),
                        "auth")
                except Exception as e:
                    hfoslog("[AUTH] No profile due to error: ", e, type(e), lvl=error)
            else:
                hfoslog("[AUTH] Password was wrong!", lvl=warn)

            hfoslog("[AUTH] Done with Login request", lvl=debug)

        else:
            hfoslog("[AUTH] Creating user")
            try:
                newuser = userobject({'username': event.username, 'passhash': event.passhash, 'uuid': str(uuid4())})
                newuser.save()
            except Exception as e:
                hfoslog("[AUTH] Problem creating new user: "******"[AUTH] New profile uuid: ", newprofile.uuid, lvl=verbose)

                newprofile.components = {'enabled': ["dashboard", "map", "weather", "settings"]}
                newprofile.save()
            except Exception as e:
                hfoslog("[AUTH] Problem creating new profile: ", type(e), e, lvl=error)
                return

            try:
                # TODO: Clone or reference systemwide default configuration
                newclientconfig = clientconfigobject()
                newclientconfig.uuid = event.clientuuid
                newclientconfig.name = "New client"
                newclientconfig.description = "New client configuration from " + newuser.username
                newclientconfig.useruuid = newuser.uuid
                newclientconfig.save()
            except Exception as e:
                hfoslog("[AUTH] Problem creating new clientconfig: ", type(e), e, lvl=error)
                return

            try:
                self.fireEvent(
                    authentication(newuser.username, (newuser, newprofile, newclientconfig), event.clientuuid,
                                   newuser.uuid,
                                   event.sock),
                    "auth")
                self.fireEvent(send(event.clientuuid, {'component': 'auth',
                                                       'action': 'new',
                                                       'data': 'registration successful'
                                                       }, sendtype="client"), "hfosweb")
            except Exception as e:
                hfoslog("[AUTH] Error during new account confirmation transmission", e, lvl=error)
Пример #19
0
    def objectmanagerrequest(self, event):
        """OM event handler for incoming events
        :param event: OMRequest with incoming OM pagename and pagedata
        """

        hfoslog("[OM] Event: '%s'" % event.__dict__)
        try:
            action = event.action
            data = event.data
            schema = data['schema']

            result = None

            if action == "list":
                if schema in objectmodels.keys():
                    if 'filter' in data:
                        filter = data['filter']
                    else:
                        filter = {}

                    if 'fields' in data:
                        fields = data['fields']
                    else:
                        fields = []

                    objlist = []

                    if objectmodels[schema].count(filter) > WARNSIZE:
                        hfoslog("[OM] Getting a very long list of items for ", schema, lvl=warn)

                    for item in objectmodels[schema].find(filter):
                        try:
                            listitem = {'uuid': item.uuid, 'name': item.name}
                            for field in fields:
                                if field in item._fields:
                                    listitem[field] = item._fields[field]
                                else:
                                    listitem[field] = None

                            objlist.append(listitem)
                        except Exception as e:
                            hfoslog("[OM] Faulty object or field: ", item._fields, fields, lvl=error)
                    hfoslog("[OM] Generated object list: ", objlist)

                    result = {'component': 'objectmanager',
                              'action': 'list',
                              'data': {'schema': schema,
                                       'list': objlist
                                       }
                              }
                else:
                    hfoslog("[OM] List for unavailable schema requested: ", schema, lvl=warn)

            elif action == "get":
                uuid = data['uuid']

                obj = None

                if schema in objectmodels.keys() and uuid.upper != "CREATE":
                    obj = objectmodels[schema].find_one({'uuid': uuid})

                if not obj:
                    hfoslog("[OM] Object not found, creating: ", data)
                    obj = objectmodels[schema]({'uuid': str(uuid4())})
                else:
                    hfoslog("[OM] Object found, delivering: ", data)

                result = {'component': 'objectmanager',
                          'action': 'get',
                          'data': obj.serializablefields()
                          }

            elif action == "put":
                try:
                    putobj = data['obj']
                    uuid = putobj['uuid']
                except KeyError:
                    hfoslog("[OM] Put request with missing arguments!", event, lvl=critical)
                    return

                try:
                    if uuid != 'create':
                        obj = objectmodels[schema].find_one({'uuid': uuid})
                    else:
                        putobj['uuid'] = uuid4()
                    if obj:
                        hfoslog("[OM] Updating object:", obj._fields, lvl=debug)
                        obj.update(putobj)

                    else:
                        obj = objectmodels[schema](putobj)
                        hfoslog("[OM] Storing object:", obj._fields, lvl=debug)
                        try:
                            obj.validate()
                        except ValidationError:
                            hfoslog("[OM] Validation of new object failed!", data, lvl=warn)

                    obj.save()

                    hfoslog("[OM] Object stored.")

                    result = {'component': 'objectmanager',
                              'action': 'put',
                              'data': (True, obj.uuid),
                              }
                except Exception as e:
                    hfoslog("[OM] Error during object storage:", e, type(e), lvl=error)

            else:
                hfoslog("[OM] Unsupported action: ", action, event, event.__dict__, lvl=warn)
                return

            if result:
                try:
                    self.fireEvent(send(event.client.uuid, result))
                except Exception as e:
                    hfoslog("[OM] Transmission error before broadcast: %s" % e, lvl=error)

        except Exception as e:
            hfoslog("[OM] Error: '%s' %s" % (e, type(e)), lvl=error)
Пример #20
0
    def mapviewrequest(self, event):
        """
        Handles new mapview category requests

        :param event: MapviewRequest with basic action types:
            * subscribe
            * unsubscribe
            * update
            * list
            * get
        """

        hfoslog("[MVM] Event: '%s'" % event.__dict__, lvl=debug)

        try:
            try:
                userobj = event.user
                action = event.action
                data = event.data
                try:
                    nickname = userobj.profile.nick
                except AttributeError:
                    nickname = userobj.account.username

                useruuid = userobj.uuid
                hfoslog("[MVM] client: ", event.client.__dict__)
                clientuuid = event.client.uuid
            except Exception as e:
                raise ValueError("[MVM] Problem during event unpacking:", e,
                                 type(e))

            if action == 'list':
                try:
                    dblist = self._generatemapviewlist()
                    self.fireEvent(
                        send(
                            clientuuid, {
                                'component': 'mapview',
                                'action': 'list',
                                'data': dblist
                            }))
                except Exception as e:
                    hfoslog("[MVM] Listing error: ", e, type(e), lvl=error)
                return
            elif action == 'get':
                dbmapview = None

                try:
                    dbmapview = mapviewobject.find_one({'uuid': useruuid})
                except Exception as e:
                    hfoslog("[MVM] Get for MapView failed, creating new one.",
                            e)

                if not dbmapview:
                    try:
                        # TODO: Move this into a seperate operation (create)
                        dbmapview = mapviewobject({
                            'uuid':
                            str(uuid4()),
                            'useruuid':
                            useruuid,
                            'name':
                            '%s Default MapView' % nickname,
                            'shared':
                            True,
                        })
                        hfoslog("[MVM] New mapviewobject: ", dbmapview)
                        dbmapview.save()
                    except Exception as e:
                        hfoslog("[MVM] Storing new view failed: ",
                                e,
                                type(e),
                                lvl=error)
                if dbmapview:
                    self.fireEvent(
                        send(
                            clientuuid, {
                                'component': 'mapview',
                                'action': 'get',
                                'data': dbmapview.serializablefields()
                            }))
                return
            elif action == 'subscribe':
                try:
                    dbmapview = mapviewobject.find_one({'uuid': data})
                except Exception as e:
                    hfoslog("[MVM] Get for MapView failed. Creating new one.",
                            e)

                if not dbmapview:
                    dbmapview = mapviewobject({
                        'uuid': str(uuid4()),
                        'useruuid': useruuid,
                        'name': '%s Default MapView' % nickname,
                        'shared': True,
                    })

                if data in self._subscribers:
                    if clientuuid not in self._subscribers[data]:
                        self._subscribers[data].append(clientuuid)
                else:
                    self._subscribers[data] = [clientuuid]

                hfoslog("[MVM] Subscription registered: ", data, clientuuid,
                        dbmapview.to_dict())

                self.fireEvent(
                    send(
                        clientuuid, {
                            'component': 'mapview',
                            'action': 'get',
                            'data': dbmapview.serializablefields()
                        }))

                return
            elif action == 'unsubscribe':
                self._unsubscribe(clientuuid, data)
                return

            # The following need a mapview object attached

            try:
                mapview = mapviewobject(data)
                mapview.validate()
            except Exception as e:
                hfoslog(
                    "[MVM] Only mapview related actions left, but no Mapviewobject.",
                    e,
                    type(e),
                    lvl=warn)
                return

            if action == 'update':

                hfoslog("[MVM] Update begin")
                try:
                    uuid = mapview.uuid
                    dbmapview = mapviewobject.find_one({'uuid': uuid})
                    hfoslog("[MVM] Database Mapview dict: ",
                            dbmapview.__dict__,
                            lvl=error)
                except Exception as e:
                    hfoslog("[MVM] Couldn't get mapview", (data, e, type(e)),
                            lvl=error)
                    return

                if dbmapview:
                    try:
                        dbmapview.update(mapview._fields)
                        dbmapview.save()

                        hfoslog("[MVM] Valid update stored.")
                    except Exception as e:
                        hfoslog("[MVM] Database mapview update failed: ",
                                (uuid, e, type(e)),
                                lvl=error)
                        return
                else:
                    try:
                        hfoslog("[MVM] New MapView: ", mapview)
                        mapview.uuid = uuid  # make sure
                        mapview.save()
                        dbmapview = mapview
                        hfoslog("[MVM] New MapView stored.")

                        if mapview.shared:
                            hfoslog(
                                "[MVM] Broadcasting list update for new mapview."
                            )
                            self.fireEvent(
                                broadcast("users",
                                          self._generatemapviewlist()))
                    except Exception as e:
                        hfoslog("[MVM] MapView creation error: '%s' (%s)" %
                                (e, type(e)),
                                lvl=error)
                        return

                try:
                    hfoslog("[MVM] Subscriptions: ", self._subscribers)
                    hfoslog("[MVM] dbmapview: ", mapview._fields)
                    if dbmapview.shared:
                        if dbmapview.uuid in self._subscribers:
                            try:
                                hfoslog(
                                    "[MVM] Broadcasting mapview update to subscribers."
                                )
                                mapviewpacket = {
                                    'component': 'mapview',
                                    'action': 'update',
                                    'data': mapview.serializablefields()
                                }
                                self._broadcast(mapviewpacket, dbmapview.uuid)
                            except Exception as e:
                                hfoslog(
                                    "[MVM] Transmission error before broadcast: %s"
                                    % e)
                        else:
                            hfoslog("[MVM] Not subscribed.")

                    else:
                        hfoslog("[MVM] Not shared.")
                except Exception as e:
                    hfoslog("[MVM] Update error during final mapview handling",
                            e)

        except Exception as e:
            hfoslog("[MVM] Global Error: '%s' %s" % (e, type(e)), lvl=error)
Пример #21
0
    def wikirequest(self, event):
        """Wiki event handler for incoming events
        :param event: WikiRequest with incoming wiki pagename and pagedata
        """

        hfoslog("[WIKI] Event: '%s'" % event.__dict__)
        try:
            action = event.action
            data = event.data

            if action == "get":
                wikipage = wikipageobject.find_one({'name': data})

                if not wikipage:
                    hfoslog("[WIKI] Page not found: ", data)
                    wikipage = wikipageobject({
                        'uuid': str(uuid4()),
                        'name': data,
                    })
                else:
                    hfoslog("[WIKI] Page found, delivering: ", data)

                wikipacket = {
                    'component': 'wiki',
                    'action': 'get',
                    'data': wikipage.serializablefields()
                }
            elif action == "put":
                if data['uuid']:
                    wikipage = wikipageobject.find_one({'uuid': data['uuid']})

                    if wikipage:
                        hfoslog("[WIKI] Updating old page.")
                        wikipage.update(data)
                    else:
                        wikipage = wikipageobject(data)
                        hfoslog("[WIKI] Storing a new page:", wikipage._fields)
                        try:
                            wikipage.validate()
                            wikipage.save()
                        except ValidationError:
                            hfoslog("[WIKI] Validation of new page failed!",
                                    data,
                                    lvl=warn)

                        hfoslog("[WIKI] Page stored. Reindexing.")
                        self._updateIndex()
                        hfoslog("[WIKI] Reindexing done.")

                    wikipacket = {
                        'component': 'wiki',
                        'action': 'put',
                        'data': (True, wikipage.name),
                    }
                else:
                    hfoslog(
                        "[WIKI] Weird request without uuid! Trying to create completely new page.",
                        lvl=warn)
                    wikipage = wikipageobject(data)
                    wikipage.uuid = str(uuid4())
                    if wikipage.validate():
                        wikipage.save()

                    wikipacket = {
                        'component': 'wiki',
                        'action': 'put',
                        'data': (True, wikipage.name),
                    }

            else:
                hfoslog("[WIKI] Unsupported action: ",
                        action,
                        event,
                        event.__dict__,
                        lvl=warn)
                return

            try:
                self.fireEvent(send(event.client.uuid, wikipacket))
            except Exception as e:
                hfoslog("[WIKI] Transmission error before broadcast: %s" % e,
                        lvl=error)

        except Exception as e:
            hfoslog("[WIKI] Error: '%s' %s" % (e, type(e)), lvl=error)
Пример #22
0
 def _broadcast(self, camerapacket, camerauuid):
     try:
         for recipient in self._subscribers[camerauuid]:
             self.fireEvent(send(recipient, camerapacket, raw=True), "hfosweb")
     except Exception as e:
         hfoslog("[CAM] Failed broadcast: ", e, type(e), lvl=error)
Пример #23
0
    def mapviewrequest(self, event):
        """
        Handles new mapview category requests

        :param event: MapviewRequest with basic action types:
            * subscribe
            * unsubscribe
            * update
            * list
            * get
        """

        hfoslog("[MVM] Event: '%s'" % event.__dict__, lvl=debug)

        try:
            try:
                userobj = event.user
                action = event.action
                data = event.data
                try:
                    nickname = userobj.profile.nick
                except AttributeError:
                    nickname = userobj.account.username

                useruuid = userobj.uuid
                hfoslog("[MVM] client: ", event.client.__dict__)
                clientuuid = event.client.uuid
            except Exception as e:
                raise ValueError("[MVM] Problem during event unpacking:", e, type(e))

            if action == 'list':
                try:
                    dblist = self._generatemapviewlist()
                    self.fireEvent(send(clientuuid, {'component': 'mapview', 'action': 'list', 'data': dblist}))
                except Exception as e:
                    hfoslog("[MVM] Listing error: ", e, type(e), lvl=error)
                return
            elif action == 'get':
                dbmapview = None

                try:
                    dbmapview = mapviewobject.find_one({'uuid': useruuid})
                except Exception as e:
                    hfoslog("[MVM] Get for MapView failed, creating new one.", e)

                if not dbmapview:
                    try:
                        # TODO: Move this into a seperate operation (create)
                        dbmapview = mapviewobject({'uuid': str(uuid4()),
                                                   'useruuid': useruuid,
                                                   'name': '%s Default MapView' % nickname,
                                                   'shared': True,
                                                   })
                        hfoslog("[MVM] New mapviewobject: ", dbmapview)
                        dbmapview.save()
                    except Exception as e:
                        hfoslog("[MVM] Storing new view failed: ", e, type(e), lvl=error)
                if dbmapview:
                    self.fireEvent(send(clientuuid, {'component': 'mapview', 'action': 'get',
                                                     'data': dbmapview.serializablefields()}))
                return
            elif action == 'subscribe':
                try:
                    dbmapview = mapviewobject.find_one({'uuid': data})
                except Exception as e:
                    hfoslog("[MVM] Get for MapView failed. Creating new one.", e)

                if not dbmapview:
                    dbmapview = mapviewobject({'uuid': str(uuid4()),
                                               'useruuid': useruuid,
                                               'name': '%s Default MapView' % nickname,
                                               'shared': True,
                                               })

                if data in self._subscribers:
                    if clientuuid not in self._subscribers[data]:
                        self._subscribers[data].append(clientuuid)
                else:
                    self._subscribers[data] = [clientuuid]

                hfoslog("[MVM] Subscription registered: ", data, clientuuid, dbmapview.to_dict())

                self.fireEvent(send(clientuuid, {'component': 'mapview', 'action': 'get',
                                                 'data': dbmapview.serializablefields()}))

                return
            elif action == 'unsubscribe':
                self._unsubscribe(clientuuid, data)
                return

            # The following need a mapview object attached

            try:
                mapview = mapviewobject(data)
                mapview.validate()
            except Exception as e:
                hfoslog("[MVM] Only mapview related actions left, but no Mapviewobject.", e, type(e), lvl=warn)
                return

            if action == 'update':

                hfoslog("[MVM] Update begin")
                try:
                    uuid = mapview.uuid
                    dbmapview = mapviewobject.find_one({'uuid': uuid})
                    hfoslog("[MVM] Database Mapview dict: ", dbmapview.__dict__, lvl=error)
                except Exception as e:
                    hfoslog("[MVM] Couldn't get mapview", (data, e, type(e)), lvl=error)
                    return

                if dbmapview:
                    try:
                        dbmapview.update(mapview._fields)
                        dbmapview.save()

                        hfoslog("[MVM] Valid update stored.")
                    except Exception as e:
                        hfoslog("[MVM] Database mapview update failed: ", (uuid, e, type(e)), lvl=error)
                        return
                else:
                    try:
                        hfoslog("[MVM] New MapView: ", mapview)
                        mapview.uuid = uuid  # make sure
                        mapview.save()
                        dbmapview = mapview
                        hfoslog("[MVM] New MapView stored.")

                        if mapview.shared:
                            hfoslog("[MVM] Broadcasting list update for new mapview.")
                            self.fireEvent(broadcast("users", self._generatemapviewlist()))
                    except Exception as e:
                        hfoslog("[MVM] MapView creation error: '%s' (%s)" % (e, type(e)), lvl=error)
                        return

                try:
                    hfoslog("[MVM] Subscriptions: ", self._subscribers)
                    hfoslog("[MVM] dbmapview: ", mapview._fields)
                    if dbmapview.shared:
                        if dbmapview.uuid in self._subscribers:
                            try:
                                hfoslog("[MVM] Broadcasting mapview update to subscribers.")
                                mapviewpacket = {'component': 'mapview',
                                                 'action': 'update',
                                                 'data': mapview.serializablefields()
                                                 }
                                self._broadcast(mapviewpacket, dbmapview.uuid)
                            except Exception as e:
                                hfoslog("[MVM] Transmission error before broadcast: %s" % e)
                        else:
                            hfoslog("[MVM] Not subscribed.")

                    else:
                        hfoslog("[MVM] Not shared.")
                except Exception as e:
                    hfoslog("[MVM] Update error during final mapview handling", e)

        except Exception as e:
            hfoslog("[MVM] Global Error: '%s' %s" % (e, type(e)), lvl=error)