Example #1
0
def create():
    if request.form["accesscode"] != "fhKjzgV/BXWq4YRxUPO4qYlHWCDf":
        return redirect(url_for("home"))
    session = db.get_db()
    username = request.form["username"]
    existing_user = (session.query(
        model.User).filter(model.User.name == username).one_or_none())
    if existing_user is not None:
        return redirect(url_for("home"))

    password = request.form["password"]
    user = model.User(name=username, password=password)
    if request.form["notify"] == "mail":
        user.notification = [
            model.Notification(ntype=model.Notification.Types.EMAIL,
                               info=request.form["info"])
        ]
    else:
        user.notification = [
            model.Notification(ntype=model.Notification.Types.PUSHOVER,
                               info=request.form["info"])
        ]
    session.add(user)
    session.commit()
    return "success"
Example #2
0
def perform_user_update(args):
    logger = logging.getLogger(__name__)
    username = args.username
    session = db.get_db()
    existing_user = (session.query(
        model.User).filter(model.User.name == username).one_or_none())
    if existing_user is not None:
        logger.info("Updating user " + username)
    else:
        logger.info("Creating User user " + username)

    if args.password is None:
        logger.info("No password provided, asking for it")
        import getpass
        password = getpass.getpass(prompt="Password: "******"Adding pushover notification")
        user.notification = model.Notification(
            ntype=model.Notification.Types.PUSHOVER, info=args.pushover)
    elif args.mail:
        logger.info("Adding email notification")
        user.notification = model.Notification(
            ntype=model.Notification.Types.EMAIL, info=args.mail)
    elif args.fake:
        logger.info("Adding fake notification")
        user.notification = model.Notification(
            ntype=model.Notification.Types.FAKE, info="")

    if (args.iclouduser is not None and args.icloudpwd is not None
            and args.icloudcalendar is not None):
        logger.info("Adding icloud calendar")
        user.icalendar = model.ICloudCalendar(
            icloud_user=args.iclouduser,
            password=args.icloudpwd,
            calendarname=args.icloudcalendar,
        )

    if args.invitationmail:
        logger.info("Activating sending of calendar entries per mail")
        user.invitation = model.Invitation(email=mail)

    session.commit()
Example #3
0
 def update_homework(self):
     session = db.get_db()
     homeworklist = self.im.get_homework_list()
     for homeworkid in homeworklist:
         homework = (
             session.query(model.Homework)
             .filter(model.Homework.homework_id == homeworkid)
             .with_parent(self.user, "homeworks")
             .one_or_none()
         )
         if homework is None:
             homework = self.im.get_homework_info(homeworkid)
             self._notify_hw(homework)
             self.user.homeworks.append(homework)
             session.commit()
Example #4
0
 def update_news(self):
     session = db.get_db()
     newslist = self.im.get_news_list()
     for news_entry in newslist:
         self.logger.debug("parsing %s", news_entry["id"])
         news = (
             session.query(model.News)
             .filter(model.News.news_id == news_entry["id"])
             .filter(model.News.date == news_entry["publishedDate"])
             .with_parent(self.user, "news")
             .one_or_none()
         )
         if news is not None:
             self.logger.debug("Skipping news %s", news_entry["id"])
             continue
         news = self.im.get_news_article(news_entry)
         self._notify_news(news)
         self.user.news.append(news)
         session.commit()
