commands.py (2867B)
1 # Copyright 2018, 2019, 2020, 2021 Matthias Balk 2 # 3 # This file is part of ya3 (yet another appointment application). 4 # 5 # ya3 is free software: you can redistribute it and/or modify it under the 6 # terms of the GNU Affero General Public License as published by the Free 7 # Software Foundation, either version 3 of the License, or (at your option) any 8 # later version. 9 # 10 # ya3 is distributed in the hope that it will be useful, but WITHOUT ANY 11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 12 # A PARTICULAR PURPOSE. See the GNU Affero General Public License for more 13 # details. 14 # 15 # You should have received a copy of the GNU Affero General Public License 16 # along with ya3. If not, see <http://www.gnu.org/licenses/>. 17 18 import os 19 import re 20 import time 21 import uuid 22 from collections import OrderedDict 23 from datetime import datetime 24 25 import dateutil.tz as tz 26 from dateutil.parser import parse 27 28 import config 29 from utils import event2string, get_events, parse2local 30 31 32 def _localtime2utc(datetimestr): 33 local = parse('%s %s' % (datetimestr, time.tzname[0])) 34 return (local - local.utcoffset()).replace(tzinfo=tz.UTC) 35 36 37 def _get_input(key): 38 if key in config.DEFAULTS: 39 i = input('%s: [%s] ' % (key, config.DEFAULTS[key])) 40 return i if i.strip() != '' else config.DEFAULTS[key] 41 return input('%s: ' % key) 42 43 44 def _event2file(event): 45 filename = '%s-%s.ics' % (event['DTSTART'].strftime('%Y-%m-%d'), 46 re.sub(r'([/:-]|\s)+', '-', 47 event['SUMMARY'].lower())) 48 f = open(os.path.join(config.CAL_DIR, filename), 'w') 49 f.write('BEGIN:VCALENDAR\nVERSION:2.0\n') 50 f.write('PRODID:-//ya3//yet another appointment application//\n') 51 52 def item2str(key, value): 53 if isinstance(value, datetime): 54 return '%s:%s\n' % (key, value.strftime('%Y%m%dT%H%M%SZ')) 55 return '%s:%s\n' % (key, value) 56 57 for key in event: 58 f.write(item2str(key, event[key])) 59 60 f.write('END:VCALENDAR\n') 61 f.close() 62 63 64 def create_event(): 65 event = OrderedDict([ 66 ('BEGIN', 'VEVENT'), 67 ('DTSTART', None), 68 ('DTEND', None), 69 ('LOCATION', None), 70 ('SUMMARY', None), 71 ('UID', str(uuid.uuid4())), 72 ('END', 'VEVENT'), 73 ]) 74 75 for key in ['DTSTART', 'DTEND', 'LOCATION', 'SUMMARY']: 76 event[key] = _get_input(key) 77 if re.match('DT', key): 78 event[key] = _localtime2utc(event[key]) 79 if key == 'DTSTART': 80 config.DEFAULTS['DTEND'] = parse2local( 81 event['DTSTART'] + config.DEFAULT_DURATION).strftime( 82 '%Y-%m-%d %H:%M') 83 84 _event2file(event) 85 86 87 def print_events(icsfilenames, ignore_configured_range=False): 88 for event in get_events(icsfilenames, ignore_configured_range): 89 print(event2string(event))