Esempio n. 1
0
def creds() -> Account:
    """Load or obtain credentials for user."""

    credentials = "8da780f3-5ea0-4d97-ab13-9e7976370624"
    protocol = MSGraphProtocol(timezone="Europe/Stockholm")
    scopes = protocol.get_scopes_for(SCOPES)
    token_backend = FileSystemTokenBackend(
        token_path=os.path.dirname(__file__), token_filename="o365_token.txt")
    connection = Connection(credentials,
                            auth_flow_type="public",
                            token_backend=token_backend)
    account = Account(
        credentials,
        auth_flow_type="public",
        protocol=protocol,
        token_backend=token_backend,
    )

    if (not os.path.exists("kronoxToGCalendar/logic/o365_token.txt")
            and not account.is_authenticated):
        print("AUTH TRIGGERED")
        auth_url = connection.get_authorization_url(
            requested_scopes=scopes,
            redirect_uri=
            "https://kronox-client-api.herokuapp.com/return_token_url",
        )

        webbrowser.open_new(auth_url[0])

        token_req = lambda: requests.get(
            "https://kronox-client-api.herokuapp.com/get_token_url")

        while token_req().text == "None":
            continue

        token_res_arr = token_req().text.split("&")
        print(token_res_arr)
        token_code = token_res_arr[0].split("?")[1][5:]
        token_state = token_res_arr[1][6:]

        token_url = (
            "https://login.microsoftonline.com/common/oauth2/nativeclient?code="
            + token_code + "&state=" + token_state)

        connection.request_token(token_url)

    print("AUTH PASSED")
    account.is_authenticated

    return account
Esempio n. 2
0
def getAccount(user_id):
    """Get account by user"""
    # prepare token backend for user
    token_backend = FileSystemTokenBackend(token_path=config.TOKEN_PATH, token_filename=user_id + '.token')

    # prepare MSGraphProtocol for user
    my_protocol = MSGraphProtocol(config.API_VERSION, user_id)

    # setup account definition for user
    return Account(credentials=(config.CLIENT_ID, config.CLIENT_SECRET), protocol=my_protocol, scopes=config.SCOPES, token_backend=token_backend)
Esempio n. 3
0
    def get_365_account(self):
        token_backend = FileSystemTokenBackend(token_path='.',token_filename='o365_token.txt')
        credentials = tuple()

        with open('credentials.json','r') as f:
                data = json.load(f)
                credentials = (data['appid'],data['secret'])
        protocal   = MSGraphProtocol(api_version='beta')
        account = Account(credentials,token_backend = token_backend,protocol=protocal)
        return account
    def authenticate(self):
        credentials = (self.client_id, self.secret_id)
        protocol = MSGraphProtocol()
        account = Account(credentials, protocol=protocol)

        if account.is_authenticated:
            print("Token file exists!")
        else:
            authenticated = account.authenticate(scopes=SCOPES)
            if authenticated:
                print('Authenticated!')
            else:
                print('Failed to authenticate.')

        return account
def get_team_data(team_id="955529db-5622-4dca-9c90-8cb0e5fe032f"):
    client_secret = "W9hAa7i62Uv?hLTLH-?BlxhRCYWIkj?A"
    application_id = "bdf4dd0c-9ba0-4bc2-b72f-d7ce5023f0b9"
    credentials = (application_id, client_secret)
    tenant_id = "17855ce0-d47e-48df-9c90-33b4fa21c861"
    account = Account(credentials,
                      auth_flow_type="credentials",
                      tenant_id=tenant_id)
    account.authenticate()

    team = Group(group_id=team_id, parent=account, protocol=MSGraphProtocol())

    print(team.get_id())
    response = team.get_reports()
    print(json.loads(response.text))
    with open('data.txt', 'w') as outfile:
        json.dump(response.text, outfile)
