Пример #1
0
async def set_rights(req):
    """
    Change rights settings for the specified sample document.

    """
    db = req.app["db"]
    data = req["data"]

    sample_id = req.match_info["sample_id"]

    if not await db.samples.count({"_id": sample_id}):
        return not_found()

    user_id = req["client"].user_id

    # Only update the document if the connected user owns the samples or is an administrator.
    if not req[
            "client"].administrator and user_id != await virtool.db.samples.get_sample_owner(
                db, sample_id):
        return insufficient_rights("Must be administrator or sample owner")

    group = data.get("group", None)

    if group:
        existing_group_ids = await db.groups.distinct("_id") + ["none"]

        if group not in existing_group_ids:
            return bad_request("Group does not exist")

    # Update the sample document with the new rights.
    document = await db.samples.find_one_and_update(
        {"_id": sample_id}, {"$set": data},
        projection=virtool.db.samples.RIGHTS_PROJECTION)

    return json_response(document)
Пример #2
0
async def blast(req):
    """
    BLAST a contig sequence that is part of a NuVs result record. The resulting BLAST data will be attached to that
    sequence.

    """
    db = req.app["db"]
    settings = req.app["settings"]

    analysis_id = req.match_info["analysis_id"]
    sequence_index = int(req.match_info["sequence_index"])

    document = await db.analyses.find_one(
        {"_id": analysis_id}, ["ready", "algorithm", "results", "sample"])

    if not document:
        return not_found("Analysis not found")

    if document["algorithm"] != "nuvs":
        return conflict("Not a NuVs analysis")

    if not document["ready"]:
        return conflict("Analysis is still running")

    sequence = virtool.analyses.find_nuvs_sequence_by_index(
        document, sequence_index)

    if sequence is None:
        return not_found("Sequence not found")

    sample = await db.samples.find_one({"_id": document["sample"]["id"]},
                                       virtool.db.samples.PROJECTION)

    if not sample:
        return bad_request("Parent sample does not exist")

    _, write = virtool.samples.get_sample_rights(sample, req["client"])

    if not write:
        return insufficient_rights()

    # Start a BLAST at NCBI with the specified sequence. Return a RID that identifies the BLAST run.
    rid, _ = await virtool.bio.initialize_ncbi_blast(req.app["settings"],
                                                     sequence)

    blast_data, document = await virtool.db.analyses.update_nuvs_blast(
        db, settings, analysis_id, sequence_index, rid)

    # Wait on BLAST request as a Task until the it completes on NCBI. At that point the sequence in the DB will be
    # updated with the BLAST result.
    await aiojobs.aiohttp.spawn(
        req,
        virtool.bio.wait_for_blast_result(db, req.app["settings"], analysis_id,
                                          sequence_index, rid))

    headers = {
        "Location": f"/api/analyses/{analysis_id}/{sequence_index}/blast"
    }

    return json_response(blast_data, headers=headers, status=201)
Пример #3
0
async def edit(req):
    """
    Update specific fields in the sample document.

    """
    db = req.app["db"]
    data = req["data"]

    sample_id = req.match_info["sample_id"]

    if not await virtool.db.samples.check_rights(db, sample_id, req["client"]):
        return insufficient_rights()

    message = await virtool.db.samples.check_name(db,
                                                  req.app["settings"],
                                                  data["name"],
                                                  sample_id=sample_id)

    if message:
        return bad_request(message)

    document = await db.samples.find_one_and_update(
        {"_id": sample_id}, {"$set": data},
        projection=virtool.db.samples.LIST_PROJECTION)

    processed = virtool.utils.base_processor(document)

    return json_response(processed)
Пример #4
0
async def edit_user(req):
    db = req.app["db"]
    data = req["data"]
    ref_id = req.match_info["ref_id"]
    user_id = req.match_info["user_id"]

    document = await db.references.find_one(
        {
            "_id": ref_id,
            "users.id": user_id
        }, ["groups", "users"])

    if document is None:
        return not_found()

    if not await virtool.db.references.check_right(req, ref_id, "modify"):
        return insufficient_rights()

    subdocument = await virtool.db.references.edit_group_or_user(
        db, ref_id, user_id, "users", data)

    if subdocument is None:
        return not_found()

    subdocument = await virtool.db.users.attach_identicons(db, subdocument)

    return json_response(subdocument)
