Compare commits

..

36 Commits

Author SHA1 Message Date
Aerex
7c972550ff docs: Cleaned up docs and added information on using cli 2021-07-05 15:41:03 -05:00
Aerex
5165567e63 chore: Updated composer file to use correct binary name 2021-07-05 15:40:46 -05:00
Aerex
ed4dc009fd feat: Added autocomplete file path in cli command 2021-07-05 15:40:16 -05:00
Aerex
a0b3e9548b refactor: Renamed the cli file 2021-07-05 15:39:45 -05:00
Aerex
31f781af0d Merge branch 'master' of github.com:Aerex/baikal-storage-plugin 2021-07-02 19:40:57 -05:00
Aerex
6cf5d4477b chore: Cleaned up code 2021-07-02 19:39:08 -05:00
Aerex
4db9237a5b chore: Generalized example config values 2021-07-02 19:38:50 -05:00
Aerex
b8963270ec chore: Added title to console command 2021-07-02 19:38:34 -05:00
9dda2d8127
Update README.md 2021-02-24 18:52:52 -06:00
Aerex
d87d4b0c5c feat: Added create config console command (support taskwarior) 2021-01-07 23:52:00 -06:00
Aerex
357531d329 fix: Retrieved displayname using getProperties from server obj
- chore: Cleaned up comments and plugin info
2020-10-09 01:12:57 -05:00
Aerex
a875bd8e2b chore: Fixed plugin description 2020-09-28 23:53:32 -05:00
Aerex
4140ded5b3 fix: Generalized import cal events not from source storages 2020-09-28 23:48:55 -05:00
Aerex
0a01e6e905 feat: Added tasks with no projects to default calendar 2020-09-18 22:15:12 -05:00
Aerex
ce60c373f8 test: Fixed unit tests directory path 2020-09-13 01:29:05 -05:00
Aerex
1217c2f5e4 refactor(tw): Removed unused project_prefix_suffix config 2020-09-13 01:26:22 -05:00
Aerex
444db318e7 fix: Ignored processing delete calendar requests 2020-08-23 17:39:56 -05:00
Aerex
bf9a55de0e fix: Prevent importing calendar tasks if coming from taskwarrior cli 2020-07-31 02:41:04 -05:00
Aerex
f63e2d0e2e fix: Used completed property instead of dtend in vtodo event 2020-07-31 02:35:51 -05:00
Aerex
a89dd17991 feat: Added deleting task when ical todo delete has been sent
- feat: Added warn logger method to logger class
2020-06-27 00:56:44 -05:00
Aerex
98eb84b3b6 feat: Added config html page for storages on baikal browser
feat(tw): Used RELATED-TO iCal prop as depends prop
feat(tw): Used DESCRIPTION iCal prop as annotations
refactor(tw): Changed project_tag_prefix to project_category_prefix
chore(tw): Added documentation on configs
2020-06-14 23:55:05 -05:00
Aerex
df7ab092cc fix: Added logger as a dependency for storage class 2020-06-11 11:43:56 -05:00
Aerex
8cafda3f26 fix: Upgraded sabre/dav 2020-06-11 11:24:06 -05:00
Aerex
b9d27d9aa2 fix: Upgrade sabre/dav 2020-06-11 11:21:28 -05:00
Aerex
728fce1b78 fix: Created log file if files does not exist 2020-06-11 11:10:45 -05:00
Aerex
c302c4653a feat(tw): Applied timezone to datetimes that are not given in local time 2020-06-03 00:46:06 -05:00
Aerex
c2e181aa75 refactor: Added general config validations and timezone config 2020-06-03 00:04:43 -05:00
Aerex
00d0ea624f fix(tw): Reloaded tasks into object array for refresh
- chore(tw): Wrapped import function in try catch and logged error
2020-06-02 21:16:18 -05:00
Aerex
2f87752f6e fix: Used ArrayNodeDefinition to append taskwarrior config to main
config
2020-05-29 11:45:53 -05:00
Aerex
346e5c239b feat(tw): Added project_tag_suffix config to use tag for tw project 2020-05-28 11:54:21 -05:00
Aerex
9d78b4a8eb fix: Downgraded symfony/yaml to fix dep confilicts 2020-05-13 00:12:36 -05:00
Aerex
84ecfb5ad1 feat: Added missing symfony/yaml dep 2020-05-13 00:09:35 -05:00
Aerex
40b66fb38b feat: Converted vcalendar todo events to taskwarrior tasks 2020-05-12 23:56:22 -05:00
Aerex
45ea34da94 fix: Created config directory recursively 2020-05-05 00:04:31 -05:00
Aerex
56eb7e7571 fix: Used correct declaration for setRawConfigs
- chore: Added README
2020-05-04 23:39:00 -05:00
Aerex
51b51e3de8 chore: Downgrade symfony/config to ^3.4 2020-05-04 23:25:11 -05:00
22 changed files with 933 additions and 152 deletions

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
vendor/ vendor/
main.uml main.uml
composer.lock composer.lock
.phpunit.result.cache

25
README.md Normal file
View File

@ -0,0 +1,25 @@
# baikal-storage-plugin
## Note
Plugin is still a work in progress
## Install
```
composer require aerex/baikal-storage-plugin
```
## Configuration
You can use the CLI to help you generate a config file or use the example configuration provided in the project. Make sure the file is *writable* by your webserver (e.g Apache, Nginx).
### Use the CLI
Run the command `./vendor/baikalstorage` and follow the instructions
### Manual
Copy the `example-config.yaml` file and rename it to `config.yaml`.
## Usage
- Add the plugin to the end of the `Server.php` file located under `Core/Frameworks/Baikal/Core/Server.php`. For example
```
$this->server->addPlugin(new \Aerex\BaikalStorage\Plugin(<absolute/path/of/config.yaml)
```

12
bin/baikalstorage Executable file
View File

@ -0,0 +1,12 @@
#!/usr/bin/env php
<?php
require __DIR__.'/../vendor/autoload.php';
use Symfony\Component\Console\Application;
use Aerex\BaikalStorage\Commands\CreateConfigFileCommand;
$application = new Application();
$application->add(new CreateConfigFileCommand());
$application->setName('Baikal Storage Plugin');
$application->run();

View File

