Beispiel #1
0
def delete_events_in_device(resource_name: str, device: dict):
    """
    Deletes the references of the given device in all the events, and deletes the full event if it references only to
    the device.
    """
    if resource_name in Device.resource_types:
        _id = device["_id"]
        qin = {"$in": [_id]}
        query = {"$or": [{"device": _id}, {"devices": qin}, {"components": qin}], "@type": {"$ne": "devices:Register"}}
        sort = {"_created": pymongo.ASCENDING}  # Order is important to find the first Snapshot (see below)
        first_snapshot_found = False
        for event in DeviceEventDomain.get({"$query": query, "$orderby": sort}):
            if not first_snapshot_found and event["@type"] == "devices:Snapshot":
                # We cannot delete the Snapshot that created the device, because there is a change to create
                # an infinite loop: Snapshot that created device -> Register -> DEL /device -> Snapshot that created...
                first_snapshot_found = True
            else:
                event_resource = Naming.resource(event["@type"])
                if event.get("device", None) == _id:  # Am I the 'device' of the event?
                    execute_delete(event_resource, event["_id"])
                elif [_id] == event.get("devices", []):  # Is there no more 'devices' in the event, apart from me?
                    execute_delete(event_resource, event["_id"])
                # All events that do not use 'components' for materialization (aka Add/Remove) should be erased
                # if there are no more components
                elif event["@type"] in ("devices:Add", "devices:Remove") and event["components"] == [_id]:
                    execute_delete(event_resource, event["_id"])
                else:  # Keep the event; just delete my reference
                    DeviceEventDomain.update_raw(event["_id"], {"$pull": {"devices": qin, "components": qin}})
Beispiel #2
0
def materialize_owners(devices_id):
    """Re-computes 'owners' for the given devices and components."""
    # First let's erase all owners
    DeviceDomain.update_many_raw({'_id': {
        '$in': devices_id
    }}, {'$set': {
        'owners': []
    }})
    # Then let's execute again the materialize hooks for Allocate/Deallocate
    query = {
        '$or': [{
            '@type': 'devices:Allocate'
        }, {
            '@type': 'devices:Deallocate'
        }],
        'devices': {
            '$in': devices_id
        }
    }
    order_by = {'_created': pymongo.ASCENDING}
    for event in DeviceEventDomain.get({
            '$query': query,
            '$orderby': order_by
    }):
        if event['@type'] == 'devices:Allocate':
            materialize_actual_owners_add([event])
        else:
            modified = materialize_actual_owners_remove([event])
            if modified == 0:  # This Remove does nothing and should be erased
                DeviceEventDomain.delete({'_id': event['_id']})
Beispiel #3
0
 def execute(self, database):
     SNAPSHOT_SOFTWARE = {
         'DDI': 'Workbench',
         'Scan': 'AndroidApp',
         'DeviceHubClient': 'Web'
     }
     for snapshot in DeviceEventDomain.get({'@type': "devices:Snapshot"}):
         with suppress(KeyError):
             snapshot['snapshotSoftware'] = SNAPSHOT_SOFTWARE[snapshot.get(
                 'snapshotSoftware', 'DDI')]
         DeviceEventDomain.update_one_raw(
             snapshot['_id'],
             {'$set': {
                 'snapshotSoftware': snapshot['snapshotSoftware']
             }})
         for device in DeviceDomain.get({'events._id': snapshot['_id']}):
             materialized_snapshot = find(
                 device['events'],
                 lambda event: event['_id'] == snapshot['_id'])
             materialized_snapshot['snapshotSoftware'] = snapshot[
                 'snapshotSoftware']
             DeviceDomain.update_one_raw(
                 device['_id'], {'$set': {
                     'events': device['events']
                 }})
