Passed
Push — master ( 618e90...2ca7ea )
by Marcel
02:31
created

ApiDataController::addDataV2()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 29
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 3
eloc 19
c 4
b 0
f 0
nc 3
nop 1
dl 0
loc 29
rs 9.6333
1
<?php
2
/**
3
 * Analytics
4
 *
5
 * This file is licensed under the Affero General Public License version 3 or
6
 * later. See the LICENSE.md file.
7
 *
8
 * @author Marcel Scherello <[email protected]>
9
 * @copyright 2020 Marcel Scherello
10
 */
11
12
namespace OCA\Analytics\Controller;
13
14
use OCA\Analytics\Activity\ActivityManager;
15
use OCP\AppFramework\ApiController;
16
use OCP\AppFramework\Http;
17
use OCP\AppFramework\Http\DataResponse;
18
use OCP\ILogger;
19
use OCP\IRequest;
20
use OCP\IUserSession;
21
22
class ApiDataController extends ApiController
23
{
24
    const UNKNOWN = 9001;
25
    const MISSING_PARAM = 9002;
26
    const NOT_FOUND = 9003;
27
    const NOT_ALLOWED = 9004;
28
29
    protected $errors = [];
30
    private $logger;
31
    private $userSession;
32
    private $ActivityManager;
33
    private $DatasetController;
34
    private $StorageController;
35
36
    public function __construct(
37
        $appName,
38
        IRequest $request,
39
        ILogger $logger,
40
        IUserSession $userSession,
41
        ActivityManager $ActivityManager,
42
        DatasetController $DatasetController,
43
        StorageController $StorageController
44
    )
45
    {
46
        parent::__construct(
47
            $appName,
48
            $request,
49
            'POST'
50
            );
51
        $this->logger = $logger;
52
        $this->userSession = $userSession;
53
        $this->ActivityManager = $ActivityManager;
54
        $this->DatasetController = $DatasetController;
55
        $this->StorageController = $StorageController;
56
    }
57
58
    /**
59
     * add data via there database names
60
     * @CORS
61
     * @NoCSRFRequired
62
     * @NoAdminRequired
63
     * @param int $datasetId
64
     * @return DataResponse
65
     * @throws \Exception
66
     */
67
    public function addData(int $datasetId)
68
    {
69
        $params = $this->request->getParams();
70
        //$this->logger->debug($datasetId);
71
        $datasetMetadata = $this->DatasetController->getOwnDataset($datasetId);
72
73
        $this->deriveMaintenancePossible($datasetMetadata);
74
75
        if (!isset($params['dimension1'])) {
76
            $this->errors[] = 'Dimension 1 required';
77
        } elseif (!isset($params['dimension2'])) {
78
            $this->errors[] = 'Dimension 2 required';
79
        } elseif (!isset($params['dimension3'])) {
80
            $this->errors[] = 'Dimension 3 required';
81
        }
82
        if (!empty($this->errors)) {
83
            return $this->requestResponse(false, self::MISSING_PARAM, implode(',', $this->errors));
84
        }
85
86
        $this->StorageController->update($datasetId, $params['dimension1'], $params['dimension2'], $params['dimension3']);
87
        $this->ActivityManager->triggerEvent($datasetId, ActivityManager::OBJECT_DATA, ActivityManager::SUBJECT_DATA_ADD_API);
88
89
        return $this->requestResponse(
90
            true,
91
            Http::STATUS_OK,
92
            'Data update successfull');
93
    }
94
95
    /**
96
     * add data via there real field names
97
     * @CORS
98
     * @NoCSRFRequired
99
     * @NoAdminRequired
100
     * @param int $datasetId
101
     * @return DataResponse
102
     * @throws \Exception
103
     */
104
    public function addDataV2(int $datasetId)
105
    {
106
        $message = 'No -data- parameter';
107
        $params = $this->request->getParams();
108
        $this->logger->debug('array: ' . json_encode($params));
109
        $datasetMetadata = $this->DatasetController->getOwnDataset($datasetId);
110
111
        $this->deriveMaintenancePossible($datasetMetadata);
112
113
        foreach ($params['data'] as $dataArray) {
114
            $this->logger->debug('array: ' . json_encode($dataArray));
115
116
            $dimension1 = $this->deriveParameterNames($dataArray, $datasetMetadata, 'dimension1');
117
            $dimension2 = $this->deriveParameterNames($dataArray, $datasetMetadata, 'dimension2');
118
            $value = $this->deriveParameterNames($dataArray, $datasetMetadata, 'value');
119
120
            if (!empty($this->errors)) {
121
                return $this->requestResponse(false, self::MISSING_PARAM, implode(',', $this->errors));
122
            }
123
124
            $this->StorageController->update($datasetId, $dimension1, $dimension2, $value);
125
            $this->ActivityManager->triggerEvent($datasetId, ActivityManager::OBJECT_DATA, ActivityManager::SUBJECT_DATA_ADD_API);
126
            $message = 'Data update successfull';
127
        }
128
129
        return $this->requestResponse(
130
            true,
131
            Http::STATUS_OK,
132
            $message);
133
    }
134
135
    /**
136
     * delete data
137
     * @CORS
138
     * @NoCSRFRequired
139
     * @NoAdminRequired
140
     * @param int $datasetId
141
     * @return DataResponse
142
     * @throws \Exception
143
     */
144
    public function deleteDataV2(int $datasetId)
145
    {
146
        $message = 'No -delete- parameter';
147
        $params = $this->request->getParams();
148
        $this->logger->debug('array: ' . json_encode($params));
149
        $datasetMetadata = $this->DatasetController->getOwnDataset($datasetId);
150
151
        $this->deriveMaintenancePossible($datasetMetadata);
152
153
        foreach ($params['delete'] as $dataArray) {
154
            $dimension1 = $this->deriveParameterNames($dataArray, $datasetMetadata, 'dimension1');
155
            $dimension2 = $this->deriveParameterNames($dataArray, $datasetMetadata, 'dimension2');
156
157
            if (!empty($this->errors)) {
158
                return $this->requestResponse(false, self::MISSING_PARAM, implode(',', $this->errors));
159
            }
160
161
            $this->StorageController->delete($datasetId, $dimension1, $dimension2);
162
            $message = 'Data deleted';
163
        }
164
165
        return $this->requestResponse(
166
            true,
167
            Http::STATUS_OK,
168
            $message);
169
    }
170
171
    /**
172
     * derive if the parameter is technical or the free text description from the report
173
     * @param $data
174
     * @param $datasetMetadata
175
     * @param $dimension
176
     * @return array | bool
177
     */
178
    protected function deriveParameterNames($data, $datasetMetadata, $dimension)
179
    {
180
        if (isset($data[$dimension])) {
181
            return $data[$dimension];
182
        } elseif (isset($data[$datasetMetadata[$dimension]])) {
183
            return $data[$datasetMetadata[$dimension]];
184
        } else {
185
            $this->errors[] = $dimension . ' required';
186
            return false;
187
        }
188
    }
189
190
    /**
191
     * derive if maintenance is possible
192
     * @param $datasetMetadata
193
     * @return DataResponse | bool
194
     */
195
    protected function deriveMaintenancePossible($datasetMetadata)
196
    {
197
        if (empty($datasetMetadata)) {
198
            $this->errors[] = 'Unknown report or dataset';
199
            return $this->requestResponse(false, self::NOT_FOUND, implode(',', $this->errors));
200
        } elseif ((int)$datasetMetadata['type'] !== 2) {
201
            $this->errors[] = 'Report does not allow data maintenance';
202
            return $this->requestResponse(false, self::NOT_ALLOWED, implode(',', $this->errors));
203
        }
204
        return true;
205
    }
206
207
    /**
208
     * @param bool $success
209
     * @param int|null $code
210
     * @param string|null $message
211
     * @return DataResponse
212
     */
213
    protected function requestResponse($success, $code = null, $message = null)
214
    {
215
        if (!$success) {
216
            if ($code === null) {
217
                $code = self::UNKNOWN;
218
            }
219
            $array = [
220
                'success' => false,
221
                'error' => ['code' => $code,
222
                    'message' => $message
223
                ]
224
            ];
225
        } else {
226
            $array = [
227
                'success' => true,
228
                'message' => $message
229
            ];
230
        }
231
        $response = new DataResponse();
232
        $response->setData($array)->render();
233
        return $response;
234
    }
235
    // curl -u Admin:2sroW-SxRcK-AmdsF-RYMJ5-CKSyf -d '{"dimension1": "x", "dimension2": "x", "dimension3": "333,3"}' -X POST -H "Content-Type: application/json" http://nc18/nextcloud/apps/analytics/api/1.0/adddata/158
236
    // curl -u Admin:2sroW-SxRcK-AmdsF-RYMJ5-CKSyf -d '[{"Spalte 1": "x", "Spalte 2": "x", "toller wert": "333,3"}]' -X POST -H "Content-Type: application/json" http://nc18/nextcloud/apps/analytics/api/2.0/adddata/158
237
    // curl -u Admin:2sroW-SxRcK-AmdsF-RYMJ5-CKSyf -d '{"data":[{"Spalte 1": "a", "Spalte 2": "a", "toller wert": "1"}, {"dimension1": "b", "dimension2": "b", "value": "2"}]}' -X POST -H "Content-Type: application/json" http://nc18/nextcloud/apps/analytics/api/2.0/adddata/158
238
239
    // curl -u Admin:2sroW-SxRcK-AmdsF-RYMJ5-CKSyf -d '{"delete":[{"dimension1": "a", "dimension2": "a"}]}' -X POST -H "Content-Type: application/json" http://nc18/nextcloud/apps/analytics/api/2.0/deletedata/158
240
    // curl -u Admin:2sroW-SxRcK-AmdsF-RYMJ5-CKSyf -d '{"del":[{"dimension1": "a", "dimension2": "a"}]}' -X POST -H "Content-Type: application/json" http://nc18/nextcloud/apps/analytics/api/2.0/deletedata/158
241
242
}