コード例 #1
0
ファイル: hooks.py プロジェクト: eReuse/DeviceHub
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}})
コード例 #2
0
ファイル: allocate.py プロジェクト: Python3pkg/DeviceHub
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']})
コード例 #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']
                 }})
コード例 #4
0
ファイル: hooks.py プロジェクト: Python3pkg/DeviceHub
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}})
コード例 #5
0
 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.')
コード例 #6
0
 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.')
コード例 #7
0
ファイル: allocate.py プロジェクト: eReuse/DeviceHub
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']})
コード例 #8
0
ファイル: hooks.py プロジェクト: eReuse/DeviceHub
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)
コード例 #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)
コード例 #10
0
ファイル: hooks.py プロジェクト: eReuse/DeviceHub
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)
コード例 #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])
コード例 #12
0
ファイル: grd_submitter.py プロジェクト: eReuse/DeviceHub
 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
コード例 #13
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.')
コード例 #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)
コード例 #15
0
ファイル: utils.py プロジェクト: eReuse/DeviceHub
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])
コード例 #16
0
ファイル: hooks.py プロジェクト: eReuse/DeviceHub
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)
コード例 #17
0
ファイル: grd_submitter.py プロジェクト: eReuse/DeviceHub
 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
コード例 #18
0
ファイル: settings.py プロジェクト: eReuse/DeviceHub
 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
コード例 #19
0
ファイル: hooks.py プロジェクト: Python3pkg/DeviceHub
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)
コード例 #20
0
ファイル: utils.py プロジェクト: Python3pkg/DeviceHub
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])
コード例 #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
コード例 #22
0
ファイル: domain.py プロジェクト: Python3pkg/DeviceHub
 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
コード例 #23
0
ファイル: snapshot.py プロジェクト: eReuse/DeviceHub
 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')
コード例 #24
0
ファイル: test_device.py プロジェクト: eReuse/DeviceHub
 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
コード例 #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
コード例 #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
コード例 #27
0
ファイル: test_snapshot.py プロジェクト: eReuse/DeviceHub
 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']
コード例 #28
0
ファイル: snapshot.py プロジェクト: Python3pkg/DeviceHub
 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')
コード例 #29
0
ファイル: hooks.py プロジェクト: eReuse/DeviceHub
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
コード例 #30
0
ファイル: hooks.py プロジェクト: Python3pkg/DeviceHub
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
コード例 #31
0
ファイル: hooks.py プロジェクト: eReuse/DeviceHub
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)
コード例 #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)
コード例 #33
0
ファイル: hooks.py プロジェクト: Python3pkg/DeviceHub
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
コード例 #34
0
ファイル: hooks.py プロジェクト: eReuse/DeviceHub
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
コード例 #35
0
 def append_add(self, component, new_parent):
     self._append(DeviceEventDomain.new_type('Add'), new_parent, component)
コード例 #36
0
 def append_remove(self, component, old_parent):
     self._append(DeviceEventDomain.new_type('Remove'), old_parent,
                  component)
コード例 #37
0
ファイル: hooks.py プロジェクト: Python3pkg/DeviceHub
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)
コード例 #38
0
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
}
コード例 #39
0
ファイル: default_settings.py プロジェクト: eReuse/DeviceHub
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
}
コード例 #40
0
ファイル: event_processor.py プロジェクト: eReuse/DeviceHub
 def append_add(self, component, new_parent):
     self._append(DeviceEventDomain.new_type('Add'), new_parent, component)
コード例 #41
0
ファイル: event_processor.py プロジェクト: eReuse/DeviceHub
 def append_remove(self, component, old_parent):
     self._append(DeviceEventDomain.new_type('Remove'), old_parent, component)
コード例 #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.')
コード例 #43
0
ファイル: hooks.py プロジェクト: eReuse/DeviceHub
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)