Beispiel #4
0
def delete_events_in_device(resource_name: str, device: dict):
    """
    Deletes the references of the given device in all the events, and deletes the full event if it references only to
    the device.
    """
    if resource_name in Device.resource_types:
        _id = device['_id']
        qin = {'$in': [_id]}
        query = {'$or': [{'device': _id}, {'devices': qin}, {'components': qin}], '@type': {'$ne': 'devices:Register'}}
        sort = {'_created': pymongo.ASCENDING}  # Order is important to find the first Snapshot (see below)
        first_snapshot_found = False
        for event in DeviceEventDomain.get({'$query': query, '$orderby': sort}):
            if not first_snapshot_found and event['@type'] == 'devices:Snapshot':
                # We cannot delete the Snapshot that created the device, because there is a change to create
                # an infinite loop: Snapshot that created device -> Register -> DEL /device -> Snapshot that created...
                first_snapshot_found = True
            else:
                event_resource = Naming.resource(event['@type'])
                if event.get('device', None) == _id:  # Am I the 'device' of the event?
                    execute_delete(event_resource, event['_id'])
                elif [_id] == event.get('devices', []):  # Is there no more 'devices' in the event, apart from me?
                    execute_delete(event_resource, event['_id'])
                # All events that do not use 'components' for materialization (aka Add/Remove) should be erased
                # if there are no more components
                elif event['@type'] in ('devices:Add', 'devices:Remove') and event['components'] == [_id]:
                    execute_delete(event_resource, event['_id'])
                else:  # Keep the event; just delete my reference
                    DeviceEventDomain.update_raw(event['_id'], {'$pull': {'devices': qin, 'components': qin}})
 def set_prefix():
     for event in DeviceEventDomain.get({}):
         try:
             resource_type = DeviceEventDomain.new_type(event['@type'])
         except TypeError:
             pass
         else:
             DeviceEventDomain.update_raw(event['_id'], {'$set': {'@type': resource_type}})
     print('Events prefixed.')
 def set_prefix():
     for event in DeviceEventDomain.get({}):
         try:
             resource_type = DeviceEventDomain.new_type(event['@type'])
         except TypeError:
             pass
         else:
             DeviceEventDomain.update_raw(
                 event['_id'], {'$set': {
                     '@type': resource_type
                 }})
     print('Events prefixed.')
Beispiel #7
0
def materialize_owners(devices_id):
    """Re-computes 'owners' for the given devices and components."""
    # First let's erase all owners
    DeviceDomain.update_many_raw({'_id': {'$in': devices_id}}, {'$set': {'owners': []}})
    # Then let's execute again the materialize hooks for Allocate/Deallocate
    query = {'$or': [{'@type': 'devices:Allocate'}, {'@type': 'devices:Deallocate'}], 'devices': {'$in': devices_id}}
    order_by = {'_created': pymongo.ASCENDING}
    for event in DeviceEventDomain.get({'$query': query, '$orderby': order_by}):
        if event['@type'] == 'devices:Allocate':
            materialize_actual_owners_add([event])
        else:
            modified = materialize_actual_owners_remove([event])
            if modified == 0:  # This Remove does nothing and should be erased
                DeviceEventDomain.delete({'_id': event['_id']})
Beispiel #8
0
def redirect_to_first_snapshot(resource, request, lookup):
    """
    DELETE /device should be an internal method, but it is open to redirect to the door that is going to effictevely
    delete the device; this is the first Snapshot that made the Register that made the device.
    """
    if resource in Device.resource_types:
        snapshot_id = str(DeviceEventDomain.get_first_snapshot(lookup['_id'])['_id'])
        execute_delete(Naming.resource('devices:Snapshot'), snapshot_id)
        raise RequestAnother('', 204)
Beispiel #9
0
def redirect_to_first_snapshot(resource, request, lookup):
    """
    DELETE /device should be an internal method, but it is open to redirect to the door that is going to effictevely
    delete the device; this is the first Snapshot that made the Register that made the device.
    """
    if resource in Device.resource_types:
        snapshot_id = str(
            DeviceEventDomain.get_first_snapshot(lookup['_id'])['_id'])
        execute_delete(Naming.resource('devices:Snapshot'), snapshot_id)
        raise RequestAnother('', 204)
Beispiel #10
0
def transfer_property(receives: list):
    for receive in receives:
        if receive['automaticallyAllocate']:
            allocate_type = DeviceEventDomain.new_type('Allocate')
            a = execute_post_internal(Naming.resource(allocate_type), {
                '@type': allocate_type,
                'to': receive['receiver'],
                'devices': receive['devices']
            })
            receive['_created'] = receive['_updated'] = a['_created'] + datetime.timedelta(milliseconds=1)