def analytics():
    client_secret = "W9hAa7i62Uv?hLTLH-?BlxhRCYWIkj?A"
    application_id = "bdf4dd0c-9ba0-4bc2-b72f-d7ce5023f0b9"
    credentials = (application_id, client_secret)
    tenant_id = "17855ce0-d47e-48df-9c90-33b4fa21c861"
    # scopes = ['https://graph.microsoft.com/beta/Analytics.Read',
    #           'https://graph.microsoft.com/beta/Analytics.ReadWrite',
    #           'https://graph.microsoft.com/beta/Analytics.Read.All',
    #           'https://graph.microsoft.com/beta/Analytics.ReadWrite.All']
    account = Account(credentials,
                      auth_flow_type="credentials",
                      tenant_id=tenant_id)

    user = User(user_id="d3f30d7a-d742-46ee-b41a-c127a2eeca6a",
                parent=account,
                protocol=MSGraphProtocol())
    print(user.get_recent_activity())
Esempio n. 7
0
def get_team(obj_name, credentials, host, site, token_filepath=None, io=None):
    """ Returns a Sharepoint site object
    :param str obj_name: a list name or a path to an excel file in sharepoint
    :param tuple credentials: a tuple with Office 365 client_id and client_secret
    :param str host: A sharepoint host like anatel365.sharepoint.com
    :param str site: a site's name or team's name
    :param str token_filepath: path where the Office 365 token is or will be stored.
    :param str io: path to where downloaded objects (list or excel file) will be stored.
    :return: a Sharepoint Site
    :rtype: Site
    """

    # obter o caracter de split do filepath
    split_char, to_path, name = get_path_name(obj_name=obj_name, io=io)

    # separar o token_filename do token_path
    if not token_filepath:
        token_filename = 'o365token.txt'
        token_path = to_path + split_char
    else:
        token_filename = token_filepath.split(split_char)[-1]
        token_path = split_char.join(
            token_filepath.split(split_char)[:-1]) + split_char

    # Obter o token
    token_backend = FileSystemTokenBackend(token_path=token_path,
                                           token_filename=token_filename)
    # criar o objeto account
    account = Account(credentials, token_backend=token_backend)
    # scope para sharepoint
    scopes = ['basic'] + MSGraphProtocol().get_scopes_for(
        user_provided_scopes='sharepoint')

    # Autenticação
    if not isfile(token_path + token_filename):
        if not account.authenticate(scopes=scopes):
            raise Exception(
                'Não foi possível autenticar com as credenciais e token informados'
            )

    sharepoint = account.sharepoint()
    team = sharepoint.get_site(host, 'sites/' + site)
    return team
def archive_nd_delete_team(gearman_worker, gearman_job):
    client_secret = "W9hAa7i62Uv?hLTLH-?BlxhRCYWIkj?A"
    application_id = "bdf4dd0c-9ba0-4bc2-b72f-d7ce5023f0b9"
    credentials = (application_id, client_secret)
    tenant_id = "17855ce0-d47e-48df-9c90-33b4fa21c861"
    account = Account(credentials,
                      auth_flow_type="credentials",
                      tenant_id=tenant_id)

    team_id = simplejson.loads(gearman_job.data)

    print(team_id)

    group = Group(group_id=team_id, parent=account, protocol=MSGraphProtocol())
    group.archive_team()

    #group.delete_team()
    print("The team was deleted!")
    group.delete()
    return "Requested team was deleted successfully!"
 def __init__(self, config: Dict):
     self.client_id = config['client-id']
     self.secret_id = config['secret-id']
     self.calendar_name = config['name']
     self.token_file = config['token-file']
     self.hours = config['hours']
     credentials = (self.client_id, self.secret_id)
     protocol = MSGraphProtocol()
     scopes = [
         'User.Read', 'Calendars.Read', 'Calendars.Read.Shared',
         'offline_access'
     ]
     self.account = Account(
         credentials,
         protocol=protocol,
         token_backend=FileSystemTokenBackend(token_path=self.token_file))
     if not self.account.is_authenticated:
         if self.account.authenticate(scopes=scopes):
             print('Authenticated!')
         else:
             print("Failed to authenticate")
     else:
         print("Skipping authentication because token already exists")
