def get_calendar_events():
    credentials = (config.client_id, config.client_secret)
    # For AWS Lambda - copy token file to /tmp (only directory with write permissions)
    if not os.path.exists('/tmp/ms_token.txt'):
        copyfile('resources/ms_token.txt', '/tmp/ms_token.txt')
        print('resources/ms_token.txt copied to /tmp')

    # TODO - refactor due to deprecation
    # token_backend = FileSystemTokenBackend(token_path='/tmp', token_filename='ms_token.txt')
    token_backend = FileSystemTokenBackend(token_path='/tmp', token_filename='ms_token.txt')
    account = Account(credentials, token_backend=token_backend)

    # get calendar
    schedule = account.schedule()
    # cal = schedule.get_calendar(calendar_name='Calendar')
    cal = schedule.get_calendar(calendar_name='Calendário')

    now = dt.datetime.utcnow().isoformat()

    # query calendar and get events that are happening right now
    q = cal.new_query('start').less_equal(now)
    q.chain(ChainOperator.AND).on_attribute('end').greater_equal(now)
    events = cal.get_events(query=q)
    events_filtered = []

    for event in events:
        events_filtered += filter_out_events(event)

    events_filtered = events_filtered[0] if events_filtered else events_filtered

    if not events_filtered:
        return get_calendar_events_cocus()
    else:
        return events_filtered  # return only one
Ejemplo n.º 2
0
 def get(self):
     time_string = '%Y-%m-%dT%H:%M:%SZ'
     response = {
         "name": "Binary sensor",
         "state": {
             "open": "false",
             "timestamp": datetime.strftime(datetime.utcnow(), time_string)
         }
     }
     credentials = (os.environ["APPLICATION_ID"],
                    os.environ["APPLICATION_SECRET"])
     start_time = time.strftime(time_string,
                                time.gmtime(time.time() - (60 * 60 * 24)))
     end_time = time.strftime(time_string,
                              time.gmtime(time.time() + (60 * 60 * 24)))
     try:
         account = Account(credentials)
         schedule = account.schedule()
         calendar = schedule.get_default_calendar()
         q = calendar.new_query('start').greater_equal(start_time)
         q.chain().on_attribute('end').less_equal(end_time)
         events = calendar.get_events(query=q)
         for event in events:
             if event.show_as == EventShowAs.Busy and event.start < datetime.now(
                     tz=pytz.utc) < event.end:
                 response["state"]["open"] = "true"
                 return response
     except Exception as e:
         app.logger.error(e)
         return response
     return response
Ejemplo n.º 3
0
    def _get_calendar(self, name=None):
        filename = pathlib.Path() / 'mrd/o365_token.txt'
        account = Account(credentials=self._credentials, scopes=self._scopes, token_file_name=filename)
        schedule = account.schedule()
        if name is not None:
            return schedule.get_calendar(calendar_name=name)

        return schedule.get_default_calendar()
class OutlookCalendar(AbstractCalendar):
    client_id: str = None
    secret_id: str = None

    def __init__(self, config: Dict):
        self.client_id = config['client-id']
        self.secret_id = config['secret-id']
        self.calendar_name = config['name']
        self.token_file = config['token-file']
        self.hours = config['hours']
        credentials = (self.client_id, self.secret_id)
        protocol = MSGraphProtocol()
        scopes = [
            'User.Read', 'Calendars.Read', 'Calendars.Read.Shared',
            'offline_access'
        ]
        self.account = Account(
            credentials,
            protocol=protocol,
            token_backend=FileSystemTokenBackend(token_path=self.token_file))
        if not self.account.is_authenticated:
            if self.account.authenticate(scopes=scopes):
                print('Authenticated!')
            else:
                print("Failed to authenticate")
        else:
            print("Skipping authentication because token already exists")

    def get_entries(self, hours: int = None) -> List[CalendarEntry]:
        if hours is None:
            hours = self.hours
        schedule = self.account.schedule()
        cal = schedule.get_calendar(calendar_name=self.calendar_name)
        if cal is None:
            calendars = [
                schedule.name for schedule in schedule.list_calendars()
            ]
            raise RuntimeError(
                f"Calendar '{self.calendar_name}' does not exist for current Outlook account. Avaiblable calendars are: {calendars}"
            )
        q = cal.new_query('start').greater_equal(datetime.datetime.now())
        q.chain('and').on_attribute('end').less_equal(datetime.datetime.now() +
                                                      datetime.timedelta(
                                                          hours=hours))
        events = cal.get_events(query=q, include_recurring=True)
        return [self.convert_entry(entry) for entry in events]

    @staticmethod
    def convert_entry(event: calendar.Event):
        return CalendarEntry(start=event.start,
                             length=event.end - event.start,
                             title=event.subject)
