def main(arg_object):
	global CALENDAR_NAME, CALENDAR_ID
	CALENDAR_NAME = arg_object.cal_name

	if arg_object.prune_temp:
		clear_dir("./temp")

	eas: EAssistantService = EAssistantService()
	gcs: GoogleCalendarService = GoogleCalendarService(CALENDAR_NAME,
	                                {
		                                  "foregroundColor": "#ECD032",
		                                  "description": "School calendar assistant calendar for subjects, exams, meals and more!",
		                                  "backgroundColor": "#ECD032",
		                                  "timeZone": "Europe/Belgrade",
		                                  "summary": CALENDAR_NAME
	                                  },
	                            remove_if_exists=arg_object.rm_cal)

	eas.introduce()
	"""
	listed_events = gcs.get_events_between(CALENDAR_ID, (datetime.date.today()+datetime.timedelta(days=1), datetime.date.today()+datetime.timedelta(days=2)), q="#school")

	for e in listed_events.get("items", []):
		print(e["start"].get("dateTime", e["start"].get("date", "")), e["summary"], e["description"], sep="\n")
	"""

	eh.update_dates(gcs, eas, datetime.date.today() + datetime.timedelta
	(days=1), datetime.date.today() + datetime.timedelta(days=1),
					datetime.date(2019, 9, 27))
def get_request_date_boundary(
        start_date: datetime.date = datetime.date.today(),
        end_date: datetime.date = None):
    # start_date += datetime.timedelta(days=1)

    # Assure we don't parse for saturday or sunday
    start_date += datetime.timedelta(
        days=-start_date.weekday())  # set on monday that week

    if not end_date:
        end_date = start_date + datetime.timedelta(days=1)
    end_date += datetime.timedelta(
        days=4 - end_date.weekday())  # set on friday that week

    return {
        "from": start_date.strftime("%Y-%m-%d"),
        "to": end_date.strftime("%Y-%m-%d")
    }
Beispiel #3
0
def update_dates(google_cal_service: GoogleCalendarService, ea_service: EAssistantService, *dates_to_update: datetime.date, google_lock: threading.Lock, logging_lock: threading.Lock) -> list:
	# Get school events
	dates_to_update = sorted(dates_to_update)
	if len(dates_to_update) == 1:
		dates_to_update.append(dates_to_update[0])
	eas_events = ea_service.get_school_events(dates_to_update[0], dates_to_update[1]+datetime.timedelta(days=1))
	logger.info("Events time boundary: " + str(eas_events["time_boundary"]))
	time_min, time_max = gstrptime(eas_events["time_boundary"]["min"]), gstrptime(eas_events["time_boundary"]["max"])

	events_from_cal = google_cal_service.get_events_between((time_min, time_max), q="#school", orderBy="startTime", singleEvents=True)

	events_to_enter = eas_events.get("events", [])
	events_google = events_from_cal.get("items", [])

	logger.debug("Retrieved google events: " + str(len(events_google)))
	logger.debug("Easistent events: " + str(len(events_to_enter)))

	# Create event list sorted by day
	EVENTS_BY_DAY = {}

	for event in events_to_enter:
		etime = get_event_start(event)
		etime, date = etime[11:19], etime[:10]  # only the date part
		if date not in EVENTS_BY_DAY:
			EVENTS_BY_DAY[date] = {}
		if etime not in EVENTS_BY_DAY[date]:
			EVENTS_BY_DAY[date][etime] = {}
		_, f_event = ea_service.ef.google_event_body_from_parsed_event(event)
		if "easistent" not in EVENTS_BY_DAY[date][etime]:
			EVENTS_BY_DAY[date][etime]["easistent"] = [f_event]
		else:
			EVENTS_BY_DAY[date][etime]["easistent"].append(f_event)

	for g_event in events_google:
		etime = get_event_start(g_event)
		etime, date = etime[11:19], etime[:10]  # only the date part
		if date not in EVENTS_BY_DAY:
			EVENTS_BY_DAY[date] = {}
		if etime not in EVENTS_BY_DAY[date]:
			EVENTS_BY_DAY[date][etime] = {}
		if "google" not in EVENTS_BY_DAY[date][etime]:
			EVENTS_BY_DAY[date][etime]["google"] = [g_event]
		else:
			EVENTS_BY_DAY[date][etime]["google"].append(g_event)

	threads = []
	for date, construct in EVENTS_BY_DAY.items():
		threads.append(threading.Thread(target=_update_single_date, daemon=True, args=(google_cal_service, construct, date, logging_lock, google_lock), name=f'thread_{date[5:]}'))
	return threads
                                                body=event_body,
                                                **patch_kwargs).execute()
        except Exception as e:
            logger.debug("Error updating:\n" + str(event_body))
            logger.error(e)

    def remove_event(self, event_id: str, **remove_kwargs):
        sleep(1)
        try:
            return self.service.events().delete(calendarId=self.calendar_id,
                                                eventId=event_id,
                                                **remove_kwargs).execute()
        except Exception as e:
            logger.debug("Error removing")
            logger.error(e)