Пример #5
0
async def get(req):
    """
    Get a complete analysis document.

    """
    db = req.app["db"]

    analysis_id = req.match_info["analysis_id"]

    document = await db.analyses.find_one(analysis_id)

    if document is None:
        return not_found()

    sample = await db.samples.find_one({"_id": document["sample"]["id"]},
                                       {"quality": False})

    if not sample:
        return bad_request("Parent sample does not exist")

    read, _ = virtool.samples.get_sample_rights(sample, req["client"])

    if not read:
        return insufficient_rights()

    if document["ready"]:
        document = await virtool.db.analyses.format_analysis(
            db, req.app["settings"], document)

    document["subtraction"] = {"id": sample["subtraction"]["id"]}

    return json_response(virtool.utils.base_processor(document))
Пример #6
0
async def add_user(req):
    db = req.app["db"]
    data = req["data"]
    ref_id = req.match_info["ref_id"]

    document = await db.references.find_one(ref_id, ["groups", "users"])

    if document is None:
        return not_found()

    if not await virtool.db.references.check_right(req, ref_id, "modify"):
        return insufficient_rights()

    try:
        subdocument = await virtool.db.references.add_group_or_user(
            db, ref_id, "users", data)
    except virtool.errors.DatabaseError as err:
        if "already exists" in str(err):
            return bad_request("User already exists")

        if "does not exist" in str(err):
            return bad_request("User does not exist")

        raise

    headers = {"Location": f"/api/refs/{ref_id}/users/{subdocument['id']}"}

    subdocument = await virtool.db.users.attach_identicons(db, subdocument)

    return json_response(subdocument, headers=headers, status=201)
Пример #7
0
async def remove(req):
    """
    Remove a reference and its otus, history, and indexes.

    """
    db = req.app["db"]

    ref_id = req.match_info["ref_id"]

    if not await virtool.db.utils.id_exists(db.references, ref_id):
        return not_found()

    if not await virtool.db.references.check_right(req, ref_id, "remove"):
        return insufficient_rights()

    user_id = req["client"].user_id

    context = {"ref_id": ref_id, "user_id": user_id}

    process = await virtool.db.processes.register(db,
                                                  "delete_reference",
                                                  context=context)

    await db.references.delete_one({"_id": ref_id})

    p = virtool.db.references.RemoveReferenceProcess(req.app, process["id"])

    await aiojobs.aiohttp.spawn(req, p.run())

    headers = {"Content-Location": f"/api/processes/{process['id']}"}

    return json_response(process, 202, headers)
Пример #8
0
async def edit_sequence(req):
    db, data = req.app["db"], req["data"]

    otu_id, isolate_id, sequence_id = (
        req.match_info[key] for key in ["otu_id", "isolate_id", "sequence_id"])

    document = await db.otus.find_one({
        "_id": otu_id,
        "isolates.id": isolate_id
    })

    if not document or not await db.sequences.count({"_id": sequence_id}):
        return not_found()

    if not await virtool.db.references.check_right(
            req, document["reference"]["id"], "modify_otu"):
        return insufficient_rights()

    old = await virtool.db.otus.join(db, otu_id, document)

    segment = data.get("segment", None)

    if segment and segment not in {
            s["name"]
            for s in document.get("schema", {})
    }:
        return not_found("Segment does not exist")

    data["sequence"] = data["sequence"].replace(" ", "").replace("\n", "")

    updated_sequence = await db.sequences.find_one_and_update(
        {"_id": sequence_id}, {"$set": data})

    document = await db.otus.find_one_and_update({"_id": otu_id}, {
        "$set": {
            "verified": False
        },
        "$inc": {
            "version": 1
        }
    })

    new = await virtool.db.otus.join(db, otu_id, document)

    await virtool.db.otus.update_verification(db, new)

    isolate = virtool.otus.find_isolate(old["isolates"], isolate_id)

    await virtool.db.history.add(
        db, "edit_sequence", old, new,
        f"Edited sequence {sequence_id} in {virtool.otus.format_isolate_name(isolate)}",
        req["client"].user_id)

    return json_response(virtool.utils.base_processor(updated_sequence))
