9 Commits

Author SHA1 Message Date
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
16 changed files with 450 additions and 111 deletions

View File

@@ -17,7 +17,7 @@
], ],
"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",
"nesbot/carbon": "^2.0.0", "nesbot/carbon": "^2.0.0",
"laminas/laminas-validator": "^2.13", "laminas/laminas-validator": "^2.13",

View File

@@ -4,4 +4,4 @@ logger:
taskwarrior: taskwarrior:
taskdata: /home/aerex/.task taskdata: /home/aerex/.task
taskrc: /home/aerex/.taskrc taskrc: /home/aerex/.taskrc
project_tag_suffix: project_ project_category_prefix: project_

10
lib/Browser.php Normal file
View File

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

View File

@@ -24,20 +24,25 @@ class ConfigBuilder implements ConfigurationInterface {
$treeBuilder = new TreeBuilder(); $treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('configs'); $rootNode = $treeBuilder->root('configs');
$ref = $rootNode->children() $ref = $rootNode->children()
->arrayNode('logger') ->arrayNode('general')
->canBeEnabled()
->children() ->children()
->scalarNode('file')->end() ->arrayNode('logger')
->scalarNode('level') ->canBeEnabled()
->defaultValue('ERROR') ->children()
->validate() ->scalarNode('file')->end()
->IfNotInArray(['DEBUG', 'INFO', 'NOTICE', 'WARNING', 'ERROR', 'CRITICAL', 'ALERT', 'EMERGENCY']) ->scalarNode('level')
->thenInvalid('Invalid log level %s') ->defaultValue('ERROR')
->end() ->validate()
->end() ->IfNotInArray(['DEBUG', 'INFO', 'NOTICE', 'WARNING', 'ERROR', 'CRITICAL', 'ALERT', 'EMERGENCY'])
->end() ->thenInvalid('Invalid log level %s')
->end(); ->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());
} }
@@ -54,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

@@ -11,12 +11,15 @@ class TaskwarriorConfig {
->children() ->children()
->scalarNode('taskdata') ->scalarNode('taskdata')
->defaultValue('~/.task') ->defaultValue('~/.task')
->info('The environment variable overrides the default and the command line, and the "data.location" configuration setting of the task data directory')
->end() ->end()
->scalarNode('taskrc') ->scalarNode('taskrc')
->defaultValue('~/.taskrc') ->defaultValue('~/.taskrc')
->info('The enivronment variable overrides the default and the command line specification of the .taskrc file')
->end() ->end()
->scalarNode('project_tag_suffix') ->scalarNode('project_category_prefix')
->defaultValue('project_') ->defaultValue('project_')
->info('The word after the given prefix for a iCal category will be used to identify a task\'s project')
->end() ->end()
->end(); ->end();

View File

@@ -16,6 +16,7 @@ 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, $envs = []) { public function execute($cmd, $args, $input = null, $envs = []) {
@@ -23,16 +24,15 @@ class Console extends AbstractConsole {
$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(implode(' ', $stdin), $input, $envs); $process = new Process(implode(' ', $stdin), null, $envs, $input);
$process->inheritEnvironmentVariables(); $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;
} }
} }

View File

