""" NTNOE SYNC is a simple script tha allows you to synchronize your NTNOE diary with Google Calendar. It will create a `ntnoe` calendar among your Google calendars and write your NTNOE calendar into. NTNOE_SYNC is availabe under the MIT license. MIT License Copyright (c) 2017 Hugo LEVY-FALK Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import datetime import httplib2 import os import requests import logging from logging.handlers import RotatingFileHandler from apiclient import discovery from oauth2client import client from oauth2client import tools from oauth2client.file import Storage import icalendar DEBUG = False APP_DIR = os.path.dirname(os.path.abspath(__file__)) if DEBUG: DATA_DIR = APP_DIR else: home_dir = os.path.expanduser('~') DATA_DIR = os.path.join(home_dir, ".ntnoe", "") if not os.path.exists(DATA_DIR): os.makedirs(DATA_DIR) ##### Logger stuff ##### logger = logging.getLogger() if DEBUG: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s') file_handler = RotatingFileHandler( os.path.join(DATA_DIR, 'log.txt'), 'a', 1000000, 1) if DEBUG: file_handler.setLevel(logging.DEBUG) else: file_handler.setLevel(logging.INFO) file_handler.setFormatter(formatter) logger.addHandler(file_handler) if DEBUG: stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.DEBUG) stream_handler.setFormatter(formatter) logger.addHandler(stream_handler) ######################## TIMEDELTA_SYNCHRO = datetime.timedelta(days=15) # Number of days to look for # for synchronization with open('ntnoe_credentials') as f: NTNOE_ID, NTNOE_PASS, _ = f.read().split('\n') SCOPES = 'https://www.googleapis.com/auth/calendar' CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME = 'Google Calendar API Python Quickstart' class Event: """ The event class allows a simple convertion between `icalendar.cal.Event` and a formatted `dict` for the google API. """ # ColorId corresponding to course code EVENT_COLOR = { '9': '9', # Amphi '11': '10', # TL '10': '6', # TD '13': '5', # Autre '12': '3', # Exam } def __init__(self, e): """ Initialize an event from a `icalendar.cal.Event`.""" self.summary = e.decoded('SUMMARY').decode('utf-8') self.start = e.decoded('DTSTART') self.end = e.decoded('DTEND') self.location = e.decoded('LOCATION').decode('utf-8') self.colorid = self.EVENT_COLOR.get( e.decoded('DESCRIPTION').decode('utf-8'), '1') def __str__(self): return str(self.as_google()) def as_google(self): """Returns the event as a formatted `dict` for the google API.""" return { 'summary': self.summary, 'location': self.location, 'start': { 'dateTime': self.start.isoformat(), 'timeZone': 'Europe/Paris', }, 'end': { 'dateTime': self.end.isoformat(), 'timeZone': 'Europe/Paris', }, 'colorId': self.colorid, 'reminders': { 'useDefault': False, 'overrides': [], }, } def get_credentials(): """Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential. """ credential_dir = os.path.join(DATA_DIR, 'credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'ntnoe.json') store = Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME logger.info('Storing credentials to ' + credential_path) credentials = tools.run_flow(flow, store) return credentials def get_ntnoe(): """Retrieves the calendar on NTNOE.""" r = requests.post( "https://ntnoe.metz.supelec.fr/ical/index.php", data={"envoyer":"Utf8_All","submit":"G%E9n%E9rer"}, auth=(NTNOE_ID, NTNOE_PASS), ) url = "https://ntnoe.metz.supelec.fr/ical/EdTcustom/Eleves/edt_{}.ics" url = url.format(NTNOE_ID) r = requests.get(url, auth=(NTNOE_ID, NTNOE_PASS)) return r.content def main(): """Get the events on NTNOE the puts them on Google Calendar. """ # Authentication on google logger.info('Authenticating on Google') credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('calendar', 'v3', http=http) # Retrieving the calendar on NTNOE logger.info('Requesting NTNOE for {}'.format(NTNOE_ID)) ical = icalendar.Calendar.from_ical(get_ntnoe()) # We need to find the id of the calendar we will edit. logger.info('Looking for `ntnoe` calendar.') calendars = service.calendarList().list().execute() ntnoe_calendar_id = None for c in calendars['items']: if c['summary'] == 'ntnoe': ntnoe_calendar_id = c['id'] if not ntnoe_calendar_id: logger.info("Creating `ntnoe` calendar...") created = service.calendars().insert(body={ 'defaultReminders' : [], 'selected' : True, 'summary' : 'ntnoe', }).execute() ntnoe_calendar_id = created['id'] now = datetime.datetime.now() then = now + TIMEDELTA_SYNCHRO time_search = datetime.datetime(now.year, now.month, now.day, 1) # NTNOE calendar often changes. So let's delete former synchronizations. logger.info('Deleting former events.') former_ones = service.events().list( calendarId=ntnoe_calendar_id, ).execute() for event in former_ones['items']: logger.debug('Deleting event : {}'.format(event['id'])) service.events().delete( calendarId=ntnoe_calendar_id, eventId=event['id'] ).execute() logger.info('Adding new events.') for e in ical.walk('VEVENT'): event = Event(e) t = ( event.summary, event.start.isoformat(), event.end.isoformat(), event.location ) if now >= event.end or event.start >= then: continue event = service.events().insert( calendarId=ntnoe_calendar_id, body=event.as_google() ).execute() logger.debug("Adding event : {}".format(event['id'])) if __name__ == '__main__': main()