Пример #9
0
async def remove_sequence(req):
    """
    Remove a sequence from an isolate.

    """
    db = req.app["db"]

    otu_id = req.match_info["otu_id"]
    isolate_id = req.match_info["isolate_id"]
    sequence_id = req.match_info["sequence_id"]

    if not await db.sequences.count({"_id": sequence_id}):
        return not_found()

    old = await virtool.db.otus.join(db, {
        "_id": otu_id,
        "isolates.id": isolate_id
    })

    if old is None:
        return not_found()

    if not await virtool.db.references.check_right(req, old["reference"]["id"],
                                                   "modify_otu"):
        return insufficient_rights()

    isolate = virtool.otus.find_isolate(old["isolates"], isolate_id)

    await db.sequences.delete_one({"_id": sequence_id})

    await db.otus.update_one({"_id": otu_id}, {
        "$set": {
            "verified": False
        },
        "$inc": {
            "version": 1
        }
    })

    new = await virtool.db.otus.join(db, otu_id)

    await virtool.db.otus.update_verification(db, new)

    isolate_name = virtool.otus.format_isolate_name(isolate)

    await virtool.db.history.add(
        db, "remove_sequence", old, new,
        f"Removed sequence {sequence_id} from {isolate_name}",
        req["client"].user_id)

    return no_content()
Пример #10
0
async def get(req):
    """
    Get a complete sample document.

    """
    document = await req.app["db"].samples.find_one(req.match_info["sample_id"]
                                                    )

    if not document:
        return not_found()

    if not virtool.samples.get_sample_rights(document, req["client"])[0]:
        return insufficient_rights()

    return json_response(virtool.utils.base_processor(document))
Пример #11
0
async def edit(req):
    db = req.app["db"]
    data = req["data"]

    ref_id = req.match_info["ref_id"]

    if not await virtool.db.utils.id_exists(db.references, ref_id):
        return not_found()

    if not await virtool.db.references.check_right(req, ref_id, "modify"):
        return insufficient_rights()

    internal_control_id = data.get("internal_control", None)

    if internal_control_id == "":
        data["internal_control"] = None

    elif internal_control_id:
        internal_control = await virtool.db.references.get_internal_control(
            db, internal_control_id, ref_id)

        if internal_control is None:
            data["internal_control"] = None
        else:
            data["internal_control"] = {"id": internal_control_id}

    document = await db.references.find_one_and_update({"_id": ref_id},
                                                       {"$set": data})

    document = virtool.utils.base_processor(document)

    document.update(await
                    virtool.db.references.get_computed(db, ref_id,
                                                       internal_control_id))

    if "name" in data:
        await db.analyses.update_many(
            {"reference.id": ref_id},
            {"$set": {
                "reference.name": document["name"]
            }})

    users = await virtool.db.utils.get_one_field(db.references, "users",
                                                 ref_id)

    document["users"] = await virtool.db.users.attach_identicons(db, users)

    return json_response(document)
Пример #12
0
async def update(req):
    app = req.app
    db = app["db"]

    ref_id = req.match_info["ref_id"]
    user_id = req["client"].user_id

    if not await virtool.db.utils.id_exists(db.references, ref_id):
        return not_found()

    if not await virtool.db.references.check_right(req, ref_id, "modify"):
        return insufficient_rights()

    release = await virtool.db.utils.get_one_field(db.references, "release",
                                                   ref_id)

    if release is None:
        return bad_request("Target release does not exist")

    created_at = virtool.utils.timestamp()

    context = {
        "created_at":
        created_at,
        "ref_id":
        ref_id,
        "release":
        await virtool.db.utils.get_one_field(db.references, "release", ref_id),
        "user_id":
        user_id
    }

    process = await virtool.db.processes.register(db,
                                                  "update_remote_reference",
                                                  context=context)

    release, update_subdocument = await virtool.db.references.update(
        req.app, created_at, process["id"], ref_id, release, user_id)

    p = virtool.db.references.UpdateRemoteReferenceProcess(
        req.app, process["id"])

    await aiojobs.aiohttp.spawn(req, p.run())

    return json_response(update_subdocument, status=201)