Example #5
0
def notify_users():
    logger = logging.getLogger(__name__)
    session = db.get_db()
    cfg = config.load()
    if cfg["healthcheck"]["url"] != "":
        logger.info("Triggering Healthcheck Start")
        requests.get(cfg["healthcheck"]["url"] + "/start")

    for user in session.query(model.User):
        logger.info("==== USER: %s =====", user.name)
        if user.password == "":
            logger.warning("User %s not enabled", user.name)
            continue
        now = datetime.datetime.now()
        im = connector.Infomentor(user.name)
        im.login(user.password)
        logger.info("User loggedin")
        statusinfo = {
            "datetime": now,
            "ok": False,
            "info": "",
            "degraded_count": 0
        }
        if user.apistatus is None:
            user.apistatus = model.ApiStatus(**statusinfo)
        logger.info("Former API status: %s", user.apistatus)
        try:
            i = informer.Informer(user, im, logger=logger)
            i.update_news()
            i.update_homework()
            i.update_calendar()
            statusinfo["ok"] = True
            statusinfo["degraded"] = False
        except Exception as e:
            inforstr = "Exception occured:\n{}:{}\n".format(
                type(e).__name__, e)
            statusinfo["ok"] = False
            statusinfo["info"] = inforstr
            logger.exception("Something went wrong")
        finally:
            if user.apistatus.ok == True and statusinfo["ok"] == False:
                logger.error("Switching to degraded state %s", user.name)
                statusinfo["degraded_count"] = 1
            if user.apistatus.ok == False and statusinfo["ok"] == False:
                if user.apistatus.degraded_count == 1 and user.wantstatus:
                    im.send_status_update(statusinfo["info"])
                try:
                    statusinfo["degraded_count"] = user.apistatus[
                        "degraded_count"] + 1
                except Exception as e:
                    statusinfo["degraded_count"] = 1
            if user.apistatus.ok == False and statusinfo["ok"] == True:
                statusinfo[
                    "info"] = "Works as expected, failed {} times".format(
                        user.apistatus.degraded_count)
                statusinfo["degraded_count"] = 0
                if user.wantstatus:
                    im.send_status_update(statusinfo["info"])
            user.apistatus.updateobj(statusinfo)
        logger.info("New API status: %s", user.apistatus)
        session.commit()

    if cfg["healthcheck"]["url"] != "":
        logger.info("Triggering Healthcheck Stop")
        requests.get(cfg["healthcheck"]["url"])
Example #6
0
    def update_calendar(self):
        session = db.get_db()
        if self.user.icalendar is None and self.user.invitation is None:
            return
        try:
            calentries = self.im.get_calendar()
            for entry in calentries:
                self.logger.debug(entry)
                uid = str(
                    uuid.uuid5(uuid.NAMESPACE_URL, "infomentor_{}".format(entry["id"]))
                )
                event_details = self.im.get_event(entry["id"])
                calend = Calendar()
                event = Event()
                event.add("uid", uid)
                event.add("summary", entry["title"])
                event.add("categories", ['Jules Verne Campus', 'Schule'])
                event.add("dtstamp", datetime.datetime.now())
                if not event_details["allDayEvent"]:
                    event.add("dtstart", dateparser.parse(entry["start"]))
                    event.add("dtend", dateparser.parse(entry["end"]))
                else:
                    event.add("dtstart", dateparser.parse(entry["start"]).date())
                    event.add("dtend", dateparser.parse(entry["end"]).date())

                description = event_details["notes"]
                eventinfo = event_details["info"]
                new_cal_entry = calend.to_ical().replace(b"\r", b"")
                new_cal_hash = hashlib.sha1(new_cal_entry).hexdigest()
                for res in eventinfo["resources"]:
                    f = self.im.download_file(res["url"], directory="files")
                    description += """\nAttachment {0}: {2}/{1}""".format(
                        res["title"], urllib.parse.quote(f), cfg["general"]["baseurl"]
                    )
                event.add("description", description)

                calend.add_component(event)
                new_cal_entry = calend.to_ical().replace(b"\r", b"")
                session = db.get_db()
                storedata = {
                    "calendar_id": uid,
                    "ical": new_cal_entry,
                    "hash": new_cal_hash,
                }
                calendarentry = (
                    session.query(model.CalendarEntry)
                    .filter(model.CalendarEntry.calendar_id == uid)
                    .with_parent(self.user, "calendarentries")
                    .one_or_none()
                )
                if calendarentry is not None:
                    if calendarentry.hash == new_cal_hash:
                        self.logger.info("calendar entry UNCHANGED {}".format(uid))
                        continue
                    else:
                        self.logger.info("calendar entry UPDATED {}".format(uid))
                        for key, value in storedata.items():
                            setattr(calendarentry, key, value)

                else:
                    self.logger.info("calendar entry NEW {}".format(uid))
                    calendarentry = model.CalendarEntry(**storedata)

                self.logger.debug(new_cal_entry.decode("utf-8"))
                if self.user.icalendar is not None:
                    self._write_icalendar(calend)
                if self.user.invitation is not None:
                    self._send_invitation(calend, self.user.invitation.email)
                self.user.calendarentries.append(calendarentry)
                session.commit()
        except Exception as e:
            self.logger.exception("Calendar failed")