コード例 #1
0
ファイル: apiVulcan.py プロジェクト: Sanitsonn/messenger-bot
def getMessages(certificate):
    UnreadMessages = []
    client = Vulcan(certificate)
    for message in client.get_messages():
        if (str(message.read_date) == 'None'):
            UnreadMessages.append(message.sender.name)
    return UnreadMessages
コード例 #2
0
def update_mailbox():
    #this function updates data about recived messages | no arguments, no returns

    if os.path.isdir("messages"):
        for file in os.listdir("messages"):
            os.remove(f"messages/{file}")
        os.rmdir("messages")

    if not os.path.isdir("messages"):
        os.makedirs("messages")

    with open("cert.json") as f:
        certificate = json.load(f)

    client = Vulcan(certificate)

    for msg in client.get_messages():
        teacher = msg.sender
        content = change_this(msg.content)
        title = change_this(msg.title)
        date = str(msg.sent_date) + " " + str(msg.sent_time).replace(
            ":", ".", 3)
        try:
            teacher_name = change_this(teacher.first_name) + " " + change_this(
                teacher.last_name)
        except AttributeError:
            continue

        path = "messages/" + date + ".txt"
        file = open(path, "a")
        try:
            file.write(f"'{title}'\nOd: {teacher_name}\n{date}\n\n{content}")
        except UnicodeEncodeError:
            continue
        file.close()