Пример #13
0
async def analyze(req):
    """
    Starts an analysis job for a given sample.

    """
    db = req.app["db"]
    data = req["data"]

    sample_id = req.match_info["sample_id"]
    ref_id = data["ref_id"]

    try:
        if not await virtool.db.samples.check_rights(db, sample_id,
                                                     req["client"]):
            return insufficient_rights()
    except virtool.errors.DatabaseError as err:
        if "Sample does not exist" in str(err):
            return not_found()

        raise

    if not await db.references.count({"_id": ref_id}):
        return bad_request("Reference does not exist")

    if not await db.indexes.count({"reference.id": ref_id, "ready": True}):
        return bad_request("No ready index")

    # Generate a unique _id for the analysis entry
    document = await virtool.db.analyses.new(req.app, sample_id, ref_id,
                                             req["client"].user_id,
                                             data["algorithm"])

    document = virtool.utils.base_processor(document)

    sample = await virtool.db.samples.recalculate_algorithm_tags(db, sample_id)

    await req.app["dispatcher"].dispatch("samples", "update",
                                         virtool.utils.base_processor(sample))

    analysis_id = document["id"]

    return json_response(document,
                         status=201,
                         headers={"Location": f"/api/analyses/{analysis_id}"})
Пример #14
0
async def create(req):
    """
    Add a new otu to the collection. Checks to make sure the supplied otu name and abbreviation are not already in
    use in the collection. Any errors are sent back to the client.

    """
    db = req.app["db"]
    data = req["data"]

    ref_id = req.match_info["ref_id"]

    reference = await db.references.find_one(ref_id, ["groups", "users"])

    if reference is None:
        return not_found()

    if not await virtool.db.references.check_right(req, reference,
                                                   "modify_otu"):
        return insufficient_rights()

    name = data["name"].strip()
    abbreviation = data["abbreviation"].strip()

    # Check if either the name or abbreviation are already in use. Send a ``400`` if they are.
    message = await virtool.db.otus.check_name_and_abbreviation(
        db, ref_id, name, abbreviation)

    if message:
        return bad_request(message)

    joined = await virtool.db.otus.create(db, ref_id, name, abbreviation)

    description = virtool.history.compose_create_description(joined)

    change = await virtool.db.history.add(db, "create", None, joined,
                                          description, req["client"].user_id)

    formatted = virtool.otus.format_otu(joined, most_recent_change=change)

    headers = {"Location": "/api/otus/" + formatted["id"]}

    return json_response(formatted, status=201, headers=headers)
Пример #15
0
async def remove(req):
    """
    Remove an analysis document by its id.

    """
    db = req.app["db"]

    analysis_id = req.match_info["analysis_id"]

    document = await db.analyses.find_one({"_id": analysis_id},
                                          ["job", "ready", "sample"])

    if not document:
        return not_found()

    sample_id = document["sample"]["id"]

    sample = await db.samples.find_one({"_id": sample_id},
                                       virtool.db.samples.PROJECTION)

    if not sample:
        return bad_request("Parent sample does not exist")

    read, write = virtool.samples.get_sample_rights(sample, req["client"])

    if not read or not write:
        return insufficient_rights()

    if not document["ready"]:
        return conflict("Analysis is still running")

    await db.analyses.delete_one({"_id": analysis_id})

    path = os.path.join(req.app["settings"]["data_path"], "samples", sample_id,
                        "analysis", analysis_id)

    await req.app["run_in_thread"](virtool.utils.rm, path, True)

    await virtool.db.samples.recalculate_algorithm_tags(db, sample_id)

    return no_content()
Пример #16
0
async def delete_user(req):
    db = req.app["db"]
    ref_id = req.match_info["ref_id"]
    user_id = req.match_info["user_id"]

    document = await db.references.find_one(
        {
            "_id": ref_id,
            "users.id": user_id
        }, ["groups", "users"])

    if document is None:
        return not_found()

    if not await virtool.db.references.check_right(req, ref_id, "modify"):
        return insufficient_rights()

    await virtool.db.references.delete_group_or_user(db, ref_id, user_id,
                                                     "users")

    return no_content()
Пример #17
0
async def remove(req):
    """
    Remove an OTU document and its associated sequence documents.

    """
    db = req.app["db"]

    otu_id = req.match_info["otu_id"]

    document = await db.otus.find_one(otu_id, ["reference"])

    if document is None:
        return not_found()

    if not await virtool.db.references.check_right(
            req, document["reference"]["id"], "modify_otu"):
        return insufficient_rights()

    await virtool.db.otus.remove(db, otu_id, req["client"].user_id)

    return web.Response(status=204)
