aboutsummaryrefslogtreecommitdiff
path: root/lib/admin/src/feedProperties/index.ts
blob: 733acde39e35f04a458a2acb78baee7085de40c7 (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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
// Copyright (C) 2023 Vaughn Nugent
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

import { cloneDeep, filter, forEach, isEmpty, join, map } from 'lodash';
import { watch, Ref, ref } from 'vue';
import { FeedProperty, XmlPropertyContainer } from '../types';

/**
 * An interface for working with xml properties from an xml feed
 */
export interface UseXmlProperties {

    /**
     * Correctly formats and exports the current properties
     */
    getCurrentProperties(): FeedProperty[] | undefined;

    /**
     * Gets the current properties as xml
     */
    getXml(): string | undefined;

    /**
     * Saves properties values from a json string
     * @param json The property json to parse
     * @returns True if the json was parsed and saved, false otherwise
     */
    saveJson: (json: string | undefined) => boolean;

    /**
     * Gets a copy of the current properties
    */
    getModel(): FeedProperty[] | undefined;

    /**
     * Manually adds an array of properties to the current properties
     */
    addProperties: (properties: FeedProperty[]) => void;
}

/**
 * Creates a new instance of the useXmlProperties api from the given feed
 * @param feed The feed to read and watch for changes from
 * @returns An api for working with xml properties
 */
export const useXmlProperties = <T extends XmlPropertyContainer>(feed: Ref<T | undefined>): UseXmlProperties => {

    //The current properties
    const currentProperties = ref<FeedProperty[]>(feed.value?.properties || []);

    //Watch for changes to the feed
    watch(feed, (newFeed) => { currentProperties.value = newFeed?.properties || [] }, { immediate: true });

    const getCurrentProperties = (): FeedProperty[] | undefined => {
        //Get all properties that are not emtpy
        return filter(currentProperties.value, p => !isEmpty(p.name));
    }

    const getPropertyXml = (properties: FeedProperty[]): string => {
        let output = '';
        forEach(properties, prop => {
            //Open tag (with namespace if present)
            output += !isEmpty(prop.namespace) ? `<${prop.namespace}:${prop.name}` : `<${prop.name}`

            if (!isEmpty(prop.attributes)) {
                forEach(prop.attributes, (value, key) => output += ` ${key}="${value}"`)
            }

            //Recursive call for nested property, or add its value
            output += !isEmpty(prop.properties) ? `>${getPropertyXml(prop.properties!)}` : `>${prop.value || ''}`

            //Close tag
            output += !isEmpty(prop.namespace) ? `</${prop.namespace}:${prop.name}>` : `</${prop.name}>`
            return output;
        })
        return output;
    }

    const getModel = (): FeedProperty[] | undefined => {
        return cloneDeep(currentProperties.value);
    }

    const getXml = (): string => {
        if (currentProperties.value === undefined) {
            return '';
        }
        return join(map(currentProperties.value, p => getPropertyXml([p])), '\n');
    }

    const saveJson = (json: string | undefined): boolean => {

        if (isEmpty(json)) {
            //Clear all properties if json is undefined
            currentProperties.value = [];
            return true
        }

        try {
            const parsed = JSON.parse(json!);

            const props = map(parsed, (prop) => ({
                name: prop.name,
                value: prop.value,
                namespace: prop.namespace,
                attributes: prop.attributes,
                properties: prop.properties
            }))

            //Remove any empty properties
            const nonEmpty = filter(props, p => !isEmpty(p.name));

            //Set the properties
            currentProperties.value = nonEmpty;

            return true;
        } catch (err) {
            return false;
        }
    }

    const addProperties = (properties: FeedProperty[]) => {
        currentProperties.value = [...currentProperties.value, ...properties];
    }

    return {
        getCurrentProperties,
        getXml,
        saveJson,
        getModel,
        addProperties
    }
}