コード例 #3
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up Uonet+ Vulcan integration."""
    hass.data.setdefault(DOMAIN, {})
    try:
        keystore = Keystore.load(entry.data["keystore"])
        account = Account.load(entry.data["account"])
        client = Vulcan(keystore, account, async_get_clientsession(hass))
        await client.select_student()
        students = await client.get_students()
        for student in students:
            if str(student.pupil.id) == str(entry.data["student_id"]):
                client.student = student
                break
    except UnauthorizedCertificateException as err:
        raise ConfigEntryAuthFailed(
            "The certificate is not authorized.") from err
    except ClientConnectorError as err:
        raise ConfigEntryNotReady(
            f"Connection error - please check your internet connection: {err}"
        ) from err
    hass.data[DOMAIN][entry.entry_id] = client

    await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)

    return True
コード例 #4
0
def prepare_average_grade_graph():
    #this function prepares data for this plot and calls function for api.py to make it | no arguments, no returns

    #prepare connection with Vulcan account
    with open("cert.json") as f:
        certificate = json.load(f)

    client = Vulcan(certificate)

    values = []
    dates = []
    components = []
    weights = []

    for grade in client.get_grades():

        if ((grade.weight == 0.0) or (grade.value == None)
                or (grade.value == 0.0)):
            continue
        else:
            components.append(grade.value * grade.weight)
            weights.append(grade.weight)
            values.append(round(sum(components) / sum(weights), 2))
            dates.append(str(grade.date.month) + "." + str(grade.date.day))

    average_grade_history_graph(dates, values)
コード例 #5
0
ファイル: apiVulcan.py プロジェクト: Sanitsonn/messenger-bot
def getExams(date, certificate):
    client = Vulcan(certificate)
    Exams = ""
    for exam in client.get_exams(date):
        Exams += exam.teacher.first_name + " " + exam.teacher.last_name + "\n" + exam.subject.name + "\n" + exam.description + "\n" + str(
            exam.date) + '\n' + "\n"
    return Exams
コード例 #6
0
def prepare_exams():
    #this function prepares txt file with exams info inside | no arguments, no returns

    #prepare connection with Vulcan account
    with open("cert.json") as f:
        certificate = json.load(f)

    client = Vulcan(certificate)

    exams = []

    for i in range(18):
        for exam in client.get_exams(date.today() + timedelta(i)):
            exams.append(exam)

    file = open("exams.txt", "w")
    file.write("Najblizsze sprawdziany:\n")

    for exam in exams:

        name = change_this(exam.subject.name)
        description = change_this(exam.description)

        file.write(f"    -{name}, dnia {exam.date}: {description}\n")

    file.close()
コード例 #7
0
ファイル: apiVulcan.py プロジェクト: Sanitsonn/messenger-bot
def getStudentInfo(certificate):
    client = Vulcan(certificate)
    Info = []
    for student in client.get_students():
        Info.append(student.name)
        Info.append(str(student.class_.name))
        Info.append(str(student.school.name))
    return Info
コード例 #8
0
ファイル: apiVulcan.py プロジェクト: Sanitsonn/messenger-bot
def getLastGrade(certificate):
    client = Vulcan(certificate)
    LastGradeID = ""
    LastGradeData = ""
    returnList = []
    for grade in client.get_grades():
        LastGradeID = grade.id
        LastGradeData = grade.subject.name + "\n" + grade.content
    returnList.append(LastGradeID)
    returnList.append(LastGradeData)
    return returnList
コード例 #9
0
def fill_subjects_list():
    #this function uses grades list to fill "subjects" list with user's subjects name | no arguments, no returns

    with open("cert.json") as f:
        certificate = json.load(f)

    client = Vulcan(certificate)

    for grade in client.get_grades():
        if not grade.subject.short in subjects:
            subjects.append(grade.subject.short)
コード例 #10
0
ファイル: login.py プロジェクト: MendelDamian/LessonReminder
def login():
    with open('cert.json', 'r') as f:
        certificate = json.load(f)

    client = Vulcan(certificate)

    return client
コード例 #11
0
    async def async_step_select_saved_credentials(self,
                                                  user_input=None,
                                                  errors=None):
        """Allow user to select saved credentials."""
        credentials_list = {}
        for entry in self.hass.config_entries.async_entries(DOMAIN):
            credentials_list[
                entry.entry_id] = entry.data["account"]["UserName"]

        if user_input is not None:
            entry = self.hass.config_entries.async_get_entry(
                user_input["credentials"])
            keystore = Keystore.load(entry.data["keystore"])
            account = Account.load(entry.data["account"])
            client = Vulcan(keystore, account)
            try:
                students = await client.get_students()
            except VulcanAPIException as err:
                if str(err) == "The certificate is not authorized.":
                    return await self.async_step_auth(
                        errors={"base": "expired_credentials"})
                _LOGGER.error(err)
                return await self.async_step_auth(errors={"base": "unknown"})
            except ClientConnectionError as err:
                _LOGGER.error("Connection error: %s", err)
                return await self.async_step_select_saved_credentials(
                    errors={"base": "cannot_connect"})
            except Exception:  # pylint: disable=broad-except
                _LOGGER.exception("Unexpected exception")
                return await self.async_step_auth(errors={"base": "unknown"})
            finally:
                await client.close()
            if len(students) == 1:
                student = students[0]
                await self.async_set_unique_id(str(student.pupil.id))
                self._abort_if_unique_id_configured()
                return self.async_create_entry(
                    title=
                    f"{student.pupil.first_name} {student.pupil.last_name}",
                    data={
                        "student_id": str(student.pupil.id),
                        "keystore": keystore.as_dict,
                        "account": account.as_dict,
                    },
                )
            # pylint:disable=attribute-defined-outside-init
            self.account = account
            self.keystore = keystore
            self.students = students
            return await self.async_step_select_student()

        data_schema = {
            vol.Required("credentials", ): vol.In(credentials_list),
        }
        return self.async_show_form(
            step_id="select_saved_credentials",
            data_schema=vol.Schema(data_schema),
            errors=errors,
        )
コード例 #12
0
def new_acc(token, symbol, pin):
    #this function connect GradesKeeper with user's Vulcan account | 3 arguments, no returns

    if os.path.isfile("cert.json"): os.remove("cert.json")

    certificate = Vulcan.register(token, symbol, pin)
    with open("cert.json", "w") as f:
        json.dump(certificate.json, f)
コード例 #13
0
ファイル: main.py プロジェクト: Remlas/UONET-REST-STUDENTINFO
def main():
    data = request.get_json()

    certyfikat = Vulcan.zarejestruj(data['token'], data['symbol'], data['pin'])

    klient = Vulcan(certyfikat)

    x=-1

    osoby = klient.uczniowie()
    osoba = klient.uczniowie()[0]
    if (len(osoby) > 1):
        for przypadek in osoby:
            x = x+1
            if ("SP" not in przypadek.szkola.skrot and "GM" not in przypadek.szkola.skrot and "ZKP" not in przypadek.szkola.skrot and "ZSO10" not in przypadek.szkola.skrot and przypadek.klasa.kod is not None):
                osoba = klient.uczniowie()[x]
    else:
        osoba = klient.uczniowie()[0]

    return {
        "id": osoba.id,
        "imie": osoba.imie,
        "drugie_imie": osoba.drugie_imie,
        "nazwisko": osoba.nazwisko,
        "plec": osoba.plec.name,

        "klasa_id": osoba.klasa.id,
        "klasa_kod": osoba.klasa.kod,

        "szkola_id": osoba.szkola.id,
        "szkola_nazwa": osoba.szkola.nazwa,
        "szkola_skrot": osoba.szkola.skrot
    }
コード例 #14
0
ファイル: config_flow.py プロジェクト: jbouwh/core
    async def async_step_reauth_confirm(self, user_input=None):
        """Reauthorize integration."""
        errors = {}
        if user_input is not None:
            try:
                credentials = await register(
                    self.hass,
                    user_input[CONF_TOKEN],
                    user_input[CONF_REGION],
                    user_input[CONF_PIN],
                )
            except InvalidSymbolException:
                errors = {"base": "invalid_symbol"}
            except InvalidTokenException:
                errors = {"base": "invalid_token"}
            except InvalidPINException:
                errors = {"base": "invalid_pin"}
            except ExpiredTokenException:
                errors = {"base": "expired_token"}
            except ClientConnectionError as err:
                errors["base"] = "cannot_connect"
                _LOGGER.error("Connection error: %s", err)
            except Exception:  # pylint: disable=broad-except
                _LOGGER.exception("Unexpected exception")
                errors["base"] = "unknown"
            if not errors:
                account = credentials["account"]
                keystore = credentials["keystore"]
                client = Vulcan(keystore, account, async_get_clientsession(self.hass))
                students = await client.get_students()
                existing_entries = []
                for entry in self.hass.config_entries.async_entries(DOMAIN):
                    existing_entries.append(entry)
                matching_entries = False
                for student in students:
                    for entry in existing_entries:
                        if str(student.pupil.id) == str(entry.data["student_id"]):
                            self.hass.config_entries.async_update_entry(
                                entry,
                                title=f"{student.pupil.first_name} {student.pupil.last_name}",
                                data={
                                    "student_id": str(student.pupil.id),
                                    "keystore": keystore.as_dict,
                                    "account": account.as_dict,
                                },
                            )
                            await self.hass.config_entries.async_reload(entry.entry_id)
                            matching_entries = True
                if not matching_entries:
                    return self.async_abort(reason="no_matching_entries")
                return self.async_abort(reason="reauth_successful")

        return self.async_show_form(
            step_id="reauth_confirm",
            data_schema=vol.Schema(LOGIN_SCHEMA),
            errors=errors,
        )
コード例 #15
0
ファイル: apiVulcan.py プロジェクト: Sanitsonn/messenger-bot
def getLessons(certificate, day):
    client = Vulcan(certificate)
    LastWeek = getLastWeek()
    Lessons = []
    if (day == "pon"):
        for lesson in client.get_lessons(LastWeek[0]):
            Lessons.append(
                str(lesson.time.from_)[:-3] + "-" + str(lesson.time.to)[:-3])
            Lessons.append(str(lesson.subject.name))
            if (str(lesson.group) != "None"):
                Lessons.append(
                    str(lesson.room) + " Grupa: " + str(lesson.group))
            else:
                Lessons.append(str(lesson.room))
        return Lessons
    elif (day == "wt"):
        for lesson in client.get_lessons(LastWeek[1]):
            Lessons.append(
                str(lesson.time.from_)[:-3] + "-" + str(lesson.time.to)[:-3])
            Lessons.append(str(lesson.subject.name))
            if (str(lesson.group) != "None"):
                Lessons.append(
                    str(lesson.room) + " Grupa: " + str(lesson.group))
            else:
                Lessons.append(str(lesson.room))
        return Lessons
    elif (day == "sr"):
        for lesson in client.get_lessons(LastWeek[2]):
            Lessons.append(
                str(lesson.time.from_)[:-3] + "-" + str(lesson.time.to)[:-3])
            Lessons.append(str(lesson.subject.name))
            if (str(lesson.group) != "None"):
                Lessons.append(
                    str(lesson.room) + " Grupa: " + str(lesson.group))
            else:
                Lessons.append(str(lesson.room))
        return Lessons
    elif (day == "czw"):
        for lesson in client.get_lessons(LastWeek[3]):
            Lessons.append(
                str(lesson.time.from_)[:-3] + "-" + str(lesson.time.to)[:-3])
            Lessons.append(str(lesson.subject.name))
            if (str(lesson.group) != "None"):
                Lessons.append(
                    str(lesson.room) + " Grupa: " + str(lesson.group))
            else:
                Lessons.append(str(lesson.room))
        return Lessons
    elif (day == "pt"):
        for lesson in client.get_lessons(LastWeek[4]):
            Lessons.append(
                str(lesson.time.from_)[:-3] + "-" + str(lesson.time.to)[:-3])
            Lessons.append(str(lesson.subject.name))
            if (str(lesson.group) != "None"):
                Lessons.append(
                    str(lesson.room) + " Grupa: " + str(lesson.group))
            else:
                Lessons.append(str(lesson.room))
        return Lessons
コード例 #16
0
    async def async_step_add_next_config_entry(self, user_input=None):
        """Flow initialized when user is adding next entry of that integration."""
        existing_entries = []
        for entry in self.hass.config_entries.async_entries(DOMAIN):
            existing_entries.append(entry)

        errors = {}
        if user_input is not None:
            if user_input["use_saved_credentials"]:
                if len(existing_entries) == 1:
                    keystore = Keystore.load(
                        existing_entries[0].data["keystore"])
                    account = Account.load(existing_entries[0].data["account"])
                    client = Vulcan(keystore, account)
                    students = await client.get_students()
                    await client.close()
                    new_students = []
                    existing_entry_ids = []
                    for entry in self.hass.config_entries.async_entries(
                            DOMAIN):
                        existing_entry_ids.append(entry.data["student_id"])
                    for student in students:
                        if str(student.pupil.id) not in existing_entry_ids:
                            new_students.append(student)
                    if not new_students:
                        return self.async_abort(
                            reason="all_student_already_configured")
                    if len(new_students) == 1:
                        await self.async_set_unique_id(
                            str(new_students[0].pupil.id))
                        self._abort_if_unique_id_configured()
                        return self.async_create_entry(
                            title=
                            f"{new_students[0].pupil.first_name} {new_students[0].pupil.last_name}",
                            data={
                                "student_id": str(new_students[0].pupil.id),
                                "keystore": keystore.as_dict,
                                "account": account.as_dict,
                            },
                        )
                    # pylint:disable=attribute-defined-outside-init
                    self.account = account
                    self.keystore = keystore
                    self.students = new_students
                    return await self.async_step_select_student()
                return await self.async_step_select_saved_credentials()
            return await self.async_step_auth()

        data_schema = {
            vol.Required("use_saved_credentials", default=True): bool,
        }
        return self.async_show_form(
            step_id="add_next_config_entry",
            data_schema=vol.Schema(data_schema),
            errors=errors,
        )
コード例 #17
0
def update_grades():
    #this function downloads grades from connected account | no arguments, no returns

    #prepare connection with Vulcan account
    with open("cert.json") as f:
        certificate = json.load(f)

    client = Vulcan(certificate)

    for grade in client.get_grades():

        #grade_to_add
        if grade.weight == 0.0: continue
        elif grade.content == "np": grade_to_add = "np"
        elif grade.content == "1": grade_to_add = "1"
        elif grade.content == "1+": grade_to_add = "1+"
        elif grade.content == "2": grade_to_add = "2"
        elif grade.content == "2+": grade_to_add = "2+"
        elif grade.content == "2-": grade_to_add = "2-"
        elif grade.content == "3": grade_to_add = "3"
        elif grade.content == "3+": grade_to_add = "3+"
        elif grade.content == "3-": grade_to_add = "3-"
        elif grade.content == "4": grade_to_add = "4"
        elif grade.content == "4-": grade_to_add = "4-"
        elif grade.content == "4+": grade_to_add = "4+"
        elif grade.content == "5": grade_to_add = "5"
        elif grade.content == "5-": grade_to_add = "5-"
        elif grade.content == "5+": grade_to_add = "5+"
        elif grade.content == "6": grade_to_add = "6"
        elif grade.content == "6-": grade_to_add = "6-"
        elif grade.content == "+": grade_to_add = "+"
        elif grade.content == "-": grade_to_add = "-"
        else: continue

        #subject_to_add
        subject_to_add = grade.subject.short

        #add grade to file
        path = "oceny/" + subject_to_add + ".txt"
        file = open(path, "a")
        file.write(grade_to_add)
        file.write("\n")
        file.close()
コード例 #18
0
ファイル: config_flow.py プロジェクト: jcgoette/core
    async def async_step_auth(self, user_input=None, errors=None):
        """Authorize integration."""

        if user_input is not None:
            try:
                credentials = await register(
                    self.hass,
                    user_input[CONF_TOKEN],
                    user_input[CONF_REGION],
                    user_input[CONF_PIN],
                )
            except InvalidSymbolException:
                errors = {"base": "invalid_symbol"}
            except InvalidTokenException:
                errors = {"base": "invalid_token"}
            except InvalidPINException:
                errors = {"base": "invalid_pin"}
            except ExpiredTokenException:
                errors = {"base": "expired_token"}
            except ClientConnectionError as err:
                errors = {"base": "cannot_connect"}
                _LOGGER.error("Connection error: %s", err)
            except Exception:  # pylint: disable=broad-except
                _LOGGER.exception("Unexpected exception")
                errors = {"base": "unknown"}
            if not errors:
                account = credentials["account"]
                keystore = credentials["keystore"]
                client = Vulcan(keystore, account,
                                async_get_clientsession(self.hass))
                students = await client.get_students()

                if len(students) > 1:
                    self.account = account
                    self.keystore = keystore
                    self.students = students
                    return await self.async_step_select_student()
                student = students[0]
                await self.async_set_unique_id(str(student.pupil.id))
                self._abort_if_unique_id_configured()
                return self.async_create_entry(
                    title=
                    f"{student.pupil.first_name} {student.pupil.last_name}",
                    data={
                        "student_id": str(student.pupil.id),
                        "keystore": keystore.as_dict,
                        "account": account.as_dict,
                    },
                )

        return self.async_show_form(
            step_id="auth",
            data_schema=vol.Schema(LOGIN_SCHEMA),
            errors=errors,
        )
コード例 #19
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up Uonet+ Vulcan integration."""
    hass.data.setdefault(DOMAIN, {})
    try:
        keystore = Keystore.load(entry.data["keystore"])
        account = Account.load(entry.data["account"])
        client = Vulcan(keystore, account)
        await client.select_student()
        students = await client.get_students()
        for student in students:
            if str(student.pupil.id) == str(entry.data["student_id"]):
                client.student = student
                break
    except VulcanAPIException as err:
        if str(err) == "The certificate is not authorized.":
            _LOGGER.error(
                "The certificate is not authorized, please authorize integration again"
            )
            raise ConfigEntryAuthFailed from err
        _LOGGER.error("Vulcan API error: %s", err)
        return False
    except ClientConnectorError as err:
        if "connection_error" not in hass.data[DOMAIN]:
            _LOGGER.error(
                "Connection error - please check your internet connection: %s",
                err)
            hass.data[DOMAIN]["connection_error"] = True
        await client.close()
        raise ConfigEntryNotReady from err
    hass.data[DOMAIN]["students_number"] = len(
        hass.config_entries.async_entries(DOMAIN))
    hass.data[DOMAIN][entry.entry_id] = client

    if not entry.update_listeners:
        entry.add_update_listener(_async_update_options)

    for platform in PLATFORMS:
        hass.async_create_task(
            hass.config_entries.async_forward_entry_setup(entry, platform))

    return True
