-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
301 lines (261 loc) · 9.92 KB
/
server.py
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
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
#!/usr/bin/env python
import json, os, uuid, requests, msal, atexit, blinkt, app_config
from datetime import datetime, timedelta
from flask import Flask, jsonify, make_response, Response, request, redirect, session, url_for, render_template
from flask_apscheduler import APScheduler
from pyngrok import ngrok
###############
## App Setup ##
###############
# FLASK #
app = Flask(__name__)
app.secret_key = os.urandom(16)
app.config.from_object(app_config)
from werkzeug.middleware.proxy_fix import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1)
# APSCHEDULER #
scheduler = APScheduler()
scheduler.api_enabled = True
scheduler.init_app(app)
scheduler.start()
# NGROK #
ngrok.set_auth_token(app_config.NGROK_SECRET)
http_tunnel = ngrok.connect('https://localhost:5000/', bind_tls=True)
# BLINKT #
blinkt.set_clear_on_exit(True)
blinkt.set_brightness(0.2)
blinkt.show()
######################
## Hardware Control ##
######################
def Available():
blinkt.set_all(0, 255, 0)
blinkt.show()
def Busy():
blinkt.set_all(255, 220, 0)
blinkt.show()
def inCall():
blinkt.set_all(255, 0, 0)
blinkt.show()
def Away():
blinkt.set_all(0, 0, 255)
blinkt.show()
def switchOff() :
blinkt.clear()
blinkt.show()
#################
## MSAL ROUTES ##
#################
@app.route("/")
def index():
if not session.get("user"):
return redirect(url_for("login"))
global globalToken
globalToken = _get_token_from_cache(app_config.SCOPE)
if not globalToken:
return redirect(url_for("login"))
return render_template('index.html', user=session["user"])
@app.route("/login")
def login():
session["state"] = str(uuid.uuid4())
auth_url = _build_auth_url(scopes=app_config.SCOPE, state=session["state"])
return render_template("login.html", auth_url=auth_url, version=msal.__version__)
@app.route(app_config.REDIRECT_PATH) # Its absolute URL must match your app's redirect_uri set in AAD
def authorized():
if request.args.get('state') != session.get("state"):
return redirect(url_for("index")) # No-OP. Goes back to Index page
if "error" in request.args: # Authentication/Authorization failure
return render_template("auth_error.html", result=request.args)
if request.args.get('code'):
cache = _load_cache()
result = _build_msal_app(cache=cache).acquire_token_by_authorization_code(
request.args['code'],
scopes=app_config.SCOPE, # Misspelled scope would cause an HTTP 400 error here
redirect_uri=url_for("authorized", _external=True))
if "error" in result:
return render_template("auth_error.html", result=result)
session["user"] = result.get("id_token_claims")
_save_cache(cache)
return redirect(url_for("index"))
@app.route("/logout")
def logout():
session.clear() # Wipe out user and its token cache from session
return redirect( # Also logout from your tenant's web session
app_config.AUTHORITY + "/oauth2/v2.0/logout" +
"?post_logout_redirect_uri=" + url_for("index", _external=True))
def _load_cache():
cache = msal.SerializableTokenCache()
cache.deserialize(open("my_cache.bin", "r").read())
return cache
def _save_cache(cache):
open("my_cache.bin", "w").write(cache.serialize())
def _build_msal_app(cache=None, authority=None):
return msal.ConfidentialClientApplication(
app_config.CLIENT_ID, authority=authority or app_config.AUTHORITY,
client_credential=app_config.CLIENT_SECRET, token_cache=cache)
def _build_auth_url(authority=None, scopes=None, state=None):
return _build_msal_app(authority=authority).get_authorization_request_url(
scopes or [],
state=state or str(uuid.uuid4()),
redirect_uri=url_for("authorized", _external=True))
def _get_token_from_cache(scope=None):
cache = _load_cache() # This web app maintains one cache per session
cca = _build_msal_app(cache=cache)
accounts = cca.get_accounts()
if accounts: # So all account(s) belong to the current signed-in user
result = cca.acquire_token_silent(scope, account=accounts[0])
_save_cache(cache)
return result
###########################
## MSGraph Subscriptions ##
###########################
@app.route("/view_subs")
def get_subscriptions():
globalToken = _get_token_from_cache(app_config.SCOPE)
if not globalToken:
return redirect(url_for("login"))
graph_data = requests.get(
app_config.SUBSCRIPTIONS_ENDPOINT,
headers={'Authorization': 'Bearer ' + globalToken['access_token']}
).json()
if not graph_data.get('value'):
print("")
print("> > >")
print("No Active Subscription")
else:
print("")
print("> > >")
print("Expires: " + graph_data['value'][0]['expirationDateTime'])
return make_response(jsonify(graph_data), 202)
@app.route("/on")
def create_subscription():
global globalToken
globalToken = _get_token_from_cache(app_config.SCOPE)
if not globalToken:
return redirect(url_for("login"))
expireTime = (datetime.utcnow() + timedelta(hours=2)).isoformat() + "2Z"
payload = {
"changeType": "updated",
"notificationUrl": http_tunnel.public_url + '/notify',
"resource": "communications/presences/87cafac4-dd3e-48db-b1f0-63f0788f2ffa",
"expirationDateTime": expireTime
}
graph_data = requests.post(
app_config.SUBSCRIPTIONS_ENDPOINT,
headers={
'Authorization': 'Bearer ' + globalToken['access_token'],
'Content-Type': 'application/json'},
json=payload,
).json()
global globalSub_ID
globalSub_ID = graph_data.get('id')
if not graph_data.get('error'):
print("")
print("> > >")
print("Subscription Successful | Expires: " + graph_data.get('expirationDateTime'))
scheduler.add_job('update_job', update_notification, trigger='interval', minutes=15, misfire_grace_time=30, coalesce=True)
else:
print("")
print("> > >")
print("Subscription ERROR")
print(graph_data.get('error'))
return redirect(url_for("index"))
@app.route("/off")
def remove_subscription():
globalToken = _get_token_from_cache(app_config.SCOPE)
if not globalToken:
return redirect(url_for("login"))
graph_data = requests.get(
app_config.SUBSCRIPTIONS_ENDPOINT,
headers={'Authorization': 'Bearer ' + globalToken['access_token']}
).json()
if not graph_data.get('value'):
print("")
print("> > >")
print("No Subscriptions to Remove")
else:
removeID = app_config.SUBSCRIPTIONS_ENDPOINT + graph_data['value'][0]['id']
remove_request = requests.delete(
removeID,
headers={'Authorization': 'Bearer ' + globalToken['access_token']}
)
print("")
print("> > >")
print("Subscription Removed")
scheduler.remove_all_jobs()
switchOff()
return redirect(url_for("index"))
@app.route("/notify", methods=['POST'])
def notification_received():
valtoken = request.args.get('validationToken')
graph_data = request.json
if valtoken != None: # VALIDATION QUERY RECVD
print("")
print("> > >")
print("- - - - - - - - - - - - - - - - - -")
print("Validation Successful | Valtoken: " + valtoken)
print("- - - - - - - - - - - - - - - - - -")
return Response(valtoken, status=200, content_type="text/plain")
else: # NOTIFICATION RECVD
updatedStatus = graph_data['value'][0]['resourceData']['availability']
updatedActivity = graph_data['value'][0]['resourceData']['activity']
subscriptionID = graph_data['value'][0]['subscriptionId']
subscriptionExp = graph_data['value'][0]['subscriptionExpirationDateTime']
timeLeftSubscription = (datetime.fromisoformat(subscriptionExp[0:19]) - datetime.now()) + timedelta(hours=1)
if updatedStatus in ["Available", "AvailableIdle"]:
Available()
elif updatedStatus in ["Busy", "BusyIdle", "DoNotDisturb"]:
if updatedActivity in ["DoNotDisturb", "InACall", "InAConferenceCall", "Presenting"]:
inCall()
else:
Busy()
elif updatedStatus in ["Away", "BeRightBack"]:
Away()
elif updatedStatus in ["Offline", "PresenceUnknown"]:
switchOff()
else:
pass
print("")
print("> > >")
print("- - - - - - - - - - - - - - - - - -")
print(subscriptionExp)
print("Expires in: " + str(timeLeftSubscription))
print("- - - - - - - - - - - - - - - - - -")
print("> > " + updatedStatus.upper() + " < <")
print("> > " + updatedActivity.upper() + " < <")
print("- - - - - - - - - - - - - - - - - -")
return Response(status=202)
@app.route("/update")
def update_notification():
globalToken = _get_token_from_cache(app_config.SCOPE)
newExpireTime = (datetime.utcnow() + timedelta(hours=2)).isoformat() + "2Z"
update_payload = {
"expirationDateTime": newExpireTime
}
sub_ID_ENDPOINT = app_config.SUBSCRIPTIONS_ENDPOINT + globalSub_ID
update_request = requests.patch(
sub_ID_ENDPOINT,
headers={
'Authorization': 'Bearer ' + globalToken['access_token'],
'Content-Type': 'application/json'},
json=update_payload,
)
print("")
print("> > >")
print("Subscription Updated")
print(update_payload)
print("- - - - - - - - - - - - - - - - -")
print(update_request.text)
return Response(status=202)
##########
## MISC ##
##########
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Not found'}), 404)
def exitScheduler():
if scheduler.running:
scheduler.shutdown(wait=False)
atexit.register(lambda: exitScheduler())
if __name__ == '__main__':
app.run(host='0.0.0.0', ssl_context='adhoc')