12.4 KiB · text History 905ae26
import QtQuick
import QtQuick.Controls as QQC2
import QtQuick.Layouts
import org.kde.kirigami as Kirigami
import org.kde.kcmutils as KCM

import "Vigil.js" as Vigil

KCM.SimpleKCM {
    id: configGeneral

    property alias cfg_serverUrl: serverUrlField.text
    property alias cfg_accessToken: accessTokenField.text
    property string cfg_organization: ""
    property string cfg_projects: "[]"
    property alias cfg_foldOrg: foldCheckBox.checked

    property bool testing: false
    property string testResult: ""
    property bool testOk: false
    property string scopeNote: ""

    property var orgs: []
    property bool loadingProjects: false
    property string projectsError: ""
    property var projects: []           // the chosen org's, for the picker

    // What a token needs to show issues and monitors: the Mobile app
    // bundle's read scopes (Vigil.ApiTokens.mobile_read_scopes/0).
    readonly property var readScopes: ["org:read", "project:read", "event:read"]

    readonly property var chosen: Vigil.parseList(cfg_projects)
    readonly property bool everyProject: chosen.length === 0
    readonly property bool canConnect: serverUrlField.text.trim() !== "" && accessTokenField.text.trim() !== ""

    VigilAPI {
        id: testApi
        baseUrl: serverUrlField.text
        accessToken: accessTokenField.text
    }

    Component.onCompleted: if (canConnect) verify()

    // Called by the config dialog on Apply and OK: check what's being
    // saved, and say so here (the popup says so too, if the dialog closed).
    function saveConfig() {
        if (canConnect) verify()
    }

    // GET /api/0/: who the token is and its scopes, then the orgs.
    function verify() {
        if (!canConnect) {
            testOk = false
            testResult = i18n("Enter the address and a token first")
            return
        }
        testing = true
        testResult = ""
        scopeNote = ""
        testApi.whoami(function(ok, data) {
            testing = false
            if (!ok) {
                testOk = false
                testResult = data
                return
            }
            if (!data.user) {
                testOk = false
                testResult = i18n("The server didn't recognise that token")
                return
            }
            var scopes = data.auth && data.auth.scopes ? data.auth.scopes : []
            var who = data.user.name && data.user.name !== data.user.email
                      ? data.user.name + " <" + data.user.email + ">" : data.user.email
            testOk = true
            testResult = scopes.indexOf("event:write") !== -1
                         ? i18n("Connected as %1. The token can triage: resolve, ignore and assign.", who)
                         : i18n("Connected as %1. Read-only: no event:write, so the triage buttons are hidden.", who)
            var missing = readScopes.filter(function(s) { return scopes.indexOf(s) === -1 })
            if (missing.length > 0) scopeNote = i18n("Missing scopes: %1. Some of the widget won't load.", missing.join(", "))
            loadOrgs()
        })
    }

    function loadOrgs() {
        testApi.organizations(function(ok, data) {
            if (!ok) {
                projectsError = data
                return
            }
            orgs = data
            loadProjects()
        })
    }

    readonly property string orgSlug: {
        for (var i = 0; i < orgs.length; i++) if (orgs[i].slug === cfg_organization) return cfg_organization
        return orgs.length > 0 ? orgs[0].slug : cfg_organization
    }

    function loadProjects() {
        if (orgSlug === "") return
        loadingProjects = true
        projectsError = ""
        testApi.projects(orgSlug, function(ok, data) {
            loadingProjects = false
            if (!ok) {
                projectsError = data
                return
            }
            var list = data.slice()
            list.sort(function(a, b) { return (a.name || a.slug).localeCompare(b.name || b.slug) })
            projects = list
        })
    }

    // ── chosen list editing ─────────────────────────────────────────────

    function save(list) {
        cfg_projects = JSON.stringify(list)
    }

    function setEvery(on) {
        if (on) save([])
        else save(projects.map(function(p) { return p.slug }))
    }

    function toggle(slug, on) {
        var list = chosen.filter(function(x) { return x !== slug })
        if (on) list.push(slug)
        // Unticking the last one would read as "every project": keep it.
        if (list.length === 0) return
        save(list)
    }

    function move(index, delta) {
        var target = index + delta
        if (target < 0 || target >= chosen.length) return
        var list = chosen.slice()
        var x = list.splice(index, 1)[0]
        list.splice(target, 0, x)
        save(list)
    }

    function nameOf(slug) {
        for (var i = 0; i < projects.length; i++) if (projects[i].slug === slug) return projects[i].name || slug
        return slug
    }

    Kirigami.FormLayout {
        QQC2.TextField {
            id: serverUrlField
            Kirigami.FormData.label: i18n("Vigil address:")
            Layout.fillWidth: true
            placeholderText: "https://vigil.neiam.org"
            onEditingFinished: text = text.trim()
        }

        QQC2.TextField {
            id: accessTokenField
            Kirigami.FormData.label: i18n("API token:")
            Layout.fillWidth: true
            echoMode: TextInput.Password
            placeholderText: i18n("Paste the token")
            onEditingFinished: text = text.trim()
        }

        QQC2.Label {
            Layout.fillWidth: true
            Layout.maximumWidth: Kirigami.Units.gridUnit * 24
            wrapMode: Text.WordWrap
            font: Kirigami.Theme.smallFont
            color: Kirigami.Theme.disabledTextColor
            text: i18n("In Vigil, open Settings → API tokens, tick Mobile app and make a token. It's shown once. Its event:write scope lets the widget resolve, ignore and assign; tick Read-only too for a widget that only watches. Revoke it there to sign the widget out.")
        }

        RowLayout {
            QQC2.Button {
                text: i18n("Test Connection")
                icon.name: "network-connect"
                enabled: configGeneral.canConnect && !configGeneral.testing
                onClicked: configGeneral.verify()
            }
            QQC2.BusyIndicator {
                visible: configGeneral.testing
                running: visible
                Layout.preferredHeight: Kirigami.Units.iconSizes.medium
            }
        }

        QQC2.Label {
            visible: configGeneral.testResult !== ""
            Layout.fillWidth: true
            Layout.maximumWidth: Kirigami.Units.gridUnit * 24
            wrapMode: Text.WordWrap
            text: configGeneral.testResult
            color: configGeneral.testOk ? Kirigami.Theme.positiveTextColor : Kirigami.Theme.negativeTextColor
        }

        QQC2.Label {
            visible: configGeneral.scopeNote !== ""
            Layout.fillWidth: true
            Layout.maximumWidth: Kirigami.Units.gridUnit * 24
            wrapMode: Text.WordWrap
            text: configGeneral.scopeNote
            color: Kirigami.Theme.neutralTextColor
        }

        Kirigami.Separator {
            Kirigami.FormData.isSection: true
            Kirigami.FormData.label: i18n("Watching")
        }

        QQC2.ComboBox {
            id: orgPicker
            Kirigami.FormData.label: i18n("Organization:")
            visible: configGeneral.orgs.length > 0
            model: configGeneral.orgs.map(function(o) { return o.name || o.slug })
            currentIndex: {
                for (var i = 0; i < configGeneral.orgs.length; i++) if (configGeneral.orgs[i].slug === configGeneral.orgSlug) return i
                return -1
            }
            onActivated: function(index) {
                var slug = configGeneral.orgs[index].slug
                if (slug === configGeneral.cfg_organization) return
                configGeneral.cfg_organization = slug
                // Another org's projects: the old picks don't apply.
                configGeneral.cfg_projects = "[]"
                configGeneral.projects = []
                configGeneral.loadProjects()
            }
        }

        QQC2.Label {
            visible: configGeneral.orgs.length === 0
            Kirigami.FormData.label: i18n("Organization:")
            text: configGeneral.cfg_organization !== "" ? configGeneral.cfg_organization
                  : i18n("The first one the token sees (Test Connection to pick)")
            opacity: 0.7
        }

        QQC2.CheckBox {
            Kirigami.FormData.label: i18n("Projects:")
            text: i18n("Every project, as one circle")
            checked: configGeneral.everyProject
            enabled: configGeneral.projects.length > 0 || !checked
            onToggled: configGeneral.setEvery(checked)
        }

        QQC2.CheckBox {
            id: foldCheckBox
            visible: !configGeneral.everyProject
            text: i18n("Fold the chosen projects into one circle")
        }

        RowLayout {
            visible: configGeneral.loadingProjects || configGeneral.projectsError !== ""
            QQC2.BusyIndicator {
                visible: configGeneral.loadingProjects
                running: visible
                Layout.preferredHeight: Kirigami.Units.iconSizes.medium
            }
            QQC2.Label {
                visible: configGeneral.projectsError !== ""
                Layout.fillWidth: true
                wrapMode: Text.WordWrap
                color: Kirigami.Theme.negativeTextColor
                text: configGeneral.projectsError
            }
        }

        // Chosen projects, in circle order.
        ColumnLayout {
            visible: !configGeneral.everyProject
            Kirigami.FormData.label: i18n("Circles, in order:")
            Layout.fillWidth: true
            spacing: 0

            Repeater {
                model: configGeneral.chosen
                RowLayout {
                    required property var modelData
                    required property int index
                    Layout.fillWidth: true

                    QQC2.Label {
                        Layout.fillWidth: true
                        Layout.minimumWidth: Kirigami.Units.gridUnit * 12
                        text: configGeneral.nameOf(modelData)
                        elide: Text.ElideRight
                    }
                    QQC2.ToolButton {
                        icon.name: "go-up"
                        enabled: index > 0
                        onClicked: configGeneral.move(index, -1)
                    }
                    QQC2.ToolButton {
                        icon.name: "go-down"
                        enabled: index < configGeneral.chosen.length - 1
                        onClicked: configGeneral.move(index, 1)
                    }
                    QQC2.ToolButton {
                        icon.name: "list-remove"
                        enabled: configGeneral.chosen.length > 1
                        onClicked: configGeneral.toggle(modelData, false)
                    }
                }
            }
        }

        // The org's projects not chosen yet.
        ColumnLayout {
            readonly property var rest: configGeneral.projects.filter(function(p) { return configGeneral.chosen.indexOf(p.slug) === -1 })
            visible: !configGeneral.everyProject && rest.length > 0
            Kirigami.FormData.label: i18n("Add:")
            Layout.fillWidth: true
            spacing: 0

            Repeater {
                model: parent.rest
                RowLayout {
                    required property var modelData
                    Layout.fillWidth: true

                    QQC2.Label {
                        Layout.fillWidth: true
                        Layout.minimumWidth: Kirigami.Units.gridUnit * 12
                        text: modelData.platform ? i18n("%1 (%2)", modelData.name || modelData.slug, modelData.platform)
                                                 : (modelData.name || modelData.slug)
                        elide: Text.ElideRight
                    }
                    QQC2.ToolButton {
                        icon.name: "list-add"
                        onClicked: configGeneral.toggle(modelData.slug, true)
                    }
                }
            }
        }
    }
}