コード例 #20
0
ファイル: apiVulcan.py プロジェクト: Sanitsonn/messenger-bot
def getAverage(certificate, przedmiot):
    client = Vulcan(certificate)
    weights = 0
    grades = 0
    for grade in client.get_grades():
        if (grade.subject.name.lower() == przedmiot):
            if (len(grade.content) == 2):
                if ("+" in grade.content):
                    gradeG = int(grade.content[:-1])
                    gradeG += 0.25
                    grades += gradeG * int(grade.weight)
                    weights += int(grade.weight)
                else:
                    gradeG = int(grade.content[:-1])
                    gradeG -= 0.25
                    grades += gradeG * int(grade.weight)
                    weights += int(grade.weight)
            elif (grade.content.isnumeric() == True):
                grades += int(grade.content) * int(grade.weight)
                weights += int(grade.weight)
    return round(grades / weights, 2)
コード例 #21
0
def register(token=None, symbol=None, pin=None):
    if not token:
        token = input('Podaj token: ').strip()
    if not symbol:
        symbol = input('Podaj symbol: ').strip()
    if not pin:
        pin = input('Podaj PIN: ').strip()

    if token and symbol and pin:
        certificate = Vulcan.register(token, symbol, pin)

        with open('cert.json', 'w') as f:
            json.dump(certificate.json, f)
    else:
        raise ValueError