Пример #18
0
async def revert(req):
    """
    Remove the change document with the given ``change_id`` and any subsequent changes.

    """
    db = req.app["db"]

    change_id = req.match_info["change_id"]

    document = await db.history.find_one(change_id, ["reference"])

    if not document:
        return not_found()

    if not await virtool.db.references.check_right(req, document["reference"]["id"], "modify_otu"):
        return insufficient_rights()

    try:
        await virtool.db.history.revert(db, change_id)
    except virtool.errors.DatabaseError:
        return conflict("Change is already built")

    return no_content()
Пример #19
0
async def remove(req):
    """
    Remove a sample document and all associated analyses.

    """
    db = req.app["db"]

    sample_id = req.match_info["sample_id"]

    try:
        if not await virtool.db.samples.check_rights(db, sample_id,
                                                     req["client"]):
            return insufficient_rights()
    except virtool.errors.DatabaseError as err:
        if "Sample does not exist" in str(err):
            return not_found()

        raise

    await virtool.db.samples.remove_samples(db, req.app["settings"],
                                            [sample_id])

    return no_content()
Пример #20
0
async def get(req):
    """
    Get a complete sample document.

    """
    db = req.app["db"]

    sample_id = req.match_info["sample_id"]

    document = await db.samples.find_one(sample_id)

    if not document:
        return not_found()

    if not virtool.samples.get_sample_rights(document, req["client"])[0]:
        return insufficient_rights()

    caches = list()

    async for cache in db.caches.find({"sample.id": sample_id}):
        caches.append(virtool.utils.base_processor(cache))

    document["caches"] = caches

    for index, file in enumerate(document["files"]):
        snake_case = document["name"].replace(" ", "_")

        file.update({
            "name":
            file["name"].replace("reads_", f"{snake_case}_"),
            "download_url":
            file["download_url"].replace("reads_", f"{snake_case}_"),
            "replace_url":
            f"/upload/samples/{sample_id}/files/{index + 1}"
        })

    return json_response(virtool.utils.base_processor(document))
Пример #21
0
async def find_analyses(req):
    """
    List the analyses associated with the given ``sample_id``.

    """
    db = req.app["db"]

    sample_id = req.match_info["sample_id"]

    try:
        if not await virtool.db.samples.check_rights(
                db, sample_id, req["client"], write=False):
            return insufficient_rights()
    except virtool.errors.DatabaseError as err:
        if "Sample does not exist" in str(err):
            return not_found()

        raise

    term = req.query.get("term", None)

    db_query = dict()

    if term:
        db_query.update(
            compose_regex_query(term, ["reference.name", "user.id"]))

    base_query = {"sample.id": sample_id}

    data = await paginate(db.analyses,
                          db_query,
                          req.query,
                          base_query=base_query,
                          projection=virtool.db.analyses.PROJECTION,
                          sort=[("created_at", -1)])

    return json_response(data)
Пример #22
0
async def edit(req):
    """
    Edit an existing OTU. Checks to make sure the supplied OTU name and abbreviation are not already in use in
    the collection.

    """
    db = req.app["db"]
    data = req["data"]

    otu_id = req.match_info["otu_id"]

    # Get existing complete otu record, at the same time ensuring it exists. Send a ``404`` if not.
    old = await virtool.db.otus.join(db, otu_id)

    if not old:
        return not_found()

    ref_id = old["reference"]["id"]

    if not await virtool.db.references.check_right(req, ref_id, "modify_otu"):
        return insufficient_rights()

    name, abbreviation, schema = virtool.otus.evaluate_changes(data, old)

    # Send ``200`` with the existing otu record if no change will be made.
    if name is None and abbreviation is None and schema is None:
        return json_response(await virtool.db.otus.join_and_format(db, otu_id))

    # Make sure new name or abbreviation are not already in use.
    message = await virtool.db.otus.check_name_and_abbreviation(
        db, ref_id, name, abbreviation)

    if message:
        return bad_request(message)

    # Update the ``modified`` and ``verified`` fields in the otu document now, because we are definitely going to
    # modify the otu.
    data["verified"] = False

    # If the name is changing, update the ``lower_name`` field in the otu document.
    if name:
        data["lower_name"] = name.lower()

    # Update the database collection.
    document = await db.otus.find_one_and_update({"_id": otu_id}, {
        "$set": data,
        "$inc": {
            "version": 1
        }
    })

    await virtool.db.otus.update_sequence_segments(db, old, document)

    new = await virtool.db.otus.join(db, otu_id, document)

    issues = await virtool.db.otus.update_verification(db, new)

    description = virtool.history.compose_edit_description(
        name, abbreviation, old["abbreviation"], schema)

    await virtool.db.history.add(db, "edit", old, new, description,
                                 req["client"].user_id)

    return json_response(await virtool.db.otus.join_and_format(db,
                                                               otu_id,
                                                               joined=new,
                                                               issues=issues))