Beispiel #11
0
 def execute(self, database):
     DeviceDomain.update_many_raw({}, {'$set': {'events': []}})
     for event in DeviceEventDomain.get({
             '$query': {},
             '$orderby': {
                 '_created': pymongo.ASCENDING
             }
     }):
         MaterializeEvents.materialize_events(
             Naming.resource(event['@type']), [event])
Beispiel #12
0
 def generate_url(self, original_resource, translated_resource):
     device_identifier = self.translator.hid_or_url(original_resource['device'])
     if not re.compile(HID_REGEX).match(device_identifier):  # It is not a HID, so it is an URL
         device_identifier = quote_plus(device_identifier.replace('/', '!'))  # Adapt it to GRD needs
     url = self.domain + '/api/devices/'
     event_type = translated_resource['@type']
     if event_type == DeviceEventDomain.new_type('Register'):
         url += 'register'
     else:
         url += '{}/{}'.format(device_identifier, Naming.resource(event_type))
     return url
 def re_materialize_events():
     DeviceDomain.update_many_raw({}, {'$set': {'events': []}})
     for event in DeviceEventDomain.get({
             '$query': {},
             '$orderby': {
                 '_created': pymongo.ASCENDING
             }
     }):
         MaterializeEvents.materialize_events(
             Naming.resource(event['@type']), [event])
     print('Events re-materialized.')
Beispiel #14
0
def submit_migrate(migrates: dict):
    """
    Sends a Migrate event to the other DeviceHub.
    Note as the other DeviceHub requires the url of this event,
    this method needs to be executed after reaching the Database.
    """
    for migrate in migrates:
        if 'to' in migrate:
            auth = AgentAuth(migrate['to']['baseUrl'])
            submitter = MigrateSubmitter(current_app, MigrateTranslator(current_app.config), auth=auth)
            try:
                response, *_ = submitter.submit(migrate, AccountDomain.get_requested_database())
                migrate['to']['url'] = migrate['to']['baseUrl'] + response['_links']['self']['href']
                _update_same_as(response['returnedSameAs'])
            except InnerRequestError as e:
                execute_delete(Migrate.resource_name, migrate['_id'])
                raise e
            else:
                _remove_devices_from_places(migrate)
                update = {'$set': {'to.url': migrate['to']['url'], 'devices': [_id for _id in migrate['devices']]}}
                DeviceEventDomain.update_one_raw(migrate['_id'], update)
Beispiel #15
0
def coerce_type(fields: dict):
    """
    Similar to a Cerberus' coercion, adds a prefix to all @types accordingly.
    :param fields: the resource (ex-JSON document) to coerce. The variable is updated.
    """
    # todo this method should be general: obtaining which resources need to be prefixed from their schema
    from ereuse_devicehub.resources.event.device import DeviceEventDomain

    references = []
    NestedLookup(fields, references, NestedLookup.key_equality_factory("@type"))
    for document, ref_key in references:
        document[ref_key] = DeviceEventDomain.add_prefix(document[ref_key])
Beispiel #16
0
def submit_migrate(migrates: dict):
    """
    Sends a Migrate event to the other DeviceHub.
    Note as the other DeviceHub requires the url of this event,
    this method needs to be executed after reaching the Database.
    """
    for migrate in migrates:
        if 'to' in migrate:
            auth = AgentAuth(migrate['to']['baseUrl'])
            submitter = MigrateSubmitter(current_app, MigrateTranslator(current_app.config), auth=auth)
            try:
                response, *_ = submitter.submit(migrate, AccountDomain.get_requested_database())
                migrate['to']['url'] = migrate['to']['baseUrl'] + response['_links']['self']['href']
                _update_same_as(response['returnedSameAs'])
            except InnerRequestError as e:
                execute_delete(Migrate.resource_name, migrate['_id'])
                raise e
            else:
                _remove_devices_from_places(migrate)
                update = {'$set': {'to.url': migrate['to']['url'], 'devices': [_id for _id in migrate['devices']]}}
                DeviceEventDomain.update_one_raw(migrate['_id'], update)
Beispiel #17
0
 def translate(self, resource: dict, database: str = None) -> list:
     self.database = database
     translated = []
     if 'devices' in resource and resource['@type'] != DeviceEventDomain.new_type('Register'):
         e = copy.deepcopy(resource)
         del e['devices']
         for device in resource['devices']:
             e['device'] = device
             translated.append((self._translate(e), copy.deepcopy(e)))
     else:
         translated.append((self._translate(resource), resource))
     return translated
