richdocuments/lib/Service/FontService.php
Julien Veyssier f2ce922721
cache font file name list
Signed-off-by: Julien Veyssier <eneiluj@posteo.net>
2022-05-02 13:05:58 +02:00

100 lines
2.7 KiB
PHP

<?php
/**
* @copyright Copyright (c) 2022 Julien Veyssier <eneiluj@posteo.net>
*
* @author Julien Veyssier <eneiluj@posteo.net>
*
* @license GNU AGPL version 3 or any later version
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Richdocuments\Service;
use OCA\Richdocuments\AppInfo\Application;
use OCP\Files\IAppData;
use OCP\Files\NotFoundException;
use OCP\Files\SimpleFS\ISimpleFile;
use OCP\Files\SimpleFS\ISimpleFolder;
use OCP\ICacheFactory;
class FontService {
private const INVALIDATE_FONT_LIST_CACHE_AFTER_SECONDS = 3600;
/**
* @var IAppData
*/
private $appData;
/**
* @var \OCP\ICache
*/
private $cache;
public function __construct(IAppData $appData,
ICacheFactory $cacheFactory) {
$this->appData = $appData;
$this->cache = $cacheFactory->createDistributed(Application::APPNAME);
}
private function getFontAppDataDir(): ISimpleFolder {
try {
return $this->appData->getFolder('fonts');
} catch (NotFoundException $e) {
return $this->appData->newFolder('fonts');
}
}
/**
* Get the list of available font files
*
*/
public function getFontFileNames(): array {
$cacheKey = 'fontFileNames';
$cachedNames = $this->cache->get($cacheKey);
if ($cachedNames === null) {
$fontDir = $this->getFontAppDataDir();
$cachedNames = array_map(
function (ISimpleFile $f) use ($fontDir) {
return $f->getName();
},
$fontDir->getDirectoryListing()
);
$this->cache->set($cacheKey, $cachedNames, self::INVALIDATE_FONT_LIST_CACHE_AFTER_SECONDS);
}
return $cachedNames;
}
public function uploadFontFile(string $fileName, $newFileResource): array {
$fontDir = $this->getFontAppDataDir();
$newFile = $fontDir->newFile($fileName, $newFileResource);
return [
'size' => $newFile->getSize(),
];
}
public function getFontFile(string $fileName): string {
$fontDir = $this->getFontAppDataDir();
return $fontDir->getFile($fileName)->getContent();
}
public function deleteFontFile(string $fileName): void {
$fontDir = $this->getFontAppDataDir();
if ($fontDir->fileExists($fileName)) {
$fontDir->getFile($fileName)->delete();
}
}
}