import os import streamlit as st import requests import msal from datetime import datetime, timedelta import calendar # Configuration APPLICATION_ID_KEY = os.getenv('APPLICATION_ID_KEY') CLIENT_SECRET_KEY = os.getenv('CLIENT_SECRET_KEY') AUTHORITY_URL = 'https://login.microsoftonline.com/common' REDIRECT_URI = 'https://huggingface.co/spaces/awacke1/MSGraphAPI' # Define product to scope mapping and links PRODUCT_SCOPES = { "📧 Outlook": ['Mail.Read', 'Mail.Send', 'Calendars.ReadWrite'], "📒 OneNote": ['Notes.Read', 'Notes.Create'], "📊 Excel": ['Files.ReadWrite.All'], "📄 Word": ['Files.ReadWrite.All'], "🗃️ SharePoint": ['Sites.Read.All', 'Sites.ReadWrite.All'], "📅 Teams": ['Team.ReadBasic.All', 'Channel.ReadBasic.All'], "💬 Viva": ['Analytics.Read'], "🚀 Power Platform": ['Flow.Read.All'], "🧠 Copilot": ['Cognitive.Read'], "🗂️ OneDrive": ['Files.ReadWrite.All'], "💡 PowerPoint": ['Files.ReadWrite.All'], "📚 Microsoft Bookings": ['Bookings.Read.All', 'Bookings.ReadWrite.All'], "📓 Loop": ['Files.ReadWrite.All'], "🗣️ Translator": ['Translation.Read'], "📋 To Do & Planner": ['Tasks.ReadWrite'], "🔗 Azure OpenAI Service": ['AzureAIServices.ReadWrite.All'] } # AI capabilities and Graph API information 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." } } BASE_SCOPES = ['User.Read'] # MSAL App Instance def get_msal_app(): return msal.ConfidentialClientApplication( client_id=APPLICATION_ID_KEY, client_credential=CLIENT_SECRET_KEY, authority=AUTHORITY_URL ) # Get Access Token def get_access_token(code): client_instance = get_msal_app() try: result = client_instance.acquire_token_by_authorization_code( code=code, scopes=st.session_state.get('request_scopes', BASE_SCOPES), redirect_uri=REDIRECT_URI ) if 'access_token' in result: return result['access_token'] else: raise Exception(f"Error acquiring token: {result.get('error_description')}") except Exception as e: st.error(f"Exception in get_access_token: {str(e)}") raise # Make API call def make_api_call(access_token, endpoint, method='GET', data=None): headers = {'Authorization': f'Bearer {access_token}', 'Content-Type': 'application/json'} url = f'https://graph.microsoft.com/v1.0/{endpoint}' if method == 'GET': response = requests.get(url, headers=headers) elif method == 'POST': response = requests.post(url, headers=headers, json=data) else: raise ValueError(f"Unsupported method: {method}") if response.status_code in [200, 201]: return response.json() else: st.error(f"API call failed: {response.status_code} - {response.text}") return None # Define product integration handlers def handle_outlook_integration(access_token): st.subheader("📧 Outlook Integration") st.markdown(f"[Open Outlook]({PRODUCT_SCOPES['📧 Outlook']['link']})") emails = make_api_call(access_token, 'me/messages?$top=10&$orderby=receivedDateTime desc') if emails and 'value' in emails: for email in emails['value']: with st.expander(f"From: {email['from']['emailAddress']['name']} - Subject: {email['subject']}"): st.write(f"Received: {email['receivedDateTime']}") st.write(f"Body: {email['bodyPreview']}") else: st.write("No emails found or unable to fetch emails.") # More handlers for other products like Calendar, OneDrive, etc., go here... # Main Function def main(): st.title("🦄 MS Graph API with AI & Cloud Integration for M365") # Sidebar product selection st.sidebar.title("📝 M365 Products") st.sidebar.write("Select products to integrate:") selected_products = {} for product, info in products.items(): selected = st.sidebar.checkbox(product) if selected: selected_products[product] = True st.sidebar.write(f"**AI Capabilities:** {info['ai_capabilities']}") st.sidebar.write(f"**Graph API:** {info['graph_api']}") # Request scopes based on selected products request_scopes = BASE_SCOPES.copy() for product in selected_products: request_scopes.extend(PRODUCT_SCOPES[product]) request_scopes = list(set(request_scopes)) # Remove duplicates st.session_state['request_scopes'] = request_scopes # MSAL login and token handling if 'access_token' not in st.session_state: client_instance = get_msal_app() auth_url = client_instance.get_authorization_request_url( scopes=request_scopes, redirect_uri=REDIRECT_URI ) st.write(f'👋 Please [click here]({auth_url}) to log in and authorize the app.') query_params = st.query_params if 'code' in query_params: code = query_params.get('code') st.write(f'🔑 Authorization Code Obtained: {code[:10]}...') try: access_token = get_access_token(code) st.session_state['access_token'] = access_token st.success("Access token acquired successfully!") st.rerun() except Exception as e: st.error(f"Error acquiring access token: {str(e)}") st.stop() else: access_token = st.session_state['access_token'] user_info = make_api_call(access_token, 'me') if user_info: st.sidebar.write(f"👋 Hello, {user_info.get('displayName', 'User')}!") if selected_products: # Integrate selected products for product in selected_products: if product == "📧 Outlook": handle_outlook_integration(access_token) # Add other product integration handlers as needed else: st.write("No products selected. Please select products from the sidebar.") # Sidebar navigation menu with AI capabilities and Graph API descriptions st.sidebar.title("Navigation") menu = st.sidebar.radio("Go to", [ "1️⃣ Dashboard", "🏠 Landing Page", "📅 Upcoming Events", "📆 Schedule", "📝 Agenda", "🔍 Event Details", "➕ Add Event", "🔎 Filter By" ]) # Display AI Capabilities and Graph API Information for the selected menu if menu in selected_products: product_info = products.get(menu, None) if product_info: st.write(f"**AI Capabilities for {menu}:** {product_info['ai_capabilities']}") st.write(f"**Graph API for {menu}:** {product_info['graph_api']}") if __name__ == "__main__": main()