Пример #23
0
async def create(req):
    """
    Starts a job to rebuild the otus Bowtie2 index on disk. Does a check to make sure there are no unverified
    otus in the collection and updates otu history to show the version and id of the new index.

    """
    db = req.app["db"]

    ref_id = req.match_info["ref_id"]

    reference = await db.references.find_one(ref_id, ["groups", "users"])

    if reference is None:
        return not_found()

    if not await virtool.db.references.check_right(req, reference, "build"):
        return insufficient_rights()

    if await db.indexes.count({"reference.id": ref_id, "ready": False}):
        return conflict("Index build already in progress")

    if await db.otus.count({"reference.id": ref_id, "verified": False}):
        return bad_request("There are unverified OTUs")

    if not await db.history.count({"reference.id": ref_id, "index.id": "unbuilt"}):
        return bad_request("There are no unbuilt changes")

    index_id = await virtool.db.utils.get_new_id(db.indexes)

    index_version = await virtool.db.indexes.get_next_version(db, ref_id)

    job_id = await virtool.db.utils.get_new_id(db.jobs)

    manifest = await virtool.db.references.get_manifest(db, ref_id)

    user_id = req["client"].user_id

    document = {
        "_id": index_id,
        "version": index_version,
        "created_at": virtool.utils.timestamp(),
        "manifest": manifest,
        "ready": False,
        "has_files": True,
        "job": {
            "id": job_id
        },
        "reference": {
            "id": ref_id
        },
        "user": {
            "id": user_id
        }
    }

    await db.indexes.insert_one(document)

    await db.history.update_many({"index.id": "unbuilt", "reference.id": ref_id}, {
        "$set": {
            "index": {
                "id": index_id,
                "version": index_version
            }
        }
    })

    # A dict of task_args for the rebuild job.
    task_args = {
        "ref_id": ref_id,
        "user_id": user_id,
        "index_id": index_id,
        "index_version": index_version,
        "manifest": manifest
    }

    # Create job document.
    job = await virtool.db.jobs.create(
        db,
        req.app["settings"],
        "build_index",
        task_args,
        user_id,
        job_id=job_id
    )

    await req.app["jobs"].enqueue(job["_id"])

    headers = {
        "Location": "/api/indexes/" + index_id
    }

    return json_response(virtool.utils.base_processor(document), status=201, headers=headers)
Пример #24
0
async def create_sequence(req):
    """
    Create a new sequence record for the given isolate.

    """
    db, data = req.app["db"], req["data"]

    # Extract variables from URL path.
    otu_id, isolate_id = (req.match_info[key]
                          for key in ["otu_id", "isolate_id"])

    # Get the subject otu document. Will be ``None`` if it doesn't exist. This will result in a ``404`` response.
    document = await db.otus.find_one({
        "_id": otu_id,
        "isolates.id": isolate_id
    })

    if not document:
        return not_found()

    ref_id = document["reference"]["id"]

    if not await virtool.db.references.check_right(req, ref_id, "modify_otu"):
        return insufficient_rights()

    segment = data.get("segment", None)

    if segment and segment not in {
            s["name"]
            for s in document.get("schema", {})
    }:
        return bad_request("Segment does not exist")

    # Update POST data to make sequence document.
    data.update({
        "otu_id": otu_id,
        "isolate_id": isolate_id,
        "host": data.get("host", ""),
        "reference": {
            "id": ref_id
        },
        "segment": segment,
        "sequence": data["sequence"].replace(" ", "").replace("\n", "")
    })

    old = await virtool.db.otus.join(db, otu_id, document)

    sequence_document = await db.sequences.insert_one(data)

    new = await db.otus.find_one_and_update({"_id": otu_id}, {
        "$set": {
            "verified": False
        },
        "$inc": {
            "version": 1
        }
    })

    new = await virtool.db.otus.join(db, otu_id, new)

    await virtool.db.otus.update_verification(db, new)

    isolate = virtool.otus.find_isolate(old["isolates"], isolate_id)

    await virtool.db.history.add(
        db, "create_sequence", old, new,
        f"Created new sequence {data['accession']} in {virtool.otus.format_isolate_name(isolate)}",
        req["client"].user_id)

    headers = {
        "Location":
        f"/api/otus/{otu_id}/isolates/{isolate_id}/sequences/{sequence_document['_id']}"
    }

    return json_response(virtool.utils.base_processor(data),
                         status=201,
                         headers=headers)
