Hilfe bei Code / Icloud

Wenn du dir nicht sicher bist, in welchem der anderen Foren du die Frage stellen sollst, dann bist du hier im Forum für allgemeine Fragen sicher richtig.
Antworten
silas
User
Beiträge: 1
Registriert: Freitag 5. Januar 2024, 23:56

hallo leute,
ich habe probleme mit meinem code, ich möchte eien kalender erstellen der daten aus meinem icloud konto zieht. kalender steht anmeldung geht bis zur MFA, ich bekomme keine anforderung auf dem handy und auch keine eingabeoption des MFA codes. wäre schön wenn mir hierbei jemand helfen könnte

Code: Alles auswählen

import tkinter as tk
from tkinter import simpledialog, OptionMenu, Listbox, Toplevel, Label, Entry, Button, messagebox
import calendar
from datetime import datetime
from pyicloud import PyiCloudService

class CalendarApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Interaktiver Kalender")
        self.appointments = {}

        self.year = tk.IntVar(value=2024)
        self.month = tk.IntVar(value=1)
        self.selected_day = None

        # Erstellen Sie die Instanz "api" außerhalb der Klasse, damit sie global verwendet werden kann
        self.api = None

        self.create_calendar()
        self.show_calendar()
        self.authenticate_and_show_calendar()

    def create_calendar(self):
        frame = tk.Frame(self.root)
        frame.pack(pady=20)

        year_menu = tk.OptionMenu(frame, self.year, *range(2024, 2061))
        month_menu = tk.OptionMenu(frame, self.month, *range(1, 13))

        year_menu.grid(row=0, column=0)
        month_menu.grid(row=0, column=1)

        self.year.trace_add('write', self.show_calendar)
        self.month.trace_add('write', self.show_calendar)

        self.date_label = tk.Label(self.root, text="")
        self.date_label.pack()

        self.canvas = tk.Canvas(self.root, width=700, height=520)
        self.canvas.pack()

        self.canvas.bind("<Button-1>", self.on_canvas_click)

    def authenticate_and_show_calendar(self):
        username = simpledialog.askstring("iCloud Anmeldung", "Benutzername:")
        password = simpledialog.askstring("iCloud Anmeldung", "Passwort:", show='*')

        try:
            self.api = PyiCloudService(username, password)

            while self.api.requires_2fa or self.api.requires_2sa:
                if self.api.requires_2fa:
                    code = simpledialog.askstring("iCloud Anmeldung", "Bitte geben Sie Ihren MFA-Code ein:")
                    result = self.api.validate_2fa_code(code)
                    if not result:
                        print("Fehler bei der Überprüfung des Sicherheitscodes")
                        return

                if self.api.requires_2sa:
                    print("Zwei-Schritt-Authentifizierung erforderlich. Ihre vertrauenswürdigen Geräte sind:")
                    devices = self.api.trusted_devices
                    for i, device in enumerate(devices):
                        print(f"  {i}: {device.get('deviceName', 'SMS an %s' % device.get('phoneNumber'))}")

                    device_index = simpledialog.askinteger("iCloud Anmeldung", "Welches Gerät möchten Sie verwenden?", default=0)
                    device = devices[device_index]
                    if not self.api.send_verification_code(device):
                        print("Fehler beim Senden des Bestätigungscodes")
                        return

                    code = simpledialog.askstring("iCloud Anmeldung", "Bitte geben Sie den Bestätigungscode ein:")
                    if not self.api.validate_verification_code(device, code):
                        print("Fehler bei der Überprüfung des Bestätigungscodes")
                        return

            # Wenn MFA oder 2SA erfolgreich ist, zeige den Kalender an
            self.fetch_and_show_calendar()
            self.show_success_message("Anmeldung erfolgreich und verifiziert!")

        except Exception as e:
            print(f"Fehler bei der Anmeldung: {e}")
            messagebox.showerror("Fehler bei der Anmeldung", f"Fehler: {e}")

    def fetch_and_show_calendar(self):
        try:
            # Nutzen Sie die fetch-Funktion, um die iCloud-Daten abzurufen
            calendar_data = self.fetch()

            for event in calendar_data:
                # Hier können Sie die Daten weiterverarbeiten und in Ihrem Kalender anzeigen
                start_date = event.get('start')
                summary = event.get('summary')
                # ...

                # Beispiel: Hinzufügen des Termins zu Ihrem Kalender
                date_key = (start_date.year, start_date.month, start_date.day)
                if date_key not in self.appointments:
                    self.appointments[date_key] = [summary]
                else:
                    self.appointments[date_key].append(summary)

            # Aktualisieren Sie den Kalender nach dem Laden der iCloud-Termine
            self.show_calendar()

        except Exception as e:
            messagebox.showerror("Fehler beim Laden von iCloud-Terminen", f"Fehler: {e}")

    def fetch(self):
        from_dt = datetime(2024, 1, 1)
        to_dt = datetime(2050, 1, 31)
        
        # Nutzen Sie die fetch-Funktion, um die iCloud-Daten abzurufen
        events = self.api.calendar.events(from_dt, to_dt) 

    def show_success_message(self, message):
        tk.messagebox.showinfo("Erfolg", message)

    def show_calendar(self, *args):
        self.canvas.delete("all")

        cal_data = calendar.monthcalendar(self.year.get(), self.month.get())

        self.date_label.config(text=f"{calendar.month_name[self.month.get()]} {self.year.get()}")

        cell_width = 100
        cell_height = 80
        week_days = list(calendar.day_abbr)

        for i, day in enumerate(week_days):
            x0 = i * cell_width
            y0 = 0
            x1 = x0 + cell_width
            y1 = y0 + cell_height
            self.canvas.create_rectangle(x0, y0, x1, y1, fill="lightgray", outline="black")
            self.canvas.create_text((x0 + x1) // 2, y0 + 10, text=day, font=("Helvetica", 12, "bold"))

        for week_num, week in enumerate(cal_data):
            for day_num, day in enumerate(week):
                x0 = day_num * cell_width
                y0 = (week_num + 1) * cell_height - 20
                x1 = x0 + cell_width
                y1 = y0 + cell_height

                if day != 0:
                    day_button = self.canvas.create_rectangle(x0, y0, x1, y1, fill="lightgray", outline="black")
                    self.canvas.create_text((x0 + x1) // 2, y0 + 10, text=str(day), font=("Helvetica", 12))

                    appointments = self.appointments.get((self.year.get(), self.month.get(), day), [])
                    for i, appointment in enumerate(appointments):
                        y_offset = 20 * (i + 1)
                        self.canvas.create_text((x0 + x1) // 2, y0 + 10 + y_offset, text=appointment, font=("Helvetica", 10), fill="blue")

                    self.canvas.tag_bind(day_button, '<Button-1>', lambda event, d=day: self.show_day_options(d, appointments))
                else:
                    self.canvas.create_rectangle(x0, y0, x1, y1, fill="white", outline="black")

    def on_canvas_click(self, event):
        cell_width = 100
        cell_height = 80

        clicked_day = (event.x // cell_width) + 1
        date_key = (self.year.get(), self.month.get(), clicked_day)

        appointments = self.appointments.get(date_key, [])

        if appointments:
            self.show_day_options(clicked_day, appointments)
        else:
            self.add_appointment(date_key)

    def show_day_options(self, day, appointments):
        self.selected_day = day
        date_key = (self.year.get(), self.month.get(), self.selected_day)

        self.show_option_dialog(date_key, appointments)

    def show_option_dialog(self, date_key, appointments):
        dialog = OptionDialog(self.root, date_key, appointments, self)
        dialog.show()

    def add_appointment(self, date_key):
        dialog = AddAppointmentDialog(self.root, date_key, self)
        dialog.show()

    def edit_appointment(self, date_key, selected_appointment):
        dialog = EditAppointmentDialog(self.root, date_key, selected_appointment, self)
        dialog.show()

class OptionDialog:
    def __init__(self, root, date_key, appointments, app):
        self.root = tk.Toplevel(root)
        self.root.title("Optionen")

        self.date_key = date_key
        self.appointments = appointments
        self.app = app

        self.listbox = Listbox(self.root)
        for appointment in self.appointments:
            self.listbox.insert(tk.END, appointment)

        self.listbox.pack(pady=10)

        self.option_var = tk.StringVar(self.root)
        self.option_var.set("Auswählen")

        self.option_menu = OptionMenu(self.root, self.option_var, *["Hinzufügen", "Bearbeiten", "Löschen"])
        self.option_menu.pack(pady=10)

        self.button = Button(self.root, text="Ausführen", command=self.option_selected)
        self.button.pack(pady=10)

    def show(self):
        self.root.wait_window()

    def option_selected(self):
        selected_option = self.option_var.get()

        if selected_option == "Hinzufügen":
            self.app.add_appointment(self.date_key)
        elif selected_option == "Bearbeiten":
            selected_appointment_index = self.listbox.curselection()
            if selected_appointment_index:
                selected_appointment = self.appointments[selected_appointment_index[0]]
                self.app.edit_appointment(self.date_key, selected_appointment)
        elif selected_option == "Löschen":
            selected_appointment_index = self.listbox.curselection()
            if selected_appointment_index:
                del self.app.appointments[self.date_key][selected_appointment_index[0]]
                self.app.show_calendar()

        self.root.destroy()

class AddAppointmentDialog:
    def __init__(self, root, date_key, app):
        self.root = tk.Toplevel(root)
        self.root.title("Termin hinzufügen")

        self.date_key = date_key
        self.app = app

        self.label = Label(self.root, text=f"Termin für den {self.date_key[2]}. {calendar.month_name[self.date_key[1]]} {self.date_key[0]}:")
        self.label.pack(pady=10)

        self.entry = Entry(self.root)
        self.entry.pack(pady=10)

        self.button = Button(self.root, text="Hinzufügen", command=self.add_appointment)
        self.button.pack(pady=10)

    def show(self):
        self.root.wait_window()

    def add_appointment(self):
        result = self.entry.get()
        if result:
            if self.date_key not in self.app.appointments:
                self.app.appointments[self.date_key] = [result]
            else:
                self.app.appointments[self.date_key].append(result)
            self.app.show_calendar()
        self.root.destroy()

class EditAppointmentDialog:
    def __init__(self, root, date_key, selected_appointment, app):
        self.root = tk.Toplevel(root)
        self.root.title("Termin bearbeiten")

        self.date_key = date_key
        self.selected_appointment = selected_appointment
        self.app = app

        self.label = Label(self.root, text=f"Termin für den {self.date_key[2]}. {calendar.month_name[self.date_key[1]]} {self.date_key[0]}:")
        self.label.pack(pady=10)

        self.entry = Entry(self.root)
        self.entry.insert(tk.END, selected_appointment)
        self.entry.pack(pady=10)

        self.button = Button(self.root, text="Speichern", command=self.save_appointment)
        self.button.pack(pady=10)

    def show(self):
        self.root.wait_window()

    def save_appointment(self):
        result = self.entry.get()
        if result:
            selected_appointment_index = self.app.appointments[self.date_key].index(self.selected_appointment)
            self.app.appointments[self.date_key][selected_appointment_index] = result
            self.app.show_calendar()
        self.root.destroy()

if __name__ == "__main__":
    root = tk.Tk()
    app = CalendarApp(root)
    root.mainloop()
Benutzeravatar
__blackjack__
User
Beiträge: 13236
Registriert: Samstag 2. Juni 2018, 10:21
Wohnort: 127.0.0.1
Kontaktdaten:

@silas: Das ist sehr viel Code von dem Du da jetzt erwartest das jemand einen Fehler sucht. Du könntest als erstes mal die Programmlogik von der GUI trennen, beziehungsweise hier auch erst mal die Schnittstelle zur Cloud. Und die ganze Anmeldung scheint mir komplex genug für einen eigenen GUI-Teil.

Die Importe könnte man mal aufräumen. Da wird einiges nicht benutzt, und so etwas wie `OptionMenu` wird mal über `tk` und mal direkt importiert verwendet. Das sollte man vereinheitlichen.

Das Hauptprogramm sollte in einer Funktion stehen statt das da globale Namen definiert werden.
Please call it what it is: copyright infringement, not piracy. Piracy takes place in international waters, and involves one or more of theft, murder, rape and kidnapping. Making an unauthorized copy of a piece of software is not piracy, it is an infringement of a government-granted monopoly.
Antworten