コード例 #22
0
ファイル: apiVulcan.py プロジェクト: Sanitsonn/messenger-bot
def getHomework(date, certificate):
    client = Vulcan(certificate)
    homeworkS = ""
    for homework in client.get_homework(date):
        homeworkS += homework.teacher.first_name + " " + homework.teacher.last_name + "\n" + homework.subject.name + "\n" + "\n"
    return homeworkS
コード例 #23
0
ファイル: apiVulcan.py プロジェクト: Sanitsonn/messenger-bot
def logInVulcan(token, symbol, pin):
    certificate = Vulcan.register(token, symbol, pin)
    """with open('cert.json', 'w') as f: # You can use other filename
        json.dump(certificate.json, f)"""
    return certificate.json
コード例 #24
0
def prepare_plan():
    #this function prepares txt files with plans for days of the week inside | no arguments, no returns

    if os.path.isdir("plan"):
        for file in os.listdir("plan"):
            os.remove(f"plan/{file}")
        os.rmdir("plan")

    if not os.path.isdir("plan"):
        os.makedirs("plan")

    #prepare connection with Vulcan account
    with open("cert.json") as f:
        certificate = json.load(f)

    client = Vulcan(certificate)

    last_num = 0
    data = ""
    day_name = ""

    for i in range(7):

        free = True
        data = date.today() + timedelta(i)

        if data.weekday() == 0: day_name = "poniedzialek"
        if data.weekday() == 1: day_name = "wtorek"
        if data.weekday() == 2: day_name = "sroda"
        if data.weekday() == 3: day_name = "czwartek"
        if data.weekday() == 4: day_name = "piatek"
        if data.weekday() in (5, 6): continue

        file = open(f"plan/{day_name}.txt", "w+")
        file.write(f"Plan na {day_name}:")

        for lesson in client.get_lessons(data):

            free = False

            if ((last_num == 0) and (lesson.number > 1)):
                last_num = lesson.number - 1

            lesson_name = change_this(lesson.subject.name)
            teacher_name = change_this(lesson.teacher.short)

            if lesson.number != last_num:
                file.write(
                    f"\n{lesson.number}. {lesson_name} ({teacher_name})")
                last_num += 1

            else:
                file.write(f" / {lesson_name} ({teacher_name})")

        last_num = 0

        file.close()

        if free:
            new_file = open(f"plan/{day_name}.txt", "w")
            new_file.write(f"Brak lekcji na {day_name}!!! WOLNE!!!")
            new_file.close()
