├── tests ├── __init__.py ├── _setup_alias ├── README ├── test_cal.py ├── test_calendar-cli.sh └── tests.sh ├── calendar_cli ├── __init__.py ├── metadata.py ├── template.py ├── config.py └── legacy.py ├── bin ├── calendar-cli └── calendar-cli.py ├── setup.py ├── examples └── task-management-examples ├── README.md ├── TASK_MANAGEMENT.md └── LICENSE.TXT /tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /calendar_cli/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /bin/calendar-cli: -------------------------------------------------------------------------------- 1 | calendar-cli.py -------------------------------------------------------------------------------- /bin/calendar-cli.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import calendar_cli.legacy 4 | calendar_cli.legacy.main() 5 | -------------------------------------------------------------------------------- /calendar_cli/metadata.py: -------------------------------------------------------------------------------- 1 | metadata = { 2 | "version": "1.0.1", 3 | "author": "Tobias Brox", 4 | "author_short": "tobixen", 5 | "copyright": "Copyright 2013-2022, Tobias Brox and contributors", 6 | "license": "GPLv3+", 7 | "license_url": "http://www.gnu.org/licenses/gpl-3.0-standalone.html", 8 | "maintainer": "Tobias Brox", 9 | "author_email": "t-calendar-cli@tobixen.no", 10 | "status": "Development", 11 | "product": "calendar_cli", 12 | "name": "calendar_cli", 13 | "description": "Simple command-line CalDav client, for adding and browsing calendar items, todo list items, etc.", 14 | "url": "https://github.com/tobixen/calendar-cli", 15 | } 16 | -------------------------------------------------------------------------------- /tests/_setup_alias: -------------------------------------------------------------------------------- 1 | test_init() { 2 | set -o pipefail 3 | __test_outfile=$(mktemp) 4 | } 5 | 6 | error() { 7 | echo "FAILURE" 8 | echo "$1" 9 | echo "sleeping 3" 10 | sleep 3 11 | exit 255 12 | } 13 | 14 | find_executable_to_test() { 15 | local candidate 16 | 17 | for candidate in \ 18 | './calendar-cli.py' \ 19 | '../calendar-cli.py' \ 20 | './bin/calendar-cli.py' 21 | do 22 | if [ -x "$candidate" ]; then 23 | echo "$candidate" 24 | return 0 25 | fi 26 | done 27 | 28 | error "couldn't find ./calendar_cli.py nor ../calendar_cli.py" 29 | } 30 | 31 | set_test_command() { 32 | __test_cmd_with_args="$*" 33 | } 34 | 35 | calendar_cli() { 36 | echo " $__test_cmd_with_args $*" 37 | __test_output=$($__test_cmd_with_args "$@" | tee $outfile) 38 | [ -z "$__test_output" ] || [ -z "$QUIET" ] || echo $__test_output 39 | } 40 | 41 | # vim: ft=bash 42 | -------------------------------------------------------------------------------- /tests/README: -------------------------------------------------------------------------------- 1 | TL;DR: do run test_calendar-cli.sh, don't run tests.sh - unless you know what 2 | you're doing. 3 | 4 | test_calendar-cli.sh will attempt to set up a radicale server and a xandikos 5 | server, and run tests.sh towards those two. At least one of those should be 6 | installed for the tests to work. It will bind up some hard coded ports on 7 | localhost, tests will fail if those ports are already in use. (Oups - xandikos 8 | doesn't work very well together with calendar-cli at the moment, so it has been 9 | skipped). 10 | 11 | The actual tests are in tests.sh. You'll have to run this one if you want to 12 | check compatibility with other calendar servers, but it requires either that 13 | the $calendar_cli environmental variable is set, or that some calendar server 14 | is configured in .config/calendar.conf. If you choose to run the tests towards 15 | some old, existing calendar, then be aware that the test code may eventually 16 | delete some historic data from 2010. 17 | 18 | Probably we should add some standard python test code here that can be run 19 | through pytest and/or tox, but after all this is a command line utility - hence 20 | I found it appropriate to start with functional tests written to be executed 21 | from through a shell. 22 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import sys 4 | import os 5 | 6 | from setuptools import setup, find_packages 7 | 8 | from calendar_cli.metadata import metadata 9 | metadata_ = metadata.copy() 10 | 11 | for x in metadata: 12 | if not x in ('author', 'version', 'license', 'maintainer', 'author_email', 13 | 'status', 'name', 'description', 'url', 'description'): 14 | metadata_.pop(x) 15 | 16 | setup( 17 | packages=['calendar_cli', 18 | ], 19 | classifiers=[ 20 | #"Development Status :: ..." 21 | "Environment :: Web Environment", 22 | #"Intended Audience :: Developers", 23 | "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", 24 | "Operating System :: POSIX", 25 | "Programming Language :: Python", 26 | "Topic :: Internet :: WWW/HTTP", 27 | "Topic :: Internet :: WWW/HTTP :: Dynamic Content :: CGI Tools/Libraries", 28 | ], 29 | scripts=['bin/calendar-cli.py', 'bin/calendar-cli'], 30 | install_requires=[ 31 | 'icalendar', 32 | 'caldav>=0.12-dev0', 33 | # 'isodate', 34 | 'pytz', ## pytz is supposed to be obsoleted, but see https://github.com/collective/icalendar/issues/333 35 | 'pyyaml', 36 | 'tzlocal', 37 | 'Click', 38 | 'six', 39 | 'vobject' 40 | ], 41 | **metadata_ 42 | ) 43 | -------------------------------------------------------------------------------- /calendar_cli/template.py: -------------------------------------------------------------------------------- 1 | """String formatter that allows default values to be passed in the 2 | template string. 3 | 4 | This does not really belong in the calendar-cli package. I was 5 | googling a bit, and didn't find anything like this out there ... but 6 | I'm sure there must exist something like this?""" 7 | 8 | import datetime 9 | import string 10 | import re 11 | 12 | class NoValue(): 13 | def __getattr__(self, attr): 14 | return self 15 | def __getitem__(self, attr): 16 | return self 17 | def __str__(self): 18 | return "" 19 | def __format__(self, spec): 20 | try: 21 | return "".__format__(spec) 22 | except: 23 | return "" 24 | 25 | no_value = NoValue() 26 | 27 | class Template(string.Formatter): 28 | def __init__(self, template): 29 | self.template = template 30 | 31 | def format(self, *pargs, **kwargs): 32 | return super().format(self.template, *pargs, **kwargs) 33 | 34 | def get_value(self, key, args, kwds): 35 | try: 36 | return string.Formatter.get_value(self, key, args, kwds) 37 | except: 38 | return no_value 39 | 40 | def format_field(self, value, format_spec): 41 | rx = re.match(r'\?([^\?]*)\?(.*)', format_spec) 42 | if rx: 43 | format_spec = rx.group(2) 44 | if value is no_value: 45 | value = rx.group(1) 46 | try: 47 | return string.Formatter.format_field(self, value, format_spec) 48 | except: 49 | return string.Formatter.format_field(self, value, "") 50 | -------------------------------------------------------------------------------- /tests/test_cal.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import sys 3 | sys.path.insert(0,'.') 4 | sys.path.insert(1,'..') 5 | from datetime import datetime, date 6 | from calendar_cli.template import Template 7 | 8 | """calendar-cli is a command line utility, and it's an explicit design 9 | goal that it should contain minimal logic except for parsing and 10 | passing command line options and parameters to the caldav library and 11 | printing output from the caldav library. Functional tests verifying 12 | that the tool actually works as intended is done through shell 13 | scripts, and can be run through test_calendar-cli.sh. There is no 14 | goal to get complete code coverage through this unit test, though any 15 | "extra" logic except for simple passing of options and parameters to 16 | the caldav library ought to be tested here. """ 17 | 18 | class TestTemplate: 19 | def setup_method(self): 20 | self.date = date(1990, 10, 10) 21 | 22 | def test_formatting_with_timespec(self): 23 | template=Template("This is an ISO date: {date:%F}") 24 | text = template.format(date=self.date) 25 | assert text == "This is an ISO date: 1990-10-10" 26 | 27 | text = template.format(foo=self.date) 28 | assert text == "This is an ISO date: " 29 | 30 | def test_formatting_with_simple_default(self): 31 | template=Template("This is an ISO date: {date:?(date is missing)?%F}") 32 | text = template.format(date=self.date) 33 | assert text == "This is an ISO date: 1990-10-10" 34 | 35 | text = template.format(foo=self.date) 36 | assert text == "This is an ISO date: (date is missing)" 37 | 38 | def test_subvalue_with_default(self): 39 | template = Template("This is a year: {date.year:?NA?>5}") 40 | text = template.format(date=self.date) 41 | assert text == "This is a year: 1990" 42 | text = template.format(foo=self.date) 43 | assert text == "This is a year: NA" 44 | 45 | def test_missing_replaced_with_advanced_default(self): 46 | template = Template("Date is maybe {date:?{foo}?%F}") 47 | text = template.format(date=self.date) 48 | assert text == "Date is maybe 1990-10-10" 49 | text = template.format(foo=self.date) 50 | assert text == "Date is maybe 1990-10-10" 51 | text = template.format(foo=self.date, date=self.date) 52 | assert text == "Date is maybe 1990-10-10" 53 | 54 | def test_missing_replaced_with_even_more_advanced_default(self): 55 | template = Template("Date is maybe {date:?{foo:?bar?}?%F}") 56 | text = template.format(date=self.date) 57 | assert text == "Date is maybe 1990-10-10" 58 | text = template.format(foo=self.date) 59 | assert text == "Date is maybe 1990-10-10" 60 | text = template.format(foo=self.date, date=self.date) 61 | assert text == "Date is maybe 1990-10-10" 62 | text = template.format() 63 | assert text == "Date is maybe bar" 64 | -------------------------------------------------------------------------------- /tests/test_calendar-cli.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | [ "$PYTHON3" ] || PYTHON3='python3' 4 | 5 | storage=$(mktemp -d) 6 | 7 | echo "This script will attempt to set up a Radicale server and a Xandikos server and run the test code towards those two servers" 8 | echo "The test code itself is found in tests.sh" 9 | 10 | export RUNTESTSNOPAUSE="foo" 11 | 12 | echo "########################################################################" 13 | echo "## RADICALE" 14 | echo "########################################################################" 15 | sh -c "$PYTHON3 -m radicale --storage-filesystem-folder='$storage' \ 16 | ${DAEMONS_OUTPUT_TO_FILES:+>$storage/radicale.stdout} \ 17 | ${DAEMONS_OUTPUT_TO_FILES:+2>$storage/radicale.stderr}" & 18 | radicale_pid=$! 19 | sleep 0.3 20 | if [ -n "$radicale_pid" ]; then 21 | echo "## Radicale now running on pid $radicale_pid" 22 | calendar_cli="env PYTHONPATH=..:$PYTHONPATH $( printf "%s%s%s%s" '../bin/calendar-cli.py ' \ 23 | '--caldav-url=http://localhost:5232/ --caldav-pass=password1 ' \ 24 | '--caldav-user=testuser ' \ 25 | '--calendar-url=/testuser/calendar-cli-test-calendar' )" 26 | echo "## Creating a calendar" 27 | $calendar_cli calendar create calendar-cli-test-calendar 28 | 29 | ## crazy, now I get a 403 forbidden on the calendar create, but 30 | ## the calendar is created. Without the statement above, I'll 31 | ## just get 404 when running tests. 32 | if [ -n "$DEBUG" ]; then 33 | echo "press enter to run tests" 34 | read -r 35 | fi 36 | ./tests.sh "$calendar_cli" 37 | if [ -n "$DEBUG" ]; then 38 | echo "press enter to take down test server" 39 | read -r 40 | fi 41 | kill "$radicale_pid" 42 | sleep 0.3 43 | else 44 | echo "## Could not start up radicale (is it installed?). Will skip running tests towards radicale" 45 | fi 46 | 47 | 48 | echo "########################################################################" 49 | echo "## XANDIKOS" 50 | echo "########################################################################" 51 | xandikos_bin=$(which xandikos 2> /dev/null) 52 | if [ -n "$xandikos_bin" ]; then 53 | sh -c "$xandikos_bin --defaults -d '$storage' \ 54 | ${DAEMONS_OUTPUT_TO_FILES:+>$storage/xandikos.stdout} \ 55 | ${DAEMONS_OUTPUT_TO_FILES:+2>$storage/xandikos.stderr}" & 56 | xandikos_pid=$! 57 | sleep 0.5 58 | fi 59 | 60 | if [ -n "$xandikos_pid" ]; then 61 | echo "## Xandikos now running on pid $xandikos_pid" 62 | calendar_cli="../bin/calendar-cli --caldav-url=http://localhost:8080/ --caldav-user=user" 63 | 64 | ./tests.sh "$calendar_cli" 65 | kill "$xandikos_pid" 66 | else 67 | echo "## Could not start up xandikos (is it installed?). Will skip running tests towards xandikos" 68 | fi 69 | 70 | 71 | echo "########################################################################" 72 | echo "## cleanup" 73 | echo "########################################################################" 74 | rm -rf "$storage" 75 | -------------------------------------------------------------------------------- /examples/task-management-examples: -------------------------------------------------------------------------------- 1 | ## This was my daily task management workflow for a while. 2 | 3 | ## Eventually I'd like to make calendar-cli easier to use, so some of the "external logic" in those examples will eventually be moved into the tool itself. Anyway, some of the power of having a command-line utility is that it's possible to do just anything ... 4 | 5 | [ -z "$EDITOR" ] && EDITOR=vi 6 | 7 | echo "Enter a category or enter for all:" 8 | read category 9 | if [ -n "$category" ] 10 | then 11 | selflags="--categories=$category" 12 | fi 13 | 14 | ## Take out a personal agenda from different calendar sources: 15 | 16 | echo "Here is your upcoming calendar events:" 17 | for section in pir seb house default work holidays 18 | do 19 | calendar-cli --config-section $section calendar agenda --agenda-days 20 20 | done | sort 21 | 22 | echo -e "\nAnd here is your upcoming calendar tasks:" 23 | for section in seb house default work-tasks pir-tasks 24 | do 25 | echo $section 26 | calendar-cli --config-section $section todo $selflags --limit 10 --hide-parent list 27 | done 28 | 29 | 30 | ## Interactively set categories on uncategorized tasks: 31 | tempfile=$(mktemp) 32 | calendar-cli todo --nocategories list --todo-template='calendar-cli todo --todo-uid={uid} edit --set-categories=foo # {summary}' > $tempfile 33 | if [ -s $tempfile ] 34 | then 35 | ## We have non-categorized tasks 36 | echo -e "\nNext up: categorization of uncategorized tasks. Press enter" 37 | read 38 | tempfile2=$(mktemp) 39 | ## Populate the tempfile with the list of categories first 40 | calendar-cli todo list --list-categories | perl -pe 's/^/# /' > $tempfile2 41 | cat $tempfile >> $tempfile2 42 | while grep -q -- '--set-categories=foo ' $tempfile2 43 | do 44 | $EDITOR $tempfile2 45 | done 46 | . $tempfile2 47 | rm $tempfile2 48 | else 49 | echo "No uncategorized todo-items on the calendar. Good!" 50 | fi 51 | 52 | 53 | ## Interactively mark tasks as completed: 54 | calendar-cli todo $selflags --hide-parents --limit 12 list --todo-template='# calendar-cli todo --todo-uid={uid} complete # {summary}' > $tempfile 55 | ## Exit if there aren't any tasks 56 | if [ ! -s $tempfile ] 57 | then 58 | echo "No tasks available. Good?" 59 | exit 0 60 | fi 61 | 62 | echo -e "\nNext up: Mark tasks that are completed as completed. Press enter" 63 | read 64 | $EDITOR $tempfile 65 | . $tempfile 66 | 67 | ## Set more realistic due-dates on overdue tasks 68 | calendar-cli todo --overdue list --todo-template='calendar-cli todo --todo-uid={uid} postpone --due "in 15d" # {summary}' > $tempfile 69 | if [ -s $tempfile ] 70 | then 71 | echo -e "\nNext up: Look over overdue tasks and consider procrastinating some of them. Press enter" 72 | read 73 | $EDITOR $tempfile 74 | . $tempfile 75 | fi 76 | 77 | ## Clean the list a bit by procrastinating tasks (this includes the overdue) 78 | calendar-cli todo --limit 10 --hide-future list --todo-template='calendar-cli todo --todo-uid={uid} postpone "in 4d" # {summary}' > $tempfile 79 | if [ -s $tempfile ] 80 | then 81 | echo -e "\nNext up: Consider procrastinating the start-date of some of the tasks on your list. Press enter" 82 | read 83 | $EDITOR $tempfile 84 | . $tempfile 85 | fi 86 | 87 | ## Simple sync of a google calendar into personal calendar 88 | wget -O- https://www.google.com/calendar/ical/gsmk.gcal%40gmail.com/public/basic.ics | calendar-cli calendar addics 89 | 90 | 91 | echo "Done!" 92 | 93 | -------------------------------------------------------------------------------- /calendar_cli/config.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import json 3 | import yaml 4 | from fnmatch import fnmatch 5 | 6 | def interactive_config(args, config, remaining_argv): 7 | import readline 8 | 9 | new_config = False 10 | section = 'default' 11 | backup = {} 12 | modified = False 13 | 14 | print("Welcome to the interactive calendar configuration mode") 15 | print("Warning - untested code ahead, raise issues at t-calendar-cli@tobixen.no or the github issue tracker") 16 | print("It might be a good idea to read the documentation in parallel if running this for your first time") 17 | if not config or not hasattr(config, 'keys'): 18 | config = {} 19 | print("No valid existing configuration found") 20 | new_config = True 21 | if config: 22 | print("The following sections have been found: ") 23 | print("\n".join(config.keys())) 24 | if args.config_section and args.config_section != 'default': 25 | section = args.config_section 26 | else: 27 | ## TODO: tab completion 28 | section = raw_input("Chose one of those, or a new name / no name for a new configuration section: ") 29 | if section in config: 30 | backup = config[section].copy() 31 | print("Using section " + section) 32 | else: 33 | section = 'default' 34 | 35 | if not section in config: 36 | config[section] = {} 37 | 38 | for config_key in ('caldav_url', 'calendar_url', 'caldav_user', 'caldav_pass', 'caldav_proxy', 'ssl_verify_cert', 'language', 'timezone', 'inherits'): 39 | 40 | if config_key == 'caldav_pass': 41 | print("Config option caldav_pass - old value: **HIDDEN**") 42 | value = getpass(prompt="Enter new value (or just enter to keep the old): ") 43 | else: 44 | print("Config option %s - old value: %s" % (config_key, config[section].get(config_key, '(None)'))) 45 | value = raw_input("Enter new value (or just enter to keep the old): ") 46 | 47 | if value: 48 | config[section][config_key] = value 49 | modified = True 50 | 51 | if not modified: 52 | print("No configuration changes have been done") 53 | else: 54 | state = 'start' 55 | while state == 'start': 56 | options = [] 57 | if section: 58 | options.append(('save', 'save configuration into section %s' % section)) 59 | if backup or not section: 60 | options.append(('save_other', 'add this new configuration into a new section in the configuration file')) 61 | if remaining_argv: 62 | options.append(('use', 'use this configuration without saving')) 63 | options.append(('abort', 'abort without saving')) 64 | print("CONFIGURATION DONE ...") 65 | for o in options: 66 | print("Type %s if you want to %s" % o) 67 | cmd = raw_input("Enter a command: ") 68 | if cmd in ('use', 'abort'): 69 | state = 'done' 70 | if cmd in ('save', 'save_other'): 71 | if cmd == 'save_other': 72 | new_section = raw_input("New config section name: ") 73 | config[new_section] = config[section] 74 | if backup: 75 | config[section] = backup 76 | else: 77 | del config[section] 78 | section = new_section 79 | try: 80 | if os.path.isfile(args.config_file): 81 | os.rename(args.config_file, "%s.%s.bak" % (args.config_file, int(time.time()))) 82 | with open(args.config_file, 'w') as outfile: 83 | json.dump(config, outfile, indent=4) 84 | except Exception as e: 85 | print(e) 86 | else: 87 | print("Saved config") 88 | state = 'done' 89 | 90 | if args.config_section == 'default' and section != 'default': 91 | config['default'] = config[section] 92 | return config 93 | 94 | ## TODO TODO TODO - write test code for all the corner cases 95 | ## TODO TODO TODO - write documentation of config format 96 | def expand_config_section(config, section='default', blacklist=None): 97 | """ 98 | In the "normal" case, will return [ section ] 99 | 100 | We allow: 101 | 102 | * * includes all sections in config file 103 | * "Meta"-sections in the config file with the keyword "contains" followed by a list of section names 104 | * Recursive "meta"-sections 105 | * Glob patterns (work_* for all sections starting with work_) 106 | * Glob patterns in "meta"-sections 107 | """ 108 | ## Optimizating for a special case. The results should be the same without this optimization. 109 | if section == '*': 110 | return [x for x in config if not config[x].get('disable', False)] 111 | 112 | ## If it's not a glob-pattern ... 113 | if set(section).isdisjoint(set('[*?')): 114 | ## If it's referring to a "meta section" with the "contains" keyword 115 | if 'contains' in config[section]: 116 | results = set() 117 | if not blacklist: 118 | blacklist = set() 119 | blacklist.add(section) 120 | for subsection in config[section]['contains']: 121 | if not subsection in results and not subsection in blacklist: 122 | for recursivesubsection in expand_config_section(config, subsection, blacklist): 123 | results.add(recursivesubsection) 124 | return results 125 | else: 126 | ## Disabled sections should be ignored 127 | if config.get('section', {}).get('disable', False): 128 | return [] 129 | 130 | ## NORMAL CASE - return [ section ] 131 | return [ section ] 132 | ## section name is a glob pattern 133 | matching_sections = [x for x in config if fnmatch(x, section)] 134 | results = set() 135 | for s in matching_sections: 136 | if set(s).isdisjoint(set('[*?')): 137 | results.update(expand_config_section(config, s)) 138 | else: 139 | ## Section names shouldn't contain []?* ... but in case they do ... don't recurse 140 | results.add(s) 141 | return results 142 | 143 | def config_section(config, section='default'): 144 | if section in config and 'inherits' in config[section]: 145 | ret = config_section(config, config[section]['inherits']) 146 | else: 147 | ret = {} 148 | if section in config: 149 | ret.update(config[section]) 150 | return ret 151 | 152 | def read_config(fn, interactive_error=False): 153 | ## This can probably be refactored into fewer lines ... 154 | try: 155 | try: 156 | with open(fn, 'rb') as config_file: 157 | return json.load(config_file) 158 | except json.decoder.JSONDecodeError: 159 | try: 160 | with open(fn, 'rb') as config_file: 161 | return yaml.load(config_file, yaml.Loader) 162 | except yaml.scanner.ScannerError: 163 | logging.error("config file exists but is neither valid json nor yaml. Check the syntax.") 164 | 165 | except FileNotFoundError: 166 | ## File not found 167 | logging.info("no config file found") 168 | except ValueError: 169 | if interactive_error: 170 | logging.error("error in config file. Be aware that the interactive configuration will ignore and overwrite the current broken config file", exc_info=True) 171 | else: 172 | logging.error("error in config file. It will be ignored", exc_info=True) 173 | return {} 174 | -------------------------------------------------------------------------------- /tests/tests.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e 4 | 5 | if [ "$1" ]; then 6 | calendar_cli="$*" 7 | fi 8 | 9 | ######################################################################## 10 | ## SETUP 11 | ######################################################################## 12 | 13 | for path in . .. ./tests ../tests; do 14 | setup="$path/_setup_alias" 15 | if [ -f $setup ]; then 16 | source $setup 17 | test_init 18 | [ "$calendar_cli" ] || calendar_cli="$( find_executable_to_test )" 19 | fi 20 | done 21 | set_test_command "$calendar_cli" 22 | 23 | if [ -z "$RUNTESTSNOPAUSE" ]; then 24 | echo "tests.sh" 25 | echo 26 | echo "Generally, tests.sh should only be run directly if you know what you are doing" 27 | echo "You may want to use test_calendar-cli.sh instead" 28 | echo 29 | echo "This script will use the following commands to access a calendar server:" 30 | echo 31 | echo "$calendar_cli" 32 | echo 33 | echo "This may work if you have configured a calendar server." 34 | echo "The tests will add and delete events and tasks." 35 | echo "Content from 2010-10 may be deleted" 36 | echo 37 | echo "Press enter or ctrl-C" 38 | read -r 39 | fi 40 | 41 | 42 | echo "## CLEANUP from earlier failed test runs, if any" 43 | 44 | export QUIET=true 45 | for uid in $( 46 | $calendar_cli calendar agenda --from-time=2010-10-09 --agenda-days=5 \ 47 | --event-template='{uid}') 48 | do 49 | $calendar_cli calendar delete --event-uid="$uid" 50 | done 51 | $calendar_cli todo --categories scripttest delete 52 | unset QUIET 53 | 54 | ######################################################################## 55 | ## TEST CODE FOLLOWS 56 | ######################################################################## 57 | 58 | echo "## EVENTS" 59 | 60 | echo "## testing $calendar_cli" 61 | echo "## this is a very simple test script without advanced error handling" 62 | echo "## if this test script doesn't output 'ALL TESTS COMPLETED! YAY!' in the end, something went wrong" 63 | 64 | echo "## Attempting to add an event at 2010-10-09 20:00:00, 2 hours duration" 65 | calendar_cli calendar add '2010-10-09 20:00:00+2h' 'testing testing' 66 | uid=$(echo $__test_output | perl -ne '/uid=(.*)$/ && print $1') 67 | [ -n "$uid" ] || error "got no UID back" 68 | 69 | echo "## Attempting to add an event at 2010-10-10 20:00:00, CET (1 hour duration is default), with description and non-ascii location" 70 | calendar_cli calendar add '2010-10-10 20:00:00+01:00' 'testing testing' --set-description='this is a test calendar event' --set-location='Москва' 71 | uid2=$(echo $__test_output | perl -ne '/uid=(.*)$/ && print $1') 72 | [ -n "$uid2" ] || error "got no UID back" 73 | 74 | echo "## Attempting to add an event at 2010-10-11 20:00:00, CET, 3h duration" 75 | calendar_cli calendar add '2010-10-11 20:00:00+01:00+3h' 'testing testing' 76 | uid3=$(echo $__test_output | perl -ne '/uid=(.*)$/ && print $1') 77 | echo "## OK: Added the event, uid is $uid" 78 | 79 | echo "## Taking out the agenda for 2010-10-09 + four days" 80 | calendar_cli calendar agenda --from-time=2010-10-09 --agenda-days=4 --event-template='{description} {location}' 81 | echo $__test_output | { grep -q 'this is a test calendar event Москва' && echo "## OK: found the event" ; } || error "didn't find the event" 82 | 83 | echo "## Taking out the agenda for 2010-10-10, with uid" 84 | calendar_cli calendar agenda --from-time=2010-10-10 --agenda-days=1 --event-template='{dtstart} {uid}' 85 | echo $__test_output | { grep -q $uid2 && echo "## OK: found the UID" ; } || error "didn't find the UID" 86 | 87 | echo "## Deleting events with uid $uid $uid2 $uid3" 88 | calendar_cli calendar delete --event-uid=$uid 89 | calendar_cli calendar delete --event-uid=$uid2 90 | calendar_cli calendar delete --event-uid=$uid3 91 | 92 | echo "## Searching again for the deleted event" 93 | calendar_cli calendar agenda --from-time=2010-10-10 --agenda-days=3 94 | echo $__test_output | { grep -q 'testing testing' && error "still found the event" ; } || echo "## OK: didn't find the event" 95 | 96 | echo "## Adding a full day event" 97 | calendar_cli calendar add --whole-day '2010-10-10+4d' 'whole day testing' 98 | uid=$(echo $__test_output | perl -ne '/uid=(.*)$/ && print $1') 99 | [ -n "$uid" ] || error "got no UID back" 100 | 101 | echo "## fetching the full day event, in ics format" 102 | calendar_cli --icalendar calendar agenda --from-time=2010-10-13 --agenda-days=1 103 | 104 | echo "$__test_output" | grep -q "whole day" || error "could not find the event" 105 | echo "$__test_output" | grep -q "20101010" || error "could not find the date" 106 | echo "$__test_output" | grep -q "20101010T" && error "a supposed whole day event was found to be with the time of day" 107 | echo "OK: found the event" 108 | 109 | echo "## cleanup, delete it" 110 | calendar_cli calendar delete --event-uid=$uid 111 | 112 | ## TODO - procrastinated, waiting for response on https://github.com/dateutil/dateutil/issues/1184 113 | #uid=$(echo $__test_output | perl -ne '/uid=(.*)$/ && print $1') 114 | #[ -n "$uid" ] || error "got no UID back" 115 | #calendar_cli --icalendar calendar agenda --from-time=2010-10-13 --agenda-days=1 116 | #echo "$__test_output" | grep -q "whole day" || error "could not find the event" 117 | #echo "$__test_output" | grep -q "20101010" || error "could not find the date" 118 | #echo "$__test_output" | grep -q "20101010T" && error "a supposed whole day event was found to be with the time of day" 119 | #echo "OK: found the event" 120 | #echo "## cleanup, delete it" 121 | #calendar_cli calendar delete --event-uid=$uid 122 | 123 | echo "## A full day event should be implicit when giving dates rather than timestamps" 124 | calendar_cli calendar add '2010-10-10+3d' 'whole day testing' 125 | uid=$(echo $__test_output | perl -ne '/uid=(.*)$/ && print $1') 126 | [ -n "$uid" ] || error "got no UID back" 127 | 128 | echo "## fetching the full day event, in ics format" 129 | calendar_cli --icalendar calendar agenda --from-time=2010-10-12 --agenda-days=1 130 | 131 | echo "$__test_output" | grep -q "whole day" || error "could not find the event" 132 | echo "$__test_output" | grep -q "20101010" || error "could not find the date" 133 | echo "$__test_output" | grep -q "20101010T" && error "a supposed whole day event was found to be with the time of day" 134 | echo "OK: found the event" 135 | 136 | echo "## cleanup, delete it" 137 | calendar_cli calendar delete --event-uid=$uid 138 | 139 | echo "## testing timezone support" 140 | echo "## Create a UTC event" 141 | calendar_cli --timezone='UTC' calendar add '2010-10-09 12:00:00+10m' 'testevent with a UTC timezone' 142 | uid=$(echo $__test_output | perl -ne '/uid=(.*)$/ && print $1') 143 | [ -n "$uid" ] || error "got no UID back" 144 | 145 | echo "## fetching the UTC-event, as ical data" 146 | calendar_cli --icalendar --timezone=UTC calendar agenda --from-time='2010-10-09 11:59' --agenda-mins=3 147 | [ -n "$__test_output" ] || error "failed to find the event that was just added" 148 | echo "$__test_output" | grep -q "20101009T120000Z" || error "failed to find the UTC timestamp. Perhaps the server is yielding timezone data for the UTC timezone? In that case, the assert in the test code should be adjusted" 149 | 150 | echo "## cleanup, delete it" 151 | calendar_cli calendar delete --event-uid=$uid 152 | 153 | echo "## Create an event with a somewhat remote time zone, west of UTC" 154 | calendar_cli --timezone='Brazil/DeNoronha' calendar add '2010-10-09 12:00:00+10m' 'testevent with a time zone west of UTC' 155 | uid=$(echo $__test_output | perl -ne '/uid=(.*)$/ && print $1') 156 | [ -n "$uid" ] || error "got no UID back" 157 | 158 | echo "## fetching the remote time zone event, as ical data" 159 | calendar_cli --icalendar --timezone=UTC calendar agenda --from-time='2010-10-09 13:59' --agenda-mins=3 160 | ## zimbra changes Brazil/DeNoronha to America/Noronha. Actually, the server may theoretically use arbitrary IDs for the timezones. 161 | echo "$__test_output" | grep -Eq "TZID=\"?[a-zA-Z/]*Noronha" || echo "$__test_output" | grep -q "140000Z" || 162 | error "failed to find the remote timezone" 163 | 164 | echo "## fetching the remote time zone event, in UTC-time" 165 | calendar_cli --timezone=UTC calendar agenda --from-time='2010-10-09 13:59' --agenda-mins=3 --event-template='{dtstart}' 166 | [ "$__test_output" == '2010-10-09 14:00 (Sat)' ] || error "expected dtstart to be 2010-10-09 14:00 (Sat)" 167 | 168 | echo "## fetching the remote time zone event, in CET-time (UTC+2 with DST, and October is defined as summer in Oslo, weird)" 169 | calendar_cli --timezone=Europe/Oslo calendar agenda --from-time='2010-10-09 15:59' --agenda-mins=3 --event-template='{dtstart}' 170 | [ "$__test_output" == '2010-10-09 16:00 (Sat)' ] || error "expected dtstart to be 2010-10-09 15:00 (Sat)" 171 | 172 | echo "## cleanup, delete it" 173 | calendar_cli calendar delete --event-uid=$uid 174 | 175 | echo "## TODOS / TASK LISTS" 176 | 177 | echo "## Attempting to add a task with category 'scripttest'" 178 | calendar_cli todo add --set-categories scripttest "edit this task" 179 | uidtodo1=$(echo $__test_output | perl -ne '/uid=(.*)$/ && print $1') 180 | calendar_cli todo add --set-categories scripttest todo "edit this task2" 181 | uidtodo2=$(echo $__test_output | perl -ne '/uid=(.*)$/ && print $1') 182 | 183 | echo "## Listing out all tasks with category set to 'scripttest'" 184 | calendar_cli todo --categories scripttest list 185 | [ $(echo "$__test_output" | wc -l) == 2 ] || error "We found more or less or none of the two todo items we just added" 186 | 187 | echo "## Editing the task" 188 | calendar_cli todo --categories scripttest edit --set-summary "editing" --add-categories "scripttest2" 189 | 190 | echo "## Verifying that the edits got through" 191 | calendar_cli todo --categories scripttest list 192 | [ $(echo "$__test_output" | wc -l) == 1 ] && echo "## OK: found the todo item we just edited and nothing more" 193 | calendar_cli todo --categories scripttest2 list 194 | [ $(echo "$__test_output" | wc -l) == 1 ] && echo "## OK: found the todo item we just edited and nothing more" 195 | calendar_cli todo --comment editing list 196 | [ $(echo "$__test_output" | wc -l) == 1 ] && echo "## OK: found the todo item we just edited and nothing more" 197 | 198 | echo "## Complete the task" 199 | calendar_cli todo --categories scripttest complete 200 | calendar_cli todo --categories scripttest list 201 | [ -z "$__test_output" ] && echo "## OK: todo-item is done" 202 | calendar_cli todo --todo-uid $uidtodo1 delete 203 | 204 | ## parent-child relationships 205 | echo "## Going to add three todo-items with children/parent relationships" 206 | calendar_cli todo add --set-categories scripttest "this is a grandparent" 207 | uidtodo2=$(echo $__test_output | perl -ne '/uid=(.*)$/ && print $1') 208 | calendar_cli todo --categories=scripttest add --set-categories scripttest --is-child "this is a parent and a child" 209 | uidtodo3=$(echo $__test_output | perl -ne '/uid=(.*)$/ && print $1') 210 | calendar_cli todo --categories=scripttest add --set-categories scripttest --is-child "this task has two parents" 211 | uidtodo4=$(echo $__test_output | perl -ne '/uid=(.*)$/ && print $1') 212 | calendar_cli todo --categories scripttest list 213 | [ $(echo "$__test_output" | wc -l) == 3 ] && echo "## OK: found three tasks" 214 | calendar_cli todo --hide-parents --categories scripttest list 215 | [ $(echo "$__test_output" | wc -l) == 1 ] && echo "## OK: found only one task now" 216 | echo "## Going to complete the children task" 217 | calendar_cli todo --hide-parents --categories scripttest complete 218 | calendar_cli todo --hide-parents --categories scripttest list 219 | [ $(echo "$__test_output" | wc -l) == 1 ] && echo "## OK: found only one task now" 220 | calendar_cli todo --hide-parents --categories scripttest complete 221 | calendar_cli todo --hide-parents --categories scripttest list 222 | [ $(echo "$__test_output" | wc -l) == 1 ] && echo "## OK: found only one task now" 223 | calendar_cli todo --hide-parents --categories scripttest complete 224 | calendar_cli todo --hide-parents --categories scripttest list 225 | [ -z "$__test_output" ] && echo "## OK: found no tasks now" 226 | 227 | echo "## ALL TESTS COMPLETED! YAY!" 228 | 229 | 230 | rm $__test_outfile 231 | 232 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | calendar-cli 2 | ============ 3 | 4 | Simple command-line CalDAV client, making it possible to add calendar events, 5 | browse an agenda and do task management using a caldav server. 6 | 7 | THIS IS THE LEGACY VERSION. If you're already using calendar-cli and don't 8 | want to change anything, then keep using it. If you need a production-ready 9 | mature command-line utility for accessing your calendar, then this is the right 10 | tool ... as for now. I decided to change a bit on the user interface, rather 11 | than breaking backward compatibility I made a new command name `plann`. I 12 | would recommend visit https://github.com/tobixen/plann for the new version. 13 | 14 | calendar-cli will be maintained primarily for backward compatibility. 15 | Pull-requests dealing with bugfixes or minor "missing" features will be 16 | considered - but for anyone in need of a command-line interface towards a 17 | CalDAV calendar server, the recommendation is to use 18 | [plann](https://github.com/tobixen/plann) instead. 19 | 20 | Other tools 21 | ----------- 22 | 23 | There is another project out there, "Command-line Interface for Google 24 | Calendar", previously located at pypi under the calendar-cli name. It has now 25 | been renamed to gcalendar-cli to avoid name conflict, and is available at 26 | https://pypi.python.org/pypi/gcalendar-cli/ 27 | 28 | There is a "competing" project at https://github.com/geier/khal - you may want 29 | to check it out - it's more mature but probably more complex. It's using a 30 | "vsyncdir" backend - if I've understood it correctly, that involves building a 31 | local copy of the calendar. The philosophy behind `calendar-cli` is slightly 32 | different, `calendar-cli` is supposed to be a simple cli-based caldav+ical 33 | client. No synchronization, no local storage, just client-side operations. 34 | 35 | Usage examples 36 | -------------- 37 | 38 | The commands and options will be described further down, however examples often 39 | beat documentation. 40 | 41 | First, check the tests folder - the file tests.sh shows some basic usage 42 | examples. If you have radicale installed (`sudo pip install radicale`), you 43 | can try executing test_calendar-cli.sh in the test folder, it basically sets up 44 | a temporary radicale server and executes the tests.sh towards that server. If 45 | test_calendar-cli.sh breaks then _please_ raise an issue on the github or try 46 | to reach out through other channels. 47 | 48 | In the examples folder there is a script I was using on a regular basis for 49 | task management for a while. 50 | 51 | Installation 52 | ------------ 53 | 54 | `calendar-cli` depends on quite some python libraries, i.e. pytz, caldav, etc. 55 | "sudo ./setup.py install" should take care of all those eventually, and will 56 | also make an executable under /usr/bin 57 | 58 | Support 59 | ------- 60 | 61 | \#calendar-cli at irc.oftc.net, eventually t-calendar-cli@tobixen.no, 62 | eventually the issue tracker at https://github.com/tobixen/calendar-cli/issues 63 | 64 | Before reaching out, please make sure all the dependencies are installed and 65 | that you've installed the latest version of the caldav python library. 66 | 67 | Rationale 68 | --------- 69 | 70 | GUIs and Web-UIs are nice for some purposes, but I really find the command line 71 | unbeatable when it comes to: 72 | 73 | * Minor stuff that is repeated often. Writing something like "todo add make a 74 | calendar-cli system" or "calendar add 'tomorrow 15:40+2h' doctor appointment" 75 | is (for me) faster than navigating into some web calendar interface and add 76 | an item there. 77 | * Things that are outside the scope of the UI. Here is one of many tasks I'd 78 | like to do: "go through the work calendar, find all new calendar events that 79 | are outside office hours, check up with the personal calendar if there are 80 | potential conflicts, add some information at the personal calendar if 81 | appropriate", and vice versa - it has to be handled very manually if doing it 82 | through any normal calendar application as far as I know, but if having some 83 | simple CLI or python library I could easily make some interactive script that 84 | would help me doing the operation above. 85 | 86 | When I started writing `calendar-cli`, all I could find was cadaver and the 87 | CalDAVClientLibrary. Both of those seems to be a bit shortcoming; they seem to 88 | miss the iCalendar parsing/generation, and there are things that simply cannot 89 | be done through those tools. 90 | 91 | Synopsis 92 | -------- 93 | 94 | ```sh 95 | calendar-cli.py [global options] [command] [command options] [subcommand] \ 96 | [subcommand options] [subcommand arguments] ... 97 | ``` 98 | 99 | I'm intending to make it easier by allowing calendar-cli.py to be symlinked to 100 | the various commands and also to allow the options to be placed wherever. 101 | 102 | ### Global options 103 | 104 | Only long options will be available in the early versions; I don't 105 | want to pollute the short option space before the CLI is reasonably 106 | well-defined. 107 | 108 | Always consult --help for up-to-date and complete listings of options. 109 | The list below will only contain the most important options and may 110 | not be up-to-date and may contain features not implemented yet. 111 | 112 | * --interactive: stop and query the user rather often 113 | * --caldav-url, --caldav-user, --caldav-pass: how to connect to the CalDAV 114 | server. Fits better into a configuration file. 115 | * --calendar-url: url to the calendar one wants to use. A relative URL (path) 116 | or a calendar-id is also accepted. 117 | * --config-file: use a specific configuration file (default: 118 | $HOME/.config/calendar.conf) 119 | * --config-section: use a specific section from the config file (i.e. to select 120 | a different caldav-server to connect to) 121 | * --icalendar: Write or read icalendar to/from stdout/stdin 122 | * --nocaldav: don't connect to a caldav server 123 | * --timezone: any "naive" timestamp should be considered to belong to the given 124 | time zone, timestamps outputted should be in this time zone, timestamps given 125 | through options should be considered to be in this time zone (Olson database 126 | identifiers, like UTC or Europe/Helsinki). (default: local timezone) 127 | 128 | The caldav URL is supposed to be something like i.e. 129 | http://some.davical.server/caldav.php/ - it is only supposed to relay the 130 | server location, not the user or calendar. Things will most likely work if you 131 | give http://some.davical.server/caldav.php/tobixen/work-calendar/ - but it will 132 | ignore the calendar part of it, and use first calendar it can find - which 133 | perhaps may be tobixen/family-calendar/. Use 134 | http://some.davical.server/caldav.php/ as the caldav URL, and 135 | /tobixen/family-calendar as the calendar-url. 136 | 137 | ### Commands 138 | 139 | As of 0.12, there are two or three distinct commands - calendar (for management 140 | of events) and todo (for task management), with quite different code paths. 141 | The third thing is journal ... but as far as I know, it's not much common to 142 | use caldav servers for keeping journals, the journal thing is not much tested 143 | nor much rich on features. 144 | 145 | There will be code refactorings in v1.0, applying quite some of the logic in 146 | the task management to the calendar management. 147 | 148 | * calendar - access/modify a calendar 149 | * subcommands: add, addics (for uploading events in ical format), agenda, 150 | delete, create (for creating a new calendar) 151 | * todo - access/modify a todo-list 152 | * subcommands: add, list, edit, postpone, complete, delete, addlist 153 | 154 | todo addlist: for creating a new task list. Most caldav servers don't make any 155 | difference between a task list and a calendar. Zimbra is an exception. 156 | addlist hasn't been tested as of version 0.12, perhaps it works, perhaps not) 157 | 158 | ### Event time specification 159 | 160 | Supported in v0.12: 161 | 162 | * anything recognized by dateutil.parser.parse() 163 | * An iso time stamp, followed with the duration, using either + or space as 164 | separator. Duration is a number postfixed by s for seconds, m for minutes, h 165 | for hours, d for days, w for weeks and y for years (i.e. 166 | 2013-09-10T13:37+30d) 167 | * ISO dates. For full day events, make sure to specify the duration in days. 168 | 169 | ### Getting out customized information through --todo-template and --event-template 170 | 171 | This is a string containing variables enclosed in curly braces, like "uid: 172 | {uid}". 173 | 174 | Particularly the uid can be useful, as one may want to use the uid for things 175 | like deleting events and postponing tasks. 176 | 177 | In the examples folder there is a task management script which will use the 178 | --todo-template to create a new shell script for postponing all overdue tasks. 179 | This shell script can then be edited interactively and run. 180 | 181 | ### Task management 182 | 183 | With the todo-command, there are quite some options available (i.e. 184 | --categories, --limit, --todo-uid, etc) to select or filter tasks. Those are 185 | used by the commands list, edit, postpone, complete and delete. A typical 186 | use-case scenario is to first use the "list" command, tweak the filtering 187 | options to get a list containing the tasks one wants to operate with, and then 188 | use either edit, postpone, complete or delete. 189 | 190 | The file TASK_MANAGEMENT.md contains some thoughts on how to organize tasks. 191 | 192 | Configuration file 193 | ------------------ 194 | 195 | Configuration file is by default located in $HOME/.config/calendar.conf. You 196 | may run `calendar-cli --interactive-config` if you don't feel comfortable with 197 | hand-crafting configuration in json syntax, though this feature is not tested 198 | regularly. 199 | 200 | (I considered .ini, but I was told that it's actually not a standard. I'd like 201 | any calendar application to be able to access the file, hence calendar.conf and 202 | not calendar-cli.conf) 203 | 204 | ### calendar-cli 205 | 206 | The file may look like this: 207 | 208 | ```json 209 | { "default": 210 | { "caldav_url": "http://foo.bar.example.com/caldav/", 211 | "caldav_user": "luser", 212 | "caldav_pass": "insecure" 213 | } 214 | } 215 | ``` 216 | A configuration with multiple sections may look like this: 217 | 218 | ```json 219 | { 220 | "default": 221 | { "caldav_url": "http://foo.bar.example.com/caldav/", 222 | "caldav_user": "luser", 223 | "caldav_pass": "insecure" 224 | }, 225 | "baz": 226 | { "caldav_url": "http://foo.baz.example.com/caldav/", 227 | "caldav_user": "luser2", 228 | "caldav_pass": "insecure2" 229 | } 230 | } 231 | ``` 232 | 233 | Sections may also include calendar urls or ids, and sections may inherit other 234 | sections: 235 | 236 | ```json 237 | { 238 | "default": 239 | { "caldav_url": "http://foo.bar.example.com/caldav/", 240 | "caldav_user": "luser", 241 | "caldav_pass": "insecure" 242 | }, 243 | "baz": 244 | { "caldav_url": "http://foo.baz.example.com/caldav/", 245 | "caldav_user": "luser2", 246 | "caldav_pass": "insecure2" 247 | } 248 | }, 249 | "bazimportant": 250 | { "inherits": "baz", 251 | "calendar_url": "important" 252 | } 253 | ``` 254 | 255 | Usage example 256 | ------------- 257 | 258 | Add a calendar item "testevent" at 2013-10-01: 259 | 260 | ```sh 261 | ./calendar-cli.py \ 262 | --calendar-url=http://calendar.bekkenstenveien53c.oslo.no/caldav.php/tobias/calendar/ \ 263 | calendar add 2013-10-01 testevent 264 | ``` 265 | 266 | (assumes that `caldav-url`, `caldav-pass` and `caldav-user` has been added into 267 | configuration file. Those may also be added as command line options) 268 | 269 | Objectives 270 | ---------- 271 | 272 | * It should be really easy and quick to add a todo-list item from the command 273 | line. 274 | * It should be really easy and quick to add a calendar item from the command 275 | line. 276 | * It should be possible to get out lists ("agenda") of calendar items and 277 | todo-items. 278 | * Interface for copying calendar items between calendars, even between 279 | calendars on distinct caldav servers 280 | 281 | Roadmap 282 | ------- 283 | 284 | calendar-cli will be maintained with bugfixes and security fixes, on requests 285 | from the community. The maintainer is no longer using calendar-cli. 286 | 287 | A new project https://github.com/tobixen/plann with a new interface has been 288 | forked off. 289 | -------------------------------------------------------------------------------- /TASK_MANAGEMENT.md: -------------------------------------------------------------------------------- 1 | Managing tasks through calendar-cli 2 | =================================== 3 | 4 | While the RFC does draw some lines on what fields are admissable in the 5 | todo-entries in the calendar, it doesn't really give good guidelines on how to 6 | use the different fields. One often gets into dilemmas ... when to use the 7 | category field vs when to use the location field vs when to branch out a 8 | completely distinct calendar, etc. Here are my considerations. 9 | 10 | Calendar scope 11 | -------------- 12 | 13 | Different categories of tasks can be put into different calendars (and even on 14 | different caldav servers). 15 | 16 | I believe it's best to keep as few calendars as possible, and rather use i.e. 17 | the categories field for splitting different types of tasks. 18 | 19 | As you can give access rights to other people for a whole caldav calendar (or 20 | "task list"), it makes sense to use the calendar level to control access 21 | rights. You would typically like to have one calendar where your family can 22 | view/add tasks, other for work, perhaps separate calendars for separate 23 | projects at work if different projects involves different people, etc. 24 | 25 | I have a boat, and it requires a lot of maintenance and attention. Should I 26 | create a separate calendar for boat maintenance tasks? Considering the 27 | thoughts above, what matters is whomelse should have the rights to view and add 28 | tasks. If the boat is a family project, use the same calendar as for other 29 | family/home-related todo-tasks. 30 | 31 | Location 32 | -------- 33 | 34 | A named location. TLDR: I've ended up almost never using the location field 35 | for tasks. 36 | 37 | With events, the location field is frequently used for which meeting room the 38 | meeting should be at, or the address of an appointment. It's often checked up 39 | just before the meeting, or copied to the navigator when one is heading for the 40 | appointment. Tasks are different, if you are at some specific location you 41 | would typically like to check up all tasks at that location or in the 42 | neighbourhood and see if you can do some of them. 43 | 44 | I had an idea that some tasks are only possible to do at a specific location 45 | (i.e. as a boat owner, there are lots of tasks that can only be done "at the 46 | boat", some work can be done from home, some work has to be done from the 47 | office, some work should be done in the garden, etc), and when being at that 48 | location, one would like to list out the pending tasks that applies for that 49 | location. However, practical experience shows that "boat", "office", "home", 50 | "garden", "grocery store", "hardware store", etc are better suited as a 51 | category than as a location. Generally, if you have a lot of tasks connected 52 | to the same address, probably it's better to do it as a category rather than 53 | location. If the location is a single-off thing used only for that specific 54 | task (or, perhaps, some very few tasks) then obviously it's better to use 55 | location than category. 56 | 57 | Geo 58 | --- 59 | 60 | A geo is a location given by coordinates. It probably makes great sense to use 61 | geo ... 62 | 63 | * if you want to stick the tasks to a map. Probably very useful if your tasks 64 | have to be done on lots of different locations (i.e. if you are a travelling 65 | salesman or a plumber). 66 | * if you want to set up the phone to automatically remind you about tasks i.e. 67 | when you are close to the supermarked, etc. (however, most of us probably 68 | have several supermarkets we can go to, so geo doesn't make sense for that) 69 | 70 | I've never used the geo field. 71 | 72 | Categories 73 | ---------- 74 | 75 | I'd like to think of categories as tags that can be stuck to tasks, and then 76 | used to filter out relevant tasks. Some tasks should be done while sitting by 77 | the keyboard. Some tasks are related to a particular project. Some tasks are 78 | best done when the weather is good. Some tasks (i.e. visit some office) has to 79 | be done in the "business day time". Add tags for this and other relevant 80 | stuff. When the sun is shining and you want to do some outdoor tasks, filter 81 | out the tasks with categories "sunny" or "garden". 82 | 83 | When to use location or geo, and when to use category? I think that for the 84 | super market example, geo is not really fitting because it can only be one geo 85 | coordinate related to a vtodo, but there are many super markeds that can be 86 | visited. One could also think that "supermarked" is not a good location for 87 | the same reason. In practice, I've never used location and geo, always been 88 | sticking such information into the categories instead. 89 | 90 | While the categories field is a freetext field, it's important that the same 91 | categories are used consistently. I made it possible to do `calendar-cli todo 92 | list --list-categories` to just take out a list of used categories. 93 | 94 | Pending-Dependent 95 | ----------------- 96 | 97 | If task A cannot be done without task B being done first, we say that A depends 98 | on B. We may want to construct a bikeshed, then paint it red. Obviously the 99 | painting depends on the construction. It may make sense to hide the paint job 100 | from the todolists, or maybe fade it away - when checking the list of immediate 101 | tasks to be executed, "painting the bikeshed" is just noise. It may also make 102 | sense to ensure the due date for the construction is before the due date for 103 | the painting. 104 | 105 | The VTODO-standard does not support this kind of relationship, but it's 106 | possible to use parent-child. Think of the parent as the dependent and the 107 | child as the pending. See below for practical experiences. 108 | 109 | Parent-child relationship 110 | ------------------------- 111 | 112 | With the parent-child relationship one can make a hierarchical task list. It 113 | makes a lot of sense when having a big task that can be split up in subtasks. 114 | Say, the task may be "build a bicycle shed". That does take quite some 115 | planning, purchases and work, so one will definitively want to break it up in 116 | subtasks. 117 | 118 | A shopping list may also be considered to be a parent-child relationship. "Buy 119 | cucumber" seems to be a subtask of "buy vegetables" which again may be a 120 | subtask of "go shopping at the supermarket". 121 | 122 | Every parent-child relationship can also be seen as a dependency as well, but 123 | it's a bit in reverse. One cannot build the bike shed without first buying 124 | planks. One cannot tick the checkbox for "go shopping" if the cucumber was not 125 | bought. (or is it the other way? One cannot "buy cucumber" before one has 126 | started the procedure of "go shopping"?) 127 | 128 | There is a bit of a difference between the typical pending-dependent and the 129 | typical parent-child relationship. In a typical "parent-child"-relationship 130 | one may want to take out hierarchical lists with the parent first, or take out 131 | simple overviews where all the details (i.e. grandchildren) are hidden. In a 132 | typical "pending-dependent"-relationship one may want to hide the dependent 133 | (parent) and emphasize on what's needed to be done first (child). 134 | 135 | There is another relationship also ... purpose and means. The purpose of the 136 | shopping trip is to buy cucumber - but the purpose of building the biking shed 137 | is not to buy planks (Unless the owner of the planks shop used some clever 138 | marketing for tricking you into building the bike shed, that is). 139 | 140 | The purpose for buying sugar could be "bake a cake". I would then start by 141 | adding "bake a cake" to the task list, then "buy sugar", and only then I would 142 | eventually add "go shopping" to the todo-list. (That's maybe just me. My wife 143 | would go to the shop to buy a cucumber, and then come home with everything 144 | needed for baking a cake and more). 145 | 146 | From my practical experience, "supermarket" and "hardware shopping" can as well 147 | be categories. So eventually when I really need that cucumber, I can check up 148 | the full list for the category "supermarket" and come home with all 149 | ingrediences needed for making a cake. I've never felt a compelling need to 150 | group the shopping list inside the calendar. 151 | 152 | Although I haven't created any bike-sheds, I've had some "projects". First I 153 | toss the project into the task-list, with the categories "keyboard" and 154 | "thinking". Later I take up that task and I start creating sub-tasks. The 155 | project then disappears from my regular overview because it has unresolved 156 | dependencies. This has worked out reasonably well for me. 157 | 158 | Parent-child-relationships aren't very well supported yet in calendar-cli yet. 159 | 160 | Recurring tasks 161 | --------------- 162 | 163 | The standard allows for recurring tasks, but doesn't really flesh out what it 164 | means that a task is recurring - except that it should show up on date searches 165 | if any of the recurrances are within the date search range. Date searches for 166 | future recurrances of tasks is ... quite exotic, why would anyone want to do 167 | that? 168 | 169 | From a "user perspective", I think there are two kind of recurrences: 170 | 171 | * Specified intervals - say, the floor should be cleaned every week. You 172 | usually do it every Monday, but one week everything is so hectic that you 173 | postpone it all until late Sunday evening. It would be irrational to wash it 174 | again the next day. And if you missed the due date with more than a week - 175 | then obviously the next recurrence is not "previous week". (Except, one may 176 | argue that the status of previous week should be set to "CANCELLED") 177 | * Fixed-time. If you actually get paid for washing the floor and you have a 178 | contract stating that you get paid a weekly sum for washing the floor weekly, 179 | then you'd probably want to wash the floor again on Monday, even if it has 180 | been done just recently. Or perhaps one of the children is having swimming 181 | at school every Tuesday, so sometime during Monday (with a hard due set to 182 | Tuesday early morning) a gym bag with swimwear and a fresh towel should be 183 | prepared for the child. Or the yearly income tax statement, should be 184 | delivered before a hard due date. 185 | 186 | I choose to interpret a RRULE with BY\*-attributes set (like BYDAY=MO) as a 187 | recurring task with "fixed" due times, while a RRULE without BY\*-attributes 188 | should be considered as a "interval"-style of recurring task. 189 | 190 | There can be only one status and one complete-date for a vtodo, no matter if 191 | it's recurring or not. 192 | 193 | Based on my interpretation of the standards, possibly the correct way to mark 194 | once recurrence of a recurring task as complete, is to use the RECURRENCE-ID 195 | parameter and make several instances of the same UID. However, based on my 196 | understanding of the RFC, the timestamps in a "recurrence set" is strictly 197 | defined by the RRULE and the original DTSTART. This does probably fit well 198 | with the fixed-time recurrences (at least if one markes a missed recurrence 199 | with CANCELLED), but it does not fit particularly well with interval-based 200 | recurrences. 201 | 202 | I tried implementing some logic like this in calendar-cli, and it was working 203 | on DAViCal. However, it was missing tests, and I realize that it's kind of 204 | broken. I'm now moving this logic to the caldav layer. I'm also creating a 205 | "safe" logic which will split the completed task into a completely separate 206 | task and editing/moving DTSTART/DUE on the recurring event. This may be the 207 | more practical solution (perhaps combined with having a common parent for all 208 | the recurring tasks). 209 | 210 | There is no support for rrules outside the task completion code, so as for now 211 | the rrule has to be put in through another caldav client tool, through the 212 | --pdb option or through manually editing ical code. I believe recurring tasks 213 | is an important functionality, so I will implement better support for this at 214 | some point. 215 | 216 | dtstart vs due vs duration 217 | -------------------------- 218 | 219 | I don't know what they were thinking of when they created the icalendar 220 | standard. 221 | 222 | An event may have a DTSTART and a DUE ... or alternatively, a DURATION instead 223 | of DUE. I assume the intention is that a task with DTSTART and DURATION set is 224 | equivalent with a task with the smae DTSTART set, and a DUE set equal to 225 | DTSTART plus DURATION. This makes a lot of sense for events, but for tasks? 226 | Not so much! 227 | 228 | Ok, DUE is pretty straight forward - it's the time when the task should be 229 | done. But what is DTSTART? Say, some bureaucracy work needs to be done "this 230 | year" - DUE should obviously be set to 1st of January at 00:00. 231 | 232 | As of 2015 my opinion was that DTSTART is the earliest time you expect to start 233 | working with the task, or maybe the earliest time it's possible to start. Say, 234 | we plan to sit down and do bureaucraziness the 15th of December. 235 | 236 | Passing DTSTART doesn't mean you need to drop everything else and start working 237 | on the task immediately. My idea was to restrict the todo-list to tasks where 238 | the DTSTART was already passed ... and then one could postpone the dtstart just 239 | to unclutter the todo-list. However, I think it is more desirable to use the 240 | DURATION field for estimations of how long time the task will take. Now, this 241 | bureaucraziness may be estimated to three hours of work. That means DTSTART 242 | should be set to 21:00 at New Years eve. Now, that's just silly! But yeah, 243 | the DTSTART has a meaning: that's the time you need to drop everything else if 244 | you didn't do the task yet. 245 | 246 | I have some more thoughts on project management in the other document, 247 | [NEXT_LEVEL](NEXT_LEVEL.md). 248 | 249 | Priority 250 | -------- 251 | 252 | The RFC defines priority as a number between 0 and 10. 253 | 254 | 0 means the priority is undefined, 1-4 means the priority is "high", 5 that 255 | it's "medium high" and 6-10 means the priority is "low". 256 | 257 | Should tasks be done in the order of their priority? Probably not, as there is 258 | also the DUE-date to consider. I do have some ideas on how to sort and 259 | organize tasks in the [NEXT_LEVEL](NEXT_LEVEL.md) document. To follow the 260 | thoughts there, let priority be defined as such: 261 | 262 | 1: The DUE timestamp MUST be met, come hell or high water. 263 | 2: The DUE timestamp SHOULD be met, if we lose it the task becomes irrelevant. 264 | 3: The DUE timestamp SHOULD be met, but worst case we can probably 265 | procrastinate it, perhaps we can apply for an extended deadline. 266 | 4: The deadline SHOULD NOT be pushed too much 267 | 5: If the deadline approaches and we have higher-priority tasks that needs to 268 | be done, then this task can be procrastinated. 269 | 6: The DUE is advisory only and expected to be pushed - but it would be nice if 270 | the task gets done within reasonable time. 271 | 7-9: Low-priority task, it would be nice if the task gets done at all ... but 272 | the DUE is overly optimistic and expected to be pushed several times. 273 | 274 | Recommendation: split ut tasks 275 | ------------------------------ 276 | 277 | Tasks that takes more than some few hours ought to be split up into several 278 | subtasks. 279 | 280 | To increase the probability that a high-priority task is done before the DUE, 281 | it may also be smart to split it up into subtasks/dependencies with lower 282 | priority but due dates set according to when one is expecting to get done with 283 | them. -------------------------------------------------------------------------------- /LICENSE.TXT: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /calendar_cli/legacy.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | https://github.com/tobixen/calendar-cli/ - high-level cli against caldav servers. 5 | 6 | This is the "legacy" interface - or, if you prefer,, the "long term support" interface. 7 | 8 | Due to user feedback the new interface has been split out in a separate project. 9 | 10 | See https://plann.no 11 | 12 | Copyright (C) 2013-2023 Tobias Brox and other contributors. 13 | 14 | See https://www.gnu.org/licenses/gpl-3.0.en.html for license information. 15 | """ 16 | import argparse 17 | import tzlocal 18 | ## we still need to use pytz, see https://github.com/collective/icalendar/issues/333 19 | #try: 20 | # import zoneinfo 21 | #except: 22 | # from backports import zoneinfo 23 | import pytz 24 | import time 25 | from datetime import datetime, timedelta, date 26 | from datetime import time as time_ 27 | import dateutil.parser 28 | from dateutil.rrule import rrulestr 29 | from icalendar import Calendar,Event,Todo,Journal,Alarm 30 | from calendar_cli.config import interactive_config, config_section, read_config 31 | import vobject 32 | import caldav 33 | import uuid 34 | import json 35 | import os 36 | import logging 37 | import sys 38 | import re 39 | import urllib3 40 | from getpass import getpass 41 | from six import PY3 42 | 43 | from calendar_cli.metadata import metadata 44 | __version__ = metadata["version"] 45 | 46 | UTC = pytz.utc 47 | #UTC = zoneinfo.ZoneInfo('UTC') 48 | 49 | def to_normal_str(text): 50 | if PY3 and text and not isinstance(text, str): 51 | text = text.decode('utf-8') 52 | elif not PY3 and text and not isinstance(text, str): 53 | text = text.encode('utf-8') 54 | return text 55 | 56 | 57 | ## ref https://github.com/tobixen/calendar-cli/issues/33, python3-compatibility 58 | try: 59 | raw_input 60 | except NameError: 61 | raw_input = input 62 | 63 | try: 64 | unicode 65 | except NameError: 66 | unicode = str 67 | 68 | def _date(ts): 69 | """ 70 | helper function to get a date out of a Date or Datetime object. 71 | """ 72 | if hasattr(ts, 'date'): 73 | return ts.date() 74 | return ts 75 | 76 | def _force_datetime(t, args): 77 | """ 78 | date objects cannot be compared with timestamp objects, neither in 79 | python2 nor python3. Silly. also, objects with time zone info 80 | cannot be compared with timestamps without time zone info. and 81 | both datetime.now() and datetime.utcnow() seems to be without 82 | those bits. Silly. 83 | 84 | This method should only be used in comparitions, never when 85 | populating fields in an icalendar object. Events with dates 86 | rather than timestamps are to be considered as full-day events, 87 | so the difference is significant. 88 | """ 89 | if type(t) == date: 90 | t = datetime(t.year, t.month, t.day) 91 | if t.tzinfo is None: 92 | return t.replace(tzinfo=_tz(args.timezone)) 93 | return t 94 | 95 | def _now(): 96 | """ 97 | python datetime is ... crap! 98 | """ 99 | return datetime.utcnow().replace(tzinfo=UTC) 100 | 101 | def _tz(timezone=None): 102 | """ 103 | gives the local time zone if no time zone is given, 104 | otherwise should return the timezone (or some canonical time zone object) 105 | """ 106 | if timezone is None: 107 | try: 108 | ## should not be needed - but see 109 | ## https://github.com/collective/icalendar/issues/333 110 | return pytz.timezone(tzlocal.get_localzone_name()) 111 | except: 112 | ## if the tzlocal version is old 113 | return tzlocal.get_localzone() 114 | 115 | elif not hasattr(timezone, 'utcoffset'): 116 | ## See https://github.com/collective/icalendar/issues/333 117 | #return zoneinfo.ZoneInfo(timezone) 118 | return pytz.timezone(timezone) 119 | else: 120 | return timezone 121 | 122 | def _localize(ts, tz=None, from_tz=None, to_tz=None): 123 | """ 124 | Should always return a non-native timestamp with timezone. 125 | If from_tz or to_tz is None, assume ts is in local timezone. 126 | if ts already has tiemzone, then it will trump from_tz 127 | """ 128 | if not from_tz and not to_tz: 129 | from_tz = tz 130 | to_tz = tz 131 | from_tz = _tz(from_tz) 132 | to_tz = _tz(to_tz) 133 | if not ts.tzinfo: 134 | if hasattr(from_tz, 'localize'): 135 | ts = from_tz.localize(ts) 136 | else: 137 | ts = ts.replace(tzinfo=tz) 138 | return ts.astimezone(to_tz) 139 | 140 | ## global constant 141 | ## (todo: this doesn't really work out that well, leap seconds/days are not considered, and we're missing the month unit) 142 | ## (todo: Sebastian Brox has made some other code using regexps and dateutil.relativedelta, should consider to steal his code) 143 | time_units = { 144 | 's': 1, 'm': 60, 'h': 3600, 145 | 'd': 86400, 'w': 604800, 'y': 31536000 146 | } 147 | 148 | vtodo_txt_one = ['location', 'description', 'geo', 'organizer', 'summary'] 149 | vtodo_txt_many = ['categories', 'comment', 'contact', 'resources'] 150 | vcal_txt_one = ['location', 'description'] 151 | vcal_txt_many = [] 152 | 153 | def niy(*args, **kwargs): 154 | if 'feature' in kwargs: 155 | raise NotImplementedError("This feature is not implemented yet: %(feature)s" % kwargs) 156 | raise NotImplementedError 157 | 158 | def caldav_connect(args): 159 | ## args.ssl_verify_cert is a string and can be a path or 'yes'/'no'. 160 | ## the library expects a path or a boolean. 161 | ## Translate 'yes' and 'no' to True and False, or pass the raw string: 162 | ssl_verify_cert = { 163 | 'yes': True, 164 | 'no': False 165 | }.get(args.ssl_verify_cert, args.ssl_verify_cert) 166 | # Create the account 167 | return caldav.DAVClient(url=args.caldav_url, username=args.caldav_user, password=args.caldav_pass, ssl_verify_cert=ssl_verify_cert, proxy=args.caldav_proxy) 168 | 169 | def parse_time_delta(delta_string): 170 | # TODO: handle bad strings more gracefully 171 | if len(delta_string) < 2 or delta_string[-1].lower() not in time_units: 172 | raise ValueError("Invalid time delta: %s" % delta_string) 173 | num = int(delta_string[:-1]) 174 | return timedelta(0, num*time_units[delta_string[-1].lower()]) 175 | 176 | def find_calendar(caldav_conn, args): 177 | if args.calendar_url: 178 | if '/' in args.calendar_url: 179 | return caldav.Calendar(client=caldav_conn, url=args.calendar_url) 180 | else: 181 | return caldav.Principal(caldav_conn).calendar(cal_id=args.calendar_url) 182 | else: 183 | ## Find default calendar 184 | calendars = caldav.Principal(caldav_conn).calendars() 185 | if not calendars: 186 | sys.stderr.write("no calendar url given and no default calendar found - can't proceed. You will need to create a calendar first") 187 | sys.exit(2) 188 | if len(calendars) > 1: 189 | sys.stderr.write("no calendar url given and several calendars found; assuming the primary is %s" % calendars[0].url) 190 | return calendars[0] 191 | 192 | def _calendar_addics(caldav_conn, ics, uid, args): 193 | """" 194 | "Internal" method for adding a calendar object item to the caldav 195 | server through a PUT. ASSUMES the ics conforms to rfc4791.txt 196 | section 4.1 Handles --calendar-url and --icalendar from the args 197 | """ 198 | if args.icalendar and args.nocaldav: 199 | print(ics) 200 | return 201 | 202 | if args.icalendar or args.nocaldav: 203 | raise ValueError("Nothing to do/invalid option combination for 'calendar add'-mode; either both --icalendar and --nocaldav should be set, or none of them") 204 | return 205 | 206 | try: 207 | c = find_calendar(caldav_conn, args) 208 | ## unicode strings vs byte strings is a minefield in python3 ... so, re.search demands a string here ... 209 | ics = to_normal_str(ics) 210 | if re.search(r'^METHOD:[A-Z]+[\r\n]+',ics,flags=re.MULTILINE) and args.ignoremethod: 211 | ics = re.sub(r'^METHOD:[A-Z]+[\r\n]+', '', ics, flags=re.MULTILINE) 212 | print ("METHOD property found and ignored") 213 | c.add_event(ics) 214 | except caldav.lib.error.AuthorizationError: 215 | print("Error logging in") 216 | sys.exit(2) 217 | """ 218 | Peter Havekes: This needs more checking. It works for me when connecting to O365 219 | 220 | except caldav.lib.error.PutError as e: 221 | if "200 OK" in str(e): 222 | print("Duplicate") 223 | else: 224 | raise 225 | """ 226 | 227 | def calendar_addics(caldav_conn, args): 228 | """ 229 | Takes an ics from external source and puts it into the calendar. 230 | 231 | From the CalDAV RFC: 232 | 233 | Calendar components in a calendar collection that have different UID 234 | property values MUST be stored in separate calendar object resources. 235 | 236 | This means the inbound .ics has to be split up into one .ics for 237 | each event as long as the uid is different. 238 | """ 239 | if args.file == '-': 240 | input_ical = sys.stdin.read() 241 | else: 242 | with open(args.file, 'r') as f: 243 | input_ical = f.read() 244 | 245 | c = Calendar.from_ical(input_ical) 246 | 247 | ## unfortunately we need to mess around with the object internals, 248 | ## since the icalendar library doesn't offer methods out of the 249 | ## hat for doing such kind of things 250 | entries = c.subcomponents 251 | 252 | ## Timezones should be duplicated into each ics, ref the RFC 253 | timezones = [x for x in entries if x.name == 'VTIMEZONE'] 254 | 255 | ## Make a mapping from UID to the other components 256 | uids = {} 257 | for x in entries: 258 | if x.name == 'VTIMEZONE' or not 'UID' in x: 259 | continue 260 | uid = x['UID'].to_ical() 261 | uids[uid] = uids.get(uid, []) + [x] 262 | 263 | for uid in uids: 264 | c.subcomponents = timezones + uids[uid] 265 | _calendar_addics(caldav_conn, c.to_ical(), uid, args) 266 | 267 | def create_alarm(message, relative_timedelta): 268 | alarm = Alarm() 269 | alarm.add('ACTION', 'DISPLAY') 270 | alarm.add('DESCRIPTION', message) 271 | alarm.add('TRIGGER', relative_timedelta, parameters={'VALUE':'DURATION'}) 272 | return alarm 273 | 274 | def calendar_add(caldav_conn, args): 275 | cal = Calendar() 276 | cal.add('prodid', '-//{author_short}//{product}//{language}'.format(language=args.language, **metadata)) 277 | cal.add('version', '2.0') 278 | event = Event() 279 | ## read timestamps from arguments 280 | event_spec = args.event_time.split('+') 281 | if len(event_spec)>3: 282 | raise ValueError('Invalid event time "%s" - can max contain 2 plus-signs' % args.event_time) 283 | elif len(event_spec)==3: 284 | event_time = '%s+%s' % tuple(event_spec[0:2]) 285 | event_duration = event_spec[2] 286 | elif len(event_spec)==2 and not event_spec[1][-1:] in time_units: 287 | event_time = '%s+%s' % tuple(event_spec[0:2]) 288 | event_duration = '1h' 289 | elif len(event_spec)==2: 290 | event_time = '%s' % event_spec[0] 291 | event_duration = event_spec[1] 292 | else: 293 | event_time = event_spec[0] 294 | event_duration = '1h' 295 | ## TODO: error handling 296 | event_duration_secs = int(event_duration[:-1]) * time_units[event_duration[-1:]] 297 | dtstart = dateutil.parser.parse(event_spec[0], ignoretz=True) 298 | if (args.whole_day or 299 | (event_duration_secs % (60*60*24) == 0 and 300 | dtstart.time() == time_(0,0))): 301 | 302 | ## allowing 1 second off due to leap seconds 303 | if (event_duration_secs+1) % (60*60*24) > 2: 304 | raise ValueError('Duration of whole-day event must be multiple of 1d') 305 | 306 | duration = event_duration_secs//60//60//24 307 | dtend = dtstart + timedelta(days=duration) 308 | event.add('dtstart', _date(dtstart.date())) 309 | event.add('dtend', _date(dtend.date())) 310 | else: 311 | dtstart = _localize(dtstart, args.timezone) 312 | event.add('dtstart', dtstart) 313 | ## TODO: handle duration and end-time as options. default 3600s by now. 314 | event.add('dtend', dtstart + timedelta(0,event_duration_secs)) 315 | if (args.private): 316 | event.add('class', 'PRIVATE') 317 | event.add('dtstamp', _now()) 318 | uid = uuid.uuid1() 319 | event.add('uid', str(uid)) 320 | for attr in vcal_txt_one + vcal_txt_many: 321 | if attr == 'summary': 322 | continue 323 | val = getattr(args, 'set_'+attr) 324 | if val: 325 | event.add(attr, val) 326 | event.add('summary', ' '.join(args.summary)) 327 | cal.add_component(event) 328 | ## workaround for getting RFC-compliant ical data, 329 | ## ref https://github.com/collective/icalendar/issues/272#issuecomment-640204031 330 | ical_data = vobject.readOne(cal.to_ical().decode('utf-8')).serialize() 331 | _calendar_addics(caldav_conn, ical_data, uid, args) 332 | print("Added event with uid=%s" % uid) 333 | 334 | def calendar_delete(caldav_conn, args): 335 | cal = find_calendar(caldav_conn, args) 336 | if args.event_uid: 337 | event = cal.event_by_uid(args.event_uid) 338 | elif args.event_url: 339 | event = cal.event_by_url(args.event_url) 340 | else: 341 | raise ValueError("Event deletion failed: either uid or url is needed") 342 | event.delete() 343 | 344 | def journal_add(caldav_conn, args): 345 | ## TODO: copied from todo_add, should probably be consolidated 346 | cal = Calendar() 347 | cal.add('prodid', '-//{author_short}//{product}//{language}'.format(language=args.language, **metadata)) 348 | cal.add('version', '2.0') 349 | journal = Journal() 350 | ## TODO: what does the cryptic comment here really mean, and why was the dtstamp commented out? dtstamp is required according to the RFC. 351 | ## TODO: (cryptic old comment:) not really correct, and it breaks i.e. with google calendar 352 | journal.add('dtstamp', datetime.now()) 353 | journal.add('dtstart', date.today()) 354 | journal.add('summary', ' '.join(args.summaryline)) 355 | uid = uuid.uuid1() 356 | journal.add('uid', str(uid)) 357 | cal.add_component(journal) 358 | _calendar_addics(caldav_conn, cal.to_ical(), uid, args) 359 | print("Added journal item with uid=%s" % uid) 360 | ## FULL STOP - should do some major refactoring before doing more work here! 361 | 362 | def todo_add(caldav_conn, args): 363 | ## TODO: copied from calendar_add, should probably be consolidated 364 | if args.icalendar or args.nocaldav: 365 | niy(feature="add todo item by icalendar raw stdin data or create raw icalendar data to stdout") 366 | if args.todo_uid: 367 | uid = args.todo_uid 368 | else: 369 | uid = uuid.uuid1() 370 | cal = Calendar() 371 | cal.add('prodid', '-//{author_short}//{product}//{language}'.format(language=args.language, **metadata)) 372 | cal.add('version', '2.0') 373 | todo = Todo() 374 | todo.add('dtstamp', _now()) 375 | 376 | for setarg in ('due', 'dtstart'): 377 | if getattr(args, 'set_'+setarg): 378 | if type(getattr(args, 'set_'+setarg)) == str: 379 | val = dateutil.parser.parse(getattr(args, 'set_'+setarg)) 380 | else: 381 | val = getattr(args, 'set_'+setarg) 382 | todo.add(setarg, val) 383 | todo.add('uid', str(uid)) 384 | todo.add('summary', ' '.join(args.summaryline)) 385 | todo.add('status', 'NEEDS-ACTION') 386 | 387 | if args.is_child: 388 | for t in todo_select(caldav_conn, args): 389 | todo.add('related-to', t.instance.vtodo.uid.value) 390 | rt = t.instance.vtodo.add('related-to') 391 | rt.params['RELTYPE']=['CHILD'] 392 | rt.value = str(uid) 393 | t.save() 394 | 395 | for attr in vtodo_txt_one: 396 | if attr == 'summary': 397 | continue 398 | val = getattr(args, 'set_'+attr) 399 | if val: 400 | todo.add(attr, val) 401 | ## TODO: this doesn't currently work quite the way we'd like it to 402 | ## work (it adds to lines to the ical, and vobject cares only 403 | ## about one of them), and if we do get it to work, we'd like to 404 | ## refactor and get the same logic in the edit-function 405 | for attr in vtodo_txt_many: 406 | val = getattr(args, 'set_'+attr) 407 | if val: 408 | vals = val.split(',') 409 | todo.add(attr, vals) 410 | 411 | if args.alarm is not None: 412 | alarm = create_alarm(' '.join(args.summaryline), parse_time_delta(args.alarm)) 413 | todo.add_component(alarm) 414 | 415 | cal.add_component(todo) 416 | _calendar_addics(caldav_conn, cal.to_ical(), uid, args) 417 | print("Added todo item with uid=%s" % uid) 418 | 419 | def calendar_agenda(caldav_conn, args): 420 | if args.nocaldav and args.icalendar: 421 | niy(feature="Read events from stdin in ical format and list out in prettified format") 422 | 423 | if args.nocaldav: 424 | raise ValueError("Agenda with --nocaldav only makes sense together with --icalendar") 425 | 426 | if args.from_time: 427 | search_dtstart = dateutil.parser.parse(args.from_time) 428 | search_dtstart = _localize(search_dtstart, args.timezone) 429 | else: 430 | search_dtstart = _now() 431 | if args.to_time: 432 | search_dtend = dateutil.parser.parse(args.to_time) 433 | search_dtend = _localize(search_dtend, args.timezone) 434 | elif args.agenda_mins: 435 | search_dtend = search_dtstart + timedelta(minutes=args.agenda_mins) 436 | elif args.agenda_days: 437 | search_dtend = search_dtstart + timedelta(args.agenda_days) 438 | ## TODO - error handling if search_dtend is not set above - but agenda_days have a default value, so that probably won't happen 439 | 440 | ## TODO: time zone 441 | events_ = find_calendar(caldav_conn, args).date_search(search_dtstart, search_dtend, expand=True) 442 | events = [] 443 | if args.icalendar: 444 | for ical in events_: 445 | print(to_normal_str(ical.data).strip()) 446 | else: 447 | for event_cal in events_: 448 | tzinfo = _tz(args.timezone) 449 | events__ = event_cal.instance.components() 450 | for event in events__: 451 | if event.name != 'VEVENT': 452 | continue 453 | dtstart = event.dtstart.value if hasattr(event, 'dtstart') else _now() 454 | if not isinstance(dtstart, datetime): 455 | dtstart = datetime(dtstart.year, dtstart.month, dtstart.day) 456 | dtstart = _localize(dtstart, tzinfo) 457 | 458 | events.append({'dtstart': dtstart, 'instance': event}) 459 | 460 | ## changed to use the "key"-parameter at 2019-09-18, as needed for python3. 461 | ## this will probably cause regression on sufficiently old versions of python 462 | events.sort(key=lambda a: a['dtstart']) 463 | for event in events: 464 | event['summary'] = "(no description)" 465 | event['dtstart'] = event['dtstart'].strftime(args.timestamp_format) 466 | for timeattr in ('dtcreated', 'dtend'): 467 | if hasattr(event['instance'], timeattr): 468 | event[timeattr] = getattr(event['instance'], timeattr).value 469 | if hasattr(event[timeattr], 'strftime'): 470 | if hasattr(event[timeattr], 'astimezone'): 471 | event[timeattr] = event[timeattr].astimezone(_tz(args.timezone)) 472 | event[timeattr] = event[timeattr].strftime(args.timestamp_format) 473 | else: 474 | event[timeattr] = '-' 475 | for textattr in vcal_txt_one: 476 | if hasattr(event['instance'], textattr): 477 | event[textattr] = getattr(event['instance'], textattr).value 478 | else: 479 | event[textattr] = '-' 480 | for summary_attr in ('summary', 'location', 'description'): 481 | if hasattr(event['instance'], summary_attr): 482 | event['summary'] = getattr(event['instance'], summary_attr).value 483 | break 484 | event['uid'] = event['instance'].uid.value if hasattr(event['instance'], 'uid') else '' 485 | for attr in vcal_txt_one + ['summary']: 486 | if isinstance(event[attr], unicode): 487 | event[attr] = to_normal_str(event[attr]) 488 | print(args.event_template.format(**event)) 489 | 490 | def create_calendar(caldav_conn, args): 491 | cal_obj = caldav.Principal(caldav_conn).make_calendar(cal_id=args.cal_id) 492 | if cal_obj: 493 | print("Created a calendar with id " + args.cal_id) 494 | 495 | def create_tasklist(caldav_conn, args): 496 | cal_obj = caldav.Principal(caldav_conn).make_calendar(cal_id=args.cal_id, supported_calendar_component_set=['VTODO']) 497 | if cal_obj: 498 | print("Created a task list with id " + args.tasklist_id) 499 | 500 | def todo_select(caldav_conn, args): 501 | if args.top+args.limit+args.offset+args.offsetn and args.todo_uid: 502 | raise ValueError("It doesn't make sense to combine --todo-uid with --top/--limit/--offset/--offsetn") 503 | if args.todo_uid: 504 | tasks = [ find_calendar(caldav_conn, args).todo_by_uid(args.todo_uid) ] 505 | else: 506 | ## TODO: we're fetching everything from the server, and then doing the filtering here. It would be better to let the server do the filtering, though that requires library modifications. 507 | ## TODO: current release of the caldav library doesn't support the multi-key sort_keys attribute. The try-except construct should be removed at some point in the future, when caldav 0.5 is released. 508 | try: 509 | tasks = find_calendar(caldav_conn, args).todos(sort_keys=('isnt_overdue', 'hasnt_started', 'due', 'dtstart', 'priority')) 510 | except: 511 | tasks = find_calendar(caldav_conn, args).todos() 512 | for attr in vtodo_txt_one + vtodo_txt_many: ## TODO: now we have _exact_ match on items in the the array attributes, and substring match on items that cannot be duplicated. Does that make sense? Probably not. 513 | if getattr(args, attr): 514 | tasks = [x for x in tasks if hasattr(x.instance.vtodo, attr) and getattr(args, attr) in getattr(x.instance.vtodo, attr).value] 515 | if getattr(args, 'no'+attr): 516 | tasks = [x for x in tasks if not hasattr(x.instance.vtodo, attr)] 517 | if args.overdue: 518 | tasks = [x for x in tasks if hasattr(x.instance.vtodo, 'due') and _force_datetime(x.instance.vtodo.due.value, args) < _force_datetime(datetime.now(), args)] 519 | if args.hide_future: 520 | tasks = [x for x in tasks if not(hasattr(x.instance.vtodo, 'dtstart') and _force_datetime(x.instance.vtodo.dtstart.value, args) > _force_datetime(datetime.now(), args))] 521 | if args.hide_parents or args.hide_children: 522 | tasks_by_uid = {} 523 | for task in tasks: 524 | tasks_by_uid[task.instance.vtodo.uid.value] = task 525 | for task in tasks: 526 | if hasattr(task.instance.vtodo, 'related_to'): 527 | uid = task.instance.vtodo.uid.value 528 | rel_uid = task.instance.vtodo.related_to.value 529 | rel_type = task.instance.vtodo.related_to.params.get('RELTYPE', 'PARENT') 530 | if ((rel_type == 'CHILD' and args.hide_parents) or (rel_type == 'PARENT' and args.hide_children)) and \ 531 | rel_uid in tasks_by_uid and uid in tasks_by_uid: 532 | del tasks_by_uid[uid] 533 | if ((rel_type == 'PARENT' and args.hide_parents) or (rel_type == 'CHILD' and args.hide_children)) and \ 534 | rel_uid in tasks_by_uid: 535 | del tasks_by_uid[rel_uid] 536 | tasks = [x for x in tasks if x.instance.vtodo.uid.value in tasks_by_uid] 537 | if args.top+args.limit: 538 | tasks = tasks[args.offset+args.offsetn:args.top+args.limit+args.offset+args.offsetn] 539 | elif args.offset+args.offsetn: 540 | tasks = tasks[args.offset+args.offsetn:] 541 | return tasks 542 | 543 | def todo_edit(caldav_conn, args): 544 | tasks = todo_select(caldav_conn, args) 545 | for task in tasks: 546 | ## TODO: code duplication - can we refactor this? 547 | for attr in vtodo_txt_one: 548 | if getattr(args, 'set_'+attr): 549 | if not hasattr(task.instance.vtodo, attr): 550 | task.instance.vtodo.add(attr) 551 | getattr(task.instance.vtodo, attr).value = getattr(args, 'set_'+attr) 552 | for attr in vtodo_txt_many: 553 | if getattr(args, 'set_'+attr): 554 | if not hasattr(task.instance.vtodo, attr): 555 | task.instance.vtodo.add(attr) 556 | getattr(task.instance.vtodo, attr).value = [ getattr(args, 'set_'+attr) ] 557 | for attr in vtodo_txt_many: 558 | if getattr(args, 'add_'+attr): 559 | if not hasattr(task.instance.vtodo, attr): 560 | task.instance.vtodo.add(attr) 561 | getattr(task.instance.vtodo, attr).value = [] 562 | getattr(task.instance.vtodo, attr).value.append(getattr(args, 'add_'+attr)) 563 | if args.pdb: 564 | import pdb; pdb.set_trace() 565 | ## you may now access task.data to edit the raw ical, or 566 | ## task.instance.vtodo to edit a vobject instance 567 | task.save() 568 | 569 | 570 | def todo_postpone(caldav_conn, args): 571 | if args.nocaldav: 572 | raise ValueError("No caldav connection, aborting") 573 | rel_skew = None 574 | new_ts = None 575 | if args.until.startswith('+'): 576 | rel_skew = timedelta(seconds=int(args.until[1:-1])*time_units[args.until[-1]]) 577 | elif args.until.startswith('in'): 578 | new_ts = _now()+timedelta(seconds=int(args.until[2:-1])*time_units[args.until[-1]]) 579 | else: 580 | new_ts = dateutil.parser.parse(args.until) 581 | if not new_ts.time(): 582 | new_ts = _date(new_ts) 583 | 584 | tasks = todo_select(caldav_conn, args) 585 | for task in tasks: 586 | if new_ts: 587 | attr = 'due' if args.due else 'dtstart' 588 | if not hasattr(task.instance.vtodo, attr): 589 | task.instance.vtodo.add(attr) 590 | getattr(task.instance.vtodo, attr).value = new_ts 591 | if rel_skew: 592 | if not args.due and hasattr(task.instance.vtodo, 'dtstart'): 593 | task.instance.vtodo.dtstart.value += rel_skew 594 | elif hasattr(task.instance.vtodo, 'due'): 595 | task.instance.vtodo.due.value += rel_skew 596 | if hasattr(task.instance.vtodo, 'dtstart') and hasattr(task.instance.vtodo, 'due'): 597 | if type(task.instance.vtodo.dtstart.value) != type(task.instance.vtodo.due.value): 598 | ## RFC states they must be of the same type 599 | if isinstance(task.instance.vtodo.dtstart.value, date): 600 | task.instance.vtodo.due.value = _date(task.instance.vtodo.due.value) 601 | else: 602 | d = task.instance.vtodo.due.value 603 | task.instance.vtodo.due.value = datetime(d.year, d.month, d.day) 604 | ## RFC also states that due cannot be before dtstart (and that makes sense) 605 | if _force_datetime(task.instance.vtodo.dtstart.value, args) > _force_datetime(task.instance.vtodo.due.value, args): 606 | task.instance.vtodo.due.value = task.instance.vtodo.dtstart.value 607 | task.save() 608 | 609 | def todo_list(caldav_conn, args): 610 | if args.nocaldav and args.icalendar: 611 | niy(feature="display a prettified tasklist based on stdin ical") 612 | if args.nocaldav: 613 | raise ValueError("Todo-listing with --nocaldav only makes sense together with --icalendar") 614 | tasks = todo_select(caldav_conn, args) 615 | if args.icalendar: 616 | for ical in tasks: 617 | print(to_normal_str(ical.data)) 618 | elif args.list_categories: 619 | categories = set() 620 | for task in tasks: 621 | if hasattr(task.instance.vtodo, 'categories'): 622 | categories.update(task.instance.vtodo.categories.value) 623 | for c in categories: 624 | print(c) 625 | else: 626 | for task in tasks: 627 | t = {'instance': task} 628 | t['dtstart'] = task.instance.vtodo.dtstart.value if hasattr(task.instance.vtodo,'dtstart') else date.today() 629 | t['dtstart_passed_mark'] = '!' if _force_datetime(t['dtstart'], args) <= _now() else ' ' 630 | t['due'] = task.instance.vtodo.due.value if hasattr(task.instance.vtodo,'due') else date.today()+timedelta(args.default_due) 631 | t['due_passed_mark'] = '!' if _force_datetime(t['due'], args) < _now() else ' ' 632 | for timeattr in ('dtstart', 'due'): 633 | t[timeattr] = t[timeattr].strftime(args.timestamp_format) 634 | for summary_attr in ('summary', 'location', 'description', 'url', 'uid'): 635 | if hasattr(task.instance.vtodo, summary_attr): 636 | t['summary'] = getattr(task.instance.vtodo, summary_attr).value 637 | t['summary'] = to_normal_str(t['summary']) 638 | break 639 | for attr in ('location', 'description', 'url'): 640 | if hasattr(task.instance.vtodo, attr): 641 | t[attr] = getattr(task.instance.vtodo, attr).value 642 | else: 643 | t[attr] = "" 644 | t[attr] = to_normal_str(t[attr]) 645 | t['uid'] = task.instance.vtodo.uid.value 646 | print(args.todo_template.format(**t)) 647 | 648 | def todo_complete(caldav_conn, args): 649 | if args.nocaldav: 650 | raise ValueError("No caldav connection, aborting") 651 | tasks = todo_select(caldav_conn, args) 652 | for task in tasks: 653 | if hasattr(task.instance.vtodo, 'rrule'): 654 | rrule = rrulestr(task.instance.vtodo.rrule.value) 655 | try: 656 | next = rrule.after(datetime.now()) 657 | except TypeError: ## pesky problem with comparition of timestamps with and without tzinfo 658 | next = rrule.after(datetime.now(tz=tzlocal.get_localzone())) 659 | if next: 660 | ## new_task is to be completed and we keep the original task open 661 | completed_task = task.copy() 662 | remaining_task = task 663 | 664 | ## the remaining task should have recurrence id set to next start time, and range THISANDFUTURE 665 | if hasattr(remaining_task.instance.vtodo, 'recurrence_id'): 666 | del remaining_task.instance.vtodo.recurrence_id 667 | remaining_task.instance.vtodo.add('recurrence-id') 668 | remaining_task.instance.vtodo.dtstart.value = next ## TODO: should be same type as dtstart (date or datetime) 669 | remaining_task.instance.vtodo.recurrence_id.params['RANGE'] = [ 'THISANDFUTURE' ] 670 | remaining_task.instance.vtodo.rrule 671 | count_search = re.search('COUNT=(\d+)', completed_task.instance.vtodo.rrule.value) 672 | if count_search: 673 | remaining_task.instance.vtodo.rrule.value = re.replace('COUNT=(\d+)', 'COUNT=%d' % int(count_search.group(1))-1) 674 | remaining_task.save() 675 | 676 | ## the completed task should have recurrence id set to current time 677 | ## count in rrule should decrease 678 | completed_task.instance.vtodo.remove(completed_task.instance.vtodo.rrule) 679 | if hasattr(completed_task.instance.vtodo, 'recurrence_id'): 680 | del completed_task.instance.vtodo.recurrence_id 681 | completed_task.instance.vtodo.add('recurrence-id') 682 | completed_task.instance.vtodo.recurrence_id.value = datetime.now() 683 | completed_task.instance.vtodo.dtstart.value = datetime.now() 684 | completed_task.complete() 685 | 686 | continue 687 | task.complete() 688 | 689 | 690 | def todo_delete(caldav_conn, args): 691 | if args.nocaldav: 692 | raise ValueError("No caldav connection, aborting") 693 | tasks = todo_select(caldav_conn, args) 694 | for task in tasks: 695 | task.delete() 696 | 697 | def main(): 698 | """ 699 | the main function does (almost) nothing but parsing command line parameters 700 | """ 701 | # sys.stderr.write(""" 702 | #The calendar-cli command is slowly being deprecated in favor of plann 703 | #Check https://github.com/tobixen/calendar-cli/issues/88 704 | #""") 705 | 706 | ## This boilerplate pattern is from 707 | ## http://stackoverflow.com/questions/3609852 708 | ## We want defaults for the command line options to be fetched from the config file 709 | 710 | # Parse any conf_file specification 711 | # We make this parser with add_help=False so that 712 | # it doesn't parse -h and print help. 713 | conf_parser = argparse.ArgumentParser( 714 | prog=metadata["product"], 715 | description=__doc__, # printed with -h/--help 716 | # Don't mess with format of description 717 | formatter_class=argparse.RawDescriptionHelpFormatter, 718 | # Turn off help, so we print all options in response to -h 719 | add_help=False 720 | ) 721 | conf_parser.add_argument("--config-file", 722 | help="Specify config file", metavar="FILE", default=os.getenv('XDG_CONFIG_HOME', os.getenv('HOME', '~') + '/.config')+'/calendar.conf') 723 | conf_parser.add_argument("--config-section", 724 | help="Specify config section; allows several caldav servers to be configured in the same config file", default='default') 725 | conf_parser.add_argument("--interactive-config", 726 | help="Interactively ask for configuration", action="store_true") 727 | args, remaining_argv = conf_parser.parse_known_args() 728 | conf_parser.add_argument("--version", action='version', version='%%(prog)s %s' % metadata["version"]) 729 | 730 | config = read_config(args.config_file) 731 | 732 | if args.interactive_config: 733 | defaults = interactive_config(args, config, remaining_argv) 734 | if not remaining_argv: 735 | return 736 | else: 737 | defaults = config_section(config, args.config_section) 738 | if not 'ssl_verify_cert' in defaults: 739 | defaults['ssl_verify_cert'] = 'yes' 740 | if not 'language' in defaults: 741 | ## TODO: shouldn't this be lower case? 742 | defaults['language'] = 'EN' 743 | 744 | # Parse rest of arguments 745 | # Don't suppress add_help here so it will handle -h 746 | parser = argparse.ArgumentParser( 747 | description=__doc__, 748 | prog=metadata["product"], 749 | # Inherit options from config_parser 750 | parents=[conf_parser] 751 | ) 752 | parser.set_defaults(**defaults) 753 | 754 | ## Global options 755 | parser.add_argument("--nocaldav", help="Do not connect to CalDAV server, but read/write icalendar format from stdin/stdout", action="store_true") 756 | parser.add_argument("--icalendar", help="Read/write icalendar format from stdin/stdout", action="store_true") 757 | parser.add_argument("--timezone", help="Timezone to use") 758 | parser.add_argument('--language', help="language used") 759 | parser.add_argument("--caldav-url", help="Full URL to the caldav server", metavar="URL") 760 | parser.add_argument("--caldav-user", help="username to log into the caldav server", metavar="USER") 761 | parser.add_argument("--caldav-pass", help="password to log into the caldav server", metavar="PASS") 762 | parser.add_argument("--caldav-proxy", help="HTTP proxy server to use (if any)") 763 | parser.add_argument("--file-pass", help="Absolute path to file containing the password") 764 | parser.add_argument("--ssl-verify-cert", help="verification of the SSL cert - 'yes' to use the OS-provided CA-bundle, 'no' to trust any cert and the path to a CA-bundle") 765 | parser.add_argument("--debug-logging", help="turn on debug logging", action="store_true") 766 | parser.add_argument("--calendar-url", help="URL for calendar to be used (may be absolute or relative to caldav URL, or just the name of the calendar)") 767 | parser.add_argument("--ignoremethod", help="Ignores METHOD property if exists in the request. This violates RFC4791 but is sometimes appended by some calendar servers", action="store_true") 768 | parser.set_defaults(print_help=parser.print_help) 769 | 770 | ## TODO: check sys.argv[0] to find command 771 | ## TODO: set up logging 772 | subparsers = parser.add_subparsers(title='command') 773 | 774 | ## Tasks 775 | todo_parser = subparsers.add_parser('todo') 776 | todo_parser.add_argument('--top', '-1', action='count', default=0) 777 | todo_parser.add_argument('--offset', action='count', default=0) 778 | todo_parser.add_argument('--offsetn', type=int, default=0) 779 | todo_parser.add_argument('--limit', type=int, default=0) 780 | todo_parser.add_argument('--todo-uid') 781 | todo_parser.add_argument('--hide-parents', help='Hide the parent if you need to work on children tasks first (parent task depends on children tasks to be done first)', action='store_true') 782 | todo_parser.add_argument('--hide-children', help='Hide the parent if you need to work on children tasks first (parent task depends on children tasks to be done first)', action='store_true') 783 | todo_parser.add_argument('--overdue', help='Only show overdue tasks', action='store_true') 784 | todo_parser.add_argument('--hide-future', help='Hide events with future dtstart', action='store_true') 785 | 786 | for attr in vtodo_txt_one + vtodo_txt_many: 787 | todo_parser.add_argument('--'+attr, help="for filtering tasks") 788 | 789 | for attr in vtodo_txt_one + vtodo_txt_many: 790 | todo_parser.add_argument('--no'+attr, help="for filtering tasks", action='store_true') 791 | 792 | #todo_parser.add_argument('--priority', ....) 793 | #todo_parser.add_argument('--sort-by', ....) 794 | #todo_parser.add_argument('--due-before', ....) 795 | todo_parser.set_defaults(print_help=todo_parser.print_help) 796 | todo_subparsers = todo_parser.add_subparsers(title='tasks subcommand') 797 | todo_create_parser = todo_subparsers.add_parser('createlist') 798 | todo_create_parser.add_argument('tasklist_id') 799 | todo_create_parser.set_defaults(func=create_tasklist) 800 | 801 | todo_add_parser = todo_subparsers.add_parser('add') 802 | todo_add_parser.add_argument('summaryline', nargs='+') 803 | todo_add_parser.add_argument('--set-dtstart', default=date.today()+timedelta(1)) 804 | todo_add_parser.add_argument('--set-due', default=date.today()+timedelta(1)) 805 | todo_add_parser.add_argument('--is-child', help="the new task is a child-task of the selected task(s)", action='store_true') 806 | for attr in vtodo_txt_one + vtodo_txt_many: 807 | if attr != 'summary': 808 | todo_add_parser.add_argument('--set-'+attr, help="Set "+attr) 809 | # TODO: we probably want to be able to set or delete alarms in other situations, yes? generalize? 810 | todo_add_parser.add_argument('--alarm', metavar='DURATION_BEFORE', 811 | help="specifies a time at which a reminder should be presented for this task, " \ 812 | "relative to the start time of the task (as a timestamp delta)") 813 | todo_add_parser.set_defaults(func=todo_add) 814 | 815 | todo_list_parser = todo_subparsers.add_parser('list') 816 | todo_list_parser.add_argument('--todo-template', help="Template for printing out the event", default="{dtstart}{dtstart_passed_mark} {due}{due_passed_mark} {summary}") 817 | todo_list_parser.add_argument('--default-due', help="If a task has no due date set, list it with the due date set N days from today", type=int, default=14) 818 | todo_list_parser.add_argument('--list-categories', help="Instead of listing the todo-items, list the unique categories used", action='store_true') 819 | todo_list_parser.add_argument('--timestamp-format', help="strftime-style format string for the output timestamps", default="%Y-%m-%d (%a)") 820 | todo_list_parser.set_defaults(func=todo_list) 821 | 822 | todo_edit_parser = todo_subparsers.add_parser('edit') 823 | for attr in vtodo_txt_one + vtodo_txt_many: 824 | todo_edit_parser.add_argument('--set-'+attr, help="Set "+attr) 825 | for attr in vtodo_txt_many: 826 | todo_edit_parser.add_argument('--add-'+attr, help="Add an "+attr) 827 | todo_edit_parser.add_argument('--pdb', help='Allow interactive edit through the python debugger', action='store_true') 828 | todo_edit_parser.set_defaults(func=todo_edit) 829 | 830 | todo_postpone_parser = todo_subparsers.add_parser('postpone') 831 | todo_postpone_parser.add_argument('until', help="either a new date or +interval to add some interval to the existing time, or i.e. 'in 3d' to set the time to a new time relative to the current time. interval is a number postfixed with a one character unit (any of smhdwy). If the todo-item has a dtstart, this field will be modified, else the due timestamp will be modified. If both timestamps exists and dstart will be moved beyond the due time, the due time will be set to dtime.") 832 | todo_postpone_parser.add_argument('--due', help="move the due, not the dtstart", action='store_true') 833 | todo_postpone_parser.set_defaults(func=todo_postpone) 834 | 835 | todo_complete_parser = todo_subparsers.add_parser('complete') 836 | todo_complete_parser.set_defaults(func=todo_complete) 837 | 838 | todo_delete_parser = todo_subparsers.add_parser('delete') 839 | todo_delete_parser.set_defaults(func=todo_delete) 840 | 841 | ## journal 842 | journal_parser = subparsers.add_parser('journal') 843 | journal_parser.set_defaults(print_help=journal_parser.print_help) 844 | journal_subparsers = journal_parser.add_subparsers(title='journal subcommand') 845 | journal_add_parser = journal_subparsers.add_parser('add') 846 | journal_add_parser.add_argument('summaryline', nargs='+') 847 | journal_add_parser.set_defaults(func=journal_add) 848 | 849 | calendar_parser = subparsers.add_parser('calendar') 850 | calendar_parser.set_defaults(print_help=calendar_parser.print_help) 851 | calendar_subparsers = calendar_parser.add_subparsers(title='cal subcommand') 852 | 853 | calendar_create_parser = calendar_subparsers.add_parser('create') 854 | calendar_create_parser.add_argument('cal_id') 855 | calendar_create_parser.set_defaults(func=create_calendar) 856 | 857 | calendar_add_parser = calendar_subparsers.add_parser('add') 858 | calendar_add_parser.add_argument('event_time', help="Timestamp and duration of the event. See the documentation for event_time specifications") 859 | calendar_add_parser.add_argument('summary', nargs='+') 860 | calendar_add_parser.set_defaults(func=calendar_add) 861 | calendar_add_parser.add_argument('--whole-day', help='Whole-day event', action='store_true', default=False) 862 | calendar_add_parser.add_argument('--private', help='Private event', action='store_true', default=False) 863 | 864 | for attr in vcal_txt_one + vcal_txt_many: 865 | calendar_add_parser.add_argument('--set-'+attr, help='Set '+attr) 866 | 867 | calendar_addics_parser = calendar_subparsers.add_parser('addics') 868 | calendar_addics_parser.add_argument('--file', help="ICS file to upload", default='-') 869 | calendar_addics_parser.set_defaults(func=calendar_addics) 870 | 871 | calendar_agenda_parser = calendar_subparsers.add_parser('agenda') 872 | calendar_agenda_parser.add_argument('--from-time', help="Fetch calendar events from this timestamp. See the documentation for time specifications. Defaults to now") 873 | calendar_agenda_parser.add_argument('--to-time', help="Fetch calendar until this timestamp") 874 | calendar_agenda_parser.add_argument('--agenda-mins', help="Fetch calendar for so many minutes", type=int) 875 | calendar_agenda_parser.add_argument('--agenda-days', help="Fetch calendar for so many days", type=int, default=7) 876 | calendar_agenda_parser.add_argument('--event-template', help="Template for printing out the event. Defaults to '{dtstart} {summary}'", default="{dtstart} {summary}") 877 | calendar_agenda_parser.add_argument('--timestamp-format', help="strftime-style format string for the output timestamps", default="%Y-%m-%d %H:%M (%a)") 878 | calendar_agenda_parser.set_defaults(func=calendar_agenda) 879 | 880 | calendar_delete_parser = calendar_subparsers.add_parser('delete') 881 | calendar_delete_parser.add_argument('--event-uid') 882 | calendar_delete_parser.add_argument('--event-url') 883 | calendar_delete_parser.set_defaults(func=calendar_delete) 884 | 885 | args = parser.parse_args(remaining_argv) 886 | 887 | if args.debug_logging: 888 | ## TODO: set up more proper logging in a more proper way 889 | logging.getLogger().setLevel(logging.DEBUG) 890 | caldav.log.setLevel(logging.DEBUG) 891 | caldav.log.addHandler(logging.StreamHandler()) 892 | 893 | if args.file_pass: 894 | with open(args.file_pass, 'r') as f: 895 | args.caldav_pass = f.read().strip() 896 | 897 | if not args.nocaldav: 898 | if not args.calendar_url and not args.caldav_url: 899 | sys.stderr.write("missing mandatory arguments ... either " 900 | "calendar_url or caldav_url needs to be set\n" 901 | "Have you set up a config file? Read the doc or " 902 | "...\n... use the --interactive-config option to " 903 | "create a config file\n" 904 | ) 905 | sys.exit(1) 906 | caldav_conn = caldav_connect(args) 907 | else: 908 | 909 | caldav_conn = None 910 | 911 | if args.ssl_verify_cert == 'no': 912 | urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) 913 | 914 | if hasattr(args, 'func'): 915 | return args.func(caldav_conn, args) 916 | else: 917 | ## We get here if a subcommand is not given - in that case we should print a friendly 918 | ## help message. With python2 this goes automatically, with python3 we get here. 919 | ## ref https://stackoverflow.com/a/22994500 subcommands are by default not required anymore 920 | ## in python3. However, setting required=True gave a traceback rather than a friendly error message. 921 | args.print_help() 922 | 923 | if __name__ == '__main__': 924 | main() 925 | --------------------------------------------------------------------------------