MSGraphAPI / backup.101424.app.py
awacke1's picture
Rename app.py to backup.101424.app.py
731c851 verified
raw
history blame
22.2 kB
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()