import logging from datetime import date, datetime, timedelta from sqlalchemy import exc from sqlmodel import select from app.model.models import Card, OneShotAccess from app.services.database import Session, add_and_refresh logger = logging.getLogger(__name__) doorIsOpen = True # I think this could also be gpio controlled # See: https://github.com/technyon/nuki_hub#gpio-lock-control-optional def openDoor(): global doorIsOpen doorIsOpen = True logger.info("Still needs gpio out") def closeDoor(): global doorIsOpen doorIsOpen = False logger.info("Still needs gpio out") def isDoorOpen(): return doorIsOpen def decrementOneshot(db: Session, oneshot: OneShotAccess): data = oneshot.model_dump() if data["uses"] > 0: data["uses"] = data["uses"] - 1 oneshot.sqlmodel_update(oneshot, update=data) add_and_refresh(db, oneshot) def checkAccess(key: str, db: Session): try: current_weekday = datetime.weekday(date.today()) current_time = datetime.now() card = db.exec(select(Card).where(Card.key == key)).one() for auth in card.group.accessauths: logger.info(f"checking auth: {auth.name}") if auth.type == "timetable": for timetable in auth.timetables: logger.info(f" checking timetable {timetable.id}") logger.info( f" comparing weekday: CUR:{current_weekday} TT:{timetable.weekday}" ) if current_weekday == timetable.weekday: starttime = datetime.combine(date.today(), timetable.starttime) endtime = starttime + timedelta(minutes=timetable.duration) logger.info( f" comparing time: Start:{starttime} Current:{current_time} End:{endtime}" ) if starttime < current_time < endtime: logger.info("Access Valid!") return True if auth.type == "oneshot": logger.info(f" oneshot auth found: {auth.oneshot}") if current_time < auth.oneshot.ends_at: if auth.oneshot.uses > 0: decrementOneshot(db, auth.oneshot) return True logger.info("No more auths found") return False except exc.NoResultFound: raise Exception("No Access with that key found, this might be a db error")