Beispiel #18
0
 def subclasses_fields(cls):
     from ereuse_devicehub.resources.event.device import DeviceEventDomain
     global_types = super(Component, cls).subclasses_fields()
     with suppress(KeyError):
         global_types['size']['type'] = global_types['speed']['type'] = 'number'
         events = {DeviceEventDomain.new_type(x) for x in ('EraseSectors', 'EraseBasic')}
         global_types['erasure']['schema']['@type']['allowed'] = events
         union_of_benchmarks = BenchmarkHardDrive()
         union_of_benchmarks.update(BenchmarkProcessor())
         union_of_benchmarks['@type']['allowed'] = set(Benchmark.TYPES)
         global_types['benchmark']['schema'] = union_of_benchmarks
     return global_types
Beispiel #19
0
def transfer_property(receives: list):
    for receive in receives:
        if receive['automaticallyAllocate']:
            allocate_type = DeviceEventDomain.new_type('Allocate')
            a = execute_post_internal(
                Naming.resource(allocate_type), {
                    '@type': allocate_type,
                    'to': receive['receiver'],
                    'devices': receive['devices']
                })
            receive['_created'] = receive['_updated'] = a[
                '_created'] + datetime.timedelta(milliseconds=1)
Beispiel #20
0
def coerce_type(fields: dict):
    """
    Similar to a Cerberus' coercion, adds a prefix to all @types accordingly.
    :param fields: the resource (ex-JSON document) to coerce. The variable is updated.
    """
    # todo this method should be general: obtaining which resources need to be prefixed from their schema
    from ereuse_devicehub.resources.event.device import DeviceEventDomain
    references = []
    NestedLookup(fields, references,
                 NestedLookup.key_equality_factory('@type'))
    for document, ref_key in references:
        document[ref_key] = DeviceEventDomain.add_prefix(document[ref_key])
Beispiel #21
0
 def translate(self, resource: dict, database: str = None) -> list:
     self.database = database
     translated = []
     if 'devices' in resource and resource[
             '@type'] != DeviceEventDomain.new_type('Register'):
         e = copy.deepcopy(resource)
         del e['devices']
         for device in resource['devices']:
             e['device'] = device
             translated.append((self._translate(e), copy.deepcopy(e)))
     else:
         translated.append((self._translate(resource), resource))
     return translated
Beispiel #22
0
 def get_similar_component(cls, component: dict, parent_id: str) -> dict:
     """Gets a component that has same parent, doesn't generate HID and their ETAG are the same"""
     # We the unsecured _id of the devices of all parent_id snapshots
     snapshots = EventDomain.get({'@type': DeviceEventDomain.new_type('Snapshot'), 'device': parent_id})
     devices_id = set()
     for snapshot in snapshots:
         for unsecured in snapshot['unsecured']:
             devices_id.add(unsecured['_id'])
     # We get the devices whose _id and etag matches
     etag = cls.generate_etag(component)
     query = {'_id': {'$in': list(devices_id)}, '_etag': etag}
     device = cls.get_one(query)
     return cls.get_one(device['_id'])  # todo if we materialize components we do not need to do double query
Beispiel #23
0
 def register(self, event_log: list):
     with suppress(NoDevicesToProcess):
         register = {
             '@type': DeviceEventDomain.new_type('Register'),
             'device': self.device,
             'components': self.components
         }
         self.set_created_conditionally(register)
         event_log.append(execute_post_internal(Naming.resource(register['@type']), register))
     for device in [self.device] + self.components:
         if 'hid' not in device and 'pid' not in device:
             self._append_unsecured(device, 'model')
         elif 'pid' in device:
             self._append_unsecured(device, 'pid')
Beispiel #24
0
 def test_materializations_events(self):
     """
     Tests materializations related to events.
     :return:
     """
     # Let's check POST
     devices = self.get_fixtures_computers()
     vaio, _ = self.get(self.DEVICES, '', devices[0])
     account_id = str(self.account['_id'])
     materialized = [
         {'@type': DeviceEventDomain.new_type('Snapshot'), 'secured': False, 'byUser': account_id,
          'incidence': False},
         {'@type': DeviceEventDomain.new_type('Register'), 'secured': False, 'byUser': account_id,
          'incidence': False},
     ]
     fields = {'@type', '_id', 'byUser', 'incidence', 'secured', '_updated'}
     self.assertIn('events', vaio)
     i = 0
     for event in vaio['events']:
         # Order needs to be preserved
         assert_that(materialized[i]).is_subset_of(event)
         assert_that(set(event.keys())).is_equal_to(fields)
         i += 1