if __name__ == '__main__':
    # When running locally, disable OAuthlib's HTTPs verification. When
    # running in production *do not* leave this option enabled.
    # os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'

    pp = pprint.PrettyPrinter(indent=2)
    gcs = GoogleCalendarService("School2")

    pp.pprint(
        gcs.get_events_between(
            (datetime.datetime.now().date() + datetime.timedelta(days=3),
             datetime.datetime.now().date() + datetime.timedelta(days=4)),
            q="#school")["items"])
Beispiel #5
0
def main():
    args_parsed = run_args_init()
    uniquestr = datetime.datetime.now().strftime("%d-%b_%H%M%S")
    logFormatter = logging.Formatter(
        fmt=
        '%(asctime)-15s - (%(relativeCreated)-8d ms) |%(levelname)-7s| @ [%(threadName)-12.12s] %(name)15.15s - %(message)s',
        datefmt='%d-%b %H:%M:%S')
    if args_parsed.verbose:
        dbg_lvl = logging.DEBUG
        print("Verbose mode:")
    elif args_parsed.quiet:
        dbg_lvl = logging.WARNING
    else:
        dbg_lvl = logging.INFO
    assure_dir(args_parsed.log_dir)
    fileHandler = logging.FileHandler(os.path.join(
        args_parsed.log_dir, args_parsed.log_file_name % uniquestr),
                                      mode=args_parsed.log_mode)

    consoleHandler = logging.StreamHandler()
    consoleHandler.setLevel(dbg_lvl)
    fileHandler.setLevel(logging.DEBUG)
    consoleHandler.setFormatter(logFormatter)
    fileHandler.setFormatter(logFormatter)

    global logger
    logger.setLevel(dbg_lvl)
    logger.addHandler(consoleHandler)
    logger.addHandler(fileHandler)
    logger.debug(str(args_parsed))
    CALENDAR_NAME = args_parsed.cal_name

    if args_parsed.prune_temp:
        clear_dir("./temp")

    eas: EAssistantService = EAssistantService()
    gcs: GoogleCalendarService = GoogleCalendarService(CALENDAR_NAME, {
        "foregroundColor": "#ECD032",
        "description":
        "School calendar assistant calendar for subjects, exams, meals and more!",
        "backgroundColor": "#ECD032",
        "timeZone": "Europe/Belgrade",
        "summary": CALENDAR_NAME
    },
                                                       remove_if_exists=
                                                       args_parsed.rm_cal)

    eas.introduce()
    THREADING_LOCKS["google"] = threading.Lock()
    THREADING_LOCKS["logging"] = threading.Lock()
    threads = eh.update_dates(
        gcs,
        eas,
        datetime.date.today() + datetime.timedelta(days=1),
        datetime.date.today() + datetime.timedelta(days=8),
        google_lock=THREADING_LOCKS["google"],
        logging_lock=THREADING_LOCKS["logging"])

    for t in threads:
        t.start()

    # Do meal inquiry

    while any([t.isAlive() for t in threads]):
        for t in threads:
            t.join(2.0)