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 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 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 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 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 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_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 _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 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 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 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 get_email_list(self, send_time_gte, subject_like=None, sender=None): """ :param send_time_gte: must be specified :param subject_like: if None, it means no restrictions :param sender: if None, it means no restrictions :return: list type """ tz = EWSTimeZone.timezone("Asia/Shanghai") email_list = [] send_time_gte = datetime.datetime.strptime(send_time_gte, "%Y-%m-%d") inbox = self.account.inbox.filter(datetime_sent__gte=tz.localize( EWSDateTime(send_time_gte.year, send_time_gte.month, send_time_gte.day))) for item in inbox.all().order_by("-datetime_sent"): subject = item.subject if not item.sender: continue sender_name = item.sender.name send_time = ( item.datetime_sent + datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S") b1 = (True if not subject_like or subject_like.lower() in subject.lower() else False) b2 = True if not sender or sender.lower() in sender_name.lower( ) else False if b1 and b2: email_list.append([subject, sender_name, send_time]) print("get {} email(s) in total".format(len(email_list))) return email_list
def fetch_all_new_messages(account): log.info("Initializing message downloads") all_new_rows = [] allfolders = account.inbox.get_folders() last_update_timestamp = db.get_timestamp() tz = account.default_timezone from_datetime_list = [int(x) for x in last_update_timestamp.split('-')] localized_from_datetime = tz.localize(EWSDateTime(*from_datetime_list)) for folder in allfolders: log.info("Looking in folder %s" % str(folder)) number_of_emails = folder.filter(datetime_received__gt=localized_from_datetime).count() log.info("Found {0} new messages in folder {1}".format(number_of_emails, folder)) for submission in folder.filter(datetime_received__gt=localized_from_datetime): try: log.info('Accessing submission with subject "%s"' % submission.subject) db_indices = store_submission(submission) # Unless store_submission has returned None, save row id in list to analyze if isinstance(db_indices, list): all_new_rows += db_indices except DuplicateFileWarning as error: log.warning(repr(error)) except DuplicateMessageWarning as error: log.warning(repr(error)) db.set_timestamp() return all_new_rows
def get_calendars(self, this_morning, this_evening): events = [] for calendar in self.calendars: if calendar["type"] == "exchange": credentials = Credentials(username=calendar["username"], password=calendar["password"]) account = Account(primary_smtp_address=calendar["address"], credentials=credentials, autodiscover=True, access_type=DELEGATE) calendar_items = account.calendar.view( start=account.default_timezone.localize( EWSDateTime(this_morning.year, this_morning.month, this_morning.day, 0, 0, 0)), end=account.default_timezone.localize( EWSDateTime(this_morning.year, this_morning.month, this_morning.day, 23, 59, 59))) for calendar_item in calendar_items: events.append({ "subject": calendar_item.subject, "start": calendar_item.start, "end": calendar_item.end }) elif calendar["type"] == "ics": c = Calendar.from_ical(requests.get(calendar["url"]).text) for component in c.walk(): if 'DTSTART' in component and 'DTEND' in component: start = None end = None if isinstance(component["DTSTART"].dt, datetime): start = component["DTSTART"].dt.astimezone( self.timezone) end = component["DTEND"].dt.astimezone( self.timezone) if end >= this_morning and start <= this_evening: events.append({ "subject": component["summary"], "start": start, "end": end }) else: raise Exception("The calendar type \"%s\" is not supported." % (calendar["type"], )) events.sort(key=lambda event: event["start"]) return events
def outlook(): now = datetime.now() highlight_hour = False if now.weekday() == 4 and now.hour > 21: # note this include time_zone_offset, ie 17 + 4 inc_days = 3 elif now.weekday() > 4: inc_days = 7 - now.weekday() elif now.hour > 21: inc_days = 1 else: inc_days = 0 highlight_hour = True dt = now + timedelta(inc_days) print "dt =",dt # below a problem at the end of the month #items = calendar.view(start=eastern.localize(EWSDateTime(now.year, now.month, now.day+next_)), end=eastern.localize(EWSDateTime(now.year, now.month, now.day+next_+1))) #below works #items = calendar.view(start=eastern.localize(EWSDateTime(now.year, now.month, now.day+next_)), end=eastern.localize(EWSDateTime(now.year, now.month, now.day+next_, now.hour+10))) #items = calendar.view(start=eastern.localize(EWSDateTime(now.year, now.month, now.day+next_), 1), end=eastern.localize(EWSDateTime(now.year, now.month, now.day+next_, 23))) items = calendar.view(start=eastern.localize(EWSDateTime(dt.year, dt.month, dt.day, 1)), end=eastern.localize(EWSDateTime(dt.year, dt.month, dt.day, 23))) try: len(items) except (errors.ErrorInternalServerTransientError, errors.ErrorMailboxStoreUnavailable) as e: print "exchangelib error: ", e return except AttributeError as e: print "outlook error - would be caused by incorrect pw", e return text = [] try: for item in items: subject = item.subject if "time off" in subject.lower(): continue # after fall back hours = 5? line = (item.start-timedelta(hours=5)).strftime("%I:%M").lstrip('0')+"-"+(item.end-timedelta(hours=5)).strftime("%I:%M").lstrip('0')+" "+subject if "12:00-12:00" in line: line = "All Day Event -"+line[11:] #if highlight_hour and (now.hour == item.start.hour - 4): if highlight_hour and (now.hour == item.start.hour): line = "#{red}"+line text.append(line) print line except (errors.ErrorTimeoutExpired, errors.ErrorInternalServerTransientError) as e: print "exchangelib error: ", e return if not text: text = ["Nothing Scheduled"] data = {"header":"Schedule "+dt.strftime("%a %b %d"), "text":text, "pos":6, "dest":(475,470), "font size":16} #expects a list mqtt_publish.single('esp_tft', json.dumps(data), hostname=aws_host, retain=False, port=1883, keepalive=60) mqtt_publish.single('esp_tft_display', json.dumps(data), hostname=aws_host, retain=False, port=1883, keepalive=60)
def _localdate(self, date): _ld = tz.localize( EWSDateTime( int(date.strftime("%Y")), int(date.strftime("%m")), int(date.strftime("%d")), )) log.debug("_ld: {}".format(_ld)) return _ld
def total_mails(self): """ Return the total amounts of content newet thatn self.start_date for the user. This includes mails and calendar items """ total_count = 0 if self.account: if False: # TODO: should be if self.start_date start_dt = UTC.localize(EWSDateTime(self.start_date.year, self.start_date.month, self.start_date.day, 0, 0)) end_dt = UTC.localize(EWSDateTime(2100, 1, 1, 0, 0)) for folder in self.account.root.walk(): items = folder.all() items = items.filter(datetime_received__range=(start_dt, end_dt)) total_count += items.count() else: for folder in self.account.root.walk(): total_count += folder.total_count return total_count
def get_new_messages(folder_name, account, from_datetime='2018-01-01-00-00-00'): target_folder = account.inbox.get_folder_by_name(folder_name) tz = account.default_timezone from_datetime_list = [int(x) for x in from_datetime.split('-')] localized_from_datetime = tz.localize(EWSDateTime(*from_datetime_list)) new_submissions = [] for submission in target_folder.filter(datetime_received__gt=localized_from_datetime): new_submissions.append(submission) return new_submissions
def miniprogram_booking_roomCode_delete(roomCode, monthToLoad, deleteInfo): # noqa: E501 # 按照月份、changekey、房间号删除预约信息 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 changekey = deleteInfo['changekey'] 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 start_year = int(monthToLoad.split("-")[0]) start_month = int(monthToLoad.split("-")[1]) start = room_account.default_timezone.localize(EWSDateTime(start_year, start_month, 1)) if start_month == 12: end = room_account.default_timezone.localize(EWSDateTime(start_year + 1, 1, 1)) else: end = room_account.default_timezone.localize(EWSDateTime(start_year, start_month + 1, 1)) try: for item in room_account.calendar.filter(start__range=(start, end)).all().order_by('start'): if item.changekey == changekey: notes = db_session.query(orm.BookingNotes_db).filter(orm.BookingNotes_db.changekey == item.changekey).one_or_none() if notes.bookedByID == learner.id: db_session.delete(notes) except Exception as e: db_session.remove() return {'code': -2005, 'message': '房间预约删除失败', 'error': str(e)}, 200 db_session.remove() return {'code': 0, 'message': 'success'}, 200
def get_appointments(self, acc): # define the timezone now = EWSDateTime.now(self.tz) items = {} try: logger.debug("Getting appointments") items = acc.calendar.view( start=self.tz.localize( EWSDateTime(now.year, now.month, now.day, 4, 0)), end=self.tz.localize( EWSDateTime(now.year, now.month, now.day, 22, 0)), ) logger.debug("Getting appointments was a success") return items, True except Exception as e: logger.error( "Failed to get appointments. Trying again later. Error: {0}". format(traceback.print_exc())) return items, False
def calitems(): i = 0 start = tz.localize(EWSDateTime(2000, 3, 1, 8, 30, 0)) end = tz.localize(EWSDateTime(2000, 3, 1, 9, 15, 0)) item = CalendarItem( subject='Performance optimization test %s by pyexchange' % i, 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, ) while True: itm = copy.copy(item) itm.subject = 'Test %s' % i i += 1 yield itm
def get_calendar_time(self, date_time): """Return a string date and time in Exchangelib format.""" # Set timezone self._tz = EWSTimeZone.timezone('Europe/Stockholm') self._calendar_time = parser.parse(date_time) return self._tz.localize( EWSDateTime(self._calendar_time.year, self._calendar_time.month, self._calendar_time.day, self._calendar_time.hour, self._calendar_time.minute))
def get_mail(self): t = datetime.datetime.now() start_time = self.tz.localize(EWSDateTime(t.year, t.month, t.day - 1)) end_time = self.tz.localize(EWSDateTime(t.year, t.month, t.day, t.hour)) print start_time, end_time items = self.account.inbox.filter(datetime_received__range=(start_time, end_time)) if len(items) == len(self.history): return for i in range(len(self.history), len(items)): item = items[i] subject = item.subject.encode(TEXT_FORMAT) #print subject self.history.append(subject) for key in self.modules.keys(): m = self.modules[key] if m.check(subject, TEXT_FORMAT) == True: m.do(item.body.encode(TEXT_FORMAT)) '''
def get_appointments(preferences): now = tz.localize(EWSDateTime.utcnow()) items = {} try: credentials = Credentials(username=preferences["username"], password=preferences["password"]) config = Configuration(service_endpoint=preferences["server"], credentials=credentials, auth_type=NTLM) account = Account(primary_smtp_address=preferences["email"], config=config, autodiscover=False, access_type=DELEGATE) logger.info("Getting reservations for {0}".format(account.primary_smtp_address)) items = account.calendar.view( start=tz.localize(EWSDateTime(now.year, now.month, now.day, 0, 0)), end=tz.localize(EWSDateTime(now.year, now.month, now.day, 23, 59)), ).order_by('start') except requests.exceptions.RequestException as e: # failure in data communication logger.exception("Failure while contacting the server.") return None except Exception as e: logger.exception("Failed to get appointments. Try again later.") return None return items
def ToEWSDateTime(_datetime): tz = EWSTimeZone.timezone('Europe/Helsinki') time = tz.localize( EWSDateTime( year=_datetime.year, month=_datetime.month, day=_datetime.day, hour=_datetime.hour, minute=_datetime.minute ) ) return time