Beispiel #25
0
 def generate_url(self, original_resource, translated_resource):
     device_identifier = self.translator.hid_or_url(
         original_resource['device'])
     if not re.compile(HID_REGEX).match(
             device_identifier):  # It is not a HID, so it is an URL
         device_identifier = quote_plus(device_identifier.replace(
             '/', '!'))  # Adapt it to GRD needs
     url = self.domain + '/api/devices/'
     event_type = translated_resource['@type']
     if event_type == DeviceEventDomain.new_type('Register'):
         url += 'register'
     else:
         url += '{}/{}'.format(device_identifier,
                               Naming.resource(event_type))
     return url
Beispiel #26
0
 def subclasses_fields(cls):
     from ereuse_devicehub.resources.event.device import DeviceEventDomain
     global_types = super(Component, cls).subclasses_fields()
     with suppress(KeyError):
         global_types['size']['type'] = global_types['speed'][
             'type'] = 'number'
         events = {
             DeviceEventDomain.new_type(x)
             for x in ('EraseSectors', 'EraseBasic')
         }
         global_types['erasure']['schema']['@type']['allowed'] = events
         union_of_benchmarks = BenchmarkHardDrive()
         union_of_benchmarks.update(BenchmarkProcessor())
         union_of_benchmarks['@type']['allowed'] = set(Benchmark.TYPES)
         global_types['benchmark']['schema'] = union_of_benchmarks
     return global_types
Beispiel #27
0
 def creation(self, input_snapshot: dict, num_of_events: int = 1, do_second_time_snapshot=True) -> str:
     pprint("1st time snapshot:")
     events = self.post_snapshot_get_full_events(input_snapshot, num_of_events)
     self.assertLen(events, num_of_events)
     register = events[0]
     self.assertType(DeviceEventDomain.new_type('Register'), register)
     self.assertSimilarDevice(input_snapshot['device'], register['device'])
     if 'components' in input_snapshot:
         self.assertSimilarDevices(input_snapshot['components'], register['components'])
     # We do a snapshot again. We should receive a new snapshot without any event on it.
     if do_second_time_snapshot:
         pprint("2nd time snapshot:")
         snapshot, status_code = self.post('{}/{}'.format(self.DEVICE_EVENT, self.SNAPSHOT), input_snapshot)
         self.assert201(status_code)
         self.assertLen(snapshot['events'], num_of_events - 1)
     return register['device']
Beispiel #28
0
 def register(self, event_log: list):
     with suppress(NoDevicesToProcess):
         register = {
             '@type': DeviceEventDomain.new_type('Register'),
             'device': self.device,
             'components': self.components
         }
         self.set_created_conditionally(register)
         event_log.append(
             execute_post_internal(Naming.resource(register['@type']),
                                   register))
     for device in [self.device] + self.components:
         if 'hid' not in device and 'pid' not in device:
             self._append_unsecured(device, 'model')
         elif 'pid' in device:
             self._append_unsecured(device, 'pid')
Beispiel #29
0
def delete_events(_, snapshot: dict):
    """
    Deletes the events that were created with the snapshot.
    """
    if snapshot.get('@type') == 'devices:Snapshot':
        for event_id in snapshot['events']:
            try:
                # If the first event is Register, erasing the device will erase the rest of events
                event = DeviceEventDomain.get_one(event_id)
            except EventNotFound:
                pass
            else:
                try:
                    execute_delete(Naming.resource(event['@type']), event['_id'])
                except InnerRequestError as e:
                    if e.status_code != 404:
                        raise e
Beispiel #30
0
def delete_events(_, snapshot: dict):
    """
    Deletes the events that were created with the snapshot.
    """
    if snapshot.get('@type') == 'devices:Snapshot':
        for event_id in snapshot['events']:
            try:
                # If the first event is Register, erasing the device will erase the rest of events
                event = DeviceEventDomain.get_one(event_id)
            except EventNotFound:
                pass
            else:
                try:
                    execute_delete(Naming.resource(event['@type']),
                                   event['_id'])
                except InnerRequestError as e:
                    if e.status_code != 404:
                        raise e
