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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
import os
import streamlit as st
import requests
import msal

# πŸ€“ Load environment variables (Ensure these are set!)
APPLICATION_ID_KEY = os.getenv('APPLICATION_ID_KEY')
CLIENT_SECRET_KEY = os.getenv('CLIENT_SECRET_KEY')
AUTHORITY_URL = 'https://login.microsoftonline.com/common'  # Use 'common' for multi-tenant apps
#REDIRECT_URI = 'http://localhost:8501'  # πŸ‘ˆ Make sure this matches your app's redirect URI
REDIRECT_URI = 'https://huggingface.co/spaces/awacke1/MSGraphAPI'  # πŸ‘ˆ Make sure this matches your app's redirect URI


# 🎯 Define the scopes your app will need
SCOPES = ['User.Read', 'Calendars.ReadWrite', 'Mail.ReadWrite', 'Notes.ReadWrite.All', 'Files.ReadWrite.All']

# πŸ› οΈ Initialize the MSAL client
def get_msal_app():
    return msal.ConfidentialClientApplication(
        client_id=APPLICATION_ID_KEY,
        client_credential=CLIENT_SECRET_KEY,
        authority=AUTHORITY_URL
    )

# πŸ” Acquire access token using authorization code
def get_access_token(code):
    client_instance = get_msal_app()
    result = client_instance.acquire_token_by_authorization_code(
        code=code,
        scopes=SCOPES,
        redirect_uri=REDIRECT_URI
    )
    if 'access_token' in result:
        return result['access_token']
    else:
        st.error('Error acquiring token: ' + str(result.get('error_description')))
        st.stop()


def process_query_parms():
    # βš™οΈq= Run ArXiv search from query parameters
    try:
        query_params = st.query_params
        query = (query_params.get('q') or query_params.get('query') or [''])
        if len(query) > 1: 
            #result = search_arxiv(query)
            #result2 = search_glossary(result) 
    
            filesearch = PromptPrefix + query
            st.markdown(filesearch)
            process_text(filesearch)
    except:
        st.markdown(' ')
    
    if 'action' in st.query_params:
        action = st.query_params()['action'][0]  # Get the first (or only) 'action' parameter
        if action == 'show_message':
            st.success("Showing a message because 'action=show_message' was found in the URL.")
        elif action == 'clear':
            clear_query_params()
            #st.rerun()
    
    if 'query' in st.query_params:
        query = st.query_params['query'][0]  # Get the query parameter
        # Display content or image based on the query
        display_content_or_image(query)




