about summary refs log tree commit diff
path: root/gn3/api/metadata_api
diff options
context:
space:
mode:
Diffstat (limited to 'gn3/api/metadata_api')
-rw-r--r--gn3/api/metadata_api/wiki.py80
1 files changed, 71 insertions, 9 deletions
diff --git a/gn3/api/metadata_api/wiki.py b/gn3/api/metadata_api/wiki.py
index 8df6cfb..70c5cf4 100644
--- a/gn3/api/metadata_api/wiki.py
+++ b/gn3/api/metadata_api/wiki.py
@@ -1,27 +1,31 @@
-"""API for accessing/editting wiki metadata"""
+"""API for accessing/editing rif/wiki metadata"""
 
 import datetime
 from typing import Any, Dict
 
+from typing import Optional
 from flask import Blueprint, request, jsonify, current_app, make_response
 
 from gn3 import db_utils
-from gn3.auth.authorisation.oauth2.resource_server import require_oauth
+from gn3.oauth2.authorisation import require_token
 from gn3.db import wiki
 from gn3.db.rdf.wiki import (
     get_wiki_entries_by_symbol,
     get_comment_history,
     update_wiki_comment,
+    get_rif_entries_by_symbol,
+    delete_wiki_entries_by_id,
 )
 
 
 wiki_blueprint = Blueprint("wiki", __name__, url_prefix="wiki")
+rif_blueprint = Blueprint("rif", __name__, url_prefix="rif")
 
 
+@wiki_blueprint.route("/edit", methods=["POST"], defaults={'comment_id': None})
 @wiki_blueprint.route("/<int:comment_id>/edit", methods=["POST"])
-@require_oauth("profile")
-def edit_wiki(comment_id: int):
-    """Edit wiki comment. This is achieved by adding another entry with a new VersionId"""
+def edit_wiki(comment_id: Optional[int]):
+    """Edit/Insert wiki comment. This is achieved by adding another entry with a new VersionId"""
     # FIXME: attempt to check and fix for types here with relevant errors
     payload: Dict[str, Any] = request.json  # type: ignore
     pubmed_ids = [str(x) for x in payload.get("pubmed_ids", [])]
@@ -48,13 +52,17 @@ def edit_wiki(comment_id: int):
     VALUES (%(Id)s, %(versionId)s, %(symbol)s, %(PubMed_ID)s, %(SpeciesID)s, %(comment)s, %(email)s, %(createtime)s, %(user_ip)s, %(weburl)s, %(initial)s, %(reason)s)
     """
     with db_utils.database_connection(current_app.config["SQL_URI"]) as conn:
-        cursor = conn.cursor()
-        next_version = 0
+        cursor, next_version = conn.cursor(), 0
+        if not comment_id:
+            comment_id = wiki.get_next_comment_id(cursor)
+            insert_dict["Id"] = comment_id
+        else:
+            next_version = wiki.get_next_comment_version(cursor, comment_id)
+
         try:
             category_ids = wiki.get_categories_ids(
                 cursor, payload["categories"])
             species_id = wiki.get_species_id(cursor, payload["species"])
-            next_version = wiki.get_next_comment_version(cursor, comment_id)
         except wiki.MissingDBDataException as missing_exc:
             return jsonify(error=f"Error editing wiki entry, {missing_exc}"), 500
         insert_dict["SpeciesID"] = species_id
@@ -83,7 +91,7 @@ def edit_wiki(comment_id: int):
                 sparql_auth_uri=current_app.config["SPARQL_AUTH_URI"]
             )
         except Exception as exc:
-            conn.rollback() # type: ignore
+            conn.rollback()  # type: ignore
             raise exc
         return jsonify({"success": "ok"})
     return jsonify(error="Error editing wiki entry, most likely due to DB error!"), 500
@@ -154,3 +162,57 @@ def get_history(comment_id):
         payload.headers["Content-Type"] = "application/ld+json"
         return payload, status_code
     return jsonify(data), status_code
+
+
+@rif_blueprint.route("/<string:symbol>", methods=["GET"])
+def get_ncbi_rif_entries(symbol: str):
+    """Fetch NCBI RIF entries"""
+    status_code = 200
+    response = get_rif_entries_by_symbol(
+        symbol,
+        sparql_uri=current_app.config["SPARQL_ENDPOINT"])
+    data = response.get("data")
+    if not data:
+        data, status_code = {}, 404
+    if request.headers.get("Accept") == "application/ld+json":
+        payload = make_response(response)
+        payload.headers["Content-Type"] = "application/ld+json"
+        return payload, status_code
+    return jsonify(data), status_code
+
+
+@wiki_blueprint.route("/delete", methods=["POST"], defaults={'comment_id': None})
+@wiki_blueprint.route("/<int:comment_id>/delete", methods=["POST"])
+@require_token
+def delete_wiki(comment_id: Optional[int] = None, **kwargs):  # pylint: disable=[unused-argument]
+    """Delete a wiki entry by its comment_id from both SQL and RDF."""
+    if comment_id is None:
+        return jsonify(error="comment_id is required for deletion."), 400
+    with (db_utils.database_connection(current_app.config["SQL_URI"]) as conn,
+          conn.cursor() as cursor):
+        try:
+            # Delete from SQL
+            delete_query = "DELETE FROM GeneRIF WHERE Id = %s"
+            current_app.logger.debug(
+                f"Running query: {delete_query} with Id={comment_id}")
+            cursor.execute(delete_query, (comment_id,))
+            # Delete from RDF
+            try:
+                delete_wiki_entries_by_id(
+                    wiki_id=comment_id,
+                    sparql_user=current_app.config["SPARQL_USER"],
+                    sparql_password=current_app.config["SPARQL_PASSWORD"],
+                    sparql_auth_uri=current_app.config["SPARQL_AUTH_URI"],
+                    graph="<http://genenetwork.org>"
+                )
+            # pylint: disable=W0718
+            except Exception as rdf_exc:
+                current_app.logger.error(f"RDF deletion failed: {rdf_exc}")
+                conn.rollback()
+                return jsonify(error="Failed to delete wiki entry from RDF store."), 500
+            return jsonify({"success": "Wiki entry deleted successfully."}), 200
+        # pylint: disable=W0718
+        except Exception as exc:
+            conn.rollback()
+            current_app.logger.error(f"Error deleting wiki entry: {exc}")
+            return jsonify(error="Error deleting wiki entry, most likely due to DB error!"), 500