@@ -9,16 +9,25 @@ class Logger {
private $configs = ['enabled' => false]; private $configs = ['enabled' => false];
function __construct($configs, $tag) { function __construct($configs, $tag) {
if (isset($configs['logger'])) { if (isset($configs['general']) && isset($configs['general']['logger'])) {
$this->configs = $configs['logger']; $this->configs = $configs['general']['logger'];
} }
if ($this->configs['enabled']) { if ($this->configs['enabled']) {
$this->createLoggerFile();
$this->logger = new Monolog($tag); $this->logger = new Monolog($tag);
$logLevel = Monolog::getLevels()[$this->configs['level']]; $logLevel = Monolog::getLevels()[$this->configs['level']];
$this->logger->pushHandler(new StreamHandler($this->configs['file'], $logLevel)); $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) { public function debug($message) {
if ($this->configs['enabled']) { if ($this->configs['enabled']) {
$this->logger->debug($message); $this->logger->debug($message);
@@ -36,6 +45,11 @@ class Logger {
$this->logger->notice($message); $this->logger->notice($message);
} }
} }
public function warn($message) {
if ($this->configs['enabled']) {
$this->logger->warning($message);
}
}
public function error($message) { public function error($message) {
if ($this->configs['enabled']) { if ($this->configs['enabled']) {

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;
@@ -31,17 +33,20 @@ class Plugin extends ServerPlugin {
*/ */
protected $storageManager; protected $storageManager;
protected $rawConfigs;
/** /**
* Creates the Taskwarrior plugin * Creates the Storage plugin
* *
* @param CalendarProcessor $TWCalManager * @param CalendarProcessor $TWCalManager
* *
*/ */
function __construct($configFile){ function __construct($configFile){
$configs = $this->buildConfigurations($configFile); $this->rawConfigs = $this->buildConfigurations($configFile);
$this->storageManager = new StorageManager($configs); $this->storageManager = new StorageManager($this->rawConfigs);
$this->initializeStorages($configs); $this->initializeStorages($this->rawConfigs);
} }
public function buildConfigurations($configFile) { public function buildConfigurations($configFile) {
@@ -56,7 +61,7 @@ class Plugin extends ServerPlugin {
*/ */
public function initializeStorages($configs) { public function initializeStorages($configs) {
$taskwarrior = new Taskwarrior(new Console(['rc.verbose=nothing', 'rc.hooks=off']), $configs); $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);
} }
@@ -81,14 +86,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
@@ -101,8 +105,14 @@ 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;
} }
@@ -129,6 +139,136 @@ 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]);
$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.
* *
@@ -146,6 +286,7 @@ class Plugin extends ServerPlugin {
'name' => $this->getPluginName(), 'name' => $this->getPluginName(),
'description' => 'The plugin provides synchronization between taskwarrior tasks and iCAL events', 'description' => 'The plugin provides synchronization between taskwarrior tasks and iCAL events',
'link' => null, 'link' => null,
'config' => true
]; ];
} }

View File

@@ -38,7 +38,7 @@ class StorageManager {
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();
@@ -46,4 +46,17 @@ class StorageManager {
$storage->save($calendar); $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

@@ -6,6 +6,8 @@ use Sabre\VObject\Component\VCalendar as Calendar;
interface IStorage { interface IStorage {
public function save(Calendar $c); public function save(Calendar $c);
public function remove($uid);
public function refresh(); public function refresh();
public function getConfig(); public function getConfigBrowser();
public function updateConfigs($postData);
} }

View File

@@ -3,8 +3,6 @@
namespace Aerex\BaikalStorage\Storages; namespace Aerex\BaikalStorage\Storages;
use Sabre\VObject\Component\VCalendar as Calendar; use Sabre\VObject\Component\VCalendar as Calendar;
use Aerex\BaikalStorage\Logger;
use Carbon\Carbon;
class Taskwarrior implements IStorage { class Taskwarrior implements IStorage {
@@ -13,19 +11,63 @@ class Taskwarrior implements IStorage {
private $configs; private $configs;
private $logger; private $logger;
public function __construct($console, $configs) { public function __construct($console, $configs, $logger) {
$this->console = $console; $this->console = $console;
$this->configs = $configs['taskwarrior']; $this->configs = $configs['storages']['taskwarrior'];
$this->logger = new Logger($configs, '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>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>project_category_prefix</th>';
$html .= "<td>The word after the given prefix for a iCal category will be used to identify a task's project</td>";
$html .= '<td><input name="tw_project_category_prefix" placeholder ="project_" name="tw_project_category_prefix" type="text" value="' . $this->configs['project_category_prefix'] . '"></td>';
$html .= '</tr>';
return $html;
}
public function updateConfigs($postData) {
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_project_category_prefix'])){
$this->configs['project_category_prefix'] = $postData['tw_project_category_prefix'];
}
return $this->configs;
} }
public function refresh() { public function refresh() {
$output = $this->console->execute('task', ['sync'], null, $output = $this->console->execute('task', ['sync'], null,
['TASKRC' => $this->configs['taskrc'],'TASKDATA' => $this->configs['taskdata']]); ['TASKRC' => $this->configs['taskrc'],'TASKDATA' => $this->configs['taskdata']]);
$this->tasks = json_decode($this->console->execute('task', ['export'], null,
['TASKRC' => $this->configs['taskrc'], 'TASKDATA' => $this->configs['taskdata']]), true);
foreach ($this->tasks as $task) {
if (isset($task['uid'])) {
$this->tasks[$task['uid']] = $task;
}
}
$this->logger->info($output); $this->logger->info($output);
} }
@@ -37,26 +79,43 @@ class Taskwarrior implements IStorage {
$task['uid'] = (string)$vtodo->UID; $task['uid'] = (string)$vtodo->UID;
} }
if (isset($vtodo->SUMMARY) && !isset($vtodo->DESCRIPTION)){ if (isset($vtodo->SUMMARY)){
$task['description'] = (string)$vtodo->SUMMARY; $task['description'] = (string)$vtodo->SUMMARY;
} else if(isset($vtodo->DESCRIPTION)) { }
$task['description'] = (string)$vtodo->DESCRIPTION;
}
if (isset($vtodo->DTSTAMP)){ if (isset($vtodo->DESCRIPTION)) {
$task['entry'] = new Carbon($vtodo->DTSTAMP->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)) { if (isset($vtodo->DTSTART)) {
$task['start'] = new Carbon($vtodo->DTSTART->getDateTime()->format(\DateTime::W3C)); $task['start'] = $vtodo->DTSTART->getDateTime()->format(\DateTime::ISO8601);
} }
if (isset($vtodo->DTEND)){ if (isset($vtodo->DTEND)){
$task['end'] = new Carbon($vtodo->DTEND->getDateTime()->format(\DateTime::W3C)); $task['end'] = $vtodo->DTEND->getDateTime()->format(\DateTime::ISO8601);
} }
if (isset($vtodo->{'LAST-MODIFIED'})) { if (isset($vtodo->{'LAST-MODIFIED'})) {
$task['modified'] = new Carbon($vtodo->{'LAST-MODIFIED'}->getDateTime()->format(\DateTime::W3C)); $task['modified'] = $vtodo->{'LAST-MODIFIED'}->getDateTime()->format(\DateTime::ISO8601);
} }
if (isset($vtodo->PRIORITY)) { if (isset($vtodo->PRIORITY)) {
@@ -71,7 +130,7 @@ class Taskwarrior implements IStorage {
} }
if (isset($vtodo->DUE)){ if (isset($vtodo->DUE)){
$task['due'] = new Carbon($vtodo->DUE->getDateTime()->format(\DateTime::W3C)); $task['due'] = $vtodo->DUE->getDateTime()->format(\DateTime::ISO8601);
} }
if (isset($vtodo->RRULE)) { if (isset($vtodo->RRULE)) {
@@ -92,13 +151,13 @@ class Taskwarrior implements IStorage {
case 'COMPLETED': case 'COMPLETED':
$task['status'] = 'completed'; $task['status'] = 'completed';
if (!isset($task['end'])) { if (!isset($task['end'])) {
$task['end'] = new Carbon($vtodo->DTSTAMP->getDateTime()->format(\DateTime::W3C)); $task['end'] = $vtodo->DTSTAMP->getDateTime()->format(\DateTime::ISO8601);
} }
break; break;
case 'CANCELED': case 'CANCELED':
$task['status'] = 'deleted'; $task['status'] = 'deleted';
if (!isset($task['end'])) { if (!isset($task['end'])) {
$task['end'] = new Carbon($vtodo->DTSTAMP->getDateTime()->format(\DateTime::W3C)); $task['end'] = $vtodo->DTSTAMP->getDateTime()->format(\DateTime::ISO8601);
} }
break; break;
} }
@@ -107,9 +166,9 @@ class Taskwarrior implements IStorage {
if (isset($vtodo->CATEGORIES)) { if (isset($vtodo->CATEGORIES)) {
$task['tags'] = []; $task['tags'] = [];
foreach ($vtodo->CATEGORIES as $category) { foreach ($vtodo->CATEGORIES as $category) {
if (isset($this->configs['project_tag_suffix'])) { if (isset($this->configs['project_category_prefix'])) {
$projTagSuffixRegExp = sprintf('/^%s_/', $this->configs['project_tag_suffix']); $projTagSuffixRegExp = sprintf('/^%s/', $this->configs['project_category_prefix']);
if (preg_match($category, $projTagSuffixRegExp)) { if (preg_match($projTagSuffixRegExp, $category)) {
$task['project'] = preg_replace($projTagSuffixRegExp, '', $category); $task['project'] = preg_replace($projTagSuffixRegExp, '', $category);
continue; continue;
} }
@@ -118,23 +177,58 @@ class Taskwarrior implements IStorage {
} }
} }
if (isset($vtodo->GEO)){
$task['geo'] = $vtodo->GEO->getRawMimeDirValue();
}
return $task; return $task;
} }
public function save(Calendar $c) { public function save(Calendar $c) {
if (!isset($c->VTODO)){ try {
throw new \Exception('Calendar event does not contain VTODO'); if (!isset($c->VTODO)){
$this->logger->error('Calendar event does not contain VTODO'); throw new \Exception('Calendar event does not contain VTODO');
}
$this->logger->info(json_encode($c->jsonSerialize()));
$this->refresh();
$task = $this->vObjectToTask($c->VTODO);
$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->logger->info($output);
} catch (\Exception $e) {
$this->logger->error($e->getTraceAsString());
throw $e;
} }
$this->logger->info($c->VTODO->getJsonValue()); }
$this->refresh();
$task = $this->vObjectToTask($c->VTODO); public function remove($uid) {
$this->logger->info(json_encode($task)); try {
$this->logger->info( $this->logger->info(sprintf('Deleting iCal %s from taskwarrior', $uid));
sprintf('Executing TASKRC = %s TASKDATA = %s task import %s', $this->configs['taskrc'], $this->configs['taskdata'], $task) $this->refresh();
); $task = $this->tasks[(string)$uid];
$output = $this->console->execute('task', ['import'], $task, if (isset($task) && $task['status'] !== 'deleted') {
['TASKRC' => $this->configs['taskrc'],'TASKDATA' => $this->configs['taskdata']]); $uuid = $task['uuid'];
$this->logger->info($output); $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);
} 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

@@ -13,18 +13,19 @@ class ConfigTest extends TestCase {
public $mockConfigBuilder; public $mockConfigBuilder;
public function testLoggerConfigs() { public function testGeneralLoggerConfigs() {
$configs = new ConfigBuilder(__DIR__ . '/Fixtures/LoggerConfig.yaml'); $configs = new ConfigBuilder(__DIR__ . '/Fixtures/LoggerConfig.yaml');
$contents = $configs->loadYaml(); $contents = $configs->loadYaml();
$this->assertEquals(sizeof($contents), 1); $this->assertEquals(sizeof($contents), 1);
$this->assertArrayHasKey('logger', $contents, 'config missing logger property'); $this->assertArrayHasKey('general', $contents, 'config missing general config');
$this->assertArrayHasKey('file', $contents['logger'], 'config missing logger.file property'); $generalConfigs = $contents['general'];
$this->assertEquals($contents['logger']['file'], '/home/user/logger.yaml'); $this->assertArrayHasKey('logger', $generalConfigs, 'general config is missing logger property');
$this->assertArrayHasKey('level', $contents['logger'], 'config missing logger.level property'); $this->assertArrayHasKey('file', $generalConfigs['logger'], 'general logger config missing file property');
$this->assertEquals($contents['logger']['level'], 'ERROR', 'ERROR is not set as default logger level'); $this->assertEquals($generalConfigs['logger']['file'], '/home/user/logger.yaml');
$this->assertArrayHasKey('enabled', $contents['logger'], 'config missing logger.enabled property'); $this->assertArrayHasKey('level', $generalConfigs['logger'], 'general logger config missing level property');
$this->assertTrue($contents['logger']['enabled']); $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() { public function testTaskwarriorConfig() {
@@ -32,19 +33,15 @@ class ConfigTest extends TestCase {
$configs->add(new TaskwarriorConfig()); $configs->add(new TaskwarriorConfig());
$contents = $configs->loadYaml(); $contents = $configs->loadYaml();
$this->assertEquals(sizeof($contents), 2); $this->assertEquals(sizeof($contents), 2);
$this->assertArrayHasKey('logger', $contents, 'config missing logger property'); $this->assertArrayHasKey('storages', $contents, 'storages config missing');
$this->assertArrayHasKey('file', $contents['logger'], 'config missing logger.file property'); $this->assertArrayHasKey('taskwarrior', $contents['storages'], 'storage config missing taskwarrior property');
$this->assertArrayHasKey('level', $contents['logger'], 'config missing logger.level property'); $taskwarriorConfigs = $contents['storages']['taskwarrior'];
$this->assertArrayHasKey('enabled', $contents['logger'], 'config missing logger.enabled property'); $this->assertArrayHasKey('taskrc', $taskwarriorConfigs, 'taskwarrior config is missing taskrc property');
$this->assertArrayHasKey('taskwarrior', $contents, 'config missing taskwarrior property'); $this->assertEquals($taskwarriorConfigs['taskrc'], '/home/aerex/.taskrc');
$this->assertArrayHasKey('taskrc', $contents['taskwarrior'], 'config missing taskwarrior.taskrc property'); $this->assertArrayHasKey('taskdata', $taskwarriorConfigs, 'taskwarrior config is missing taskdata property');
$this->assertEquals($contents['taskwarrior']['taskrc'], '/home/aerex/.taskrc'); $this->assertEquals($taskwarriorConfigs['taskdata'], '/home/aerex/.task');
$this->assertArrayHasKey('taskdata', $contents['taskwarrior'], 'config missing taskwarrior.taskdata property'); $this->assertArrayHasKey('project_category_prefix', $taskwarriorConfigs, 'taskwarrior config is missing project_category_prefix property');
$this->assertEquals($contents['taskwarrior']['taskdata'], '/home/aerex/.task'); $this->assertEquals($taskwarriorConfigs['project_category_prefix'], 'project_');
$this->assertArrayHasKey('project_tag_suffix', $contents['taskwarrior'], 'config missing taskwarrior.taskdata property');
$this->assertEquals($contents['taskwarrior']['project_tag_suffix'], 'project_');
} }
} }

View File

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

View File

@@ -1,7 +1,9 @@
logger: general:
file: /home/aerex/baikal-storage-plugin.log logger:
level: DEBUG file: /home/aerex/baikal-storage-plugin.log
taskwarrior: level: DEBUG
taskdata: /home/aerex/.task storages:
taskrc: /home/aerex/.taskrc taskwarrior:
project_tag_suffix: project_ taskdata: /home/aerex/.task
taskrc: /home/aerex/.taskrc
project_category_prefix: project_

View File

@@ -6,7 +6,7 @@ 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\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 {
@@ -27,15 +27,23 @@ class StorageManagerTest extends TestCase {
->getMock(); ->getMock();
$this->mockConsole = $this->createMock(AbstractConsole::class); $this->mockConsole = $this->createMock(AbstractConsole::class);
$this->mockStorage = $this->createMock(Taskwarrior::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() {
$configs = ['taskwarrior' => ['taskrc' => '', 'taskdata' => '']]; $tw = new Taskwarrior($this->mockConsole, $this->configs, $this->mockLogger);
$tw = new Taskwarrior($this->mockConsole, $configs);
$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();
$configs = $manager->getConfigs(); $this->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->assertArrayHasKey('taskwarrior', $storages, 'Storages should have taskwarrior'); $this->assertArrayHasKey('taskwarrior', $storages, 'Storages should have taskwarrior');
} }
@@ -46,8 +54,7 @@ class StorageManagerTest extends TestCase {
->method('save') ->method('save')
->with($this->equalTo($cal)); ->with($this->equalTo($cal));
$configs = ['taskwarrior' => ['taskrc' => '', 'taskdata' => '']]; $manager = new StorageManager($this->configs);
$manager = new StorageManager($configs);
$manager->addStorage(Taskwarrior::NAME, $this->mockStorage); $manager->addStorage(Taskwarrior::NAME, $this->mockStorage);
$manager->import($cal); $manager->import($cal);

View File

@@ -4,6 +4,7 @@ namespace Aerex\BaikalStorage;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
use Aerex\BaikalStorage\AbstractConsole; use Aerex\BaikalStorage\AbstractConsole;
use Aerex\BaikalStorage\Logger;
use Sabre\VObject\Component\VCalendar as Calendar; use Sabre\VObject\Component\VCalendar as Calendar;
use Aerex\BaikalStorage\Storages\Taskwarrior; use Aerex\BaikalStorage\Storages\Taskwarrior;
@@ -16,11 +17,19 @@ class TaskwarriorTest extends TestCase {
protected function setUp(): void { protected function setUp(): void {
$this->mockConsole = $this->createMock(AbstractConsole::class); $this->mockConsole = $this->createMock(AbstractConsole::class);
$this->mockLogger = $this->createMock(Logger::class);
} }
public function testVObjectToTask() { public function testVObjectToTask() {
$configs = ['taskwarrior' => ['taskrc' => '', 'taskdata' => ''], 'logger' => ['file' => '', 'level'=> 'DEBUG', 'enabled' => true]]; $configs = [
$this->taskwarrior = new Taskwarrior($this->mockConsole, $configs); 'general' => [
'logger' => ['file' => '', 'level'=> 'DEBUG', 'enabled' => true],
],
'storages' => [
'taskwarrior' => ['taskrc' => '', 'taskdata' => '']
]
];
$this->taskwarrior = new Taskwarrior($this->mockConsole, $configs, $this->mockLogger);
$vcalendar = new Calendar([ $vcalendar = new Calendar([
'VTODO' => [ 'VTODO' => [
'SUMMARY' => 'Finish project', 'SUMMARY' => 'Finish project',
@@ -40,11 +49,47 @@ class TaskwarriorTest extends TestCase {
$this->assertArrayHasKey('description', $task, 'task should have description'); $this->assertArrayHasKey('description', $task, 'task should have description');
$this->assertEquals((string)$vcalendar->VTODO->SUMMARY, $task['description']); $this->assertEquals((string)$vcalendar->VTODO->SUMMARY, $task['description']);
$this->assertArrayHasKey('due', $task, 'task should have due'); $this->assertArrayHasKey('due', $task, 'task should have due');
$this->assertEquals($vcalendar->VTODO->DUE->getDateTime(), $task['due']); $this->assertEquals($vcalendar->VTODO->DUE->getDateTime()->format(\DateTime::ISO8601), $task['due']);
$this->assertArrayHasKey('entry', $task, 'task should have an entry'); $this->assertArrayHasKey('entry', $task, 'task should have an entry');
$this->assertEquals($vcalendar->VTODO->DTSTAMP->getDateTime(), $task['entry']); $this->assertEquals($vcalendar->VTODO->DTSTAMP->getDateTime()->format(\DateTime::ISO8601), $task['entry']);
$this->assertArrayHasKey('start', $task, 'task should have start'); $this->assertArrayHasKey('start', $task, 'task should have start');
$this->assertEquals($vcalendar->VTODO->DTSTART->getDateTime(), $task['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']);
//
// }
} }