# πŸƒβ€β™‚οΈ Main application function
def main():
    st.title("πŸ¦„ Simple Streamlit App with MS Graph API")
    
    # πŸš€ Sidebar navigation
    st.sidebar.title("Navigation")
    menu = st.sidebar.radio("Go to", [
        "1️⃣ Dashboard with Widgets",
        "🏠 Landing Page",
        "πŸ“… Upcoming Events",
        "πŸ“† Schedule",
        "πŸ“ Agenda",
        "πŸ” Event Details",
        "βž• Add Event",
        "πŸ”Ž Filter By"
    ])
    
    # πŸ“ M365 Products with MS Graph Integration & AI Features
    st.sidebar.title("πŸ“ M365 Products")
    st.sidebar.write("Toggle integration for each product:")
    
    # πŸŽ›οΈ Product Integration Toggles
    products = {
        "πŸ“§ Outlook": {
            "ai_capabilities": "Copilot for enhanced email writing, calendar management, and scheduling.",
            "graph_api": "Access to mail, calendar, contacts, and events."
        },
        "πŸ“’ OneNote": {
            "ai_capabilities": "Content suggestion, note organization, and OCR for extracting text from images.",
            "graph_api": "Manage notebooks, sections, and pages."
        },
        "πŸ“Š Excel": {
            "ai_capabilities": "Copilot for advanced data analysis, data insights, and formula generation.",
            "graph_api": "Create and manage worksheets, tables, charts, and workbooks."
        },
        "πŸ“„ Word": {
            "ai_capabilities": "Copilot for document drafting, summarization, and grammar improvements.",
            "graph_api": "Document content access, templates, and file management."
        },
        "πŸ—ƒοΈ SharePoint": {
            "ai_capabilities": "Intelligent search, document tagging, and metadata extraction.",
            "graph_api": "Access to sites, lists, files, and document libraries."
        },
        "πŸ“… Teams": {
            "ai_capabilities": "Copilot for meeting summaries, transcription, and chat suggestions.",
            "graph_api": "Manage chats, teams, channels, and meetings."
        },
        "πŸ’¬ Viva": {
            "ai_capabilities": "Personalized learning insights, well-being insights, and productivity suggestions.",
            "graph_api": "Access to user analytics and learning modules."
        },
        "πŸš€ Power Platform": {
            "ai_capabilities": "Automation with AI Builder, data insights, and custom AI models.",
            "graph_api": "Automation workflows, app creation, and data visualization."
        },
        "🧠 Copilot": {
            "ai_capabilities": "Embedded across Word, Excel, Outlook, Teams, and more for AI-driven productivity.",
            "graph_api": "Underpins Copilot's access to data and integrations."
        },
        "πŸ—‚οΈ OneDrive": {
            "ai_capabilities": "Intelligent file organization and search.",
            "graph_api": "File and folder access, sharing, and metadata."
        },
        "πŸ’‘ PowerPoint": {
            "ai_capabilities": "Design suggestions, presentation summarization, and speaker coaching.",
            "graph_api": "Presentation creation, slide management, and templates."
        },
        "πŸ“š Microsoft Bookings": {
            "ai_capabilities": "Automated scheduling and reminders.",
            "graph_api": "Booking calendars, services, and appointment details."
        },
        "πŸ““ Loop": {
            "ai_capabilities": "Real-time collaboration and content suggestions.",
            "graph_api": "Access to shared workspaces and collaborative pages."
        },
        "πŸ—£οΈ Translator": {
            "ai_capabilities": "Real-time language translation and text-to-speech.",
            "graph_api": "Integrated into communication and translation services."
        },
        "πŸ“‹ To Do & Planner": {
            "ai_capabilities": "Task prioritization and smart reminders.",
            "graph_api": "Task creation, management, and synchronization."
        },
        "πŸ”— Azure OpenAI Service": {
            "ai_capabilities": "Access to GPT models for custom AI implementations.",
            "graph_api": "Used indirectly for building custom AI models into workflows."
        }
    }
    
    # πŸ—³οΈ Create toggles for each product
    selected_products = {}
    for product, info in products.items():
        selected = st.sidebar.checkbox(product)
        if selected:
            st.sidebar.write(f"**AI Capabilities:** {info['ai_capabilities']}")
            st.sidebar.write(f"**Graph API:** {info['graph_api']}")
            selected_products[product] = True
    
    # πŸ”‘ Authentication
    if 'access_token' not in st.session_state:
        # πŸ•΅οΈβ€β™‚οΈ Check for authorization code in query parameters
        query_params = st.query_params
        query = (query_params.get('code'))
        #if len(query) > 1: 
        
        st.write('Parsing query ' + query_params )
        if 'code' in query_params:
            #code = query_params['code'][0]
            code = query_params.get('code')
            
            st.write('πŸ”‘Access Code Obtained from MS Graph RedirectπŸ”‘!:' + code)
            
            st.write('πŸ”‘ Acquiring access token from redirect URL for code parameter.')
            access_token = get_access_token(code)
            
            st.session_state['access_token'] = access_token  # πŸ”‘ Save it for later
            
            st.rerun()  # Reload the app to clear the code from URL
        else:
            # πŸ“’ Prompt user to log in
            client_instance = get_msal_app()
            authorization_url = client_instance.get_authorization_request_url(
                scopes=SCOPES,
                redirect_uri=REDIRECT_URI
            )
            st.write('πŸ‘‹ Please [click here]({}) to log in and authorize the app.'.format(authorization_url))
            st.stop()

                
    else:
        # πŸ₯³ User is authenticated, proceed with the app
        access_token = st.session_state['access_token']
        headers = {'Authorization': 'Bearer ' + access_token}
        
        # πŸ€— Greet the user
        response = requests.get('https://graph.microsoft.com/v1.0/me', headers=headers)
        if response.status_code == 200:
            user_info = response.json()
            st.sidebar.write(f"πŸ‘‹ Hello, {user_info['displayName']}!")
        else:
            st.error('Failed to fetch user info.')
            st.write(response.text)
        
        # πŸŽ›οΈ Handle menu options
        if menu == "1️⃣ Dashboard with Widgets":
            st.header("1️⃣ Dashboard with Widgets")
            st.write("Widgets will be displayed here. πŸŽ›οΈ")
            # Add your widgets here
        
        elif menu == "🏠 Landing Page":
            st.header("🏠 Landing Page")
            st.write("Welcome to the app! πŸ₯³")
            # Add landing page content here
        
        elif menu == "πŸ“… Upcoming Events":
            st.header("πŸ“… Upcoming Events")
            events = get_upcoming_events(access_token)
            for event in events:
                st.write(f"πŸ“† {event['subject']} on {event['start']['dateTime']}")
            # Display upcoming events
        
        elif menu == "πŸ“† Schedule":
            st.header("πŸ“† Schedule")
            schedule = get_schedule(access_token)
            st.write(schedule)
            # Display schedule
        
        elif menu == "πŸ“ Agenda":
            st.header("πŸ“ Agenda")
            st.write("Your agenda for today. πŸ“‹")
            # Display agenda
        
        elif menu == "πŸ” Event Details":
            st.header("πŸ” Event Details")
            event_id = st.text_input("Enter Event ID")
            if event_id:
                event_details = get_event_details(access_token, event_id)
                st.write(event_details)
            # Display event details based on ID
        
        elif menu == "βž• Add Event":
            st.header("βž• Add Event")
            event_subject = st.text_input("Event Subject")
            event_start = st.date_input("Event Start Date")
            event_start_time = st.time_input("Event Start Time")
            event_end = st.date_input("Event End Date")
            event_end_time = st.time_input("Event End Time")
            if st.button("Add Event"):
                event_details = {
                    "subject": event_subject,
                    "start": {
                        "dateTime": f"{event_start}T{event_start_time}",
                        "timeZone": "UTC"
                    },
                    "end": {
                        "dateTime": f"{event_end}T{event_end_time}",
                        "timeZone": "UTC"
                    }
                }
                add_event(access_token, event_details)
                st.success("Event added successfully! πŸŽ‰")
            # Form to add new event
        
        elif menu == "πŸ”Ž Filter By":
            st.header("πŸ”Ž Filter Events")
            filter_criteria = st.text_input("Enter filter criteria")
            if filter_criteria:
                filtered_events = filter_events(access_token, filter_criteria)
                for event in filtered_events:
                    st.write(f"πŸ“… {event['subject']} on {event['start']['dateTime']}")
            # Filter events based on criteria
        
        # 🧩 Handle selected products
        if selected_products:
            st.header("🧩 M365 Product Integrations")
            for product in selected_products:
                st.subheader(f"{product}")
                # Call the function corresponding to the product
                handle_product_integration(access_token, product)
        else:
            st.write("No products selected.")
    