Ejemplo n.º 5
0
    def _get_calendar(self, name=None):
        token_path = pathlib.Path() / 'mrd'
        token_filename = 'o365_token.txt'
        token_backend = FileSystemTokenBackend(token_path=token_path,
                                               token_filename=token_filename)

        account = Account(credentials=self._credentials,
                          scopes=self._scopes,
                          token_backend=token_backend)
        schedule = account.schedule()
        if name is not None:
            return schedule.get_calendar(calendar_name=name)

        return schedule.get_default_calendar()
Ejemplo n.º 6
0
    def _authenticate(self):
        token_backend = FileSystemTokenBackend(
            token_path=os.path.dirname(os.path.realpath(__file__)))
        connection = Connection(config.credentials,
                                scopes=['basic', 'Calendars.Read'],
                                token_backend=token_backend)
        connection.refresh_token()
        account = Account(config.credentials,
                          scopes=['basic', 'Calendars.Read'],
                          token_backend=token_backend)

        if not account.is_authenticated:
            if account.authenticate():
                print('Authenticated!')
            else:
                print('Authentication failed!')
                return
        self._schedule = account.schedule()
Ejemplo n.º 7
0
def get_outlook_events(cfg, now, end):
    credential = (cfg['AZURE_APP_APPLICATION_ID'],
                  cfg['AZURE_APP_CLIENT_SECRET'])
    account = Account(credential)
    if not account.is_authenticated:
        account.authenticate(scopes=['basic', 'calendar_all'])
    schedule = account.schedule()
    calendar = schedule.get_default_calendar()

    q = calendar.new_query('start').greater_equal(now)
    q.chain('and').on_attribute('end').less_equal(end)
    events = calendar.get_events(limit=100, query=q, include_recurring=True)
    """
    # we can only get 25 events, so I will get every weeks
    now = dt.datetime.now().astimezone()
    events = []
    for i in range(WEEKS):
        end = now + dt.timedelta(weeks=1)
        q = calendar.new_query('start').greater_equal(now)
        q.chain('and').on_attribute('end').less_equal(end)
        now = end
        events = events + list(calendar.get_events(limit=100, query=q, include_recurring=True))
    """

    garoon_origin_events = {}
    outlook_events = {}
    for event in events:
        #print('Outlook ' + event.subject)
        if event.subject.startswith('GID:'):
            gidpair = event.subject.split()[0]
            garoon_id = gidpair.split(':')[1]
            garoon_origin_events[garoon_id] = event
            print('Outlook - Garoon Origin Event ' + event.subject)
        else:
            outlook_events[event.object_id] = event
            print('Outlook - Outlook Origin Event ' + event.subject)
    return calendar, garoon_origin_events, outlook_events
Ejemplo n.º 8
0
        credentials = tuple(config.read().strip().split(','))
except:
    print("User credentials not found")
    sys.exit()

def authenticate():
    account = Account(credentials=credentials, token_file_name=token_location)
    account.authenticate(scopes=scope_helpers)
    # Move token file to default location

account = Account(credentials=credentials, token_file_name=token_location)
if not account.connection.check_token_file():
    print("Auth problem!")
    sys.exit()

schedule = account.schedule()
cal = schedule.get_default_calendar()

now = datetime.datetime.now()
future = now + datetime.timedelta(minutes=10)

# Get events that start in less than 10 minutes
q = cal.new_query('start').less_equal(future).chain('and').on_attribute('end').greater(future)
q.order_by('start', ascending=False)
events = cal.get_events(query=q)

if events:
    print("{} {}".format(events[0].start.strftime("%H:%M"), events[0].subject))
else:
    print("Nothing")