Beispiel #31
0
def check_migrate(_, resource: dict):
    """
    Raises an exception if any of the device(s) in the resource is in another database, as a result of a Migrate event.

    This is done to avoid adding/modifying/deleting events or places that have a relationship with a device that
    is not legally bound in a DeviceHub.

    The method checks if the last Migrate has a 'to' field, meaning the device is in another database and has not
    come back.
    :raises DeviceHasMigrated
    """
    devices = ([resource['device']] if 'device' in resource else []) + resource.get('devices', [])
    for device_id in devices:
        with suppress(EventNotFound):
            # todo can it be done with only one access to the DB for all devices (optimization)?
            # Note that this is executed for every post / delete /update / patch, resulting in queries = n of devices
            query = {'@type': Migrate.type_name, 'devices': {'$in': [device_id]}}
            last_migrate = DeviceEventDomain.get_one({'$query': query, '$orderby': {'_created': pymongo.DESCENDING}})
            if 'to' in last_migrate:
                raise DeviceHasMigrated(device_id, last_migrate)
Beispiel #32
0
def check_migrate(_, resource: dict):
    """
    Raises an exception if any of the device(s) in the resource is in another database, as a result of a Migrate event.

    This is done to avoid adding/modifying/deleting events or places that have a relationship with a device that
    is not legally bound in a DeviceHub.

    The method checks if the last Migrate has a 'to' field, meaning the device is in another database and has not
    come back.
    :raises DeviceHasMigrated
    """
    devices = ([resource['device']] if 'device' in resource else []) + resource.get('devices', [])
    for device_id in devices:
        with suppress(EventNotFound):
            # todo can it be done with only one access to the DB for all devices (optimization)?
            # Note that this is executed for every post / delete /update / patch, resulting in queries = n of devices
            query = {'@type': Migrate.type_name, 'devices': {'$in': [device_id]}}
            last_migrate = DeviceEventDomain.get_one({'$query': query, '$orderby': {'_created': pymongo.DESCENDING}})
            if 'to' in last_migrate:
                raise DeviceHasMigrated(device_id, last_migrate)
Beispiel #33
0
def get_place(resource_name: str, events: list):
    """

    :param resource_name:
    :param events:
    :return:
    """
    if resource_name in Event.resource_types:
        for event in events:
            if 'geo' in event:
                try:
                    place = PlaceDomain.get_with_coordinates(event['geo']['coordinates'])
                except (KeyError, NoPlaceForGivenCoordinates) as e:
                    # Receive and Locate are forced to have a place for their coordinates
                    if event['@type'] in (DeviceEventDomain.new_type(x) for x in ('Receive', 'Locate')):
                        raise e
                else:
                    if 'place' in event:
                        if event['place']['_id'] != str(place['_id']):  # geo 1 place 1
                            raise CoordinatesAndPlaceDoNotMatch()
                    else:
                        event['place'] = place['_id']  # geo 1 place found in DB
Beispiel #34
0
def get_place(resource_name: str, events: list):
    """

    :param resource_name:
    :param events:
    :return:
    """
    if resource_name in Event.resource_types:
        for event in events:
            if "geo" in event:
                try:
                    place = PlaceDomain.get_with_coordinates(event["geo"]["coordinates"])
                except (KeyError, NoPlaceForGivenCoordinates) as e:
                    # Receive and Locate are forced to have a place for their coordinates
                    if event["@type"] in (DeviceEventDomain.new_type(x) for x in ("Receive", "Locate")):
                        raise e
                else:
                    if "place" in event:
                        if event["place"]["_id"] != str(place["_id"]):  # geo 1 place 1
                            raise CoordinatesAndPlaceDoNotMatch()
                    else:
                        event["place"] = place["_id"]  # geo 1 place found in DB
Beispiel #35
0
 def append_add(self, component, new_parent):
     self._append(DeviceEventDomain.new_type('Add'), new_parent, component)
Beispiel #36
0
 def append_remove(self, component, old_parent):
     self._append(DeviceEventDomain.new_type('Remove'), old_parent,
                  component)
