Spaces:
Running
Running
import os | |
import streamlit as st | |
import requests | |
import msal | |
import urllib.parse | |
import base64 | |
import hashlib | |
import secrets | |
# π€ 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'] | |
SCOPES = ['User.Read'] | |
# New function to generate PKCE code verifier and challenge | |
def generate_pkce_codes(): | |
code_verifier = secrets.token_urlsafe(128)[:128] | |
code_challenge = base64.urlsafe_b64encode(hashlib.sha256(code_verifier.encode()).digest()).decode().rstrip('=') | |
return code_verifier, code_challenge | |
def get_msal_app(code_challenge=None): | |
return msal.PublicClientApplication( | |
client_id=APPLICATION_ID_KEY, | |
authority=AUTHORITY_URL | |
) | |
# π οΈ Initialize the MSAL client | |
def get_msal_app_old(): | |
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() | |
# Debug: Print MSAL app configuration (be careful not to expose secrets) | |
st.write("Debug: MSAL App Configuration:") | |
st.write(f"Client ID: {APPLICATION_ID_KEY[:5]}...") # Show first 5 chars | |
st.write(f"Authority: {AUTHORITY_URL}") | |
st.write(f"Redirect URI: {REDIRECT_URI}") | |
try: | |
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: | |
error_description = result.get('error_description', 'No error description provided') | |
raise Exception(f"Error acquiring token: {error_description}") | |
except Exception as e: | |
st.error(f"Exception in get_access_token: {str(e)}") | |
raise | |
#st.stop() | |
def get_access_token(code, code_verifier): | |
client_instance = get_msal_app() | |
st.write("Debug: MSAL App Configuration:") | |
st.write(f"Client ID: {APPLICATION_ID_KEY[:5]}...") | |
st.write(f"Authority: {AUTHORITY_URL}") | |
st.write(f"Redirect URI: {REDIRECT_URI}") | |
try: | |
result = client_instance.acquire_token_by_authorization_code( | |
code=code, | |
scopes=SCOPES, | |
redirect_uri=REDIRECT_URI, | |
code_verifier=code_verifier # Include the code verifier here | |
) | |
if 'access_token' in result: | |
return result['access_token'] | |
else: | |
error_description = result.get('error_description', 'No error description provided') | |
raise Exception(f"Error acquiring token: {error_description}") | |
except Exception as e: | |
st.error(f"Exception in get_access_token: {str(e)}") | |
raise | |
def process_query_params(): | |
# βοΈq= Run ArXiv search from query parameters | |
try: | |
query_params = st.query_params | |
st.write("Debug: All query parameters:", query_params) | |
if 'error' in query_params: | |
error = query_params.get('error') | |
error_description = query_params.get('error_description', 'No description provided') | |
st.error(f"Authentication Error: {error}") | |
st.error(f"Error Description: {urllib.parse.unquote(error_description)}") | |
st.stop() | |
if 'code' in query_params: | |
code = query_params.get('code') | |
st.write('π Authorization Code Obtained:', code[:10] + '...') | |
try: | |
code_verifier = st.session_state.get('code_verifier') | |
if not code_verifier: | |
st.error("Code verifier not found in session state.") | |
st.stop() | |
access_token = get_access_token(code, code_verifier) | |
st.session_state['access_token'] = access_token | |
st.success("Access token acquired successfully!") | |
# Clear the code from the URL | |
st.experimental_set_query_params() | |
st.rerun() | |
except Exception as e: | |
st.error(f"Error acquiring access token: {str(e)}") | |
st.stop() | |
else: | |
st.warning("No authorization code found in the query parameters.") | |
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("π¦ MS Graph API with AI & Cloud Integration with M365") | |
process_query_params() | |
if 'access_token' not in st.session_state: | |
if 'code_verifier' not in st.session_state: | |
# Generate PKCE codes | |
code_verifier, code_challenge = generate_pkce_codes() | |
st.session_state['code_verifier'] = code_verifier | |
else: | |
code_verifier = st.session_state['code_verifier'] | |
code_challenge = base64.urlsafe_b64encode(hashlib.sha256(code_verifier.encode()).digest()).decode().rstrip('=') | |
client_instance = get_msal_app() | |
auth_url = client_instance.get_authorization_request_url( | |
scopes=SCOPES, | |
redirect_uri=REDIRECT_URI, | |
code_challenge=code_challenge, | |
code_challenge_method="S256" | |
) | |
st.write('π Please [click here]({}) to log in and authorize the app.'.format(auth_url)) | |
#st.stop() | |
# π Sidebar navigation | |
st.sidebar.title("Navigation") | |
menu = st.sidebar.radio("Go to", [ | |
"1οΈβ£ Dashboard", | |
"π 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.") | |
pass | |
# 𧩠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() | |