@ -15,20 +15,25 @@
"url": "https://git.aerex.me/Aerex/baikal-storage-plugin" "url": "https://git.aerex.me/Aerex/baikal-storage-plugin"
} }
], ],
"bin": [
"bin/baikalstorage"
],
"require": { "require": {
"php": ">=5.5", "php": ">=5.5",
"sabre/dav" : "~4.0.2", "sabre/dav" : "~4.1.0",
"sabre/vobject": "^4.0", "sabre/vobject": "^4.0",
"easycorp/easy-log-handler": "^1.0",
"nesbot/carbon": "^2.0.0", "nesbot/carbon": "^2.0.0",
"laminas/laminas-validator": "^2.13", "laminas/laminas-validator": "^2.13",
"laminas/laminas-stdlib": "^3.2", "laminas/laminas-stdlib": "^3.2",
"psr/container": "^1.0", "psr/container": "^1.0",
"symfony/config": "^5.0", "symfony/config": "3.4",
"symfony/process": "^3.4" "symfony/process": "^3.4",
"monolog/monolog": "^2.0",
"symfony/yaml": "~3.0|~4.0",
"symfony/console": "^3.4|^4.0|^5.0"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "^7.4" "phpunit/phpunit": "^8.5.3"
}, },
"authors": [ "authors": [
{ {

6
example-config.yaml Executable file
View File

@ -0,0 +1,6 @@
logger:
file: /home/user/baikal-storage-plugin.log
level: 'DEBUG'
taskwarrior:
taskdata: /home/user/.task
taskrc: /home/user/.taskrc

10
lib/Browser.php Normal file
View File

@ -0,0 +1,10 @@
<?php
class Browser {
public function generateDropDown(
}

View File

@ -0,0 +1,158 @@
<?php
namespace Aerex\BaikalStorage\Commands;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Question\Question;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ChoiceQuestion;
use Monolog\Logger as Monolog;
use Aerex\BaikalStorage\Configs\ConfigBuilder;
class CreateConfigFileCommand extends Command {
protected $io;
protected static $defaultName = 'app:create-config';
protected static $CONFIG_FILE_NAME = 'config.yaml';
protected static $LOGGER_FILE_NAME = 'log';
private $configs = [];
private $fullFilePath;
public function addtaskwarriorConfig() {
$configs = [];
$filePath = $this->io->askQuestion(new Question('Where is the location for the taskrc file?'));
$taskrcFilePath = $filePath . '/.taskrc';
if (!file_exists($taskrcFilePath)) {
throw new \RuntimeException("The taskrc file at $taskrcFilePath does not exist");
}
$configs['taskrc'] = $taskrcFilePath;
$filePath = $this->io->askQuestion(new Question('Where is the data location (taskdata)'));
$taskDataFilePath = $filePath;
if (!file_exists($taskDataFilePath)) {
throw new \RuntimeException("The task.data location $taskDataFilePath does not exist");
}
$configs['taskdata'] = $taskDataFilePath;
$displayName = $this->io->askQuestion(new Question('What is the displayname for the default calendar (e.g default)'));
$configs['default_calendar'] = isset($displayName) ? $displayName : 'default';
$this->configs['storages']['taskwarior'] = $configs;
}
protected function configure() {
$this
->setName('create-config')
->setDescription('Create baikal storage plugin configuration file');
}
protected function autocompleteFilePathCallback(string $input): array {
// Strip any characters from the last slash to the end of the string
// to keep only the last directory and generate suggestions for it
$inputPath = preg_replace('%(/|^)[^/]*$%', '$1', $input);
$inputPath = '' === $inputPath ? '.': $inputPath;
$foundFilesAndDirs = scandir($inputPath) ?: [];
// Excluded restricted directories
$restrictedDirs = ['dev', 'bin', 'boot', 'etc', 'input', 'lib',
'lib64', 'mnt', 'proc', 'run', 'sbin', 'sys', 'srv', 'usr', 'var'];
$foundSafeFileAndDirs = array_diff($foundFilesAndDirs, $restrictedDirs);
return array_map(function($dirOrFile) use ($inputPath) {
return $inputPath.$dirOrFile;
}, $foundSafeFileAndDirs);
}
protected function execute(InputInterface $input, OutputInterface $output) {
$this->io = new SymfonyStyle($input, $output);
$this->io->title('Baikal Storage Plugin Configuration Creation');
// TODO: move create config file code block to function
$question = new Question('Where to create `config.yaml` configuration file?');
$question->setAutocompleterCallback($this->autocompleteFilePathCallback);
$filePath = $this->io->askQuestion($question);
try {
$this->fullFilePath = $this->verifyAndCreateFile($filePath, CreateConfigFileCommand::$CONFIG_FILE_NAME);
$this->setupGeneralConfigs()
->setupStorages()
->saveConfigs();
} catch (\Exception $e) {
return Command::FAILURE;
}
$this->output->writeln("`config.yaml file created at $filePath");
return Command::SUCCESS;
}
protected function getStorageNames() {
$storageDir = __DIR__ . '/../Storages';
$storageFiles = scandir($storageDir);
$storages = array_values(array_filter($storageFiles, function($storageFile) use ($storageDir) {
return !preg_match('/^IStorage/', $storageFile) && !is_dir("$storageDir/$storageFile");
}));
array_walk($storages, function(&$storage) {
$storage = strtolower(preg_replace('/\.php/', '', $storage));
});
return $storages;
}
protected function verifyAndCreateFile($filePath, $fileName) {
if (empty($filePath)) {
throw new \RuntimeException('Configuration file path cannot be empty');
}
if (!is_dir($filePath)) {
throw new \RuntimeException("File path $filePath does not exist");
}
if ((strrpos($filePath, '/') + 1) === strlen($filePath)) {
$fullFilePath = substr($filePath, 0, -1) . $fileName;
} else {
$fullFilePath = $filePath . '/' . $fileName;
}
if (file_exists($fullFilePath)) {
throw new \RuntimeException("The configuration file at $this->fullFilePath already exists");
}
return $fullFilePath;
}
protected function setupGeneralConfigs() {
$this->io->section('Setting up general configurations');
$this->configs['general'] = [];
if ($this->io->confirm('Enable logging?')) {
$this->configs['general']['logger'] = [];
$logFilePath = $this->io->askQuestion(new Question('Where to create log file?'));
$this->configs['general']['logger']['file'] = $this->verifyAndCreateFile($logFilePath, CreateConfigFileCommand::$LOGGER_FILE_NAME);
$logLevelChoiceQuestion = new ChoiceQuestion('Log level (defaults to ERROR)', array_keys(Monolog::getLevels()), 4);
$logLevelChoiceQuestion->setErrorMessage('Log level %s is invalid');
$logLevel = $this->io->askQuestion($logLevelChoiceQuestion);
$this->configs['general']['logger']['level'] = $logLevel;
}
return $this;
}
protected function setupStorages() {
$this->configs['storages'] = [];
$this->io->section('Setup storage configurations');
$storagesMultiSelectQuestion = new ChoiceQuestion('Select the storages to add', $this->getStorageNames());
$storagesMultiSelectQuestion->setMultiselect(true);
$storagesMultiSelectQuestion->setErrorMessage('Storages %s is not supported');
$storages = $this->io->askQuestion($storagesMultiSelectQuestion);
foreach ($storages as $storage) {
$methodName = "add${storage}Config";
$storageConfigMethod = new \ReflectionMethod(CreateConfigFileCommand::class, $methodName);
$storageConfigMethod->invoke($this);
}
return $this;
}
protected function saveConfigs() {
$configBuilder = new ConfigBuilder($this->fullFilePath);
$configBuilder->saveConfigs($this->configs);
}
}

View File

@ -11,7 +11,7 @@ class ConfigBuilder implements ConfigurationInterface {
private $configs = []; private $configs = [];
private $configFile; private $configFile;
public function __construct($configFile = '~/.config/baikal') { public function __construct($configFile) {
$this->configFile = $configFile; $this->configFile = $configFile;
$this->processor = new Processor(); $this->processor = new Processor();
} }
@ -21,9 +21,28 @@ class ConfigBuilder implements ConfigurationInterface {
} }
public function getConfigTreeBuilder() { public function getConfigTreeBuilder() {
$treeBuilder = new TreeBuilder('configs'); $treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->getRootNode(); $rootNode = $treeBuilder->root('configs');
$ref = $rootNode->children(); $ref = $rootNode->children()
->arrayNode('general')
->children()
->arrayNode('logger')
->canBeEnabled()
->children()
->scalarNode('file')->end()
->scalarNode('level')
->defaultValue('ERROR')
->validate()
->IfNotInArray(['DEBUG', 'INFO', 'NOTICE', 'WARNING', 'ERROR', 'CRITICAL', 'ALERT', 'EMERGENCY'])
->thenInvalid('Invalid log level %s')
->end()
->end()
->end()
->end()
->end()
->end()
->arrayNode('storages')
->children();
foreach ($this->configs as $config) { foreach ($this->configs as $config) {
$ref = $ref->append($config->get()); $ref = $ref->append($config->get());
} }
@ -32,11 +51,7 @@ class ConfigBuilder implements ConfigurationInterface {
} }
public function readContent() { public function readContent() {
if (!is_dir($this->configFile)) { return file_get_contents($this->configFile);
mkdir($this->configFile);
}
$contents = sprintf('%s/storage.yml', $this->configFile);
return file_get_contents($contents);
} }
public function loadYaml() { public function loadYaml() {
@ -44,4 +59,9 @@ class ConfigBuilder implements ConfigurationInterface {
$parseContents = Yaml::parse($contents); $parseContents = Yaml::parse($contents);
return $this->processor->processConfiguration($this, [$parseContents]); return $this->processor->processConfiguration($this, [$parseContents]);
} }
public function saveConfigs($configs) {
$yaml = Yaml::dump($configs, 3, 2);
file_put_contents($this->configFile, $yaml);
}
} }

View File

@ -2,16 +2,27 @@
namespace Aerex\BaikalStorage\Configs; namespace Aerex\BaikalStorage\Configs;
use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
class TaskwarriorConfig { class TaskwarriorConfig {
public function get() { public function get() {
$treeBuilder = new TreeBuilder('taskwarrior'); $node = new ArrayNodeDefinition('taskwarrior');
$node = $treeBuilder->getRootNode(); $node->canBeEnabled()
$node->children() ->children()
->scalarNode('data_dir') ->scalarNode('taskdata')
->defaultValue('~/.task') ->defaultValue('~/.task')
->end(); ->info('The environment variable overrides the default and the command line, and the "data.location" configuration setting of the task data directory')
->end()
->scalarNode('taskrc')
->defaultValue('~/.taskrc')
->info('The enivronment variable overrides the default and the command line specification of the .taskrc file')
->end()
->scalarNode('default_calendar')
->info('The default calendar to send tasks if no task project is set. The value is the calendar\'s displayname')
->end()
->end();
return $node; return $node;
} }
} }

View File

@ -16,22 +16,23 @@ class Console extends AbstractConsole {
if (is_array($input)) { if (is_array($input)) {
return json_encode($input); return json_encode($input);
} }
return $input;
} }
public function execute($cmd, $args, $input = null) { public function execute($cmd, $args, $input = null, $envs = []) {
$stdin[] = $cmd; $stdin[] = $cmd;
$stdin[] = array_merge($stdin, $this->defaultArgs, $args); $stdin = array_merge($stdin, $this->defaultArgs, $args);
if (isset($input)) { if (isset($input)) {
$stdin[] = $this->convertToString($input); $input = $this->convertToString($input);
$process = new Process($stdin);
} }
$process = new Process(implode(' ', $stdin), null, $envs, $input);
$process->inheritEnvironmentVariables();
try { try {
$process->mustRun(); $process->mustRun();
return $process->getOutput(); return $process->getOutput();
} catch (ProcessFailedException $error) { } catch (ProcessFailedException $error) {
echo $error->getMessage();
throw $error; throw $error;
} }
} }

77
lib/Logger.php Normal file
View File

@ -0,0 +1,77 @@
<?php
namespace Aerex\BaikalStorage;
use Monolog\Logger as Monolog;
use Monolog\Handler\StreamHandler;
class Logger {
private $configs = ['enabled' => false];
function __construct($configs, $tag) {
if (isset($configs['general']) && isset($configs['general']['logger'])) {
$this->configs = $configs['general']['logger'];
}
if ($this->configs['enabled']) {
$this->createLoggerFile();
$this->logger = new Monolog($tag);
$logLevel = Monolog::getLevels()[$this->configs['level']];
$this->logger->pushHandler(new StreamHandler($this->configs['file'], $logLevel));
}
}
public function createLoggerFile() {
if (!file_exists($this->configs['file'])) {
if (!fopen($this->configs['file'], 'w')) {
throw new \Exception(sprintf('Could not create logger file %s', $this->configs['file']));
}
}
}
public function debug($message) {
if ($this->configs['enabled']) {
$this->logger->debug($message);
}
}
public function info($message) {
if ($this->configs['enabled']) {
$this->logger->info($message);
}
}
public function notice($message) {
if ($this->configs['enabled']) {
$this->logger->notice($message);
}
}
public function warn($message) {
if ($this->configs['enabled']) {
$this->logger->warning($message);
}
}
public function error($message) {
if ($this->configs['enabled']) {
$this->logger->error($message);
}
}
public function critical($message) {
if ($this->configs['enabled']) {
$this->logger->critical($message);
}
}
public function alert($message) {
if ($this->configs['enabled']) {
$this->logger->alert($message);
}
}
public function emergency($message) {
if ($this->configs['enabled']) {
$this->logger->emergency($message);
}
}
}

View File

@ -2,6 +2,8 @@
namespace Aerex\BaikalStorage; namespace Aerex\BaikalStorage;
use Aerex\BaikalStorage\Logger;
use Monolog\Logger as Monolog;
use Aerex\BaikalStorage\Storages\Taskwarrior; use Aerex\BaikalStorage\Storages\Taskwarrior;
use Aerex\BaikalStorage\Configs\ConfigBuilder; use Aerex\BaikalStorage\Configs\ConfigBuilder;
use Aerex\BaikalStorage\Configs\TaskwarriorConfig; use Aerex\BaikalStorage\Configs\TaskwarriorConfig;
@ -32,25 +34,36 @@ class Plugin extends ServerPlugin {
protected $storageManager; protected $storageManager;
/** /**
* @var ConfigBuilder * @var $rawconfigs
*/ */
protected $rawConfigs;
protected $config;
/** /**
* Creates the Taskwarrior plugin * Creates the Storage plugin
* *
* @param CalendarProcessor $TWCalManager * @param CalendarProcessor $TWCalManager
* *
*/ */
function __construct($config = null){ function __construct($configFile){
if (isset($config)) { $this->rawConfigs = $this->buildConfigurations($configFile);
$this->config = $config; $this->storageManager = new StorageManager($this->rawConfigs);
} else { $this->initializeStorages($this->rawConfigs);
$this->config = new ConfigBuilder(); }
}
$this->storageManager = new StorageManager($this->config); private function getDisplayName($path) {
$this->addStorages(); // Remove filepath (e.g Remove xxxx.ics from calendars/collection_name/xxxx.ics)
$urlParts = explode('/', $path);
$calendarUrl = implode('/', array_slice($urlParts, 0, sizeof($urlParts)-1));
// Get displayname from collection
$properties = $this->server->getProperties($calendarUrl, ['{DAV:}displayname']);
return $properties['{DAV:}displayname'] ?? '';
}
public function buildConfigurations($configFile) {
$this->config = new ConfigBuilder($configFile);
$this->config->add(new TaskwarriorConfig());
return $this->config->loadYaml();
} }
/** /**
@ -58,10 +71,10 @@ class Plugin extends ServerPlugin {
* *
*/ */
public function addStorages() { public function initializeStorages($configs) {
$taskwarrior = new Taskwarrior(new Console(['rc.verbose=nothing', 'rc.hooks=off']), new TaskwarriorConfig()); $taskwarrior = new Taskwarrior(new Console(['rc.verbose=nothing',
'rc.hooks=off', 'rc.confirmation=no']), $configs, new Logger($configs, 'Taskwarrior'));
$this->storageManager->addStorage(Taskwarrior::NAME, $taskwarrior); $this->storageManager->addStorage(Taskwarrior::NAME, $taskwarrior);
$this->storageManager->init();
} }
/** /**
@ -85,14 +98,13 @@ class Plugin extends ServerPlugin {
*/ */
function getPluginName() { function getPluginName() {
return 'taskwarrior'; return 'baikal-storage';
} }
/** /**
* This method is called before any HTTP method handler. * This method is called before any HTTP method handler.
* *
* This method intercepts any GET, DELETE, PUT and PROPFIND calls to * This method intercepts any GET, DELETE, PUT and PROPFIND.
* filenames that are known to match the 'temporary file' regex.
* *
* @param RequestInterface $request * @param RequestInterface $request
* @param ResponseInterface $response * @param ResponseInterface $response
@ -105,11 +117,15 @@ class Plugin extends ServerPlugin {
switch ($request->getMethod()) { switch ($request->getMethod()) {
case 'PUT': case 'PUT':
$this->httpPut($request, $response); $this->httpPut($request, $response);
break;
case 'POST':
$this->httpPost($request, $response);
break;
case 'DELETE':
$this->httpDelete($request);
return;
} }
return;
} }
/** /**
* This method handles the PUT method. * This method handles the PUT method.
@ -121,8 +137,11 @@ class Plugin extends ServerPlugin {
function httpPut(RequestInterface $request){ function httpPut(RequestInterface $request){
$body = $request->getBodyAsString(); $body = $request->getBodyAsString();
$vCal = \Sabre\VObject\Reader::read($body); $vCal = \Sabre\VObject\Reader::read($body);
$displayname = $this->getDisplayName($request->getPath());
try { try {
$this->storageManager->import($vCal); if (!$this->storageManager->fromStorageSource($vCal)) {
$this->storageManager->import($vCal, $displayname);
}
} catch(BadRequest $e){ } catch(BadRequest $e){
throw new BadRequest($e->getMessage(), null, $e); throw new BadRequest($e->getMessage(), null, $e);
} catch(\Exception $e){ } catch(\Exception $e){
@ -133,6 +152,139 @@ class Plugin extends ServerPlugin {
} }
/**
* This method handles the POST method.
*
* @param RequestInterface $request
*
*/
function httpPost(RequestInterface $request, ResponseInterface $response) {
$postVars = $request->getPostData();
$body = $request->getBodyAsString();
if (isset($postVars['baikalStorage'])) {
foreach ($this->storageManager->getStorages() as $storage) {
if ($storage::NAME == $postVars['baikalStorage']
&& $postVars['baikalStorageAction'] == 'saveConfigs') {
$updateStorageConfigs = $storage->updateConfigs($postVars);
$this->rawConfigs['storages'][$postVars['baikalStorage']] = $updateStorageConfigs;
}
}
}
if (isset($postVars['logLevel'])) {
$this->rawConfigs['general']['logger']['level'] = $postVars['logLevel'];
}
if (isset($postVars['logFilePath'])) {
$this->rawConfigs['general']['logger']['file'] = $postVars['logFilePath'];
}
$this->config->saveConfigs($this->rawConfigs);
$response->setHeader('Location', $request->getUrl());
$response->setStatus(302);
$request->setBody($body);
}
/**
* This method handles the DELETE method.
*
* @param RequestInterface $request
* @param ResponseInterface $response
*
*/
public function httpDelete(RequestInterface $request) {
try {
$body = $request->getBodyAsString();
$path = $request->getPath();
$paths = explode('/', $path);
if (sizeof($paths) > 1) {
$uid = str_replace('.ics', '', $paths[sizeof($paths)-1]);
// Attempt to delete if we are removing an ics file
if ($uid != '') {
$this->storageManager->remove($uid);
}
}
} catch(BadRequest $e){
throw new BadRequest($e->getMessage(), null, $e);
} catch(\Exception $e){
throw new \Exception($e->getMessage(), null, $e);
}
$request->setBody($body);
}
/**
* Generates the 'general' configuration section
* @return string
*/
public function generateGeneralConfigSection() {
$configuredLogLevel = '';
$logFilePath = '';
if (isset($this->rawConfigs['general'])
&& isset($this->rawConfigs['general']['logger'])
&& $this->rawConfigs['general']['logger']['enabled']) {
$configuredLogLevel = $this->rawConfigs['general']['logger']['level'];
$logFilePath = $this->rawConfigs['general']['logger']['file'];
}
$html = '<form method="post" action="">';
$html .= '<section><h1>Configuration - Baikal Storage</h1>';
$html .= '<section><h2>general</h2>';
$html .= '<table class="propTable">';
$html .= '<tr>';
$html .= '<th>log level</th>';
$html .= '<td>The minimum log level </td>';
$html .= '<td>';
$html .= '<select name="logLevel">';
foreach (Monolog::getLevels() as $key => $value) {
if ($key == $configuredLogLevel) {
$selected = ' selected ';
} else {
$selected = '';
}
$html .= '<option value="'. $key .'"' . $selected . '>'. $key .'</option>';
}
$html .= '</select>';
$html .= '</tr>';
$html .= '<tr>';
$html .= '<th>log file path</th>';
$html .= '<td>The absolute file path of the log</td>';
$html .= '<td><input name="logFilePath" placeholder="/opt/baikal/log" value='. $logFilePath . ' type="text" id="logFilePath"></input></td>';
$html .= '</tr>';
$html .= '<tr>';
$html .= '</table>';
$html .= '</section>';
return $html;
}
/**
* Returns a html to display an optional configuration page for the plugin
* @return array
*/
public function getConfigBrowser() {
$html = $this->generateGeneralConfigSection();
foreach ($this->storageManager->getStorages() as $storage) {
$html .= '<section>';
$html .= '<h2>' . $storage::NAME . '</h2>';
$html .= '<table class="propTable">';
$html .= '<input type="hidden" name="baikalStorageAction" value="saveConfigs"></input>';
$html .= '<input type="hidden" name="baikalStorage" value="taskwarrior"></input>';
$html .= $storage->getConfigBrowser();
$html .= '</table>';
$html .= '</section>';
$html .= '<input type="submit" value="save"></input>';
$html .= '</form>';
}
return $html;
}
/** /**
* Returns a bunch of meta-data about the plugin. * Returns a bunch of meta-data about the plugin.
* *
@ -148,9 +300,11 @@ class Plugin extends ServerPlugin {
return [ return [
'name' => $this->getPluginName(), 'name' => $this->getPluginName(),
'description' => 'The plugin provides synchronization between taskwarrior tasks and iCAL events', 'description' => 'The plugin provides synchronization between remote storages and iCal todo events',
'link' => null, 'link' => 'https://git.aerex.me/Aerex/baikal-storage-plugin',
'config' => true
]; ];
} }
} }

View File

@ -3,7 +3,6 @@
namespace Aerex\BaikalStorage; namespace Aerex\BaikalStorage;
use Sabre\VObject\Component\VCalendar as Calendar; use Sabre\VObject\Component\VCalendar as Calendar;
use Aerex\BaikalStorage\Configs\ConfigBuilder;
class StorageManager { class StorageManager {
@ -15,13 +14,24 @@ class StorageManager {
/** /**
* @var Config * @var array()
*/ */
private $configBuilder;
private $configs; private $configs;
public function __construct($configBuilder){ public function __construct($configs){
$this->configBuilder = $configBuilder; $this->configs = $configs;
}
public function fromStorageSource(Calendar $calendar) {
if (!isset($this->configs)) {
throw new \Exception('StorageManager was not initialize or configs are not defined');
}
foreach ($this->configs['storages'] as $storage => $value) {
if (stristr($calendar->PRODID, $storage)) {
return true;
}
}
return false;
} }
public function getStorages() { public function getStorages() {
@ -33,25 +43,33 @@ class StorageManager {
} }
public function addStorage($name, $storage) { public function addStorage($name, $storage) {
$this->configBuilder->add($storage->getConfig());
$this->storages[$name] = $storage; $this->storages[$name] = $storage;
} }
public function init() { public function import(Calendar $calendar, string $displayname) {
$this->configs = $this->configBuilder->loadYaml();
}
public function import(Calendar $calendar) {
if (!isset($this->configs)) { if (!isset($this->configs)) {
throw new \Exception('StorageManger was not initialize or configs are not defined'); throw new \Exception('StorageManger was not initialize or configs are not defined');
} }
foreach ($this->configs as $key => $value) { foreach ($this->configs['storages'] as $key => $value) {
$storage = $this->storages[$key]; $storage = $this->storages[$key];
if (!isset($storage)){ if (!isset($storage)){
throw new \Exception(); throw new \Exception();
} }
$storage->setRawConfigs($this->configs[$key]); $storage->save($calendar, $displayname);
$storage->save($calendar); }
}
public function remove($uid) {
if (!isset($this->configs)) {
throw new \Exception('StorageManger was not initialize or configs are not defined');
}
foreach ($this->configs['storages'] as $key => $value) {
$storage = $this->storages[$key];
if (!isset($storage)){
throw new \Exception();
}
$storage->remove($uid);
} }
} }
} }

View File

@ -5,8 +5,10 @@ namespace Aerex\BaikalStorage\Storages;
use Sabre\VObject\Component\VCalendar as Calendar; use Sabre\VObject\Component\VCalendar as Calendar;
interface IStorage { interface IStorage {
public function save(Calendar $c); public function save(Calendar $c, string $displayname);
public function remove($uid);
public function refresh(); public function refresh();
public function getConfig(); public function getConfigBrowser();
public function setRawConfigs(); public function updateConfigs($postData);
} }

View File

@ -3,87 +3,228 @@
namespace Aerex\BaikalStorage\Storages; namespace Aerex\BaikalStorage\Storages;
use Sabre\VObject\Component\VCalendar as Calendar; use Sabre\VObject\Component\VCalendar as Calendar;
use Carbon\Carbon;
class Taskwarrior implements IStorage { class Taskwarrior implements IStorage {
private const DATA_FILES = ['pending.data', 'completed.data', 'undo.data'];
private $rawConfigs;
public const NAME = 'taskwarrior'; public const NAME = 'taskwarrior';
private $tasks = []; private $tasks = [];
public function __construct($console, $config) { private $configs;
private $logger;
public function __construct($console, $configs, $logger) {
$this->console = $console; $this->console = $console;
$this->config = $config; $this->configs = $configs['storages']['taskwarrior'];
$this->logger = $logger;
} }
public function getConfig() { public function getConfigBrowser() {
return $this->config; $html = '<tr>';
$html .= '<th>taskrc</th>';
$html .= '<td>The enivronment variable overrides the default and the command line specification of the .taskrc file</td>';
$html .= '<td><input name="tw_taskrc" type="text" value="' . $this->configs['taskrc'] . '"></td>';
$html .= '</tr>';
$html .= '<tr>';
$html .= '<th>taskdata</th>';
$html .= '<td>The environment variable overrides the default and the command line, and the "data.location" configuration setting of the task data directory</td>';
$html .= '<td><input name="tw_taskdata" type="text" value="' . $this->configs['taskdata'] . '"></td>';
$html .= '</tr>';
$html .= '<tr>';
$html .= '<th>default_calendar</th>';
$html .= '<td>The default calendar to send tasks if no task project is set. The value is the calendar\'s displayname</td>';
$html .= '<td><input name="tw_default_calendar" type="text" value="' . $this->configs['default_calendar'] . '"></td>';
$html .= '</tr>';
return $html;
} }
public function setRawConfigs($rawConfigs) { public function updateConfigs($postData) {
$this->rawConfigs = $rawConfigs; if (isset($postData['tw_taskrc'])) {
$this->configs['taskrc'] = $postData['tw_taskrc'];
}
if (isset($postData['tw_taskdata'])){
$this->configs['taskdata'] = $postData['tw_taskdata'];
}
if (isset($postData['tw_default_calendar'])){
$this->configs['default_calendar'] = $postData['tw_default_calendar'];
}
return $this->configs;
} }
public function refresh() { public function refresh() {
$dataDir = $this->rawConfigs['data_dir']; $this->logger->info('Syncing taskwarrior tasks...');
$fp = fopen(sprintf('%s/taskwarrior-baikal-storage.lock', $dataDir), 'a'); $this->console->execute('task', ['sync'], null,
['TASKRC' => $this->configs['taskrc'],'TASKDATA' => $this->configs['taskdata']]);
if (!$fp || !flock($fp, LOCK_EX | LOCK_NB, $eWouldBlock) || $eWouldBlock) { $this->tasks = json_decode($this->console->execute('task', ['export'], null,
fputs(STDERR, 'Could not get lock'); ['TASKRC' => $this->configs['taskrc'], 'TASKDATA' => $this->configs['taskdata']]), true);
} foreach ($this->tasks as $task) {
if (isset($task['uid'])) {
$mtime = 0; $this->tasks[$task['uid']] = $task;
$tasksUpdated = false;
foreach (Taskwarrior::DATA_FILES as $dataFile) {
$fmtime = filemtime(sprintf('%s/%s', $this->config['data_dir'], $dataFile));
if ($fmtime > $mtime) {
$mtime = $fmtime;
$tasksUpdated = true;
} }
}
if ($tasksUpdated) {
$tasks = $this->console->execute('task', ['export']);
foreach ($tasks as $task) {
$this->tasks[$task['uuid']] = $task;
} }
}
fclose($fp);
unlink(sprintf('%s/taskwarrior-baikal-storage.lock', $dataDir));
} }
public function vObjectToTask($vtodo) { public function vObjectToTask($vtodo, string $displayname) {
if ($this->tasks['uid'] == $vtodo->UID) { if (isset($this->tasks[(string)$vtodo->UID])) {
$task = $this->tasks['uid']; $task = $this->tasks[(string)$vtodo->UID];
} else { } else {
$task = []; $task = [];
$task['uid'] = $vtodo->UID; $task['uid'] = (string)$vtodo->UID;
} }
if (isset($vtodo->SUMMARY)){
if (!isset($vtodo->DESCRIPTION) && isset($vtodo->SUMMARY)){ $task['description'] = (string)$vtodo->SUMMARY;
$task['description'] = $vtodo->SUMMARY;
} else {
$task['description'] = $vtodo->DESCRIPTION;
}
if (isset($vtodo->DTSTAMP)){
$task['entry'] = new Carbon($vtodo->DTSTAMP->getDateTime()->format(\DateTime::W3C));
} }
if (isset($vtodo->DUE)){ if (isset($vtodo->DESCRIPTION)) {
$task['due'] = new Carbon($vtodo->DUE->getDateTime()->format(\DateTime::W3C)); $annotations = [];
if (isset($task['annotations'])) {
$annotations = $task['annotations'];
}
$task['annotations'] = [];
$descriptionLines = explode('\n', $vtodo->DESCRIPTION);
foreach ($descriptionLines as $key => $descriptionLine) {
$annotationEntry = $vtodo->DTSTAMP->getDateTime()->modify("+$key second")->format(\DateTime::ISO8601);
foreach ($annotations as $annotation) {
if ($annotation['description'] == $descriptionLine) {
$annotationEntry = $annotation['entry'];
break;
}
}
array_push($annotations, ['description' => $descriptionLine, 'entry' => $annotationEntry]);
$task['annotations'] = $annotations;
}
}
if (!isset($task['entry'])){
$task['entry'] = $vtodo->DTSTAMP->getDateTime()->format(\DateTime::ISO8601);
}
if (isset($vtodo->DTSTART)) {
$task['start'] = $vtodo->DTSTART->getDateTime()->format(\DateTime::ISO8601);
} }
return $task; if (isset($vtodo->DTEND)){
$task['end'] = $vtodo->DTEND->getDateTime()->format(\DateTime::ISO8601);
}
if (isset($vtodo->{'LAST-MODIFIED'})) {
$task['modified'] = $vtodo->{'LAST-MODIFIED'}->getDateTime()->format(\DateTime::ISO8601);
}
if (isset($vtodo->PRIORITY)) {
$priority = $vtodo->PRIORITY->getJsonValue();
if ($priority < 5) {
$task['priority'] = 'H';
} else if ($priority === 5) {
$task['priority'] = 'M';
} else if ($priority > 5 && $priority < 10) {
$task['priority'] = 'L';
}
}
if (isset($vtodo->DUE)) {
$task['due'] = $vtodo->DUE->getDateTime()->format(\DateTime::ISO8601);
} else if (isset($task['due'])) {
$task['due'] = '';
}
if (isset($vtodo->RRULE)) {
$rules = $vtodo->RRULE->getParts();
if (isset($rules['FREQ'])) {
$task['recu'] = $rules['FREQ'];
}
if (isset($rules['UNTIL'])) {
$task['until'] = $rules['UNTIL'];
}
}
if (isset($vtodo->STATUS)) {
switch((string)$vtodo->STATUS) {
case 'NEEDS-ACTION':
$task['status'] = 'pending';
break;
case 'COMPLETED':
$task['status'] = 'completed';
if (!isset($task['end'])) {
$task['end'] = $vtodo->DTSTAMP->getDateTime()->format(\DateTime::ISO8601);
}
break;
case 'CANCELED':
$task['status'] = 'deleted';
if (!isset($task['end'])) {
$task['end'] = $vtodo->DTSTAMP->getDateTime()->format(\DateTime::ISO8601);
}
break;
}
}
if (isset($vtodo->CATEGORIES)) {
$task['tags'] = $vtodo->CATEGORIES->getJsonValue();
}
if (isset($vtodo->GEO)){
$task['geo'] = $vtodo->GEO->getRawMimeDirValue();
}
if ($this->configs['default_calendar'] != $displayname) {
$task['project'] = $displayname;
}
return $task;
} }
public function save(Calendar $c) { public function save(Calendar $c, string $displayname) {
if (!isset($c->VTODO)){ try {
throw new \Exception('Calendar event does not contain VTODO'); if (!isset($c->VTODO)){
throw new \Exception('Calendar event does not contain VTODO');
}
$this->logger->info(json_encode($c->jsonSerialize()));
$this->refresh();
$task = $this->vObjectToTask($c->VTODO, $displayname);
$this->logger->info(json_encode($task));
$this->logger->info(
sprintf('Executing TASKRC = %s TASKDATA = %s task import %s', $this->configs['taskrc'], $this->configs['taskdata'], json_encode($task))
);
$output = $this->console->execute('task', ['import'], $task,
['TASKRC' => $this->configs['taskrc'],'TASKDATA' => $this->configs['taskdata']]);
$this->refresh();
$this->logger->info($output);
} catch (\Exception $e) {
$this->logger->error($e->getTraceAsString());
throw $e;
} }
$this->refresh(); }
$task = $this->vObjectToTask($c->VTODO);
$this->console->execute('task', ['import'], $task); public function remove($uid) {
} try {
$this->logger->info(sprintf('Deleting iCal %s from taskwarrior', $uid));
$this->refresh();
if (!array_key_exists((string)$uid, $this->tasks)) {
$this->logger->warn(sprintf('Could not find task %s to be remove. Skipping', (string)$uid));
return;
}
$task = $this->tasks[(string)$uid];
if (isset($task) && $task['status'] !== 'deleted') {
$uuid = $task['uuid'];
$this->logger->info(
sprintf('Executing TASKRC = %s TASKDATA = %s task delete %s', $this->configs['taskrc'], $this->configs['taskdata'], $uuid)
);
$output = $this->console->execute('task', ['delete', (string)$uuid], null,
['TASKRC' => $this->configs['taskrc'],'TASKDATA' => $this->configs['taskdata']]);
$this->logger->info($output);
$this->refresh();
} else if (isset($task) && $task['status'] === 'deleted') {
$this->logger->warn(sprintf('Task %s has already been deleted', $task['uuid']));
} else {
$this->logger->error(sprintf('Could not find task for iCal %s to be deleted', $uid));
}
} catch (\Exception $e) {
$this->logger->error($e->getMessage());
$this->logger->error($e->getTraceAsString());
throw $e;
}
}
} }

View File

@ -8,8 +8,8 @@
beStrictAboutTestsThatDoNotTestAnything="true"> beStrictAboutTestsThatDoNotTestAnything="true">
<testsuite name="Baikal Storage Plug Tests"> <testsuite name="Baikal Storage Plugin Tests">
<directory>./lib/tests</directory> <directory>./tests/</directory>
</testsuite> </testsuite>
<filter> <filter>

View File

@ -0,0 +1,45 @@
<?php
namespace Aerex\BaikalStorage;
use PHPUnit\Framework\TestCase;
use Aerex\BaikalStorage\Configs\ConfigBuilder;
use Aerex\BaikalStorage\Configs\TaskwarriorConfig;
class ConfigTest extends TestCase {
/**
* @var \PHPUnit_Framework_MockObject_MockObject
* */
public $mockConfigBuilder;
public function testGeneralLoggerConfigs() {
$configs = new ConfigBuilder(__DIR__ . '/Fixtures/LoggerConfig.yaml');
$contents = $configs->loadYaml();
$this->assertEquals(sizeof($contents), 1);
$this->assertArrayHasKey('general', $contents, 'config missing general config');
$generalConfigs = $contents['general'];
$this->assertArrayHasKey('logger', $generalConfigs, 'general config is missing logger property');
$this->assertArrayHasKey('file', $generalConfigs['logger'], 'general logger config missing file property');
$this->assertEquals($generalConfigs['logger']['file'], '/home/user/logger.yaml');
$this->assertArrayHasKey('level', $generalConfigs['logger'], 'general logger config missing level property');
$this->assertEquals($generalConfigs['logger']['level'], 'ERROR', 'ERROR is not set as default logger level');
$this->assertArrayHasKey('enabled', $generalConfigs['logger'], 'general config logger enabled property is missing');
$this->assertTrue($generalConfigs['logger']['enabled']);
}
public function testTaskwarriorConfig() {
$configs = new ConfigBuilder(__DIR__ . '/Fixtures/TaskwarriorConfig.yaml');
$configs->add(new TaskwarriorConfig());
$contents = $configs->loadYaml();
$this->assertEquals(sizeof($contents), 2);
$this->assertArrayHasKey('storages', $contents, 'storages config missing');
$this->assertArrayHasKey('taskwarrior', $contents['storages'], 'storage config missing taskwarrior property');
$taskwarriorConfigs = $contents['storages']['taskwarrior'];
$this->assertArrayHasKey('taskrc', $taskwarriorConfigs, 'taskwarrior config is missing taskrc property');
$this->assertEquals($taskwarriorConfigs['taskrc'], '/home/aerex/.taskrc');
$this->assertArrayHasKey('taskdata', $taskwarriorConfigs, 'taskwarrior config is missing taskdata property');
$this->assertEquals($taskwarriorConfigs['taskdata'], '/home/aerex/.task');
}
}

View File

@ -0,0 +1,3 @@
general:
logger:
file: /home/user/logger.yaml

View File

@ -0,0 +1,8 @@
general:
logger:
file: /home/aerex/baikal-storage-plugin.log
level: DEBUG
storages:
taskwarrior:
taskdata: /home/aerex/.task
taskrc: /home/aerex/.taskrc

View File

@ -1,2 +0,0 @@
taskwarrior:
data_dir: '~/task'

View File

@ -5,9 +5,8 @@ namespace Aerex\BaikalStorage;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
use Aerex\BaikalStorage\AbstractConsole; use Aerex\BaikalStorage\AbstractConsole;
use Aerex\BaikalStorage\Configs\ConfigBuilder; use Aerex\BaikalStorage\Configs\ConfigBuilder;
use Aerex\BaikalStorage\Configs\TaskwarriorConfig;
use Aerex\BaikalStorage\Storages\Taskwarrior; use Aerex\BaikalStorage\Storages\Taskwarrior;
use Aerex\BaikalStorage\Storages\IStorage; use Aerex\BaikalStorage\Logger;
use Sabre\VObject\Component\VCalendar as Calendar; use Sabre\VObject\Component\VCalendar as Calendar;
class StorageManagerTest extends TestCase { class StorageManagerTest extends TestCase {
@ -21,50 +20,42 @@ class StorageManagerTest extends TestCase {
public $mockConfigBuilder; public $mockConfigBuilder;
function setUp() { protected function setUp(): void {
$this->mockConfigBuilder = $this->getMockBuilder(ConfigBuilder::class) $this->mockConfigBuilder = $this->getMockBuilder(ConfigBuilder::class)
->setMethods(['readContent']) ->setMethods(['readContent'])
->setConstructorArgs(['']) ->setConstructorArgs([''])
->getMock(); ->getMock();
$this->mockConsole = $this->createMock(AbstractConsole::class); $this->mockConsole = $this->createMock(AbstractConsole::class);
$this->mockStorage = $this->createMock(IStorage::class); $this->mockStorage = $this->createMock(Taskwarrior::class);
} $this->mockLogger = $this->createMock(Logger::class);
$this->configs = [
'general' => [
'logger' => ['file' => '', 'level'=> 'DEBUG', 'enabled' => true]
],
'storages' => [
'taskwarrior' => ['taskrc' => '', 'taskdata' => '']
]
];
}
public function testAddTaskwarriorStorage() { public function testAddTaskwarriorStorage() {
$this->mockConfigBuilder->expects($this->once()) $tw = new Taskwarrior($this->mockConsole, $this->configs, $this->mockLogger);
->method('readContent')
->willReturn(file_get_contents(__DIR__ . '/Fixtures/taskwarrior_config.yml'));
$tw = new Taskwarrior($this->mockConsole, new TaskwarriorConfig());
$manager = new StorageManager($this->mockConfigBuilder); $manager = new StorageManager($this->mockConfigBuilder);
$manager->addStorage(Taskwarrior::NAME, $tw); $manager->addStorage(Taskwarrior::NAME, $tw);
$storages = $manager->getStorages(); $storages = $manager->getStorages();
$manager->init(); $this->configs = $manager->getConfigs();
$configs = $manager->getConfigs();
$this->assertEquals(sizeof(array_keys($storages)), 1, 'Taskwarrior storage was not added'); $this->assertEquals(sizeof(array_keys($storages)), 1, 'Taskwarrior storage was not added');
$this->assertEquals(sizeof(array_keys($configs)), 1, 'Taskwarrior config was not loaded');
$this->assertArrayHasKey('taskwarrior', $storages, 'Storages should have taskwarrior'); $this->assertArrayHasKey('taskwarrior', $storages, 'Storages should have taskwarrior');
$this->assertArrayHasKey('taskwarrior', $configs, 'Configs should have taskwarrior');
} }
public function testTaskwarriorImport() { public function testTaskwarriorImport() {
$cal = new Calendar(); $cal = new Calendar();
$this->mockConfigBuilder->expects($this->once())
->method('readContent')
->willReturn(file_get_contents(__DIR__ . '/Fixtures/taskwarrior_config.yml'));
$this->mockStorage->expects($this->once()) $this->mockStorage->expects($this->once())
->method('save') ->method('save')
->with($this->equalTo($cal)); ->with($this->equalTo($cal));
$this->mockStorage->expects($this->once())
->method('setRawConfigs')
->with($this->equalTo(['data_dir' => '~/.task']));
$this->mockStorage->expects($this->once())
->method('getConfig')
->willReturn(new TaskwarriorConfig());
$manager = new StorageManager($this->mockConfigBuilder); $manager = new StorageManager($this->configs);
$manager->addStorage(Taskwarrior::NAME, $this->mockStorage); $manager->addStorage(Taskwarrior::NAME, $this->mockStorage);
$manager->init();
$manager->import($cal); $manager->import($cal);
} }

View File

@ -0,0 +1,95 @@
<?php
namespace Aerex\BaikalStorage;
use PHPUnit\Framework\TestCase;
use Aerex\BaikalStorage\AbstractConsole;
use Aerex\BaikalStorage\Logger;
use Sabre\VObject\Component\VCalendar as Calendar;
use Aerex\BaikalStorage\Storages\Taskwarrior;
class TaskwarriorTest extends TestCase {
/**
* @var \PHPUnit_Framework_MockObject_MockObject
* */
private $mockConsole;
protected function setUp(): void {
$this->mockConsole = $this->createMock(AbstractConsole::class);
$this->mockLogger = $this->createMock(Logger::class);
}
public function testVObjectToTask() {
$configs = [
'general' => [
'logger' => ['file' => '', 'level'=> 'DEBUG', 'enabled' => true],
],
'storages' => [
'taskwarrior' => ['taskrc' => '', 'taskdata' => '']
]
];
$this->taskwarrior = new Taskwarrior($this->mockConsole, $configs, $this->mockLogger);
$vcalendar = new Calendar([
'VTODO' => [
'SUMMARY' => 'Finish project',
'DTSTAMP' => new \DateTime('2020-07-04 10:00:00'),
'DTSTART' => new \DateTime('2020-07-04 12:00:00'),
'DTEND' => new \DateTime('2020-07-05 01:00:00'),
'DUE' => new \DateTime('2020-07-05 03:00:00'),
'LAST_MODIFIED' => new \DateTime('2020-07-04 13:00:00'),
'PRIORITY' => 5,
'RRULE' => 'FREQ=MONTHLY'
]
]);
$task = $this->taskwarrior->vObjectToTask($vcalendar->VTODO);
$this->assertArrayHasKey('uid', $task, 'task should have a uid');
$this->assertEquals((string)$vcalendar->VTODO->UID, $task['uid']);
$this->assertArrayHasKey('description', $task, 'task should have description');
$this->assertEquals((string)$vcalendar->VTODO->SUMMARY, $task['description']);
$this->assertArrayHasKey('due', $task, 'task should have due');
$this->assertEquals($vcalendar->VTODO->DUE->getDateTime()->format(\DateTime::ISO8601), $task['due']);
$this->assertArrayHasKey('entry', $task, 'task should have an entry');
$this->assertEquals($vcalendar->VTODO->DTSTAMP->getDateTime()->format(\DateTime::ISO8601), $task['entry']);
$this->assertArrayHasKey('start', $task, 'task should have start');
$this->assertEquals($vcalendar->VTODO->DTSTART->getDateTime()->format(\DateTime::ISO8601), $task['start']);
}
// public function testVObjectToTaskWithDifferentTimezone() {
// $configs = [
// 'general' => [
// 'logger' => ['file' => '', 'level'=> 'DEBUG', 'enabled' => true],
// ],
// 'storages' => [
// 'taskwarrior' => ['taskrc' => '', 'taskdata' => '']
// ]
// ];
// $this->taskwarrior = new Taskwarrior($this->mockConsole, $configs, $this->mockLogger);
// $vcalendar = new Calendar([
// 'VTODO' => [
// 'SUMMARY' => 'Finish project',
// 'DTSTAMP' => new \DateTime('2020-07-04 10:00:00'),
// 'DTSTART' => new \DateTime('2020-07-04 12:00:00'),
// 'DTEND' => new \DateTime('2020-07-05 01:00:00'),
// 'DUE' => new \DateTime('2020-07-05 03:00:00'),
// 'LAST_MODIFIED' => new \DateTime('2020-07-04 13:00:00'),
// 'PRIORITY' => 5,
// 'RRULE' => 'FREQ=MONTHLY'
// ]
// ]);
//
// $task = $this->taskwarrior->vObjectToTask($vcalendar->VTODO);
// $this->assertArrayHasKey('uid', $task, 'task should have a uid');
// $this->assertEquals((string)$vcalendar->VTODO->UID, $task['uid']);
// $this->assertArrayHasKey('description', $task, 'task should have description');
// $this->assertEquals((string)$vcalendar->VTODO->SUMMARY, $task['description']);
// $this->assertArrayHasKey('due', $task, 'task should have due');
// $this->assertEquals($vcalendar->VTODO->DUE->getDateTime(), $task['due']);
// $this->assertArrayHasKey('entry', $task, 'task should have an entry');
// $this->assertEquals($vcalendar->VTODO->DTSTAMP->getDateTime(), $task['entry']);
// $this->assertArrayHasKey('start', $task, 'task should have start');
// $this->assertEquals($vcalendar->VTODO->DTSTART->getDateTime(), $task['start']);
//
// }
}