Example #1
0
def items_delete_check_support(id_, class_type, path, is_collection):
    """Check if class_type supports PUT operation"""
    try:
        # Delete the Item with ID == id_
        # for colletions, id_ is corresponding to their collection_id and not the id_
        # primary key
        crud.delete(id_,
                    class_type,
                    session=get_session(),
                    collection=is_collection)
        method = "DELETE"
        resource_url = f"{get_hydrus_server_url()}{get_api_name()}/{path}/{id_}"
        last_job_id = crud.get_last_modification_job_id(session=get_session())
        new_job_id = crud.insert_modification_record(method,
                                                     resource_url,
                                                     session=get_session())
        send_sync_update(socketio=socketio,
                         new_job_id=new_job_id,
                         last_job_id=last_job_id,
                         method=method,
                         resource_url=resource_url)
        status_description = f"Object with ID {id_} successfully deleted"
        status = HydraStatus(code=200,
                             title="Object successfully deleted.",
                             desc=status_description)
        return set_response_headers(jsonify(status.generate()))

    except (ClassNotFound, InstanceNotFound) as e:
        error = e.get_HTTP()
        return error_response(error)
Example #2
0
 def test_connect(self, socketio, app, session):
     """Test connect event."""
     socket_client = socketio.test_client(app, namespace='/sync')
     data = socket_client.get_received('/sync')
     assert len(data) > 0
     event = data[0]
     assert event['name'] == 'connect'
     last_job_id = crud.get_last_modification_job_id(session)
     assert event['args'][0]['last_job_id'] == last_job_id
     socket_client.disconnect(namespace='/sync')
Example #3
0
def send_update(method: str, path: str):
    """Handler for sending synchronization update to all connected clients.
    :param method: Method type of the operation.
    :type method: str
    :param path: Path to the Item collection to which update is made.
    :type path: str
    """
    resource_url = f"{get_hydrus_server_url()}{get_api_name()}/{path}"
    session = get_session()
    last_job_id = crud.get_last_modification_job_id(session)
    new_job_id = crud.insert_modification_record(method, resource_url, session)
    send_sync_update(socketio, new_job_id, last_job_id, method, resource_url)
Example #4
0
def items_post_check_support(id_, object_, class_path, path, is_collection):
    """Check if class_type supports POST operation"""
    collections, parsed_classes = get_collections_and_parsed_classes()
    if path in parsed_classes:
        class_path = path
        obj_type = getType(path, "PUT")
    elif path in collections:
        collection = collections[path]["collection"]
        class_path = collection.path
        obj_type = collection.name
    link_props, link_type_check = get_link_props(class_path, object_)
    # Load new object and type
    if (validate_object(object_, obj_type, class_path) and link_type_check):
        if is_collection:
            object_ = parse_collection_members(object_)
        try:
            # Update the right ID if the object is valid and matches
            # type of Item
            object_id = crud.update(object_=object_,
                                    id_=id_,
                                    type_=object_["@type"],
                                    session=get_session(),
                                    api_name=get_api_name(),
                                    collection=is_collection)
            method = "POST"
            resource_url = f"{get_hydrus_server_url()}{get_api_name()}/{path}/{object_id}"
            last_job_id = crud.get_last_modification_job_id(
                session=get_session())
            new_job_id = crud.insert_modification_record(method,
                                                         resource_url,
                                                         session=get_session())
            send_sync_update(socketio=socketio,
                             new_job_id=new_job_id,
                             last_job_id=last_job_id,
                             method=method,
                             resource_url=resource_url)
            headers_ = [{"Location": resource_url}]
            status_description = (f"Object with ID {object_id} successfully "
                                  "updated")
            status = HydraStatus(code=200,
                                 title="Object updated",
                                 desc=status_description)
            return set_response_headers(jsonify(status.generate()),
                                        headers=headers_)

        except (ClassNotFound, InstanceNotFound, InstanceExists,
                PropertyNotFound) as e:
            error = e.get_HTTP()
            return error_response(error)
    else:
        error = HydraError(code=400, title="Data is not valid")
        return error_response(error)
Example #5
0
 def test_reconnect(self, socketio, app, session):
     """Test reconnect event."""
     socket_client = socketio.test_client(app, namespace='/sync')
     # Flush data of first connect event
     socket_client.get_received('/sync')
     # Client reconnects by emitting 'reconnect' event.
     socket_client.emit('reconnect', namespace='/sync')
     # Get update received on reconnecting to the server
     data = socket_client.get_received('/sync')
     assert len(data) > 0
     # Extract the event information
     event = data[0]
     assert event['name'] == 'connect'
     last_job_id = crud.get_last_modification_job_id(session)
     # Check last job id with last_job_id received by client in the update.
     assert event['args'][0]['last_job_id'] == last_job_id
     socket_client.disconnect(namespace='/sync')
Example #6
0
def items_delete_response(path: str, int_list="") -> Response:
    """
    Handles DELETE operation to insert multiple items.

    :param path: Path for Item Collection
    :type path: str
    :param int_list: Optional String containing ',' separated ID's
    :type int_list: List
    :return: Appropriate response for the DELETE operation on multiple items.
    :rtype: Response
    """
    _, parsed_classes = get_collections_and_parsed_classes()
    if path in parsed_classes:
        class_type = getType(path, "DELETE")

    if checkClassOp(class_type, "DELETE"):
        # Check if class_type supports PUT operation
        try:
            # Delete the Item with ID == id_
            crud.delete_multiple(int_list, class_type, session=get_session())
            method = "DELETE"
            path_url = f"{get_hydrus_server_url()}{get_api_name()}/{path}"
            last_job_id = crud.get_last_modification_job_id(session=get_session())
            id_list = int_list.split(',')
            for item in id_list:
                resource_url = path_url + item
                new_job_id = crud.insert_modification_record(method,
                                                             resource_url,
                                                             session=get_session())
                send_sync_update(socketio=socketio, new_job_id=new_job_id,
                                 last_job_id=last_job_id, method=method,
                                 resource_url=resource_url)
                last_job_id = new_job_id
            status_description = f"Objects with ID {id_list} successfully deleted"
            status = HydraStatus(code=200,
                                 title="Objects successfully deleted",
                                 desc=status_description)
            return set_response_headers(jsonify(status.generate()))

        except (ClassNotFound, InstanceNotFound) as e:
            error = e.get_HTTP()
            return error_response(error)

    abort(405)
Example #7
0
 def test_modification_table_diff(self, socketio_client, session):
     """Test 'modification-table-diff' events."""
     # Flush old received data at socket client
     socketio_client.get_received('/sync')
     # Set last_job_id as the agent_job_id
     agent_job_id = crud.get_last_modification_job_id(session)
     # Add an extra modification record newer than the agent_job_id
     new_latest_job_id = crud.insert_modification_record(method='POST',
                                                         resource_url='',
                                                         session=session)
     socketio_client.emit('get_modification_table_diff',
                          {'agent_job_id': agent_job_id},
                          namespace='/sync')
     data = socketio_client.get_received('/sync')
     assert len(data) > 0
     event = data[0]
     assert event['name'] == 'modification_table_diff'
     # Check received event contains data of newly added modification record.
     assert event['args'][0][0]['method'] == 'POST'
     assert event['args'][0][0]['resource_url'] == ''
     assert event['args'][0][0]['job_id'] == new_latest_job_id
Example #8
0
 def on_reconnect(self):
     print('A client reconnected.')
     emit('connect', {'last_job_id': get_last_modification_job_id(self.db_session)})