def connect(self): if self.use_proxy: client = caldav.DAVClient(proxy=self.proxy_url, url=self.caldav_url, username=self.username, password=self.password) else: client = caldav.DAVClient(url=self.caldav_url, username=self.username, password=self.password) self.principal = client.principal()
def add_event(title, start, end, description='', public=True): """Adds an event. title..the Summary of the event start..Start of the event. Format: YYYY-MM-DD HH:MM end..End of the event. Format see above description..Description public..True/False """ client = caldav.DAVClient(CALENDAR_URL) principal = client.principal() calendars = principal.calendars() for calendar in calendars: if CALENDAR_UUID in str(calendar.url): break vcal = VCAL_TEMPLATE.format( uuid=uuid.uuid4(), timestamp=tfmt(datetime.now()), start=tfmt(start), end=tfmt(end), summary=title, description=description, klass='PUBLIC' if public else 'PRIVATE', ) event = calendar.add_event(vcal) return event
def getCaldavEvents(url): my_events = [] date_from = date.today() date_to = date.today() + timedelta(7) client = caldav.DAVClient(url) principal = client.principal() calendars = principal.calendars() if len(calendars) > 0: for calendar in calendars: results = calendar.date_search( datetime(date_from.year, date_from.month, date_from.day), datetime(date_to.year, date_to.month, date_to.day)) for dav_event in results: ev = vobject.readOne(dav_event.data) new_event = calendarEvent(ev.vevent.dtstart.value, ev.vevent.dtend.value, ev.vevent.summary.valueRepr()) my_events.append(new_event) my_events.sort(key=lambda r: r.datetimestart) return my_events
def _register_remote_calendar(self, calendar): client = caldav.DAVClient(self._url) principal = client.principal() remote_calendar = principal.make_calendar(name=calendar.name, cal_id=str(uuid.uuid1())) return remote_calendar
def _register_remote_event(self, event): client = caldav.DAVClient(self._url) principal = client.principal() calendars = principal.calendars() if len(calendars) > 0: calendar = calendars[0] UID = uuid.uuid1() SUMMARY = event.summary DESCRIPTION = event.description LOCATION = event.location #parse Date input_start = dateutil.parser.parse(event.dtstart) input_end = dateutil.parser.parse(event.dtend) input_stamp = datetime.today() DTSTAMP = input_stamp.strftime("%Y%m%dT%H%M%SZ%z") DTSTART = input_start.strftime("%Y%m%dT%H%M%SZ%z") DTEND = input_end.strftime("%Y%m%dT%H%M%SZ%z") vcal_parsed = self._vcal.format(UID, DTSTAMP, DTSTART, DTEND, SUMMARY, DESCRIPTION, LOCATION) if log.isEnabledFor(logging.DEBUG): log.debug("_register_remote_event(): vcal_parsed - " + str(vcal_parsed)) new_event = calendar.add_event(vcal_parsed) return new_event
def get_all_calendars(calendar_id=None): """ Fetch a user's calendars """ global TOKEN_CACHE if TOKEN_CACHE is None: load_credentials() calendars_to_fetch = [] calendars = [] if calendar_id is not None and calendar_id not in TOKEN_CACHE: raise Exception('You must authenticate first') elif calendar_id is not None: calendars_to_fetch.append(calendar_id) else: calendars_to_fetch = TOKEN_CACHE.keys() for cal_id in calendars_to_fetch: expires_at = TOKEN_CACHE[cal_id].get('expires_at') credentials = dict_to_credentials(TOKEN_CACHE[cal_id]) if expires_at and datetime.fromtimestamp(expires_at) < datetime.now(): print('Credentials expired for calendar {}'.format(cal_id)) credentials.refresh(Request()) TOKEN_CACHE[cal_id] = credentials_to_dict(credentials) save_credentials() try: client = caldav.DAVClient(GOOGLE_CAL_URL_TMPL.format(cal_id), auth=OAuth(credentials)) principal = client.principal() calendars.extend(principal.calendars()) except AuthorizationError as err: print('Error fetching calendar {}: {}'.format(cal_id, err)) return calendars
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 __init__(self, conf): self.conf = conf if ('username' not in self.conf or 'password' not in self.conf or 'url' not in self.conf): raise KeyError( "Specify the properties username, password, url and \ inbox_name in the config notion section") if conf['url'].startswith('https://'): self.url = conf['url'].replace( 'https://', 'https://' + conf['username'] + ":" + conf["password"] + "@") elif conf['url'].startswith('http://'): self.url = conf['url'].replace( 'http://', 'http://' + conf['username'] + ":" + conf["password"] + "@") else: raise KeyError("Config url should start with http:// or https://") self.url += "/remote.php/caldav/calendars/" + conf['username'] + "/" logging.info("Using url %s", self.url) client = caldav.DAVClient(self.url) principal = client.principal() calendars = principal.calendars() def cal_filter(c): return str(c).endswith(conf['inbox_name'] + '/') filtered_calendars = list(filter(cal_filter, calendars)) if len(filtered_calendars) > 0: self.inbox_calendar = filtered_calendars[0] logging.info("Using calendar %s", str(self.inbox_calendar)) else: raise KeyError("Could not find inbox calendar")
def getcalendars(): client = caldav.DAVClient(url, username=user, password=password) # principal = client.principal() # calendars = principal.calendars() calendar = caldav.objects.Calendar(client=client, url=url) # return(calendars) return (calendar)
def __init__(self, tourServerVar): self.tourServerVar = tourServerVar self.expFunctions = { # keys in lower case "titel": expTitel, "desc": expDesc, "start": expStart, "end": expEnd, "location": expLocation, } with open("cal.json", "r", encoding="utf-8") as jsonFile: conf = json.load(jsonFile) url = conf["url"] username = conf["username"] password = conf["password"] # url = "https://hh.adfc-clouds.de/remote.php/dav" # url = "https://hh.adfc-clouds.de/remote.php/dav/calendars/MichaelUhlenberg/personal/" # username = "******" # password="******" client = caldav.DAVClient(url=url, username=username, password=password) principal = client.principal() self.calendar = principal.calendars()[0] events = self.calendar.events() for ev in events: print(ev) if ev.vobject_instance.contents["prodid"][0].value.find("TTP2CAL") > 0: ev.delete() pass
def create_vevents(person, json_file, login, password): """ Create the events on the online calendar. :param person: the minister as a dictionary :param json_file: the input events to add to the calendar :param login: login for the remote calendar :param password: password for the remote calendar :return: """ client = caldav.DAVClient( "https://framagenda.org/remote.php/dav/calendars/Orage/", auth=HTTPBasicAuth(login, password)) principal = client.principal() calendars = principal.calendars() for cal in calendars: if person["calendar"] in str(cal.url): calendar = cal break else: logging.error("no calendar not found: {}".format(person["calendar"])) return vcalendars = from_json(json_file) for vcal in vcalendars: event = calendar.add_event(vcal) print("Event {} created".format(event))
def addToCal(url, date_from, date_end, summary): """ Add entry in calendar to period date_from, date_end """ vcal_entry = """BEGIN:VCALENDAR VERSION:2.0 PRODID:Pyvac Calendar BEGIN:VEVENT SUMMARY:%s DTSTART;VALUE=DATE:%s DTEND;VALUE=DATE:%s END:VEVENT END:VCALENDAR """ client = caldav.DAVClient(url) principal = client.principal() calendars = principal.calendars() if not len(calendars): return False vcal_entry = vcal_entry % (summary, date_from.strftime('%Y%m%d'), (date_end + relativedelta(days=1)).strftime('%Y%m%d')) calendar = calendars[0] log.info('Using calendar %r' % calendar) log.info('Using entry: %s' % vcal_entry) event = caldav.Event(client, data=vcal_entry, parent=calendar).save() log.info('Event %s created' % event) url_obj = event.url url_obj = str(url_obj) url_obj = urllib.quote(url_obj, safe='/:') return url_obj
def watch(): """ Loops through all remote calendars, synchronizing them with their calendar server. We first send local changes to the server, then retrieve remote changes into our database. Deserves more documentation. """ for dbcal in Calendar.objects.filter(url_template__isnull=False): #~ if not dbcal.url_template: #~ continue url = dbcal.get_url() #~ dblogger.info("Synchronize calendar %s using %s",dbcal.name, url) dblogger.info("Synchronize calendar %s...", dbcal.name) client = caldav.DAVClient(url) principal = caldav.Principal(client, url) #~ print "url.username:"******"url.hostname:", principal.url.hostname calendars = principal.calendars() if len(calendars) == 0: dblogger.info("--> Sorry, no calendar") elif len(calendars) > 1: #~ print "WARNING: more than 1 calendar" dblogger.warning("--> More than 1 calendar") else: send(dbcal, calendars[0], client) receive(dbcal, calendars[0])
def update(): params = request.json if SECRET_KEY == params["key"]: now = datetime.now() global tempTest # tempTest = params["name"] name = params["name"] uid = params["uid"] caldav_url = 'https://cal.bonner.hopto.org/' username = os.getenv("caluser") password = os.getenv("calpass") client = caldav.DAVClient(url=caldav_url, username=username, password=password) my_principal = client.principal() pacCalendar = client.calendar( url= "https://cal.bonner.hopto.org/user1/eccc554d-2a25-6b9e-ee95-59d96066cea4/" ) event = pacCalendar.event_by_uid(uid) oldDescription = event.vobject_instance.vevent.description.value newDescription = """{0} {1} """.format(name, oldDescription) # this will update description event.vobject_instance.vevent.description.value = newDescription event.save() return newDescription
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 fetch_calendars(data): #Check if called from client side (not necessary) if (isinstance(data, str)): data = json.loads(data) account = frappe.get_doc("CalDav Account", data["caldavaccount"]) client = caldav.DAVClient(url=data["url"], username=data["username"], password=data["password"]) principal = client.principal() calendars = principal.calendars() for calendar in calendars: #Check if Calendar exists already #If not create doc = frappe.new_doc("iCalendar") doc.title = cleanName(calendar.name) doc.caldav_account = data["caldavaccount"] doc.calendar_url = str(calendar) #doc.parent = data["caldavaccount"] #doc.parentfield = "calendars" #doc.parenttype = "CalDav Account" doc.insert() doc.link = cleanName(calendar.name) account.append('icalendars', {'icalendar': doc.name}) account.save() doc.save() print("Done") return "response"
def getFacts(): params = request.json if SECRET_KEY == params["key"]: uid = params["uid"] caldav_url = 'https://cal.bonner.hopto.org/' username = os.getenv("caluser") password = os.getenv("calpass") client = caldav.DAVClient(url=caldav_url, username=username, password=password) pacCalendar = client.calendar( url= "https://cal.bonner.hopto.org/user1/eccc554d-2a25-6b9e-ee95-59d96066cea4/" ) event = pacCalendar.event_by_uid(uid) payload = { "data": event.data, "description": event.vobject_instance.vevent.description.value } return payload
def _prepare_cal(self): url_caldav2 = self.config.get("webdav_calendar") url_caldav = urlparse(url_caldav2) url_caldav2 = urlparse(url_caldav2) url_caldav = url_caldav._replace(netloc="{}:{}@{}".format( self.config.get("webdav_login"), self.config.get( "webdav_password"), url_caldav.hostname)) dav = caldav.DAVClient(url_caldav) principal = dav.principal() calendars = principal.calendars() cal = None if len(calendars) > 0: if self._get_caldav_type() == CalDavType.NEXTCLOUD: for calendar in calendars: calendar_parsed = urlparse(str(calendar.url)) if calendar_parsed.hostname == url_caldav2.hostname and calendar_parsed.path == url_caldav2.path: cal = calendar if cal == None: cal = calendars[0] elif self._get_caldav_type() == CalDavType.GOOGLE: cal = calendars[0] else: raise Exception( "Not valid URL! Only: Google and Nextcloud are compatible!" ) return cal
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 connectCalendar(): with open('../conf/config.json') as json_data_file: data = json.load(json_data_file) client = caldav.DAVClient(data["url"], username=data["username"], password=data["password"]) principal = client.principal() return principal.calendars()
def get_calendar(url, username=None, password=None): """ Returns the CalDAV calendar found behind the given URL. Logs can be given to this function or in the URL. """ davclient_url = rebuild_url(url, with_logs=True, username=username, password=password, with_port=True, port=DEFAULT_HTTP_PORT) davclient = caldav.DAVClient(davclient_url) calendar_url = rebuild_url(url, with_logs=False, with_port=True, port=DEFAULT_HTTP_PORT) try: return [ c for c in davclient.principal().calendars() if c.url.rstrip('/') == calendar_url.rstrip('/') ][0] except: raise Exception('Calendar `%s` does not exist.' % url)
def caldav_today(): def filter_fn(cal_name): if CALDAV_CALENDARS: return cal_name in CALDAV_CALENDARS.split(";") else: return True day_start = datetime.now(TZ).replace(hour=0, minute=0, second=0, microsecond=0) day_end = datetime.now(TZ).replace(hour=23, minute=59, second=59, microsecond=999999) client = caldav.DAVClient(CALDAV_URL, username=CALDAV_USER, password=CALDAV_PASSWORD) principal = caldav.Principal(client, CALDAV_URL) LOG.info([cal.name for cal in principal.calendars()]) todays_events = (cal.date_search(start=day_start, end=day_end) for cal in principal.calendars() if filter_fn(cal.name)) combined_cal = vobject.iCalendar() vevents = [ event.vobject_instance.vevent for event in itertools.chain(*todays_events) ] combined_cal.contents["vevent"] = vevents return combined_cal
def caldavConnect(self): username = self.settings.get('username') password = self.settings.get('password') protocol = self.settings.get('protocol') url = self.settings.get('url') LOGGER.info(username) # FIXME If a parameter is missing, the skill should warn the user and stop. if not username: LOGGER.error("No username in configuration.") self.speak_dialog('err.conf.username') return False elif not password: LOGGER.error("No password in configuration.") self.speak_dialog('err.conf.password') return False elif not url: self.speak_dialog('err.conf.url') return False caldavLink = protocol + "://" + username + ":" + password + "@" + url LOGGER.info(caldavLink) obj = caldav.DAVClient(caldavLink) # Not sure how to close the connection once we are done. return obj
def init(self, config_file=None): if config_file is not None: logging.info("Initialising config %s from Calendar_Client.", config_file) CONFIG.init(cfile=config_file) url = CONFIG.get_cal_url() logging.info("connecting to %s", url) try: client = caldav.DAVClient(url) except KeyError: CONFIG.request_calendar() client = caldav.DAVClient(CONFIG.get_cal_url()) principal = client.principal() calendars = principal.calendars() if calendars: self.calendar = calendars[0]
def export_calendar(): export_cal = Calendar() export_cal.add('prodid', '-//Mozilla.org/NONSGML Mozilla Calendar V1.1//EN') export_cal.add('version', '2.0') # Use a breakpoint in the code line below to debug your script. client = caldav.DAVClient(os.getenv("CALDAV_URI"), username=os.getenv("CALDAV_USR"), password=os.getenv("CALDAV_PWD")) principal = client.principal() import_calendar = principal.calendars()[0] events = import_calendar.events() print(f'Found {len(events)} calendar events.') for import_event in import_calendar.events(): export_event = Event() for subcomponent in import_event.icalendar_instance.subcomponents: export_cal.add_component(subcomponent) create_folder_if_missing('out') f = open(os.path.join('out/calendar.ics'), 'wb') f.write(export_cal.to_ical()) f.close() print(f'Exported calendar events.') pass
def test_func__radicale_auth__fail__as_john_doe(self): radicale_base_url = CalendarManager.get_base_url() client = caldav.DAVClient( radicale_base_url, username='******', password='******' ) client.propfind()
def test_func__radicale_auth__ok__as_lawrence(self): radicale_base_url = CalendarManager.get_base_url() client = caldav.DAVClient( radicale_base_url, username='******', password='******' ) client.propfind()
def get_calendar(caldav_url): """ Get the calendar using credentials from `credentials.py`. """ url = caldav_url client = caldav.DAVClient(url) princ = caldav.Principal(client, url) return princ.calendars()[0]
def modifyEvent(oldEventId, newEvent, backendparam): url, user, pw = backendparam client = caldav.DAVClient(url=url, username=user, password=pw) authenticatedClient = client.principal() defaultCal = authenticatedClient.calendars()[0] dummyCal = icalendar.Calendar() dummyCal.add_component(newEvent) defaultCal.add_event(dummyCal.to_ical())
def connectCalendar(): global config client = caldav.DAVClient(config["url"], username=config["username"], password=config["password"]) principal = client.principal() calendars = principal.calendars() return sorted(calendars,key=lambda calendar: str(calendar.url))