Пример #25
0
async def remove_isolate(req):
    """
    Remove an isolate and its sequences from a otu.

    """
    db = req.app["db"]

    otu_id = req.match_info["otu_id"]
    isolate_id = req.match_info["isolate_id"]

    document = await db.otus.find_one({
        "_id": otu_id,
        "isolates.id": isolate_id
    })

    if not document:
        return not_found()

    if not await virtool.db.references.check_right(
            req, document["reference"]["id"], "modify_otu"):
        return insufficient_rights()

    isolates = deepcopy(document["isolates"])

    # Get any isolates that have the isolate id to be removed (only one should match!).
    isolate_to_remove = virtool.otus.find_isolate(isolates, isolate_id)

    # Remove the isolate from the otu' isolate list.
    isolates.remove(isolate_to_remove)

    new_default = None

    # Set the first isolate as default if the removed isolate was the default.
    if isolate_to_remove["default"] and len(isolates):
        new_default = isolates[0]
        new_default["default"] = True

    old = await virtool.db.otus.join(db, otu_id, document)

    document = await db.otus.find_one_and_update({"_id": otu_id}, {
        "$set": {
            "isolates": isolates,
            "verified": False
        },
        "$inc": {
            "version": 1
        }
    })

    new = await virtool.db.otus.join(db, otu_id, document)

    issues = await virtool.db.otus.verify(db, otu_id, joined=new)

    if issues is None:
        await db.otus.update_one({"_id": otu_id}, {"$set": {"verified": True}})

        new["verified"] = True

    # Remove any sequences associated with the removed isolate.
    await db.sequences.delete_many({
        "otu_id": otu_id,
        "isolate_id": isolate_id
    })

    old_isolate_name = virtool.otus.format_isolate_name(isolate_to_remove)

    description = f"Removed {old_isolate_name}"

    if isolate_to_remove["default"] and new_default:
        new_isolate_name = virtool.otus.format_isolate_name(new_default)
        description += f" and set {new_isolate_name} as default"

    await virtool.db.history.add(db, "remove_isolate", old, new, description,
                                 req["client"].user_id)

    return no_content()
Пример #26
0
async def set_as_default(req):
    """
    Set an isolate as default.

    """
    db = req.app["db"]

    otu_id = req.match_info["otu_id"]
    isolate_id = req.match_info["isolate_id"]

    document = await db.otus.find_one({
        "_id": otu_id,
        "isolates.id": isolate_id
    })

    if not document:
        return not_found()

    if not await virtool.db.references.check_right(
            req, document["reference"]["id"], "modify_otu"):
        return insufficient_rights()

    isolates = deepcopy(document["isolates"])

    isolate = virtool.otus.find_isolate(isolates, isolate_id)

    # Set ``default`` to ``False`` for all existing isolates if the new one should be default.
    for existing_isolate in isolates:
        existing_isolate["default"] = False

    isolate["default"] = True

    if isolates == document["isolates"]:
        complete = await virtool.db.otus.join_and_format(db, otu_id)
        for isolate in complete["isolates"]:
            if isolate["id"] == isolate_id:
                return json_response(isolate)

    old = await virtool.db.otus.join(db, otu_id)

    # Replace the isolates list with the updated one.
    document = await db.otus.find_one_and_update({"_id": otu_id}, {
        "$set": {
            "isolates": isolates,
            "verified": False
        },
        "$inc": {
            "version": 1
        }
    })

    # Get the joined entry now that it has been updated.
    new = await virtool.db.otus.join(db, otu_id, document)

    await virtool.db.otus.update_verification(db, new)

    isolate_name = virtool.otus.format_isolate_name(isolate)

    # Use the old and new entry to add a new history document for the change.
    await virtool.db.history.add(db, "set_as_default", old, new,
                                 f"Set {isolate_name} as default",
                                 req["client"].user_id)

    complete = await virtool.db.otus.join_and_format(db, otu_id, new)

    for isolate in complete["isolates"]:
        if isolate["id"] == isolate_id:
            return json_response(isolate)
