File size: 6,396 Bytes
aeb40fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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
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']
}

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 PRODUCT_SCOPES.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]['scopes'])
    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.experimental_get_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
    st.sidebar.title("Navigation")
    menu = st.sidebar.radio("Go to", [
        "1️⃣ Dashboard",
        "🏠 Landing Page",
        "πŸ“… Upcoming Events",
        "πŸ“† Schedule",
        "πŸ“ Agenda",
        "πŸ” Event Details",
        "βž• Add Event",
        "πŸ”Ž Filter By"
    ])

if __name__ == "__main__":
    main()