# 🧩 Function to handle product integration
def handle_product_integration(access_token, product):
    if product == "πŸ“§ Outlook":
        st.write("Accessing Outlook data...")
        # Implement Outlook integration
        inbox_messages = get_outlook_messages(access_token)
        st.write("Inbox Messages:")
        for msg in inbox_messages:
            st.write(f"βœ‰οΈ {msg['subject']}")
    elif product == "πŸ“’ OneNote":
        st.write("Accessing OneNote data...")
        # Implement OneNote integration
        notebooks = get_onenote_notebooks(access_token)
        st.write("Notebooks:")
        for notebook in notebooks:
            st.write(f"πŸ“” {notebook['displayName']}")
    elif product == "πŸ“Š Excel":
        st.write("Accessing Excel data...")
        # Implement Excel integration
        st.write("Excel integration is a placeholder.")
    elif product == "πŸ“„ Word":
        st.write("Accessing Word documents...")
        # Implement Word integration
        st.write("Word integration is a placeholder.")
    elif product == "πŸ—ƒοΈ SharePoint":
        st.write("Accessing SharePoint sites...")
        # Implement SharePoint integration
        sites = get_sharepoint_sites(access_token)
        st.write("Sites:")
        for site in sites:
            st.write(f"🌐 {site['displayName']}")
    elif product == "πŸ“… Teams":
        st.write("Accessing Teams data...")
        # Implement Teams integration
        teams = get_user_teams(access_token)
        st.write("Teams:")
        for team in teams:
            st.write(f"πŸ‘₯ {team['displayName']}")
    # Add additional product integrations as needed
    else:
        st.write(f"No integration implemented for {product}.")