Beispiel #37
0
def remove_from_other_events(resource_name: str, event: dict):
    """Removes the event from other events (Snapshot's 'event' per example)"""
    if resource_name in DeviceEvent.resource_types:
        update = {'$pull': {'events': {'$in': [event['_id']]}}}
        DeviceEventDomain.update_many_raw({}, update)
VALIDATION_ERROR_AS_LIST = True  # We always use list to show errors
ITEM_CACHE = 120  # We differentiate from Resource cache (Cache setting from Eve) from Item cache

# Role settings
from ereuse_devicehub.resources.account.role import Role

ALLOWED_WRITE_ROLES = {Role.AMATEUR}
ALLOWED_ITEM_WRITE_ROLES = {Role.AMATEUR}
ALLOWED_READ_ROLES = {Role.BASIC}
ALLOWED_ITEM_READ_ROLES = {Role.BASIC}

# GRD Settings, do not change them
_events_in_grd = ('Deallocate', 'Migrate', 'Allocate', 'Receive', 'Remove',
                  'Add', 'Register', 'Locate', 'UsageProof', 'Recycle')
EVENTS_IN_GRD = [
    Naming.resource(DeviceEventDomain.new_type(event))
    for event in _events_in_grd
]
# Generation of the API (DOMAIN)
from ereuse_devicehub.resources.device.settings import DeviceSettings
from ereuse_devicehub.resources.account.settings import AccountSettings
from ereuse_devicehub.resources.event.settings import EventSettings
from ereuse_devicehub.resources.place.settings import PlaceSettings

DOMAIN = {
    'devices': DeviceSettings,
    'events': EventSettings,
    'accounts': AccountSettings,
    'places': PlaceSettings
}
Beispiel #39
0
PAGINATION_LIMIT = 100
DATE_FORMAT = '%Y-%m-%dT%H:%M:%S'
SCHEMA_ENDPOINT = 'schema'
VALIDATION_ERROR_AS_LIST = True  # We always use list to show errors
ITEM_CACHE = 120  # We differentiate from Resource cache (Cache setting from Eve) from Item cache

# Role settings
from ereuse_devicehub.resources.account.role import Role

ALLOWED_WRITE_ROLES = {Role.AMATEUR}
ALLOWED_ITEM_WRITE_ROLES = {Role.AMATEUR}
ALLOWED_READ_ROLES = {Role.BASIC}
ALLOWED_ITEM_READ_ROLES = {Role.BASIC}

# GRD Settings, do not change them
_events_in_grd = ('Deallocate', 'Migrate', 'Allocate', 'Receive',
                  'Remove', 'Add', 'Register', 'Locate', 'UsageProof', 'Recycle')
EVENTS_IN_GRD = [Naming.resource(DeviceEventDomain.new_type(event)) for event in _events_in_grd]
# Generation of the API (DOMAIN)
from ereuse_devicehub.resources.device.settings import DeviceSettings
from ereuse_devicehub.resources.account.settings import AccountSettings
from ereuse_devicehub.resources.event.settings import EventSettings
from ereuse_devicehub.resources.place.settings import PlaceSettings

DOMAIN = {
    'devices': DeviceSettings,
    'events': EventSettings,
    'accounts': AccountSettings,
    'places': PlaceSettings
}
Beispiel #40
0
 def append_add(self, component, new_parent):
     self._append(DeviceEventDomain.new_type('Add'), new_parent, component)
Beispiel #41
0
 def append_remove(self, component, old_parent):
     self._append(DeviceEventDomain.new_type('Remove'), old_parent, component)
Beispiel #42
0
 def re_materialize_events():
     DeviceDomain.update_many_raw({}, {'$set': {'events': []}})
     for event in DeviceEventDomain.get({'$query': {}, '$orderby': {'_created': pymongo.ASCENDING}}):
         MaterializeEvents.materialize_events(Naming.resource(event['@type']), [event])
     print('Events re-materialized.')
Beispiel #43
0
def remove_from_other_events(resource_name: str, event: dict):
    """Removes the event from other events (Snapshot's 'event' per example)"""
    if resource_name in DeviceEvent.resource_types:
        update = {"$pull": {"events": {"$in": [event["_id"]]}}}
        DeviceEventDomain.update_many_raw({}, update)