def createAppointment(self, sendAppointment: SendAppointment): required_recipients = [] optional_recipients = [] for attendee in sendAppointment.requiredAttendees.split(';'): if attendee == "": continue required_recipients.append(attendee) for attendee in sendAppointment.optionalAttendees.split(';'): if attendee == "": continue optional_recipients.append(attendee) calendar_item = CalendarItem( account=self.account, folder=self.account.calendar, start=self.account.default_timezone.localize( EWSDateTime.from_datetime(sendAppointment.startTime)), end=self.account.default_timezone.localize( EWSDateTime.from_datetime(sendAppointment.endTime)), subject=sendAppointment.subject, body=sendAppointment.body, required_attendees=required_recipients, optional_attendees=optional_recipients) # 'SendToNone', 'SendOnlyToAll', 'SendToAllAndSaveCopy calendar_item.save(send_meeting_invitations='SendToAllAndSaveCopy')
def outlook_calendar_event_exists(appointment, calendar_service, summary): ews_tz = EWSTimeZone.timezone('America/Chicago') d = appointment.start_time.datetime start_date_time = datetime(d.year, d.month, d.day, d.hour, d.minute, d.second, d.microsecond, ews_tz) start_ews_date_time = EWSDateTime.from_datetime(start_date_time) d = appointment.end_time.datetime end_date_time = datetime(d.year, d.month, d.day, d.hour, d.minute, d.second, d.microsecond, ews_tz) end_ews_date_time = EWSDateTime.from_datetime(end_date_time) matching_events = calendar_service.calendar.find_items( start=start_ews_date_time, end=end_ews_date_time, shape=AllProperties) if matching_events: for event in matching_events: if event.subject == summary: print( "Found a matching Outlook calendar event for appointment {app}. Will not create a new one.".format( app=appointment)) return True return False
def create_meeting(self, username, start_time, end_time, subject, body, required_attendees, optional_attendees): """Create a meeting object""" account = self.connect_to_account( username, impersonation=(username != self.email)) if required_attendees: required_attendees = [ ra.strip() for ra in required_attendees.split(',') ] if optional_attendees: optional_attendees = [ oa.strip() for oa in optional_attendees.split(',') ] tz = EWSTimeZone.timezone('Etc/GMT') meeting = CalendarItem( account=account, folder=account.calendar, start=EWSDateTime.from_datetime( datetime.datetime.fromtimestamp(start_time / 1000, tz=tz)), end=EWSDateTime.from_datetime( datetime.datetime.fromtimestamp(end_time / 1000, tz=tz)), subject=subject, body=body, required_attendees=required_attendees, optional_attendees=optional_attendees) return meeting
def upcomingEvents(self, window=timedelta(minutes=5)): start = datetime.now() #start = datetime(2017, 3, 17, 12, 56) endtm = start + window start = TZ.localize(EWSDateTime.from_datetime(start)) endtm = TZ.localize(EWSDateTime.from_datetime(endtm)) return self.account.calendar.view(start=start, end=endtm)
def get_exchange_events(server: str, domain: Optional[str], username: str, password: str, range_start: datetime, range_end: datetime) -> List[CalendarEvent]: """Connect to exchange calendar server and get events within range.""" # load exchange module if necessary from exchangelib import Credentials, Configuration, Account, DELEGATE from exchangelib import EWSDateTime, EWSTimeZone # setup access full_username = r'{}\{}'.format(domain, username) if domain else username account = Account(primary_smtp_address=username, config=Configuration(server=server, credentials=Credentials( full_username, password)), autodiscover=False, access_type=DELEGATE) # collect event information within given time range events: List[CalendarEvent] = [] localzone = EWSTimeZone.localzone() local_start = localzone.localize(EWSDateTime.from_datetime(range_start)) local_end = localzone.localize(EWSDateTime.from_datetime(range_end)) for item in account.calendar.filter( ##pylint: disable=no-member start__range=(local_start, local_end)).order_by('start'): events.append( CalendarEvent(title=item.subject, start=item.start, end=item.end, duration=(item.end - item.start).seconds / 3600, categories=item.categories)) return events
def miniprogram_pushMessage_get(isGetAll: bool = False): db_session = None if "DEVMODE" in os.environ: if os.environ["DEVMODE"] == "True": db_session = orm.init_db(os.environ["DEV_DATABASEURI"]) else: db_session = orm.init_db(os.environ["DATABASEURI"]) else: db_session = orm.init_db(os.environ["DATABASEURI"]) learner = weapp.getLearner() if not learner: db_session.remove() return {'code': -1001, 'message': '没有找到对应的Learner'}, 200 response = [] if isGetAll: pushMessageList = db_session.query(orm.PushMessage_db).all() else: pushMessageList = db_session.query(orm.PushMessage_db).filter(orm.PushMessage_db.expireDateTime > datetime.datetime.utcnow()).all() for pushMessage in pushMessageList: if util.isRecipient(learner, json.loads(pushMessage.recipients)): response.append({ "id": pushMessage.id, "messageType": pushMessage.messageType, "entityId": pushMessage.entityId, "senderId": pushMessage.senderId, "recipients": json.loads(pushMessage.recipients), "rsvp": json.loads(pushMessage.rsvp), "sentDateTime": EWSDateTime.from_datetime(tzinfo.localize(pushMessage.sentDateTime)).ewsformat(), "modifiedDateTime": EWSDateTime.from_datetime(tzinfo.localize(pushMessage.modifiedDateTime)).ewsformat(), "expireDateTime": EWSDateTime.from_datetime(tzinfo.localize(pushMessage.expireDateTime)).ewsformat(), "content": json.loads(pushMessage.content) }) db_session.remove() return {'code': 0, 'data': response, 'message': '成功'}, 200
def test_get_free_busy_info(self): tz = EWSTimeZone('Europe/Copenhagen') server_timezones = list(self.account.protocol.get_timezones(return_full_timezone_data=True)) start = EWSDateTime.now(tz=tz) end = EWSDateTime.now(tz=tz) + datetime.timedelta(hours=6) accounts = [(self.account, 'Organizer', False)] with self.assertRaises(ValueError): self.account.protocol.get_free_busy_info(accounts=[(123, 'XXX', 'XXX')], start=0, end=0) with self.assertRaises(ValueError): self.account.protocol.get_free_busy_info(accounts=[(self.account, 'XXX', 'XXX')], start=0, end=0) with self.assertRaises(ValueError): self.account.protocol.get_free_busy_info(accounts=[(self.account, 'Organizer', 'XXX')], start=0, end=0) with self.assertRaises(ValueError): self.account.protocol.get_free_busy_info(accounts=accounts, start=end, end=start) with self.assertRaises(ValueError): self.account.protocol.get_free_busy_info(accounts=accounts, start=start, end=end, merged_free_busy_interval='XXX') with self.assertRaises(ValueError): self.account.protocol.get_free_busy_info(accounts=accounts, start=start, end=end, requested_view='XXX') for view_info in self.account.protocol.get_free_busy_info(accounts=accounts, start=start, end=end): self.assertIsInstance(view_info, FreeBusyView) self.assertIsInstance(view_info.working_hours_timezone, TimeZone) ms_id = view_info.working_hours_timezone.to_server_timezone(server_timezones, start.year) self.assertIn(ms_id, {t[0] for t in CLDR_TO_MS_TIMEZONE_MAP.values()}) # Test account as simple email for view_info in self.account.protocol.get_free_busy_info( accounts=[(self.account.primary_smtp_address, 'Organizer', False)], start=start, end=end ): self.assertIsInstance(view_info, FreeBusyView)
def get_meeting_invite_counts_by_time(self, start, end): count = self.exchangelib_connection.calendar.filter(start__range=( self.tz.localize(EWSDateTime(start[0], start[1], start[2])), self.tz.localize(EWSDateTime(start[0], start[1], start[2])) )).all().count() return count
def outlook_calendar_event_exists(appointment, calendar_service, summary): ews_tz = EWSTimeZone.timezone('America/Chicago') d = appointment.start_time.datetime start_date_time = datetime(d.year, d.month, d.day, d.hour, d.minute, d.second, d.microsecond, ews_tz) start_ews_date_time = EWSDateTime.from_datetime(start_date_time) d = appointment.end_time.datetime end_date_time = datetime(d.year, d.month, d.day, d.hour, d.minute, d.second, d.microsecond, ews_tz) end_ews_date_time = EWSDateTime.from_datetime(end_date_time) matching_events = calendar_service.calendar.find_items( start=start_ews_date_time, end=end_ews_date_time, shape=AllProperties) if matching_events: for event in matching_events: if event.subject == summary: print( "Found a matching Outlook calendar event for appointment {app}. Will not create a new one." .format(app=appointment)) return True return False
def test_sessionpool(self): # First, empty the calendar start = EWSDateTime(2011, 10, 12, 8, tzinfo=self.account.default_timezone) end = EWSDateTime(2011, 10, 12, 10, tzinfo=self.account.default_timezone) self.account.calendar.filter( start__lt=end, end__gt=start, categories__contains=self.categories).delete() items = [] for i in range(75): subject = 'Test Subject %s' % i item = CalendarItem( start=start, end=end, subject=subject, categories=self.categories, ) items.append(item) return_ids = self.account.calendar.bulk_create(items=items) self.assertEqual(len(return_ids), len(items)) ids = self.account.calendar.filter(start__lt=end, end__gt=start, categories__contains=self.categories) \ .values_list('id', 'changekey') self.assertEqual(ids.count(), len(items))
def miniprogram_booking_roomCode_get(roomCode, monthToLoad): # noqa: E501 # 按房间信息和月份(query中)获取所有的预约信息 db_session = None if "DEVMODE" in os.environ: if os.environ["DEVMODE"] == "True": db_session = orm.init_db(os.environ["DEV_DATABASEURI"]) else: db_session = orm.init_db(os.environ["DATABASEURI"]) else: db_session = orm.init_db(os.environ["DATABASEURI"]) responseList = [] learner = weapp.getLearner() if not learner: db_session.remove() return {'code': -1001, 'message': '没有找到对应的Learner'}, 200 try: room_account = Account( primary_smtp_address=('*****@*****.**' % roomCode), credentials=credentials, config=config ) except Exception as e: db_session.remove() return {'code': -2002, 'message': '代理用的Office Account初始化失败', "log": str(e)}, 200 monthToLoad_year = int(monthToLoad.split("-")[0]) monthToLoad_month = int(monthToLoad.split("-")[1]) if monthToLoad_month == 1: start = room_account.default_timezone.localize(EWSDateTime(monthToLoad_year - 1, 12, 1)) else: start = room_account.default_timezone.localize(EWSDateTime(monthToLoad_year, monthToLoad_month - 1, 1)) if monthToLoad_month == 11: end = room_account.default_timezone.localize(EWSDateTime(monthToLoad_year + 1, 1, 1)) elif monthToLoad_month == 12: end = room_account.default_timezone.localize(EWSDateTime(monthToLoad_year + 1, 2, 1)) else: end = room_account.default_timezone.localize(EWSDateTime(monthToLoad_year, monthToLoad_month + 2, 1)) try: for item in room_account.calendar.view(start=start, end=end).all().order_by('start'): notes = db_session.query(orm.BookingNotes_db).filter(orm.BookingNotes_db.changekey == item.changekey).one_or_none() localizedStart = item.start.astimezone(get_localzone()) localizedEnd = item.end.astimezone(get_localzone()) bookedByID = getattr(notes, "bookedByID", 0) bookedByName = getattr(notes, "bookedByName", "") responseList.append({ 'startDate': ("%d-%0*d-%0*d" % (localizedStart.year, 2, localizedStart.month, 2, localizedStart.day)), 'endDate': ("%d-%0*d-%0*d" % (localizedEnd.year, 2, localizedEnd.month, 2, localizedEnd.day)), 'startTime': ("%0*d:%0*d" % (2, localizedStart.hour, 2, localizedStart.minute)), 'endTime': ("%0*d:%0*d" % (2, localizedEnd.hour, 2, localizedEnd.minute)), 'subject': item.subject, 'changekey': item.changekey, 'bookedByID': bookedByID, 'bookedByName': bookedByName, 'description': '' if not getattr(item, 'text_body') else getattr(item, 'text_body'), 'type': 'appointment' }) except Exception as e: db_session.remove() return {'code': -2003, 'message': '获取房间事件列表失败', 'log': str(e)}, 200 db_session.remove() return {'code': 0, 'data': responseList, 'message': '成功'}, 200
def addAgendaSubmit(self): fromDate = self.ui_addAgenda.agndFromDateInput.date() fromTime = self.ui_addAgenda.agndFromTimeInput.time() toDate = self.ui_addAgenda.agndToDateInput.date() toTime = self.ui_addAgenda.agndToTimeInput.time() fromDatetime = QDateTime(fromDate, fromTime, timeSpec=Qt.LocalTime) toDatetime = QDateTime(toDate, toTime, timeSpec=Qt.LocalTime) localTimeZone = EWSTimeZone.localzone() fromEWSDatetime = EWSDateTime.from_datetime( fromDatetime.toPyDateTime()) toEWSDatetime = EWSDateTime.from_datetime(toDatetime.toPyDateTime()) fromDT = fromEWSDatetime.astimezone(tz=localTimeZone) toDT = toEWSDatetime.astimezone(tz=localTimeZone) location = self.ui_addAgenda.agndPosInput.text() subject = self.ui_addAgenda.agndSubjectInput.text() detail = self.ui_addAgenda.agndDetailInput.toPlainText() reminderEnable = self.ui_addAgenda.agndAlarmEnableCheck.isChecked() reminder = self.ui_addAgenda.agndAlarmInput.value() self.timerRoutine.exchAccount.login() self.timerRoutine.exchAccount.addAgenda(fromDT, toDT, location, subject, detail, reminderEnable, reminder) self.addAgendaDialog.close() self.listDialog.show() self.timerRoutine.unrdAutoUpdateTimerStart() self.timerRoutine.timer2.start()
def clear_reservations(preferences): logger.info("Cancelling appointments made by the device") appointments = get_appointments(preferences) if appointments is None: logger.error("Failed to cancel requested appointment. Perhaps there is an issue with network connectivity.") return now = tz.localize(EWSDateTime.utcnow()) if(len(appointments) > 0): for app in appointments: start_time = tz.localize(app.start.replace(tzinfo=None)) end_time = tz.localize(app.end.replace(tzinfo=None)) if "Pikavaraus" in app.subject and "Naurunappula" in app.body and now < end_time: logger.info("Cancelling an appointment named {0} at {1} - {2}".format(app.subject, start_time, end_time)) try: app.start = app.start.astimezone(tz) app.end = tz.localize(EWSDateTime.now()) app.save() return True except Exception as e: logger.exception("Couldn't cancel appointment.") return False else: logger.info("No appointments to cancel.") return False
def mail_ids_by_date( self, *, before: Optional[float] = None, after: Optional[float] = None, ) -> Iterable[float]: # exchangelib needs a timezone to be applied in order to select mails by # date. Providing none (and thus keep the default) results in errors # on some machines, so we hardcode one here. # In order to make EWS filter correctly in different timezones we need # a way to configure the enforced setting and keep the defaults if # none are given. tz = EWSTimeZone("Europe/Berlin") dt_start = EWSDateTime.from_datetime( datetime.fromtimestamp(after) if after else datetime(1990, 1, 1) ).astimezone(tz) dt_end = EWSDateTime.from_datetime( datetime.fromtimestamp(before) if before else datetime.now() ).astimezone(tz) logging.debug("fetch mails from %s (from %s)", dt_start, after) logging.debug("fetch mails to %s (from %s)", dt_end, before) return [ item.datetime_sent.timestamp() for item in self._selected_folder.filter( datetime_received__range=(dt_start, dt_end)) ]
def miniprogram_announcement_announcementId_get(announcementId): # 获取通知的详情 db_session = None if "DEVMODE" in os.environ: if os.environ["DEVMODE"] == "True": db_session = orm.init_db(os.environ["DEV_DATABASEURI"]) else: db_session = orm.init_db(os.environ["DATABASEURI"]) else: db_session = orm.init_db(os.environ["DATABASEURI"]) learner = weapp.getLearner() if not learner: db_session.remove() return {'code': -1001, 'message': '没有找到对应的Learner'}, 200 announcement = db_session.query(orm.Announcement_db).filter(orm.Announcement_db.id == announcementId).one_or_none() try: response = { "id": announcement.id, "initiatorId": announcement.initiatorId, "initiatorDisplayName": announcement.initiatorDisplayName, "recipients": json.loads(announcement.recipients), "sentDateTime": EWSDateTime.from_datetime(tzinfo.localize(announcement.sentDateTime)).ewsformat(), "modifiedDateTime": EWSDateTime.from_datetime(tzinfo.localize(announcement.modifiedDateTime)).ewsformat(), "thumbnail": json.loads(announcement.thumbnail), "title": announcement.title, "description": announcement.description, "body": json.loads(announcement.body), "attachment": json.loads(announcement.attachment), } db_session.remove() return {'code': 0, 'data': response, 'message': '成功'}, 200 except Exception as e: db_session.remove() return {'code': -5003, 'message': '获取通知详情失败', 'log': str(e)}, 200
def calendarIteration(): global meetingList, busyTimes, busyTimesFlat, account, tz, year, month, day dst = time.localtime().tm_isdst calendarItems = [] now = datetime.datetime.now() day, month, year = now.day, now.month, now.year tz = EWSTimeZone.timezone('Europe/Oslo') credentials = Credentials(username=config['username'], password=config['password']) account = Account(config['account'], credentials=credentials, autodiscover=True) items = account.calendar.view( start=tz.localize(EWSDateTime(year, month, day)), end=tz.localize(EWSDateTime(year, month, day)) + datetime.timedelta(days=1), ) if dst == 0: for item in items: today_events = [item.start + datetime.timedelta(hours=1), item.end + datetime.timedelta(hours=1), item.organizer] calendarItems.append(today_events) else: for item in items: today_events = [item.start + datetime.timedelta(hours=2), item.end + datetime.timedelta(hours=2), item.organizer] calendarItems.append(today_events) meetingList = [] busyTimes = [] busyTimesFlat = [] counter = 0 for events in calendarItems: tempDict = {'start':str(calendarItems[counter][0]), 'end':str(calendarItems[counter][1]), 'title':calendarItems[counter][2].name} busyTimes = busyTimes+[list(range(int(tempDict['start'][11:16].replace(':','')),(int(tempDict['end'][11:16].replace(':','')))+1))] busyTimesFlat = [item for sublist in busyTimes for item in sublist] meetingList.append(tempDict) counter += 1 with open('web/events.json', 'w') as f: f.write(json.dumps(meetingList)) f.close()
def test_q(self): tz = EWSTimeZone.timezone('Europe/Copenhagen') start = tz.localize(EWSDateTime(1950, 9, 26, 8, 0, 0)) end = tz.localize(EWSDateTime(2050, 9, 26, 11, 0, 0)) result = '''\ <m:Restriction xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"> <t:And xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"> <t:Or> <t:Contains ContainmentMode="Substring" ContainmentComparison="Exact"> <t:FieldURI FieldURI="item:Categories"/> <t:Constant Value="FOO"/> </t:Contains> <t:Contains ContainmentMode="Substring" ContainmentComparison="Exact"> <t:FieldURI FieldURI="item:Categories"/> <t:Constant Value="BAR"/> </t:Contains> </t:Or> <t:IsGreaterThan> <t:FieldURI FieldURI="calendar:End"/> <t:FieldURIOrConstant> <t:Constant Value="1950-09-26T08:00:00+01:00"/> </t:FieldURIOrConstant> </t:IsGreaterThan> <t:IsLessThan> <t:FieldURI FieldURI="calendar:Start"/> <t:FieldURIOrConstant> <t:Constant Value="2050-09-26T11:00:00+01:00"/> </t:FieldURIOrConstant> </t:IsLessThan> </t:And> </m:Restriction>''' q = Q(Q(categories__contains='FOO') | Q(categories__contains='BAR'), start__lt=end, end__gt=start) r = Restriction(q, folders=[Calendar()], applies_to=Restriction.ITEMS) self.assertEqual(str(r), ''.join(l.lstrip() for l in result.split('\n'))) # Test empty Q q = Q() self.assertEqual( q.to_xml(folders=[Calendar()], version=None, applies_to=Restriction.ITEMS), None) with self.assertRaises(ValueError): Restriction(q, folders=[Calendar()], applies_to=Restriction.ITEMS) # Test validation with self.assertRaises(ValueError): Q(datetime_created__range=(1, )) # Must have exactly 2 args with self.assertRaises(ValueError): Q(datetime_created__range=(1, 2, 3)) # Must have exactly 2 args with self.assertRaises(TypeError): Q(datetime_created=Build(15, 1)).clean() # Must be serializable with self.assertRaises(ValueError): Q(datetime_created=EWSDateTime(2017, 1, 1)).clean() # Must be tz-aware date with self.assertRaises(ValueError): Q(categories__contains=[[1, 2], [3, 4] ]).clean() # Must be single value
def miniprogram_notification_get(isGetAll: bool = False): def constructContent(notification: Notification_db): if notification.notificationType == "活动日程": event: Event_db = db_session.query(orm.Event_db).filter( orm.Event_db.id == notification.entityId).one_or_none() return { "startDateTime": json.loads(event.eventInfo)["startDateTime"], "endDateTime": json.loads(event.eventInfo)["endDateTime"], "initiatorId": event.initiatorId, "initiatorDisplayName": event.initiatorDisplayName } db_session = None if "DEVMODE" in os.environ: if os.environ["DEVMODE"] == "True": db_session = orm.init_db(os.environ["DEV_DATABASEURI"]) else: db_session = orm.init_db(os.environ["DATABASEURI"]) else: db_session = orm.init_db(os.environ["DATABASEURI"]) learner = weapp.getLearner() if not learner: db_session.remove() return {'code': -1001, 'message': '没有找到对应的Learner'}, 200 response = [] if isGetAll: notificationList: List[Notification_db] = db_session.query( orm.Notification_db).filter( orm.Notification_db.learnerId == learner.id).all() else: notificationList = db_session.query(orm.Notification_db).filter( orm.Notification_db.learnerId == learner.id).filter( orm.Notification_db.expireDateTime > datetime.datetime.utcnow()).all() for notification in notificationList: response.append({ "notificationType": notification.notificationType, "entityId": notification.entityId, "createdDateTime": EWSDateTime.from_datetime( tzinfo.localize(notification.createdDateTime)).ewsformat(), "expireDateTime": EWSDateTime.from_datetime( tzinfo.localize(notification.expireDateTime)).ewsformat(), "status": notification.status, "title": notification.title, "description": notification.description, "content": constructContent(notification) }) db_session.remove() return {'code': 0, 'data': response, 'message': '成功'}, 200
def create_meeting(): meeting = MagicMock(spec=CalendarItem) meeting.subject = "Test" meeting.body = "Just a test" meeting.attachments = [] meeting.start = EWSDateTime(2020, 11, 10, 14, 0, tzinfo=TEST_TZ) meeting.end = EWSDateTime(2020, 11, 10, 15, 0, tzinfo=TEST_TZ) meeting.required_attendees = ['*****@*****.**'] return meeting
def test_naive_datetime(self): # Test that we can survive naive datetimes on a datetime field tz = EWSTimeZone.timezone('Europe/Copenhagen') account = namedtuple('Account', ['default_timezone'])(default_timezone=tz) default_value = tz.localize(EWSDateTime(2017, 1, 2, 3, 4)) field = DateTimeField('foo', field_uri='item:DateTimeSent', default=default_value) # TZ-aware datetime string payload = b'''\ <?xml version="1.0" encoding="utf-8"?> <Envelope xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"> <t:Item> <t:DateTimeSent>2017-06-21T18:40:02Z</t:DateTimeSent> </t:Item> </Envelope>''' elem = to_xml(payload).find('{%s}Item' % TNS) self.assertEqual(field.from_xml(elem=elem, account=account), UTC.localize(EWSDateTime(2017, 6, 21, 18, 40, 2))) # Naive datetime string is localized to tz of the account payload = b'''\ <?xml version="1.0" encoding="utf-8"?> <Envelope xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"> <t:Item> <t:DateTimeSent>2017-06-21T18:40:02</t:DateTimeSent> </t:Item> </Envelope>''' elem = to_xml(payload).find('{%s}Item' % TNS) self.assertEqual(field.from_xml(elem=elem, account=account), tz.localize(EWSDateTime(2017, 6, 21, 18, 40, 2))) # Garbage string returns None payload = b'''\ <?xml version="1.0" encoding="utf-8"?> <Envelope xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"> <t:Item> <t:DateTimeSent>THIS_IS_GARBAGE</t:DateTimeSent> </t:Item> </Envelope>''' elem = to_xml(payload).find('{%s}Item' % TNS) self.assertEqual(field.from_xml(elem=elem, account=account), None) # Element not found returns default value payload = b'''\ <?xml version="1.0" encoding="utf-8"?> <Envelope xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"> <t:Item> </t:Item> </Envelope>''' elem = to_xml(payload).find('{%s}Item' % TNS) self.assertEqual(field.from_xml(elem=elem, account=account), default_value)
def miniprogram_announcement_post(announcementPostBody): db_session = None if "DEVMODE" in os.environ: if os.environ["DEVMODE"] == "True": db_session = orm.init_db(os.environ["DEV_DATABASEURI"]) else: db_session = orm.init_db(os.environ["DATABASEURI"]) else: db_session = orm.init_db(os.environ["DATABASEURI"]) announcementPostBody_dict = connexion.request.get_json() learner = weapp.getLearner() if not learner: db_session.remove() return {'code': -1001, 'message': '没有找到对应的Learner'}, 200 # 自定义鉴权 if not learner.isAdmin: db_session.remove() return {'code': -1007, 'message': '需要管理员权限', "detail": "只有管理员有权限发送通知"}, 200 try: newAnnouncement = orm.Announcement_db( initiatorId=learner.id, initiatorDisplayName=announcementPostBody_dict['initiatorDisplayName'], recipients=json.dumps(announcementPostBody_dict['recipients']), sentDateTime=util.EWSDateTimeToDateTime(account.default_timezone.localize(EWSDateTime.now())), modifiedDateTime=util.EWSDateTimeToDateTime(account.default_timezone.localize(EWSDateTime.now())), expireDateTime=util.EWSDateTimeToDateTime(EWSDateTime.from_string(announcementPostBody_dict["expireDateTime"])), thumbnail=json.dumps(announcementPostBody_dict['thumbnail']), title=announcementPostBody_dict['title'], description=announcementPostBody_dict['description'], body=json.dumps(announcementPostBody_dict['body']), attachment=json.dumps(announcementPostBody_dict['attachment']), ) db_session.add(newAnnouncement) db_session.commit() newPushMessage = orm.PushMessage_db( messageType="Announcement", entityId=newAnnouncement.id, senderId=learner.id, senderDisplayName=announcementPostBody_dict['initiatorDisplayName'], recipients=json.dumps(announcementPostBody_dict['recipients']), sentDateTime=util.EWSDateTimeToDateTime(account.default_timezone.localize(EWSDateTime.now())), modifiedDateTime=util.EWSDateTimeToDateTime(account.default_timezone.localize(EWSDateTime.now())), expireDateTime=util.EWSDateTimeToDateTime(EWSDateTime.from_string(announcementPostBody_dict["expireDateTime"])), content=json.dumps(announcementPostBody_dict["content"]) ) db_session.add(newPushMessage) db_session.commit() newAnnouncement.pushMessageId = newPushMessage.id db_session.commit() except Exception as e: db_session.remove() return {'code': -5001, 'message': '创建通知失败', 'log': str(e)}, 200 response = {'pushMessage_id': newPushMessage.id, 'announcment_id': newAnnouncement.id} return {'code': 0, 'data': response, 'message': '成功'}, 200
def miniprogram_booking_roomCode_post(roomCode, appointment): # noqa: E501 # 添加预约信息 db_session = None if "DEVMODE" in os.environ: if os.environ["DEVMODE"] == "True": db_session = orm.init_db(os.environ["DEV_DATABASEURI"]) else: db_session = orm.init_db(os.environ["DATABASEURI"]) else: db_session = orm.init_db(os.environ["DATABASEURI"]) learner = weapp.getLearner() if not learner: db_session.remove() return {'code': -1001, 'message': '没有找到对应的Learner'}, 200 room_account = Account( primary_smtp_address=('*****@*****.**' % roomCode), credentials=credentials, config=config ) startDateTime = room_account.default_timezone.localize(EWSDateTime( appointment['startYear'], appointment['startMonth'], appointment['startDay'], appointment['startHour'], appointment['startMinute'] )) endDateTime = room_account.default_timezone.localize(EWSDateTime( appointment['endYear'], appointment['endMonth'], appointment['endDay'], appointment['endHour'], appointment['endMinute'] )) try: item = CalendarItem( account=room_account, folder=room_account.calendar, start=startDateTime, end=endDateTime, subject=appointment['subject'], body=appointment['description'], ) item.save(send_meeting_invitations=SEND_TO_ALL_AND_SAVE_COPY) db_session.add(orm.BookingNotes_db( changekey=item.changekey, bookedByID=learner.id, bookedByName=learner.familyName + learner.givenName )) db_session.commit() except Exception as e: db_session.remove() return {'code': -2004, 'message': '房间预约失败', 'log': str(e)}, 200 db_session.remove() return {'code': 0, 'message': 'success'}, 200
def run(self, start_year, start_day, start_month, end_year, end_day, end_month): items = self.account.calendar.filter( start__lt=self.timezone.localize( EWSDateTime(end_year, end_month, end_day)), end__gt=self.timezone.localize( EWSDateTime(start_year, start_month, start_day)), ) self.logger.info('Found {0} calendar entries'.format(len(items))) return [self._format_item(item) for item in items]
def main(): config_file_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'exchange-calendar-to-org.cfg') config = configparser.ConfigParser() config.read(config_file_path) email = config.get('Settings', 'email') try: server_url = config.get('Settings', 'server_url') except configparser.NoOptionError: server_url = None password = config.get('Settings', 'password') sync_days = int(config.get('Settings', 'sync_days')) org_file_path = config.get('Settings', 'org_file') tz_string = config.get('Settings', 'timezone_string') sslverify = config.getboolean('Settings', 'verify_ssl') tz = EWSTimeZone.timezone(tz_string) credentials = Credentials(username=email, password=password) if server_url is None: account = Account( primary_smtp_address=email, credentials=credentials, autodiscover=True, access_type=DELEGATE) else: server = Configuration(server=server_url, credentials=credentials, verify_ssl=sslverify) account = Account( primary_smtp_address=email, config=server, autodiscover=False, access_type=DELEGATE) now = datetime.datetime.now() end = now + datetime.timedelta(days=sync_days) items = account.calendar.filter( start__lt=tz.localize(EWSDateTime(end.year, end.month, end.day)), end__gt=tz.localize(EWSDateTime(now.year, now.month, now.day)), ) text = [] text.append('* Calendar') text.append('\n') for item in items: text.append(get_item_text(item, tz)) text.append('\n') f = open(org_file_path, 'w') f.write(''.join(text))
def get_appointments(): now = tz.localize(EWSDateTime.now()) items = {} try: items = account.calendar.view( start=tz.localize(EWSDateTime(now.year, now.month, now.day, 6, 0)), end=tz.localize(EWSDateTime(now.year, now.month, now.day, 18, 0)), ).order_by('start') except Exception as e: logger.error("Failed to get appointments. Trying again later. Error: {0}".format(e)) return items
def send_outlook_invitation(header="Invitation", body="Please come to my meeting", attendee=None, start_time=None, end_time=None): """Sends an outlook invitation.""" logger.info("Sent outlook invitation") tz = EWSTimeZone.timezone('Europe/Stockholm') start_time = parser.parse(start_time) end_time = parser.parse(end_time) credentials = Credentials(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD) config = Configuration(server='outlook.office365.com', credentials=credentials) account = Account(primary_smtp_address=settings.EMAIL_HOST_USER, config=config, autodiscover=False, access_type=DELEGATE) if os.environ['ENVIRONMENT_MODE'] in ['UAT', 'DEV']: header_prefix = '*** TEST SYSTEM (env {}), NO REAL DATA *** | '.\ format(os.environ['ENVIRONMENT_MODE']) else: header_prefix = '' # create a meeting request and send it out calendar_item = CalendarItem( account=account, folder=account.calendar, start=tz.localize(EWSDateTime(start_time.year, start_time.month, start_time.day, start_time.hour + 1, start_time.minute)), end=tz.localize(EWSDateTime(end_time.year, end_time.month, end_time.day, end_time.hour + 2, end_time.minute)), subject=header_prefix + header, body=body, required_attendees=[attendee] ) calendar_item.save( send_meeting_invitations=SEND_TO_ALL_AND_SAVE_COPY) logger.info("Sent calendar invitation")
def _export_folder_subset(self, folder, start_dt=None, end_dt=None): """ Export a time-subset of an exchange folder :param folder: The exchange folder to export :start_dt: The start date to export from, default 1900-01-01 :end_dt: The end date to export to, default 2100-01-01 :return: Number of attachments in folder """ try: logger.info('Export subset: {} to {}'.format(start_dt, end_dt)) attachments = 0 if start_dt is None: start_dt = EWSDate(1900, 1, 1) if end_dt is None: end_dt = EWSDate(2100, 1, 1) items = folder.all() start_dt = UTC.localize( EWSDateTime(start_dt.year, start_dt.month, start_dt.day, 0, 0)) end_dt = UTC.localize( EWSDateTime(end_dt.year, end_dt.month, end_dt.day, 0, 0)) items = items.filter(datetime_received__range=(start_dt, end_dt)) for chunk in chunkify(items, 10): for item in chunk: self.actual_exported_mails += 1 logger.error( str(item.datetime_created) + ':' + str(item.subject)) skip_list = self.export_item_body(item) attachments += self.export_attachments(item, skip_list) self.update_amqp(only_mails=True) except ErrorMimeContentConversionFailed: msg = '{}: ErrorMimeContentConversionFailed, giving up sub-folder' msg += ' Attachment value: {}' logger.warning(msg.format(self.export_path, attachments)) except ErrorInternalServerError: # Possibly happens on p7m files? msg = '{}: ErrorInternalServerError, giving up sub-folder' msg += ' Attachment value: {}' logger.warning(msg.format(self.export_path, attachments)) except ErrorInvalidOperation: msg = '{}: ErrorInvalidOperation, giving up sub-folder' msg += ' Attachment value: {}' logger.warning(msg.format(self.export_path, attachments)) except ErrorTimeoutExpired: attachments = -1 time.sleep(30) logger.warning('{}: ErrorTimeoutExpired'.format(self.export_path)) except ErrorInternalServerTransientError: attachments = -1 time.sleep(30) warning = '{}, {}: ErrorInternalServerTransientError' logger.warning(warning.format(self.export_path, folder)) return attachments
def main(): parser = argparse.ArgumentParser(description='Synchronize ICS to Exchange') parser.add_argument('ics', help="URL of the ICS") parser.add_argument('username', help="EWS username") parser.add_argument('--password', help="EWS password") parser.add_argument('mail', help="EWS primary SMTP mail address") parser.add_argument('--server', help="EWS server") args = parser.parse_args() if not args.password: args.password = getpass() c = Calendar(requests.get(args.ics).text) credentials = Credentials(username=args.username, password=args.password) config = None autodiscover = True if args.server: config = Configuration(server=args.server, credentials=credentials) autodiscover = False my_account = Account(primary_smtp_address=args.mail, credentials=credentials, access_type=DELEGATE, config=config, autodiscover=autodiscover) for i in list(c.timeline): start = EWSDateTime.from_string(str(i.begin)) end = EWSDateTime.from_string(str(i.end)) found = False for calendar_item in my_account.calendar.filter(start__lt=end, end__gt=start): if calendar_item.text_body and args.ics in calendar_item.text_body and i.uid in calendar_item.text_body: found = True break if found: continue item = CalendarItem(account=my_account, folder=my_account.calendar, start=start, end=end, subject=i.name, body="{}\nics2ews: {}\nuid: {}".format( i.description, args.ics, i.uid), location=i.location) item.save()
def init_time(self): ''' Initialize the time with start and endTime saves a localized EWSDateTime formatted start and endtime ''' tz = self._tz today = datetime.date.today() st = datetime.time(hour=21, minute=00) et = datetime.time(hour=22, minute=00) # forgive me father because I have sinned self._startTime = EWSDateTime.from_datetime( tz.localize(datetime.datetime.combine(today, st))) self._endTime = EWSDateTime.from_datetime( tz.localize(datetime.datetime.combine(today, et)))
def list_today_events(): credentials = Credentials(user, password) account = Account(user, credentials=credentials, autodiscover=True) calendar_folder = account.public_folders_root / calendar now = datetime.datetime.now() year, mount, day = now.year, now.month, now.day items = calendar_folder.view( start=timezone.localize(EWSDateTime(year, mount, day, 0, 0, 1)), end=timezone.localize(EWSDateTime(year, mount, day, 23, 59, 59))).order_by('subject') return list(items)
def generate_items(n): start = tz.localize(EWSDateTime(2000, 3, 1, 8, 30, 0)) end = tz.localize(EWSDateTime(2000, 3, 1, 9, 15, 0)) tpl_item = CalendarItem( start=start, end=end, body='This is a performance optimization test of server %s intended to find the optimal batch size and ' 'concurrent connection pool size of this server.' % config.protocol.server, location="It's safe to delete this", categories=categories, ) for j in range(n): item = copy.copy(tpl_item) item.subject = 'Performance optimization test %s by exchangelib' % j, yield item
def make_a_reservation(timeslot): logger.info("Trying to make a reservation for {0} minutes.".format(timeslot)) now = tz.localize(EWSDateTime.now()) start_time = tz.localize(EWSDateTime(now.year, now.month, now.day, now.hour, now.minute, 0, 0)) end_time = tz.localize(EWSDateTime(now.year, now.month, now.day, now.hour, now.minute, 0, 0) + timedelta(minutes=timeslot)) item = CalendarItem(folder=account.calendar, subject='Pikavaraus', body='Made with Naurunappula at '+ str(now), start=start_time, end=end_time) try: item.save() logger.info("Reservation successful.") return True except Exception as e: logger.info("Reservation failed: {0}".format(e)) return False
def create_outlook_calendar_event(appointment, calendar_service, summary): ews_tz = EWSTimeZone.timezone('America/Chicago') d = appointment.start_time.datetime start_date_time = datetime(d.year, d.month, d.day, d.hour, d.minute, d.second, d.microsecond, ews_tz) start_ews_date_time = EWSDateTime.from_datetime(start_date_time) d = appointment.end_time.datetime end_date_time = datetime(d.year, d.month, d.day, d.hour, d.minute, d.second, d.microsecond, ews_tz) end_ews_date_time = EWSDateTime.from_datetime(end_date_time) event = CalendarItem( subject=summary, body='This event was created by Frontline Calendar. Contact Abby Lance with issues.', start=start_ews_date_time, end=end_ews_date_time ) calendar_service.calendar.add_items([event]) print('Outlook calendar event created. Details: {0}'.format(event))