def create_team(gearman_worker, gearman_job):
    data = simplejson.loads(gearman_job.data)
    maria_user_id = "d3f30d7a-d742-46ee-b41a-c127a2eeca6a"
    louis_user_id = "92ced39c-df19-4ae6-b370-59a118b0e767"
    developer_id = "e95e11ac-4423-4bfd-813d-d7fb38b28e3c"

    members_list = []
    if data[3] is False:
        members_list = [maria_user_id, louis_user_id]
    else:
        csv = data[3].split(',')
        for x in csv:
            if "-" in x:
                members_list.append(x)
        members_list = members_list[0:10]

    client_secret = "W9hAa7i62Uv?hLTLH-?BlxhRCYWIkj?A"
    application_id = "bdf4dd0c-9ba0-4bc2-b72f-d7ce5023f0b9"
    credentials = (application_id, client_secret)
    tenant_id = "17855ce0-d47e-48df-9c90-33b4fa21c861"
    account = Account(credentials,
                      auth_flow_type="credentials",
                      tenant_id=tenant_id)

    new_group = Group(parent=account, protocol=MSGraphProtocol())
    new_group.create(data[0],
                     mail_enabled=True,
                     security_enabled=True,
                     owners=[developer_id],
                     members=members_list,
                     description=data[1])

    new_group.create_team(True, True, True, True, True, True, True, True, True,
                          True, True, True, True, "strict", True, True)

    # send the team is for later database storage
    return new_group.team_id
def update_team(gearman_worker, gearman_job):

    client_secret = "W9hAa7i62Uv?hLTLH-?BlxhRCYWIkj?A"
    application_id = "bdf4dd0c-9ba0-4bc2-b72f-d7ce5023f0b9"
    credentials = (application_id, client_secret)
    tenant_id = "17855ce0-d47e-48df-9c90-33b4fa21c861"
    account = Account(credentials,
                      auth_flow_type="credentials",
                      tenant_id=tenant_id)

    data = simplejson.loads(gearman_job.data)

    team_id = str(data[0])
    new_name = str(data[1])

    print(team_id, new_name)

    group = Group(group_id=team_id, parent=account, protocol=MSGraphProtocol())
    group.update(display_name=new_name,
                 mail_enabled=True,
                 security_enabled=True)

    print("Group id: " + group.team_id)
    return group.team_id
Esempio n. 12
0
        if item.is_file:
            download_file(item, current_path)


def create_folder(item, current_path):
    folder = os.path.join(current_path, item.name)
    os.makedirs(folder, exist_ok=1)
    print(f"Dossier {item.name} créé avec succès !")
    return folder


def download_file(item, path):
    item.download(to_path=path, chunk_size=None)
    print(f"Fichier {item.name} téléchargé avec succès !")


protocol = MSGraphProtocol(api_version='beta')
credentials = ('7b9c81d7-2c01-4d48-86fc-9a7cd9700b85',
               'cBPj06Vjh_[HNkntI-e6pEf.h1JKn12H')

token_backend = FileSystemTokenBackend(token_path='my_folder',
                                       token_filename='my_token.txt')
account = Account(credentials, protocol=protocol, token_backend=token_backend)
account.authenticate(
    scopes=['basic', 'message_all', 'onedrive_all', 'address_book_all'])

storage = account.storage()
my_drive = storage.get_default_drive()

save_folder(my_drive)
Esempio n. 13
0
from O365 import Account, FileSystemTokenBackend, MSGraphProtocol
import time
import datetime
import re

CLIENT_ID = '85b6aa4d-103c-48f4-b0da-d766f18c7518'
SECRET_ID = 'edBgd-L0FAMELEYuaZ:t8=S8F9DoJhK]'

credentials = (CLIENT_ID, SECRET_ID)
protocol = MSGraphProtocol(default_resource='*****@*****.**') 

token_backend = FileSystemTokenBackend(token_path='auth_token', token_filename='auth_token.txt')
scopes = ['Calendars.Read.Shared','offline_access']
account = Account(credentials, protocol=protocol, token_backend=token_backend)
account.authenticate(scopes=scopes)

schedule = account.schedule()

calendar = schedule.get_default_calendar()

start_time = float(time.time())
end_time = float(time.time())

flag = 0