Пример #27
0
async def edit_isolate(req):
    """
    Edit an existing isolate.

    """
    db = req.app["db"]
    data = req["data"]

    otu_id = req.match_info["otu_id"]
    isolate_id = req.match_info["isolate_id"]

    document = await db.otus.find_one({
        "_id": otu_id,
        "isolates.id": isolate_id
    })

    if not document:
        return not_found()

    ref_id = document["reference"]["id"]

    if not await virtool.db.references.check_right(req, ref_id, "modify_otu"):
        return insufficient_rights()

    reference = await db.references.find_one(
        ref_id, ["restrict_source_types", "source_types"])

    isolates = deepcopy(document["isolates"])

    isolate = virtool.otus.find_isolate(isolates, isolate_id)

    # All source types are stored in lower case.
    if "source_type" in data:
        data["source_type"] = data["source_type"].lower()

        if reference["restrict_source_types"] and data[
                "source_type"] not in reference["source_types"]:
            return bad_request("Source type is not allowed")

    old_isolate_name = virtool.otus.format_isolate_name(isolate)

    isolate.update(data)

    old = await virtool.db.otus.join(db, otu_id)

    # Replace the isolates list with the update one.
    document = await db.otus.find_one_and_update({"_id": otu_id}, {
        "$set": {
            "isolates": isolates,
            "verified": False
        },
        "$inc": {
            "version": 1
        }
    })

    # Get the joined entry now that it has been updated.
    new = await virtool.db.otus.join(db, otu_id, document)

    await virtool.db.otus.update_verification(db, new)

    isolate_name = virtool.otus.format_isolate_name(isolate)

    # Use the old and new entry to add a new history document for the change.
    await virtool.db.history.add(
        db, "edit_isolate", old, new,
        f"Renamed {old_isolate_name} to {isolate_name}", req["client"].user_id)

    complete = await virtool.db.otus.join_and_format(db, otu_id, joined=new)

    for isolate in complete["isolates"]:
        if isolate["id"] == isolate_id:
            return json_response(isolate, status=200)
Пример #28
0
async def add_isolate(req):
    """
    Add a new isolate to a otu.

    """
    db = req.app["db"]
    data = req["data"]

    otu_id = req.match_info["otu_id"]

    document = await db.otus.find_one(otu_id)

    if not document:
        return not_found()

    if not await virtool.db.references.check_right(
            req, document["reference"]["id"], "modify_otu"):
        return insufficient_rights()

    isolates = deepcopy(document["isolates"])

    # True if the new isolate should be default and any existing isolates should be non-default.
    will_be_default = not isolates or data["default"]

    # Get the complete, joined entry before the update.
    old = await virtool.db.otus.join(db, otu_id, document)

    # All source types are stored in lower case.
    data["source_type"] = data["source_type"].lower()

    if not await virtool.db.references.check_source_type(
            db, document["reference"]["id"], data["source_type"]):
        return bad_request("Source type is not allowed")

    # Set ``default`` to ``False`` for all existing isolates if the new one should be default.
    if isolates and data["default"]:
        for isolate in isolates:
            isolate["default"] = False

    # Force the new isolate as default if it is the first isolate.
    if not isolates:
        data["default"] = True

    # Set the isolate as the default isolate if it is the first one.
    data["default"] = will_be_default

    isolate_id = await virtool.db.otus.append_isolate(db, otu_id, isolates,
                                                      data)

    # Get the joined entry now that it has been updated.
    new = await virtool.db.otus.join(db, otu_id)

    await virtool.db.otus.update_verification(db, new)

    isolate_name = virtool.otus.format_isolate_name(data)

    description = f"Added {isolate_name}"

    if will_be_default:
        description += " as default"

    await virtool.db.history.add(db, "add_isolate", old, new, description,
                                 req["client"].user_id)

    headers = {"Location": f"/api/otus/{otu_id}/isolates/{isolate_id}"}

    return json_response(dict(data, id=isolate_id, sequences=[]),
                         status=201,
                         headers=headers)