aboutsummaryrefslogtreecommitdiff
path: root/gn2/wqflask/edit.py
blob: 3b28482ecc3fc2ce8d6cf225b24802500bdc0f38 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import requests
import subprocess

from urllib.parse import urljoin
from pathlib import Path
from gn2.wqflask.oauth2.session import session_info

from pymonad.tools import curry
from pymonad.either import Either, Left

from flask import (Blueprint,
                   flash,
                   redirect,
                   render_template,
                   request)

from gn2.wqflask.decorators import login_required


metadata = Blueprint("metadata", __name__)


def save_dataset_metadata(
        git_dir: str, output: str,
        author: str, content: str, msg: str
) -> Either:
    """Save dataset metadata to git"""
    @curry(2)
    def __run_cmd(cmd, status_code):
        __result = subprocess.run(
            cmd, capture_output=True
        )
        if __result.stderr or status_code != 0:
            return Left({
                "command": cmd,
                "error": __result.stderr.decode()
            })
        return 0

    (Either.insert(0)
        .then(__run_cmd(f"git -C {git_dir} reset --hard origin".split(" ")))
        .then(__run_cmd(f"git -C {git_dir} pull".split(" "))))

    with Path(output).open(mode="w") as _f:
        _f.write(content)
    return (
        Either.insert(0)
        .then(__run_cmd(f"git -C {git_dir} add .".split(" ")))
        .then(__run_cmd(f"git -C {git_dir} commit -m".split(" ") + [f'{msg}', f"--author='{author}'", "--no-gpg-sign"]))
        .then(__run_cmd(f"git -C {git_dir} push origin master --dry-run".split(" ")))
    )


@metadata.route("/edit")
@login_required(pagename="Dataset Metadata Editing")
def metadata_edit():
    from gn2.utility.tools import GN3_LOCAL_URL
    __name = request.args.get("name")
    match request.args.get("type"):
        case "dcat:Dataset":
            __metadata = requests.get(
                urljoin(
                    GN3_LOCAL_URL,
                    f"api/metadata/datasets/{ __name }"
                )
            ).json()
            __section = request.args.get("section")
            return render_template(
                "metadata/editor.html",
                name=__name,
                metadata=__metadata,
                section=__section,
                edit=__metadata.get(__section),
            )


@metadata.route("/save", methods=["POST"])
@login_required(pagename="Dataset Metadata Editing")
def save():
    from gn2.utility.tools import get_setting
    __gn_docs = Path(
        get_setting("DATA_DIR"),
        "gn-docs"
    )
    __map = {
        "description": "summary.rtf",
        "tissueInfo": "tissue.rtf",
        "specifics": "specifics.rtf",
        "caseInfo": "cases.rtf",
        "platformInfo": "platform.rtf",
        "processingInfo": "processing.rtf",
        "notes": "notes.rtf",
        "experimentDesignInfo": "experiment-design.rtf",
        "acknowledgement": "acknowledgement.rtf",
        "citation": "citation.rtf",
        "experimentType": "experiment-type.rtf",
        "contributors": "contributors.rtf"
    }
    __output = Path(
        __gn_docs,
        "general/datasets/",
        request.form.get("id").split("/")[-1],
        f"{__map.get(request.form.get('section'))}"
    )
    __result = {}
    match request.form.get("type"):
        case "dcat:Dataset":
            __session = session_info()["user"]
            __author = f"{__session['name']} <{__session['email']}>"
            __result = save_dataset_metadata(
                git_dir=__gn_docs,
                output=__output,
                author=__author,
                content=request.form.get("editor"),
                msg=request.form.get("edit-summary")
            ).either(
                lambda error: flash(
                    f"{error=}",
                    "error"
                ),
                lambda x: flash(
                    "Successfully updated data.",
                    "success"
                )
            )
    return redirect(
        f"/datasets/{request.form.get('label')}"
    )