def parse_event_string(event):
    event_string = str(event)

    start_index = event_string.find('from:') + 6
    end_index = event_string.find('to:') - 1 
    start_meeting_time = event_string[start_index:end_index]
Esempio n. 14
0
from O365 import Account, FileSystemTokenBackend, MSGraphProtocol
import creds

# set vars
token_backend = FileSystemTokenBackend(token_path='auth_token',
                                       token_filename='o365_auth_token.txt')
protocol = MSGraphProtocol(default_resource=creds.user)
scopes = ['User.Read', 'Calendars.Read', 'offline_access']

# test auth
account = Account(creds.credentials,
                  token_backend=token_backend,
                  protocol=protocol)
if account.authenticate(scopes=scopes):
    print('Authenticated!!!')
Esempio n. 15
0
from O365 import Account, FileSystemTokenBackend, MSGraphProtocol
import creds
import time
import datetime

# set vars
token_backend = FileSystemTokenBackend(token_path='auth_token',
                                       token_filename='o365_auth_token.txt')
protocol = MSGraphProtocol()
scopes = ['User.Read', 'Calendars.Read', 'offline_access']
account = Account(creds.credentials,
                  token_backend=token_backend,
                  protocol=protocol)
schedule = account.schedule()
calendar = schedule.get_default_calendar()

# find out when it is
now = float(time.time())
print(now)
today = datetime.datetime.now()
print(today)

# query the calendar
q = calendar.new_query('start').greater_equal(datetime.datetime(2020, 5, 26))
q.chain('and').on_attribute('end').less_equal(datetime.datetime(2020, 5, 27))

# print out the events
events = calendar.get_events(query=q, include_recurring=True)