コード例 #25
0
ファイル: main.py プロジェクト: Majroch/vulcan-plan
from CalDavManager import CalDavManager
from Config import Config

config = Config("main.cfg")
caldav = CalDavManager(config)

try:
    with open(config.get("cert"), "r") as file:
        cert = json.load(file)
except FileNotFoundError:
    print("Cannot find Cert! Creating one:")
    token = input("Enter Token: ")
    symbol = input("Enter Symbol: ")
    pin = input("Enter PIN: ")

    cert = Vulcan.register(token, symbol, pin)

    if cert != None:
        with open(config.get("cert"), "w") as file:
            file.write(json.dumps(cert.json))
    else:
        print("No cert found!")
        exit()

vulcan = Vulcan(cert)

while True:
    dates = []
    for x in range(30):
        dates.append(datetime.date.today() + datetime.timedelta(days=x))
コード例 #26
0
ファイル: main.py プロジェクト: Majroch/vulcan-sprawdziany
from CalDavManager import CalDavManager
from Config import Config

config = Config("main.cfg")
caldav = CalDavManager(config)

try:
    with open(config.get("cert"), "r") as file:
        cert = json.load(file)
except FileNotFoundError:
    print("Cannot find Cert! Creating one:")
    token = input("Enter Token: ")
    symbol = input("Enter Symbol: ")
    pin = input("Enter PIN: ")

    cert = Vulcan.register(token, symbol, pin)

    if cert != None:
        with open(config.get("cert"), "w") as file:
            file.write(json.dumps(cert.json))
    else:
        print("No cert found!")
        exit()
    
vulcan = Vulcan(cert)

while True:
    dates = []
    for x in range(30):
        dates.append(datetime.date.today() + datetime.timedelta(days=x))