aboutsummaryrefslogtreecommitdiffstats
path: root/apps/dav/lib/Controller/ExampleContentController.php
blob: 9146eeb639d85fa2738e43da770e395c81f73fba (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
<?php

declare(strict_types=1);

/**
 * SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

namespace OCA\DAV\Controller;

use OCA\DAV\AppInfo\Application;
use OCP\App\IAppManager;
use OCP\AppFramework\ApiController;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\JSONResponse;
use OCP\Files\AppData\IAppDataFactory;
use OCP\Files\IAppData;
use OCP\Files\NotFoundException;
use OCP\IConfig;
use OCP\IRequest;
use Psr\Log\LoggerInterface;

class ExampleContentController extends ApiController {
	private IAppData $appData;
	public function __construct(
		IRequest $request,
		private IConfig $config,
		private IAppDataFactory $appDataFactory,
		private IAppManager $appManager,
		private LoggerInterface $logger,
	) {
		parent::__construct(Application::APP_ID, $request);
		$this->appData = $this->appDataFactory->get('dav');
	}

	public function setEnableDefaultContact($allow) {
		if ($allow === 'yes' && !$this->defaultContactExists()) {
			try {
				$this->setCard();
			} catch (\Exception $e) {
				$this->logger->error('Could not create default contact', ['exception' => $e]);
				return new JSONResponse([], Http::STATUS_INTERNAL_SERVER_ERROR);
			}
		}
		$this->config->setAppValue(Application::APP_ID, 'enableDefaultContact', $allow);
		return new JSONResponse([], Http::STATUS_OK);
	}

	public function setDefaultContact(?string $contactData = null) {
		if (!$this->config->getAppValue(Application::APP_ID, 'enableDefaultContact', 'no')) {
			return new JSONResponse([], Http::STATUS_FORBIDDEN);
		}
		$this->setCard($contactData);
		return new JSONResponse([], Http::STATUS_OK);
	}

	private function setCard(?string $cardData = null) {
		try {
			$folder = $this->appData->getFolder('defaultContact');
		} catch (NotFoundException $e) {
			$folder = $this->appData->newFolder('defaultContact');
		}

		if (is_null($cardData)) {
			$cardData = file_get_contents(__DIR__ . '/../ExampleContentFiles/exampleContact.vcf');
		}

		if (!$cardData) {
			throw new \Exception('Could not read exampleContact.vcf');
		}

		$file = (!$folder->fileExists('defaultContact.vcf')) ? $folder->newFile('defaultContact.vcf') : $folder->getFile('defaultContact.vcf');
		$file->putContent($cardData);
	}

	private function defaultContactExists(): bool {
		try {
			$folder = $this->appData->getFolder('defaultContact');
		} catch (NotFoundException $e) {
			return false;
		}
		return $folder->fileExists('defaultContact.vcf');
	}

}