# πŸ“¨ Function to get Outlook messages
def get_outlook_messages(access_token):
    headers = {'Authorization': 'Bearer ' + access_token}
    response = requests.get('https://graph.microsoft.com/v1.0/me/messages?$top=5', headers=headers)
    if response.status_code == 200:
        messages = response.json().get('value', [])
        return messages
    else:
        st.error('Failed to fetch messages.')
        st.write(response.text)
        return []

# πŸ“” Function to get OneNote notebooks
def get_onenote_notebooks(access_token):
    headers = {'Authorization': 'Bearer ' + access_token}
    response = requests.get('https://graph.microsoft.com/v1.0/me/onenote/notebooks', headers=headers)
    if response.status_code == 200:
        notebooks = response.json().get('value', [])
        return notebooks
    else:
        st.error('Failed to fetch notebooks.')
        st.write(response.text)
        return []

# 🌐 Function to get SharePoint sites
def get_sharepoint_sites(access_token):
    headers = {'Authorization': 'Bearer ' + access_token}
    response = requests.get('https://graph.microsoft.com/v1.0/sites?search=*', headers=headers)
    if response.status_code == 200:
        sites = response.json().get('value', [])
        return sites
    else:
        st.error('Failed to fetch sites.')
        st.write(response.text)
        return []

# πŸ‘₯ Function to get user's Teams
def get_user_teams(access_token):
    headers = {'Authorization': 'Bearer ' + access_token}
    response = requests.get('https://graph.microsoft.com/v1.0/me/joinedTeams', headers=headers)
    if response.status_code == 200:
        teams = response.json().get('value', [])
        return teams
    else:
        st.error('Failed to fetch teams.')
        st.write(response.text)
        return []

# πŸ“… Function to get upcoming events
def get_upcoming_events(access_token):
    headers = {'Authorization': 'Bearer ' + access_token}
    response = requests.get('https://graph.microsoft.com/v1.0/me/events?$orderby=start/dateTime&$top=10', headers=headers)
    if response.status_code == 200:
        events = response.json().get('value', [])
        return events
    else:
        st.error('Failed to fetch upcoming events.')
        st.write(response.text)
        return []

# πŸ“† Function to get schedule (Placeholder)
def get_schedule(access_token):
    # Implement API call to get schedule
    return "πŸ“† Your schedule goes here."

# βž• Function to add a new event
def add_event(access_token, event_details):
    headers = {
        'Authorization': 'Bearer ' + access_token,
        'Content-Type': 'application/json'
    }
    response = requests.post('https://graph.microsoft.com/v1.0/me/events', headers=headers, json=event_details)
    if response.status_code == 201:
        st.success('Event created successfully! πŸŽ‰')
    else:
        st.error('Failed to create event.')
        st.write(response.text)

# πŸ” Function to get event details
def get_event_details(access_token, event_id):
    headers = {'Authorization': 'Bearer ' + access_token}
    response = requests.get(f'https://graph.microsoft.com/v1.0/me/events/{event_id}', headers=headers)
    if response.status_code == 200:
        event = response.json()
        return event
    else:
        st.error('Failed to fetch event details.')
        st.write(response.text)
        return {}

# πŸ”Ž Function to filter events
def filter_events(access_token, filter_criteria):
    headers = {'Authorization': 'Bearer ' + access_token}
    # Implement filtering logic based on criteria
    response = requests.get(f"https://graph.microsoft.com/v1.0/me/events?$filter=startswith(subject,'{filter_criteria}')", headers=headers)
    if response.status_code == 200:
        events = response.json().get('value', [])
        return events
    else:
        st.error('Failed to filter events.')
        st.write(response.text)
        return []

# πŸš€ Run the main function
if __name__ == "__main__":
    main()