def load_gift_list(username, password, cal_url): client = caldav.DAVClient(url=cal_url, username=username, password=password) calendar = caldav.Calendar(client=client, url=cal_url) wunsch_list = calendar.todos(include_completed=True) outputliszt = [] for item in wunsch_list: #print (item.data) faucal = vobject.readOne(item.data) #print(faucal.vtodo.summary.value) is_completed = False if 'status' in faucal.vtodo.contents: status = faucal.vtodo.contents['status'][0].value if status in ['COMPLETED', 'CANCELLED']: is_completed = True dictionary = { 'name': faucal.vtodo.summary.value, 'completed': is_completed, } outputliszt.append(dictionary) return sorted(outputliszt, key=sort_score) # ['COMPLETED', 'NEEDS-ACTION', 'CANCELLED', 'IN-PROCESS']
def test_func__rights_read_workspace_calendar__fail__as_unauthorized(self): lawrence = DBSession.query(User).filter( User.email == '*****@*****.**' ).one() workspace = WorkspaceApi(lawrence).create_workspace( 'workspace_1', save_now=False ) workspace.calendar_enabled = True DBSession.flush() workspace_calendar_url = CalendarManager.get_workspace_calendar_url( workspace.workspace_id ) transaction.commit() radicale_base_url = CalendarManager.get_base_url() client = caldav.DAVClient( radicale_base_url, username='******', password='******' ) caldav.Calendar( parent=client, client=client, url=workspace_calendar_url ).events()
def get_calendar(self, url, date_start, date_end): # print("%s %s" % (date_start, date_end)) client = caldav.DAVClient(url=url, username=self.username, password=self.password, ssl_verify_cert=False) calendar = caldav.Calendar(client=client, url=url) returned_events = [] events_found = calendar.date_search(start=date_start, end=date_end, compfilter='VEVENT', expand=True) if events_found: for event in events_found: cal = icalendar.Calendar.from_ical(event.data) single_event = {} for event in cal.walk('vevent'): date_start = event.get('dtstart') duration = event.get('duration') summary = event.get('summary') single_event['event_start'] = date_start.dt.astimezone(self.tz) single_event['event_end'] = (date_start.dt + duration.dt).astimezone(self.tz) single_event['event_title'] = summary returned_events.append(single_event) return returned_events
def getDavCalendar(calN: str) -> caldav.Calendar: URLFULL = ids.URL + "calendars/" + ids.USERN + "/" + calN client = caldav.DAVClient(url=ids.URL, username=ids.USERN, password=ids.PASSW) calendar = caldav.Calendar(client=client, url=URLFULL) return calendar
def find_calendar(caldav_conn, args): if args.calendar_url: if '/' in args.calendar_url: return caldav.Calendar(client=caldav_conn, url=args.calendar_url) else: return caldav.Principal(caldav_conn).calendar(name=args.calendar_url) else: ## Find default calendar return caldav.Principal(caldav_conn).calendars()[0]
def test_func__rights_read_user_calendar__ok__as_lawrence(self): radicale_base_url = CalendarManager.get_base_url() client = caldav.DAVClient(radicale_base_url, username='******', password='******') user = DBSession.query(User).filter( User.email == '*****@*****.**').one() user_calendar_url = CalendarManager.get_user_calendar_url(user.user_id) caldav.Calendar(parent=client, client=client, url=user_calendar_url).events()
def test_func__rights_read_user_calendar__fail__as_john_doe(self): radicale_base_url = CalendarManager.get_base_url() client = caldav.DAVClient(radicale_base_url, username='******', password='******') other_user = DBSession.query(User).filter( User.email == '*****@*****.**').one() user_calendar_url = CalendarManager.get_user_calendar_url( other_user.user_id) caldav.Calendar(parent=client, client=client, url=user_calendar_url).events()
def find_calendar(caldav_conn, args): if args.calendar_url: if '/' in args.calendar_url: return caldav.Calendar(client=caldav_conn, url=args.calendar_url) else: return caldav.Principal(caldav_conn).calendar(cal_id=args.calendar_url) else: ## Find default calendar calendars = caldav.Principal(caldav_conn).calendars() if not calendars: sys.stderr.write("no calendar url given and no default calendar found - can't proceed. You will need to create a calendar first") return caldav.Principal(caldav_conn).calendars()[0]
def test_func__event_create__ok__nominal_case(self): lawrence = DBSession.query(User).filter( User.email == '*****@*****.**' ).one() radicale_base_url = CalendarManager.get_base_url() client = caldav.DAVClient( radicale_base_url, username='******', password='******' ) user_calendar_url = CalendarManager.get_user_calendar_url( lawrence.user_id ) user_calendar = caldav.Calendar( parent=client, client=client, url=user_calendar_url ) event_ics = """BEGIN:VCALENDAR VERSION:2.0 PRODID:-//Example Corp.//CalDAV Client//EN BEGIN:VEVENT UID:1234567890 DTSTAMP:20100510T182145Z DTSTART:20100512T170000Z DTEND:20100512T180000Z SUMMARY:This is an event LOCATION:Here END:VEVENT END:VCALENDAR """ user_calendar.add_event(event_ics) user_calendar.save() daemons.execute_in_thread('radicale', lambda: transaction.commit()) # TODO - 20160606 - Bastien: lock should be better here ? time.sleep(3) # Wait for be sure transaction commited in daemon transaction.commit() try: event = DBSession.query(Content) \ .filter(Content.label == 'This is an event') \ .filter(Content.owner_id == lawrence.user_id) \ .filter(Content.id == ContentRevisionRO.content_id) \ .one() except NoResultFound: ok_(False, 'Content record should exist for ' '"This is an event" label') eq_(event.properties['location'], 'Here') eq_(event.properties['start'], '2010-05-12 18:00:00+0000') eq_(event.properties['end'], '2010-05-12 17:00:00+0000')
def loadCalDavEvents(self, url, start, end): client = caldav.DAVClient(url) calendar = caldav.Calendar(client=client, url=url) results = calendar.date_search(start, end) events = [] for event in results: cal = icalendar.Calendar.from_ical(event.data) for e in cal.walk('vevent'): if 'DTSTART' in e: events.append(e) else: self.logger.error('Skipping %s', repr(e)) self.request_events.extend(events)
def main(inputfile): with open(inputfile, 'r') as f: tasks = json.load(f) lists = tasks['items'] for l in lists: title = l['title'] print title items = l['items'] # change this logic, if your calendar .ics files are named # differently than the calendar title in the google takeout json calendar = caldav.Calendar(client, url=davurl + title + '.ics') for t in items: ititle = t['title'] updated = t['updated'] notes = t.get('notes', "") status = t['status'] completed = t.get('completed', None) uid = t['id'] updated = datetime.datetime.strptime(updated, gcal_timeparse_string) updated_str = updated.strftime(vcal_timeformat_string) if completed: completed = datetime.datetime.strptime( completed, gcal_timeparse_string) completed_str = completed.strftime(vcal_timeformat_string) print ititle todo_str = "BEGIN:VCALENDAR\nVERSION:2.0\nBEGIN:VTODO\n" todo_str += "DTSTAMP:%s\n" % updated_str todo_str += "UID:%s\n" % uid todo_str += "CREATED:%s\n" % updated_str todo_str += "LAST-MODIFIED:%s\n" % updated_str todo_str += "SUMMARY:%s\n" % ititle todo_str += "DESCRIPTION:%s\n" % notes.replace('\n', '\\n') if status == "completed": todo_str += "STATUS:COMPLETED\n" todo_str += "PERCENT-COMPLETE:100\n" if completed: todo_str += "COMPLETED:%s\n" % completed_str elif status == "needsAction": todo_str += "STATUS:NEEDS-ACTION\n" else: raise ValueError("unknown status: %s" % status) todo_str += "END:VTODO\nEND:VCALENDAR" calendar.add_todo(todo_str)
def show_todos(epd): ''' Given an EPD instance, fetch todos from Nextcloud tasks and render them on the display. ''' client = caldav.DAVClient(url) principal = client.principal() # Get all calendars associated with user v calendars = principal.calendars() # Get single personal calendar for todos calendar = caldav.Calendar(client=client, url=url) if len(calendars) > 0: # Sort todos based on creation date todos = calendar.todos(sort_keys=('created', )) # Prepare display for rendering LBlackimage = Image.new('1', (epd.width, epd.height), 255) # 126*298 LRedimage = Image.new('1', (epd.width, epd.height), 255) # 126*298 drawblack = ImageDraw.Draw(LBlackimage) drawred = ImageDraw.Draw(LRedimage) newimage = Image.open('img/todo.bmp') LBlackimage.paste(newimage, (12, 0)) # Gather todos from calendar personal if len(todos) == 0: drawblack.text((2, 60), "Nothing to do! :)", font=font24, fill=0) else: position_counter = 40 for todo in todos: todo.load() t = todo.instance.vtodo todoCreated = t.created.value.strftime("%Y-%m-%d %H:%M:%S") drawblack.text((2, position_counter), "- " + t.summary.value, font=font16, fill=0) position_counter += 20 epd.display(epd.getbuffer(LBlackimage), epd.getbuffer(LRedimage)) else: print("Calendar with todos not found!")
def create_then_remove_fake_event( self, calendar_class, related_object_id, ) -> None: radicale_base_url = self.get_base_url(low_level=True) client = caldav.DAVClient( radicale_base_url, username=self._user.email, password=self._user.auth_token, ) if calendar_class == WorkspaceCalendar: calendar_url = self.get_workspace_calendar_url( related_object_id, low_level=True, ) elif calendar_class == UserCalendar: calendar_url = self.get_user_calendar_url( related_object_id, low_level=True, ) else: raise Exception('Unknown calendar type {0}'.format(calendar_class)) user_calendar = caldav.Calendar(parent=client, client=client, url=calendar_url) event_ics = """BEGIN:VCALENDAR VERSION:2.0 PRODID:-//Example Corp.//CalDAV Client//EN BEGIN:VEVENT UID:{uid} DTSTAMP:20100510T182145Z DTSTART:20100512T170000Z DTEND:20100512T180000Z SUMMARY:This is an event LOCATION:Here END:VEVENT END:VCALENDAR """.format(uid='{0}FAKEEVENT'.format(related_object_id)) try: event = user_calendar.add_event(event_ics) event.delete() except PutError: pass # TODO BS 20161128: Radicale is down. Record this event ?
def get_calendar_setup(settings: calview.settings.FrozenSettings, password: str) -> caldav.Calendar: """Set up connection to `CALDAV_SERVER`` and specifying which calendar to query later on. This does not establish a connection yet. Args: settings: full settings password: password Returns: The setup Calendar we want to search later """ client = caldav.DAVClient(url=settings.server, username=settings.user, password=password) my_calendar = caldav.Calendar(client=client, url=settings.cal_url) return my_calendar
def getCalendar(self, calendar_name, url, user, password): try: URL = 'https://{}/remote.php/dav/calendars/{}'.format( url, user) # build base URL calURL = '{}/{}'.format( URL, calendar_name ) # add calendar name to URL to get URL to calendar self.log.info('calendar url: {}'.format(calURL)) client = caldav.DAVClient( url=URL, username=user, password=password) # construct the client calendar = caldav.Calendar( client=client, url=calURL) # constuct the calendar object return calendar except Exception as e: self.speak_dialog('caldav.error', { "method": "accessing", "kind": "calendar" }) self.log.error(e) return None
def __init__(self, uid, name, url, username, password, local_storage): self.uid = uid self.name = name self.url = url self.username = username self.password = password self.local_storage = local_storage if self.uid and self.local_storage: self.local_server = LocalServer(self.local_storage, self.uid) else: self.local_server = None if self.url: self.client = caldav.DAVClient( url=self.url, username=self.username, password=self.password, ) self.calendar = caldav.Calendar(client=self.client, url=self.url) else: self.client = self.calendar = None
import caldav from radicale import ical # # Run it in gearbox command with app context (radicale must running) # pip package caldav==0.4.0 must be installed # run following client = caldav.DAVClient('http://127.0.0.1:5232', username='******', password='******') calendar = caldav.Calendar( parent=client, client=client, id='/user/1.ics/', # url='http://127.0.0.1:5232/user/1.ics/' ) calendar.save() # FOR EACH EVENT IN THIS CALENDAR: coll = ical.Collection.from_path('/user/1.ics/')[0] with coll.filesystem_only(): coll.append(name='THE EVENT NAME (ID)', text='THE ICS EVENT RAW') pass
'property_items', 'required', 'set_inline', 'setdefault', 'singletons', 'sorted_items', 'sorted_keys', 'subcomponents', 'to_ical', 'update', 'values', 'walk'] # https://caldav.calendar.naver.com/caldav/cinema76/calendar/974967/ # https://caldav.calendar.naver.com/caldav/cinema76/calendar/2506846/ # https://caldav.calendar.naver.com/caldav/cinema76/calendar/25981363/ caldav.Calendar(client=client, url='https://caldav.calendar.naver.com/caldav/cinema76/calendar/974967') each_calendar = caldav.Calendar(client=client, url=calendars[0].url) all_events = each_calendar.events() # >>> calendars[0].name # '내 캘린더' # >>> calendars[0].search # <bound method Calendar.search of Calendar(https://caldav.calendar.naver.com/caldav/cinema76/calendar/974967/)> # >>> dir(calendars[0].search) # ['__call__', '__class__', '__delat # events_fetched = calendars[0].date_search(start=datetime(2020, 8, 4), end=datetime(2024, 1, 1), compfilter='VEVENT', expand=True)
# Setting up a caldav client object and a principal object client = caldav.DAVClient(url=URL, username=UserName, password=Password) my_principal = client.principal() # List up all calendars in Nextcloud through the principal-object calendars = my_principal.calendars() if calendars: print("your principal has %i calendars:" % len(calendars)) for c in calendars: print(" Name: %-20s URL: %s" % (c.name, c.url)) else: print("your principal has no calendars") # Access the calendar with events from created ics file a_calendar = caldav.Calendar(client=client, url= 'https://nextcloud05.webo.cloud/remote.php/dav/calendars/[email protected]/new/') events_fetched = a_calendar.date_search( start=datetime(2021, 1, 1), end=datetime(2021, 3, 1), expand=True) # Loop to list up all data from fetched events for y in range(len(events_fetched)): print (y,':', events_fetched[y].data) # Chose an event from listed events event = events_fetched[0] # Modify event parameters using vobject module and save the event event.vobject_instance.vevent.summary.value = 'MOMO' event.vobject_instance.vevent.location.value = 'BUEHNE' event.save() print(event.data)
def _get_beamtimes(date=None): _CATEGORIES = [ '4 - 4 MV (NT 06)', '3 - 500 kV (NT 06)', '2 - 100 kV (NT 07)', '1 - 100 kV (NI 05)' ] _APPLICATION_CATEGORIES = [ 'Analyse-Research', 'Implantation-Research', 'Modifikation-Research', '1 - Implantation-Industry', '2 - Service-Engineering' ] _CATNAMES = { '4 - 4 MV (NT 06)': 'Tandem', '3 - 500 kV (NT 06)': '500 kV', '2 - 100 kV (NT 07)': '100 kV', '1 - 100 kV (NI 05)': 'Med-Implanter' } _CAT_COLORS = { 'Tandem': '#FF3300', '500 kV': '#666600', '100 kV': '#ff6600', 'Med-Implanter': '#FF9900', 'Analyse-Research': '#CC3333', 'Implantation-Research': '#00FFFF', 'Modifikation-Research': '#0066ff', '1 - Implantation-Industry': '#00ff00', '2 - Service-Engineering': '#990000' } _CAT_FGCOLORS = {'2 - Service-Engineering': '#fff'} cal = caldav.Calendar(client=client, url=settings.EGROUPWARE_CAL_URLS['beamtime']) tz = pytz.timezone('Europe/Berlin') td = date or datetime.datetime.today(tzinfo=tz) tm = td + relativedelta(days=1) heute = datetime.datetime(2020, 11, 16, 0, 0, tzinfo=tz) morgen = datetime.datetime(2020, 11, 17, 0, 0, tzinfo=tz) evts = cal.date_search(td, tm) beamtimes = OrderedDict() for c in _CATEGORIES: beamtimes[_CATNAMES[c]] = [] for evt in evts: evt = evt.vobject_instance n = 0 for event in evt.vevent_list: n = n + 1 try: categories = event.categories.value except AttributeError: continue cat = None ccat = None for c in categories: if c in _CATEGORIES: cat = _CATNAMES[c] if c in _APPLICATION_CATEGORIES: ccat = c if cat and ccat: break if not ccat: ccat = cat rr = [] if cat: try: rr = rrule.rrulestr(event.rrule.value, dtstart=event.dtstart.value) except AttributeError: # check if event is today. might be an exception for a rrule... if _is_on_date(event.dtstart.value, td): try: desc = event.description.value except AttributeError: desc = None beamtimes[cat].append({ 'summary': event.summary.value, 'start': event.dtstart.value, 'end': event.dtend.value, 'desc': desc, 'startPercent': _percent_for_display(event.dtstart.value), 'durationPercent': _percent_for_display(event.dtstart.value, event.dtend.value), 'bgcolor': _CAT_COLORS[ccat], 'fgcolor': _CAT_FGCOLORS.get(ccat, '#000') }) if rr: try: excl = event.exdate.value except AttributeError: excl = None rs = rrule.rruleset() rs.rrule(rr) if excl and rs: if not isinstance(excl, list): excl = [excl] for e in excl: rs.exdate(e) if rs: for dt in rs.between(td, tm): try: desc = event.description.value except AttributeError: desc = None beamtimes[cat].append({ 'summary': event.summary.value, 'start': event.dtstart.value, 'end': event.dtend.value, 'desc': desc, 'startPercent': _percent_for_display(event.dtstart.value), 'durationPercent': _percent_for_display(event.dtstart.value, event.dtend.value), 'bgcolor': _CAT_COLORS[ccat], 'fgcolor': _CAT_FGCOLORS.get(ccat, '#000') }) return beamtimes
## Let's search for the newly added event. print("Here is some icalendar data:") events_fetched = my_new_calendar.date_search(start=datetime(2021, 1, 1), end=datetime(2024, 1, 1), expand=True) print(events_fetched[0].data) event = events_fetched[0] ## To modify an event, it's best to use either the vobject or icalendar module for it. The caldav library has always been supporting vobject out of the box, but icalendar is more popular. event.instance will as of version 0.x yield a vobject instance, but this may change in future versions. Use .vobject_instance or .icalendar_instance instead. event.vobject_instance.vevent.summary.value = 'Norwegian national day celebrations' event.save() ## It's possible to access objects such as calendars without going ## through a Principal object, i.e. if one knows the URL the_same_calendar = caldav.Calendar(client=client, url=my_new_calendar.url) ## to get all events from the calendar, it's also possible to use the ## events()-method. Recurring events will not be expanded. all_events = the_same_calendar.events() ## Let's check that the summary got right assert all_events[0].vobject_instance.vevent.summary.value.startswith( 'Norwegian') ## Clean up - remove the new calendar my_new_calendar.delete() ## Let's try with a task list. Some servers cannot combine events and todos in the same calendar. my_new_tasklist = my_principal.make_calendar( name="Test tasklist", supported_calendar_component_set=['VTODO'])