for event in events:
    print(event)
    def analyzeText(self, command):
        if not self.startedReminder:
            self.startReminder()
            self.startedReminder = True

        if "wikipedia" in command:

            # top_grid = GridLayout(
            # # row_force_default = True,
            # # row_default_height = 40,
            # # col_force_default = True,
            # # col_default_width = 500
            #         )
            # top_grid.cols = 1

            # self.speak("Searching wikipedia")

            top_grid = GridLayout()
            top_grid.cols = 1

            command = command.replace("wikipedia ", "")

            results = wikipedia.summary(command, sentences=2)
            label = Label(text=results)
            label.size_hint = (1, None)
            label.v_align = "middle"
            label.h_align = "middle"
            label.font_size = '18dp'
            # label.pos_hint = top_grid.width/2, top_grid.height/2
            label.bind(size=label.setter('text_size'))
            top_grid.add_widget(label)

            button_grid = RelativeLayout()
            button_grid.cols = 1
            cancelButton = Button(text="Close",
                                  size_hint=(.1, .075),
                                  pos_hint={
                                      'center_x': .95,
                                      'center_y': .95
                                  })
            button_grid.add_widget(cancelButton)

            top_grid.add_widget(button_grid)
            # Instantiate the modal popup and display
            popup = Popup(title=f'Summary of "{command}"',
                          content=top_grid,
                          auto_dismiss=False)

            def onOpen(miss):
                # threading.Thread(target=self.speak, args=(results,)).start()
                self.speak(results)

            popup.bind(on_open=onOpen)

            cancelButton.bind(on_press=popup.dismiss)
            popup.open()

            cancelButton.bind(on_press=popup.dismiss)
        # elif "open youtube" in command:
        #     webbrowser.open("www.youtube.com")
        elif "what can you do" in command:
            self.speak(
                "Hello! I am Unisys Natural Assistant. Let me take you through what I am capable of!"
            )
            self.speak("Want me to send your emails? Done!")
            self.speak("Want me to search wikipedia? Done!")
            self.speak(
                "What about summarize your meetings and make your life easier? Done!"
            )
            self.speak("Want me to open your favorite website? Done!")
            self.speak("Want me to take you through your day? Done!")
            self.speak("Want me to remind you that I am the best? Done!")
            self.speak("Okay! See you soon! sending you back to my creators!")

        elif "open" in command:
            command = command.replace("open", "").strip()

            self.speak(f"opening {command}")
            print(command)
            webbrowser.open(f"www.{command}.com")

        # elif "add" in command and ("todo" in command or "to do" in command):
        #     r = sr.Recognizer()
        #     with sr.Microphone() as source:
        #         print('In Add Todo')
        #         audio = r.listen(source)
        #         time.sleep(1)
        #         try:
        #             todo = r.recognize_google(audio)
        #             todos.append(todo.lower())
        #             print(todo)
        #         except:
        #             print("Error")
        #             self.speak("Sorry I didn't understand that, please try again.")

        # elif "show" in command and "todo" in command:
        #     for todo in todos:
        #         self.speak(todo)

        elif "mail" in command:
            s = get_subject()
            m = get_mail()
            get_receivers()
            attatch = attachments()
            receivers_string = ",".join(str(x) for x in receivers)
            # message = MIMEMultipart("alternative")
            # message["Subject"] = subject
            # message["From"] = sender
            # message["To"] = receivers_string
            # text = MIMEText(mail, "plain")
            # message.attach(text)
            # attachments()
            # try:
            #     with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
            #         smtp.login(sender, EMAIL_PASSWORD)
            #         smtp.sendmail(sender, receivers, message.as_string())
            #         print("Done")
            # except Exception as e:
            #     print(e)

            top_grid = GridLayout(row_force_default=False,
                                  row_default_height=20,
                                  col_force_default=False,
                                  col_default_width=200)
            top_grid.cols = 2

            top_grid.add_widget(Label(text="Subject: "))
            subject = TextInput(text=s, multiline=True)
            top_grid.add_widget(subject)

            top_grid.add_widget(Label(text="Body: "))
            mail = TextInput(text=m, multiline=True)
            top_grid.add_widget(mail)

            top_grid.add_widget(Label(text="Receiver(s): "))
            receiver = TextInput(text=receivers_string, multiline=True)
            top_grid.add_widget(receiver)

            if attatch != None:
                top_grid.add_widget(Label(text="Attatchment(if any) : "))
                attatch = TextInput(text=attatch, multiline=True)
                top_grid.add_widget(attatch)

            cancelButton = Button(text="Cancel")
            top_grid.add_widget(cancelButton)
            closeButton = Button(text="Send")
            top_grid.add_widget(closeButton)

            # Instantiate the modal popup and display
            popup = Popup(title='Email',
                          content=top_grid,
                          size_hint=(None, None),
                          size=(900, 450),
                          auto_dismiss=False)
            popup.open()

            def onClose(miss):
                popup.dismiss()
                message = MIMEMultipart("alternative")

                message["Subject"] = subject.text
                message["From"] = sender
                message["To"] = receiver.text
                text = MIMEText(mail.text, "plain")
                message.attach(text)

                if attatch != None:
                    try:
                        files = os.listdir()
                        filename = attatch.text
                        print(filename)

                        with open(os.getcwd() + "\\" + filename,
                                  "rb") as attachment:
                            part = MIMEBase("application", "octet-stream")
                            part.set_payload(attachment.read())

                        encoders.encode_base64(part)

                        part.add_header(
                            "Content-Disposition",
                            f"attachment; filename= {filename}",
                        )

                        message.attach(part)
                    except Exception as e:
                        print(e)

                try:
                    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
                        smtp.login(sender, EMAIL_PASSWORD)
                        smtp.sendmail(sender, receivers, message.as_string())
                        print("Done")
                except Exception as e:
                    print(e)

            closeButton.bind(on_press=onClose)
            cancelButton.bind(on_press=popup.dismiss)

        elif "directory" in command:
            print(os.getcwd())

        # elif "reminder" in command:
        #     MyPopup().open()

        # elif "show" in command and "reminder" in command:
        #     myres = ShowReminders()
        #     for res in myres:
        #         self.speak(res)

        elif "add" in command and "reminder" in command:
            self.speak("Name of reminder")
            s = self.speechInput()

            top_grid = GridLayout(row_force_default=True,
                                  row_default_height=40,
                                  col_force_default=True,
                                  col_default_width=200)
            top_grid.cols = 2

            while True:
                try:
                    self.speak('Date')
                    d = f'{next(dtf.find_dates(self.speechInput()))}'.split(
                        ' ')[0]
                    print(d)
                    break
                except:
                    pass
            while True:
                try:
                    self.speak('Time')
                    t = f'{next(dtf.find_dates(self.speechInput()))}'.split(
                        ' ')[1]
                    print(t)
                    break
                except:
                    pass

            top_grid.add_widget(Label(text="Subject: "))
            subject = TextInput(text=s, multiline=True)
            top_grid.add_widget(subject)

            top_grid.add_widget(Label(text="Date(YYYY/MM/DD): "))
            date = TextInput(text=d, multiline=False)
            top_grid.add_widget(date)

            top_grid.add_widget(Label(text="Start Time(hh:mm:ss): "))
            t = TextInput(text=t, multiline=False)
            top_grid.add_widget(t)

            cancelButton = Button(text="Cancel")
            top_grid.add_widget(cancelButton)
            closeButton = Button(text="Set")
            top_grid.add_widget(closeButton)

            # Instantiate the modal popup and display
            popup = Popup(title='Set Reminder',
                          content=top_grid,
                          size_hint=(None, None),
                          size=(900, 450),
                          auto_dismiss=False)
            popup.open()

            def onClose(miss):
                popup.dismiss()
                AddNewReminder(subject.text, f'{date.text} {t.text}')

            closeButton.bind(on_press=onClose)
            cancelButton.bind(on_press=popup.dismiss)

        elif "calendar" in command:
            global isAuth
            global account
            if not isAuth:
                event = namedtuple("event", "Start Subject Duration")
                # #from here

                CLIENT_ID = outlook_client_id
                SECRET_ID = outlook_secret_id
                credentials = (CLIENT_ID, SECRET_ID)

                # protocol = MSGraphProtocol()
                # scopes = ['Calendars.Read', 'Calendars.ReadWrite']
                # account = Account(credentials, protocol=protocol)

                protocol = MSGraphProtocol()
                scopes = ['Calendars.Read', 'Calendars.ReadWrite']
                account = Account(credentials, protocol=protocol)
                account.con.scopes = account.protocol.get_scopes_for(scopes)
                print(account.con.get_authorization_url(scopes=scopes)[0])
                webbrowser.open(
                    account.con.get_authorization_url(scopes=scopes)[0])

                top_grid = GridLayout(row_force_default=True,
                                      row_default_height=100,
                                      col_force_default=True,
                                      col_default_width=800)
                top_grid.cols = 1

                # label = Label(text=reminder_text)

                top_grid.add_widget(Label(text="URL: "))
                url = TextInput()
                top_grid.add_widget(url)
                # label.pos_hint = top_grid.width/2, top_grid.height/2

                bottom_grid = GridLayout(row_force_default=True,
                                         row_default_height=40,
                                         col_force_default=True,
                                         col_default_width=100)
                bottom_grid.cols = 2

                cancelButton = Button(text="Cancel")
                bottom_grid.add_widget(cancelButton)

                submitButton = Button(text="Submit")
                bottom_grid.add_widget(submitButton)

                top_grid.add_widget(bottom_grid)

                # submitButton = Button(text="Submit")
                # top_grid.add_widget(submitButton)

                # Instantiate the modal popup and display
                popup = Popup(title='Paste Authenticated URL',
                              content=top_grid,
                              size_hint=(None, None),
                              size=(900, 450),
                              auto_dismiss=False)

                popup.open()

                def onSubmit(miss):
                    print(url.text)
                    if account.con.request_token(url.text, scopes=scopes):
                        print('Authenticated!')
                        global isAuth
                        isAuth = True

                    popup.dismiss()

                submitButton.bind(on_press=onSubmit)
                cancelButton.bind(on_press=popup.dismiss)

                # if account.authenticate(scopes=scopes):
                #     print('Authenticated!')
                #     isAuth = True

            if "show" in command and isAuth:

                top_grid = GridLayout(row_force_default=True,
                                      row_default_height=40,
                                      col_force_default=True,
                                      col_default_width=200)
                top_grid.cols = 2

                while True:
                    try:
                        self.speak('End Date')
                        d = f'{next(dtf.find_dates(self.speechInput()))}'.split(
                            ' ')[0]
                        print(d)
                        break
                    except:
                        pass
                # while True:
                #     try:
                #         self.speak('End Time')
                #         t = f'{next(dtf.find_dates(self.speechInput()))}'.split(' ')[1]
                #         print(t)
                #         break
                #     except:
                #         pass

                top_grid.add_widget(Label(text="End Date(YYYY/MM/DD): "))
                endDate = TextInput(text=d, multiline=False)
                top_grid.add_widget(endDate)

                # top_grid.add_widget(Label(text="End Time(hh:mm:ss): "))
                # endTime = TextInput(text = t, multiline=False)
                # top_grid.add_widget(endTime)

                cancelButton = Button(text="Cancel")
                top_grid.add_widget(cancelButton)
                closeButton = Button(text="Search")
                top_grid.add_widget(closeButton)

                # Instantiate the modal popup and display
                popup = Popup(title='Calendar',
                              content=top_grid,
                              size_hint=(None, None),
                              size=(900, 450),
                              auto_dismiss=False)
                popup.open()

                def onClose(miss):
                    popup.dismiss()
                    schedule = account.schedule()
                    calendar = schedule.get_default_calendar()
                    print(endDate)
                    end = list(map(int, str(endDate.text).split('-')))
                    # eTime = list(map(int, str(endTime.text).split(':')))

                    q = calendar.new_query('start').greater_equal(
                        datetime.datetime.today())
                    q.chain('and').on_attribute('end').less_equal(
                        datetime.datetime(end[0], end[1], end[2], 5, 30))
                    events = calendar.get_events(query=q,
                                                 include_recurring=False)

                    allevents = []
                    allevents_text = ""
                    for event in events:
                        print(event)
                        new_event = parse_event(event)
                        print(new_event["date"], new_event["subject"],
                              new_event["from"], new_event["to"])
                        allevents.append(
                            f'{new_event["subject"]} on {new_event["date"]} from {new_event["from"]} to {new_event["to"]}'
                        )
                        allevents_text = f'{new_event["subject"]} on {new_event["date"]} from {new_event["from"]} to {new_event["to"]}' + allevents_text
                        allevents_text += "\n"

                    print(allevents_text)
                    print(q)

                    if len(allevents_text) > 0:
                        top_grid1 = GridLayout(row_force_default=True,
                                               row_default_height=60,
                                               col_force_default=True,
                                               col_default_width=900)

                        top_grid1.cols = 1

                        for e in allevents[::-1]:
                            label1 = Label(text=e)
                            top_grid1.add_widget(label1)

                        # label.pos_hint = top_grid.width/2, top_grid.height/2

                        cancelButton1 = Button(text="Close")
                        top_grid1.add_widget(cancelButton1)

                        # Instantiate the modal popup and display
                        popup1 = Popup(title='All Events',
                                       content=top_grid1,
                                       size_hint=(None, None),
                                       size=(900, 450),
                                       auto_dismiss=False)

                        def onOpen1(miss):
                            self.speak("Your Schedule Looks Like This")
                            for e in allevents[::-1]:
                                self.speak(e)

                        popup1.bind(on_open=onOpen1)
                        popup1.open()

                        cancelButton1.bind(on_press=popup1.dismiss)

                closeButton.bind(on_press=onClose)
                cancelButton.bind(on_press=popup.dismiss)

            elif "add" in command and isAuth:
                # add_event(account)

                top_grid = GridLayout(row_force_default=True,
                                      row_default_height=40,
                                      col_force_default=True,
                                      col_default_width=200)
                top_grid.cols = 2

                # global startDate
                # global endDate, startTime, endTime
                self.speak("Subject of the event")
                s = self.speechInput()

                while True:
                    try:
                        self.speak('Date')
                        d = f'{next(dtf.find_dates(self.speechInput()))}'.split(
                            ' ')[0]
                        print(d)
                        break
                    except:
                        pass
                while True:
                    try:
                        self.speak('Start Time')
                        t = f'{next(dtf.find_dates(self.speechInput()))}'.split(
                            ' ')[1]
                        print(t)
                        break
                    except:
                        pass

                while True:
                    try:
                        self.speak('End Time')
                        t1 = f'{next(dtf.find_dates(self.speechInput()))}'.split(
                            ' ')[1]
                        print(t)
                        break
                    except:
                        pass

                top_grid.add_widget(Label(text="Subject: "))
                subject = TextInput(text=s, multiline=True)
                top_grid.add_widget(subject)

                top_grid.add_widget(Label(text="Start Date(DD-MM-YYYY): "))
                startDate = TextInput(text=d, multiline=False)
                top_grid.add_widget(startDate)

                top_grid.add_widget(Label(text="Start Time(hh:mm): "))
                startTime = TextInput(text=t, multiline=False)
                top_grid.add_widget(startTime)

                top_grid.add_widget(Label(text="End Date(DD-MM-YYYY): "))
                endDate = TextInput(text=d, multiline=False)
                top_grid.add_widget(endDate)

                top_grid.add_widget(Label(text="End Time(hh:mm): "))
                endTime = TextInput(text=t1, multiline=False)
                top_grid.add_widget(endTime)

                cancelButton = Button(text="Cancel")
                top_grid.add_widget(cancelButton)
                closeButton = Button(text="Set")
                top_grid.add_widget(closeButton)

                # Instantiate the modal popup and display
                popup = Popup(title='Outlook Calendar',
                              content=top_grid,
                              size_hint=(None, None),
                              size=(900, 450),
                              auto_dismiss=False)
                popup.open()

                def onClose(miss):
                    try:
                        popup.dismiss()
                        schedule = account.schedule()
                        calendar = schedule.get_default_calendar()
                        new_event = calendar.new_event()
                        new_event.subject = subject.text
                        start = list(map(int, str(startDate.text).split('-')))
                        end = list(map(int, str(endDate.text).split('-')))
                        sTime = list(map(int, str(startTime.text).split(':')))
                        eTime = list(map(int, str(endTime.text).split(':')))

                        print(start, end, sTime, eTime)
                        # new_event.start = datetime.datetime(2021, 3, 7, 14, 30)
                        # new_event.end = datetime.datetime(2021, 3, 7, 15, 0)
                        new_event.start = datetime.datetime(
                            start[0], start[1], start[2], sTime[0], sTime[1])
                        new_event.end = datetime.datetime(
                            end[0], end[1], end[2], eTime[0], eTime[1])
                        new_event.save()

                    except Exception as e:
                        print(e)

                closeButton.bind(on_press=onClose)
                cancelButton.bind(on_press=popup.dismiss)

        elif "mom" in command or (
            ("minutes " in command or "summarize" in command
             or "summarise" in command) and "meeting" in command):
            top_grid = GridLayout(row_force_default=True,
                                  row_default_height=100,
                                  col_force_default=True,
                                  col_default_width=800)
            top_grid.cols = 1

            # label = Label(text=reminder_text)

            top_grid.add_widget(Label(text="File Name: "))
            fileName = TextInput()
            top_grid.add_widget(fileName)
            # label.pos_hint = top_grid.width/2, top_grid.height/2

            bottom_grid = GridLayout(row_force_default=True,
                                     row_default_height=40,
                                     col_force_default=True,
                                     col_default_width=100)
            bottom_grid.cols = 2

            cancelButton = Button(text="Cancel")
            bottom_grid.add_widget(cancelButton)

            submitButton = Button(text="Submit")
            bottom_grid.add_widget(submitButton)

            top_grid.add_widget(bottom_grid)

            # Instantiate the modal popup and display
            popup = Popup(title='Minutes Of Meeting',
                          content=top_grid,
                          size_hint=(None, None),
                          size=(900, 450),
                          auto_dismiss=False)

            popup.open()

            def onSubmit(miss):
                subprocess.Popen(f"python una_mom.py {fileName.text}")
                popup.dismiss()

            submitButton.bind(on_press=onSubmit)
            cancelButton.bind(on_press=popup.dismiss)

        else:
            self.speak('Error')