feat: Converted vcalendar todo events to taskwarrior tasks

This commit is contained in:
Aerex 2020-05-12 23:56:22 -05:00
parent 45ea34da94
commit 40b66fb38b
13 changed files with 198 additions and 114 deletions

View File

@ -5,8 +5,11 @@
composer require aerex/baikal-storage-plugin composer require aerex/baikal-storage-plugin
``` ```
## Configuration
Copy sample configuration to your baikal installation. Make sure that the folder is writable
## Usage ## Usage
- Add the plugin to `Core/Frameworks/Baikal/Core/Server.php` - Add the plugin to `Core/Frameworks/Baikal/Core/Server.php`
``` ```
$this->server->addPlugin(new \Aerex\BaikalStorage\Plugin()) $this->server->addPlugin(new \Aerex\BaikalStorage\Plugin(<path-of-config-file>))
``` ```

View File

@ -19,13 +19,13 @@
"php": ">=5.5", "php": ">=5.5",
"sabre/dav" : "~4.0.2", "sabre/dav" : "~4.0.2",
"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": "3.4", "symfony/config": "3.4",
"symfony/process": "^3.4" "symfony/process": "^3.4",
"monolog/monolog": "^2.0"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "^7.4" "phpunit/phpunit": "^7.4"

View File

@ -11,32 +11,18 @@ class ConfigBuilder implements ConfigurationInterface {
private $configs = []; private $configs = [];
private $configDir; private $configDir;
public function __construct($configDir = null) { public function __construct($configDir) {
if (!isset($configDir)) {
$this->configDir = $this->getHomeDir() . '~/.config/baikal';
} else {
$this->configDir = $configDir; $this->configDir = $configDir;
}
$this->processor = new Processor(); $this->processor = new Processor();
} }
private function getHomeDir() {
if (stristr(PHP_OS, 'WIN')) {
return rtrim($_SERVER['HOMEDRIVE'] . $_SERVER['HOMEPATH'], '\\/');
} else {
return rtrim($_SERVER['HOME'], '/');
}
}
public function add($config) { public function add($config) {
$this->configs[] = $config; $this->configs[] = $config;
} }
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();
foreach ($this->configs as $config) { foreach ($this->configs as $config) {
$ref = $ref->append($config->get()); $ref = $ref->append($config->get());
@ -46,10 +32,7 @@ class ConfigBuilder implements ConfigurationInterface {
} }
public function readContent() { public function readContent() {
if (!is_dir($this->configDir)) { $contents = sprintf('%s/storage.yaml', $this->configDir);
mkdir($this->configDir, 0755, true);
}
$contents = sprintf('%s/storage.yml', $this->configDir);
return file_get_contents($contents); return file_get_contents($contents);
} }

View File

@ -6,12 +6,17 @@ use Symfony\Component\Config\Definition\Builder\TreeBuilder;
class TaskwarriorConfig { class TaskwarriorConfig {
public function get() { public function get() {
$treeBuilder = new TreeBuilder('taskwarrior'); $treeBuilder = new TreeBuilder();
$node = $treeBuilder->getRootNode(); $node = $treeBuilder->root('taskwarrior');
$node->children() $node->children()
->scalarNode('data_dir') ->scalarNode('taskdata')
->defaultValue('~/.task') ->defaultValue('~/.task')
->end()
->scalarNode('taskrc')
->defaultValue('~/.taskrc')
->end()
->end(); ->end();
return $node; return $node;
} }
} }

View File

@ -18,14 +18,15 @@ class Console extends AbstractConsole {
} }
} }
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); $stdin[] = $this->convertToString($input);
$process = new Process($stdin);
} }
$process = new Process(implode(' ', $stdin), $input, $envs);
$process->inheritEnvironmentVariables();
try { try {
$process->mustRun(); $process->mustRun();

View File

@ -31,11 +31,6 @@ class Plugin extends ServerPlugin {
*/ */
protected $storageManager; protected $storageManager;
/**
* @var ConfigBuilder
*/
protected $config;
/** /**
* Creates the Taskwarrior plugin * Creates the Taskwarrior plugin
@ -43,14 +38,16 @@ class Plugin extends ServerPlugin {
* @param CalendarProcessor $TWCalManager * @param CalendarProcessor $TWCalManager
* *
*/ */
function __construct($config = null){ function __construct($configDir){
if (isset($config)) { $configs = $this->buildConfigurations($configDir);
$this->config = $config; $this->storageManager = new StorageManager($configs);
} else { $this->initializeStorages($configDir, $configs);
$this->config = new ConfigBuilder();
} }
$this->storageManager = new StorageManager($this->config);
$this->addStorages(); public function buildConfigurations($configDir) {
$this->config = new ConfigBuilder($configDir);
$this->config->add(new TaskwarriorConfig());
return $this->config->loadYaml();
} }
/** /**
@ -58,10 +55,9 @@ class Plugin extends ServerPlugin {
* *
*/ */
public function addStorages() { public function initializeStorages($configDir, $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']), $configDir, $configs);
$this->storageManager->addStorage(Taskwarrior::NAME, $taskwarrior); $this->storageManager->addStorage(Taskwarrior::NAME, $taskwarrior);
$this->storageManager->init();
} }
/** /**

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,12 @@ 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 getStorages() { public function getStorages() {
@ -33,14 +31,9 @@ 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() {
$this->configs = $this->configBuilder->loadYaml();
}
public function import(Calendar $calendar) { 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');
@ -50,7 +43,6 @@ class StorageManager {
if (!isset($storage)){ if (!isset($storage)){
throw new \Exception(); throw new \Exception();
} }
$storage->setRawConfigs($this->configs[$key]);
$storage->save($calendar); $storage->save($calendar);
} }
} }

View File

@ -8,5 +8,4 @@ interface IStorage {
public function save(Calendar $c); public function save(Calendar $c);
public function refresh(); public function refresh();
public function getConfig(); public function getConfig();
public function setRawConfigs($rawConfigs);
} }

View File

@ -8,25 +8,22 @@ use Carbon\Carbon;
class Taskwarrior implements IStorage { class Taskwarrior implements IStorage {
private const DATA_FILES = ['pending.data', 'completed.data', 'undo.data']; 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 $configDir;
private $configs;
public function __construct($console, $configDir, $configs) {
$this->console = $console; $this->console = $console;
$this->config = $config; $this->configDir = $configDir;
$this->configs = $configs['taskwarrior'];
} }
public function getConfig() { public function getConfig() {
return $this->config; return $this->config;
} }
public function setRawConfigs($rawConfigs) {
$this->rawConfigs = $rawConfigs;
}
public function refresh() { public function refresh() {
$dataDir = $this->rawConfigs['data_dir']; $fp = fopen(sprintf('%s/taskwarrior-baikal-storage.lock', $this->configDir), 'a');
$fp = fopen(sprintf('%s/taskwarrior-baikal-storage.lock', $dataDir), 'a');
if (!$fp || !flock($fp, LOCK_EX | LOCK_NB, $eWouldBlock) || $eWouldBlock) { if (!$fp || !flock($fp, LOCK_EX | LOCK_NB, $eWouldBlock) || $eWouldBlock) {
fputs(STDERR, 'Could not get lock'); fputs(STDERR, 'Could not get lock');
@ -35,7 +32,7 @@ class Taskwarrior implements IStorage {
$mtime = 0; $mtime = 0;
$tasksUpdated = false; $tasksUpdated = false;
foreach (Taskwarrior::DATA_FILES as $dataFile) { foreach (Taskwarrior::DATA_FILES as $dataFile) {
$fmtime = filemtime(sprintf('%s/%s', $this->config['data_dir'], $dataFile)); $fmtime = filemtime(sprintf('%s/%s', $this->configs['taskdata'], $dataFile));
if ($fmtime > $mtime) { if ($fmtime > $mtime) {
$mtime = $fmtime; $mtime = $fmtime;
$tasksUpdated = true; $tasksUpdated = true;
@ -43,38 +40,107 @@ class Taskwarrior implements IStorage {
} }
if ($tasksUpdated) { if ($tasksUpdated) {
$tasks = $this->console->execute('task', ['export']); $tasks = json_decode($this->console->execute('task', ['export'], null,
['TASKRC' => $this->configs['taskrc'], 'TASKDATA' => $this->configs['taskdata']]), true);
foreach ($tasks as $task) { foreach ($tasks as $task) {
$this->tasks[$task['uuid']] = $task; $this->tasks[$task['uuid']] = $task;
} }
} }
fclose($fp); fclose($fp);
unlink(sprintf('%s/taskwarrior-baikal-storage.lock', $dataDir)); unlink(sprintf('%s/taskwarrior-baikal-storage.lock', $this->configDir));
} }
public function vObjectToTask($vtodo) { public function vObjectToTask($vtodo) {
if ($this->tasks['uid'] == $vtodo->UID) { if (isset($this->tasks['uid']) && $this->tasks['uid'] == $vtodo->UID) {
$task = $this->tasks['uid']; $task = $this->tasks['uid'];
} else { } else {
$task = []; $task = [];
$task['uid'] = $vtodo->UID; $task['uid'] = (string)$vtodo->UID;
} }
if (!isset($vtodo->DESCRIPTION) && isset($vtodo->SUMMARY)){ if (!isset($vtodo->DESCRIPTION) && isset($vtodo->SUMMARY)){
$task['description'] = $vtodo->SUMMARY; $task['description'] = (string)$vtodo->SUMMARY;
} else { } else {
$task['description'] = $vtodo->DESCRIPTION; $task['description'] = (string)$vtodo->DESCRIPTION;
} }
if (isset($vtodo->DTSTAMP)){ if (isset($vtodo->DTSTAMP)){
$task['entry'] = new Carbon($vtodo->DTSTAMP->getDateTime()->format(\DateTime::W3C)); $task['entry'] = new Carbon($vtodo->DTSTAMP->getDateTime()->format(\DateTime::W3C));
} }
if (isset($vtodo->DTSTART)) {
$task['start'] = new Carbon($vtodo->DTSTART->getDateTime()->format(\DateTime::W3C));
}
if (isset($vtodo->DTEND)){
$task['end'] = new Carbon($vtodo->DTEND->getDateTime()->format(\DateTime::W3C));
}
if (isset($vtodo->{'LAST-MODIFIED'})) {
$task['modified'] = new Carbon($vtodo->{'LAST-MODIFIED'}->getDateTime()->format(\DateTime::W3C));
}
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)){ if (isset($vtodo->DUE)){
$task['due'] = new Carbon($vtodo->DUE->getDateTime()->format(\DateTime::W3C)); $task['due'] = new Carbon($vtodo->DUE->getDateTime()->format(\DateTime::W3C));
} }
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'] = new Carbon($vtodo->DTSTAMP->getDateTime()->format(\DateTime::W3C));
}
break;
case 'CANCELED':
$task['status'] = 'deleted';
if (!isset($task['end'])) {
$task['end'] = new Carbon($vtodo->DTSTAMP->getDateTime()->format(\DateTime::W3C));
}
break;
}
}
if (isset($vtodo->CATEGORIES)) {
$task['tags'] = [];
foreach ($vtodo->CATEGORIES as $category) {
if (isset($this->configs['project_tag_suffix'])) {
$projTagSuffixRegExp = sprintf('/^%s_/', $this->configs['project_tag_suffix']);
if (preg_match($category, $projTagSuffixRegExp)) {
$task['project'] = preg_replace($projTagSuffixRegExp, '', $category);
continue;
}
}
$task['tags'] = $category;
}
}
return $task; return $task;
} }
@ -84,6 +150,7 @@ class Taskwarrior implements IStorage {
} }
$this->refresh(); $this->refresh();
$task = $this->vObjectToTask($c->VTODO); $task = $this->vObjectToTask($c->VTODO);
$this->console->execute('task', ['import'], $task); $this->console->execute('task', ['import'], $task,
['TASKRC' => $this->configs['taskrc'],'TASKDATA' => $this->configs['taskdata']]);
} }
} }

View File

@ -9,7 +9,7 @@
<testsuite name="Baikal Storage Plug Tests"> <testsuite name="Baikal Storage Plug Tests">
<directory>./lib/tests</directory> <directory>./lib/tests/</directory>
</testsuite> </testsuite>
<filter> <filter>

View File

@ -1,2 +1,4 @@
taskwarrior: taskwarrior:
data_dir: '~/task' taskdata: '/home/user/.task'
taskrc: '~/home/user/.taskrc'
project_tag_suffix: 'project_'

View File

@ -31,40 +31,25 @@ class StorageManagerTest extends TestCase {
} }
public function testAddTaskwarriorStorage() { public function testAddTaskwarriorStorage() {
$this->mockConfigBuilder->expects($this->once()) $configs = ['taskwarrior' => ['taskrc' => '', 'taskdata' => '']];
->method('readContent') $tw = new Taskwarrior($this->mockConsole, '', $configs);
->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();
$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); $configs = ['taskwarrior' => ['taskrc' => '', 'taskdata' => '']];
$manager = new StorageManager($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,51 @@
<?php
namespace Aerex\BaikalStorage;
use PHPUnit\Framework\TestCase;
use Aerex\BaikalStorage\AbstractConsole;
use Sabre\VObject\Component\VCalendar as Calendar;
use Aerex\BaikalStorage\Storages\Taskwarrior;
class TaskwarriorTest extends TestCase {
/**
* @var \PHPUnit_Framework_MockObject_MockObject
* */
private $mockConsole;
function setUp() {
$this->mockConsole = $this->createMock(AbstractConsole::class);
}
public function testVObjectToTask() {
$configs = ['taskwarrior' => ['taskrc' => '', 'taskdata' => '']];
$this->taskwarrior = new Taskwarrior($this->mockConsole, '', $configs);
$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'
]
]);
echo $vcalendar->VTODO->RRULE->getJsonValue()[0]['freq'];
$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']);
}
}