ms-graph 1.5.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ms_graph/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """ms_graph — A Python client for the Microsoft Graph API."""
2
+
3
+ from ms_graph.client import MicrosoftGraphClient
4
+
5
+ __all__ = ["MicrosoftGraphClient"]
ms_graph/client.py ADDED
@@ -0,0 +1,546 @@
1
+ """ Graph Client class for MSGraphClient objects """
2
+ import json
3
+ import os
4
+ import pathlib
5
+ import random
6
+ import string
7
+ import time
8
+ import urllib
9
+ from typing import Dict, List
10
+
11
+ import msal
12
+ from azkees.az import Az
13
+
14
+ from ms_graph.drive_items import DriveItems
15
+ from ms_graph.drives import Drives
16
+ from ms_graph.groups import Groups
17
+ from ms_graph.logger.logger_setup import log
18
+ from ms_graph.mail import Mail
19
+ from ms_graph.notes import Notes
20
+ from ms_graph.personal_contacts import PersonalContacts
21
+ from ms_graph.search import Search
22
+ from ms_graph.session import GraphSession
23
+ from ms_graph.users import Users
24
+ from ms_graph.workbooks_and_charts.range import Range
25
+ from ms_graph.workbooks_and_charts.table import Table
26
+ from ms_graph.workbooks_and_charts.workbook import Workbooks
27
+
28
+
29
+ class MicrosoftGraphClient:
30
+
31
+ """
32
+ ### Overview:
33
+ ----
34
+ Used as the main entry point for the Microsoft Graph
35
+ API Service.
36
+ """
37
+
38
+ RESOURCE = "https://graph.microsoft.com/"
39
+
40
+ AUTHORITY_URL = "https://login.microsoftonline.com/"
41
+ AUTH_ENDPOINT = "/oauth2/v2.0/authorize?"
42
+ TOKEN_ENDPOINT = "/oauth2/v2.0/token"
43
+
44
+ OFFICE365_AUTHORITY_URL = "https://login.live.com"
45
+ OFFICE365_AUTH_ENDPOINT = "/oauth20_authorize.srf?"
46
+ OFFICE365_TOKEN_ENDPOINT = "/oauth20_token.srf"
47
+
48
+ def __init__(
49
+ self,
50
+ client_id: str,
51
+ client_secret: str,
52
+ redirect_uri: str,
53
+ scope: List[str],
54
+ account_type: str = "consumers",
55
+ office365: bool = False,
56
+ az_client: Az = None,
57
+ credentials: str = None,
58
+ ):
59
+ """Initializes the Graph Client.
60
+
61
+ ### Parameters
62
+ ----
63
+ client_id : str
64
+ The application Client ID assigned when
65
+ creating a new Microsoft App.
66
+
67
+ client_secret : str
68
+ The application Client Secret assigned when
69
+ creating a new Microsoft App.
70
+
71
+ redirect_uri : str
72
+ The application Redirect URI assigned when
73
+ creating a new Microsoft App.
74
+
75
+ scope : List[str]
76
+ The list of scopes you want the application
77
+ to have access to.
78
+
79
+ account_type : str, optional
80
+ [description], by default "common"
81
+
82
+ office365 : bool, optional
83
+ [description], by default False
84
+ """
85
+
86
+ # printing lowercase
87
+ letters = string.ascii_lowercase
88
+
89
+ # handle the credentials object
90
+ # if its a str then handle credentials
91
+ # needs to be handled as dictionary
92
+ # i.e. load the str first and save
93
+ # json to azure key vault if not exists
94
+
95
+ self.is_credential_file = True
96
+ if isinstance(credentials, str):
97
+ self.is_credential_file = False
98
+
99
+ self.credentials = credentials
100
+ self.token_dict = None
101
+
102
+ log.info("Initiating GraphClient Object")
103
+
104
+ self.client_id = client_id
105
+ self.client_secret = client_secret
106
+ self.api_version = "v1.0"
107
+ self.account_type = account_type
108
+ self.redirect_uri = redirect_uri
109
+ self.az_client = az_client
110
+
111
+ self.scope = scope
112
+ self.state = "".join(random.choice(letters) for i in range(10))
113
+
114
+ self.access_token = None
115
+ self.refresh_token = None
116
+ self.graph_session = None
117
+ self.id_token = None
118
+
119
+ self.base_url = self.RESOURCE + self.api_version + "/"
120
+ self.office_url = self.OFFICE365_AUTHORITY_URL + self.OFFICE365_AUTH_ENDPOINT
121
+ self.graph_url = self.AUTHORITY_URL + self.account_type + self.AUTH_ENDPOINT
122
+ self.office365 = office365
123
+ self._redirect_code = None
124
+
125
+ # Initialize the Credential App.
126
+ self.client_app = msal.ConfidentialClientApplication(
127
+ client_id=self.client_id,
128
+ authority=self.AUTHORITY_URL + self.account_type,
129
+ client_credential=self.client_secret,
130
+ )
131
+ self.ms_graph_state_az_key = os.environ.get("key_msgraph_credentials_state")
132
+
133
+ def _state(self, action: str, token_dict: dict = None) -> bool:
134
+ """Sets the session state for the Client Library.
135
+
136
+ ### Arguments
137
+ ----
138
+ action : str
139
+ Defines what action to take when determining the state. Either
140
+ `load` or `save`.
141
+
142
+ token_dict : dict, optional
143
+ If the state is defined as `save` then pass through the
144
+ token dictionary you want to save, by default None.
145
+
146
+ ### Returns
147
+ ----
148
+ bool:
149
+ If the state action was successful, then returns `True`
150
+ otherwise it returns `False`.
151
+ """
152
+
153
+ # Determine if the Credentials file exists or dict exists.
154
+ # if credentials have come from dictionary then this has to be
155
+ # handled seperately hence checking with if else statement
156
+ if self.is_credential_file:
157
+ does_exists = pathlib.Path(self.credentials).exists()
158
+ else:
159
+ does_exists = True
160
+
161
+ # If it exists and we are loading it then proceed.
162
+ if does_exists and action == "load":
163
+
164
+ if self.is_credential_file:
165
+ # Load the file.
166
+ with open(file=self.credentials, mode="r", encoding="utf-8") as state_file:
167
+ credentials = json.load(fp=state_file)
168
+ else:
169
+ credentials = json.loads(self.credentials)
170
+ # Grab the Token if it exists.
171
+ if "refresh_token" in credentials:
172
+
173
+ self.refresh_token = credentials["refresh_token"]
174
+ self.access_token = credentials["access_token"]
175
+ self.id_token = credentials["id_token"]
176
+ self.token_dict = credentials
177
+
178
+ return True
179
+
180
+ else:
181
+ return False
182
+
183
+ # If we are saving the state then open the file and dump the dictionary.
184
+ elif action == "save":
185
+
186
+ token_dict["expires_in"] = time.time(
187
+ ) + int(token_dict["expires_in"])
188
+ token_dict["ext_expires_in"] = time.time() + int(
189
+ token_dict["ext_expires_in"]
190
+ )
191
+
192
+ self.refresh_token = token_dict["refresh_token"]
193
+ self.access_token = token_dict["access_token"]
194
+ self.id_token = token_dict["id_token"]
195
+ self.token_dict = token_dict
196
+
197
+ if self.is_credential_file:
198
+
199
+ # if it is a file then dump to a file
200
+ with open(file=self.credentials, mode="w+", encoding="utf-8") as state_file:
201
+ json.dump(obj=token_dict, fp=state_file, indent=2)
202
+ else:
203
+
204
+ # if not a file then dump to the azure vault
205
+ az_update_result = self.az_client.set_secrets(
206
+ name=self.ms_graph_state_az_key,
207
+ value=json.dumps(obj=token_dict)
208
+ )
209
+
210
+ return az_update_result
211
+
212
+ def _token_seconds(self, token_type: str = "access_token") -> int:
213
+ """Determines time till expiration for a token.
214
+
215
+ Return the number of seconds until the current access token or refresh token
216
+ will expire. The default value is access token because this is the most commonly used
217
+ token during requests.
218
+
219
+ ### Arguments:
220
+ ----
221
+ token_type {str} -- The type of token you would like to determine lifespan for.
222
+ Possible values are ["access_token", "refresh_token"] (default: {access_token})
223
+
224
+ ### Returns:
225
+ ----
226
+ {int} -- The number of seconds till expiration.
227
+ """
228
+
229
+ # Initialize token_exp with a default value.
230
+ token_exp = 0
231
+
232
+ # if needed check the access token.
233
+ if token_type == "access_token":
234
+
235
+ # if the time to expiration is less than or equal to 0, return 0.
236
+ if not self.access_token or (
237
+ time.time() + 60 >= self.token_dict["expires_in"]
238
+ ):
239
+ return 0
240
+
241
+ # else return the number of seconds until expiration.
242
+ token_exp = int(self.token_dict["expires_in"] - time.time() - 60)
243
+
244
+ # if needed check the refresh token.
245
+ elif token_type == "refresh_token":
246
+
247
+ # if the time to expiration is less than or equal to 0, return 0.
248
+ if not self.refresh_token or (
249
+ time.time() + 60 >= self.token_dict["ext_expires_in"]
250
+ ):
251
+ return 0
252
+
253
+ # else return the number of seconds until expiration.
254
+ token_exp = int(
255
+ self.token_dict["ext_expires_in"] - time.time() - 60)
256
+
257
+ return token_exp
258
+
259
+ def _token_validation(self, nseconds: int = 60):
260
+ """Checks if a token is valid.
261
+
262
+ Verify the current access token is valid for at least N seconds, and
263
+ if not then attempt to refresh it. Can be used to assure a valid token
264
+ before making a call to the TD Ameritrade API.
265
+
266
+ Arguments:
267
+ ----
268
+ nseconds {int} -- The minimum number of seconds the token has to be
269
+ valid for before attempting to get a refresh token. (default: {5})
270
+ """
271
+
272
+ if self._token_seconds(token_type="access_token") < nseconds:
273
+ self.grab_refresh_token()
274
+
275
+ def _silent_sso(self) -> bool:
276
+ """Attempts a Silent Authentication using the Access Token and Refresh Token.
277
+
278
+ Returns
279
+ ----
280
+ (bool)
281
+ `True` if it was successful and `False` if it failed.
282
+ """
283
+
284
+ # if the current access token is not expired then we are still authenticated.
285
+ if self._token_seconds(token_type="access_token") > 0:
286
+ return True
287
+
288
+ # if the current access token is expired then try and refresh access token.
289
+ elif self.refresh_token and self.grab_refresh_token():
290
+ return True
291
+
292
+ # More than likely a first time login, so can"t do silent authenticaiton.
293
+ return False
294
+
295
+ def login(self) -> None:
296
+ """Logs the user into the session."""
297
+
298
+ # Load the State.
299
+ self._state(action="load")
300
+
301
+ # Try a Silent SSO First.
302
+ if self._silent_sso():
303
+
304
+ # Set the Session.
305
+ self.graph_session = GraphSession(client=self)
306
+
307
+ return True
308
+
309
+ else:
310
+
311
+ # Build the URL.
312
+ url = self.authorization_url()
313
+
314
+ # aks the user to go to the URL provided, they will be prompted
315
+ # to authenticate themsevles.
316
+ print(f"Please go to URL provided authorize your account: {url}")
317
+
318
+ # ask the user to take the final URL after authentication and
319
+ # paste here so we can parse.
320
+ my_response = input("Paste the full URL redirect here: ")
321
+
322
+ # store the redirect URL
323
+ self._redirect_code = my_response
324
+
325
+ # this will complete the final part of the authentication process.
326
+ self.grab_access_token()
327
+
328
+ # Set the session.
329
+ self.graph_session = GraphSession(client=self)
330
+
331
+ def authorization_url(self):
332
+ """Builds the authorization URL used to get an Authorization Code.
333
+
334
+ ### Returns:
335
+ ----
336
+ A string.
337
+ """
338
+
339
+ # Build the Auth URL.
340
+ auth_url = self.client_app.get_authorization_request_url(
341
+ scopes=self.scope, state=self.state, redirect_uri=self.redirect_uri
342
+ )
343
+
344
+ return auth_url
345
+
346
+ def grab_access_token(self) -> Dict:
347
+ """Exchanges a code for an Access Token.
348
+
349
+ ### Returns:
350
+ ----
351
+ dict : A dictionary containing a new access token and refresh token.
352
+ """
353
+
354
+ # Parse the Code.
355
+ query_dict = urllib.parse.parse_qs(self._redirect_code)
356
+
357
+ # Grab the Code.
358
+ code = query_dict[self.redirect_uri + "?code"]
359
+
360
+ # Grab the Token.
361
+ token_dict = self.client_app.acquire_token_by_authorization_code(
362
+ code=code, scopes=self.scope, redirect_uri=self.redirect_uri
363
+ )
364
+
365
+ # Save the token dict.
366
+ self._state(action="save", token_dict=token_dict)
367
+
368
+ return token_dict
369
+
370
+ def grab_refresh_token(self) -> Dict:
371
+ """Grabs a new access token using a refresh token.
372
+
373
+ ### Returns
374
+ ----
375
+ dict :
376
+ A token dictionary with a new access token.
377
+ """
378
+
379
+ # Grab a new token using our refresh token.
380
+ token_dict = self.client_app.acquire_token_by_refresh_token(
381
+ refresh_token=self.refresh_token, scopes=self.scope
382
+ )
383
+
384
+ if "error" in token_dict:
385
+ raise PermissionError(
386
+ "Permissions not authorized, delete json file and run again."
387
+ )
388
+
389
+ # Save the Token.
390
+ self._state(action="save", token_dict=token_dict)
391
+
392
+ return token_dict
393
+
394
+ def users(self) -> Users:
395
+ """Used to access the User Services and metadata.
396
+
397
+ ### Returns
398
+ ---
399
+ Users:
400
+ The `Users` services Object.
401
+ """
402
+
403
+ # Grab the Users Object for the session.
404
+ users_object: Users = Users(session=self.graph_session)
405
+
406
+ return users_object
407
+
408
+ def drives(self) -> Drives:
409
+ """Used to access the Drives Services and metadata.
410
+
411
+ ### Returns
412
+ ---
413
+ Drives:
414
+ The `Drives` services Object.
415
+ """
416
+
417
+ # Grab the Drives Object for the session.
418
+ drives_object: Drives = Drives(session=self.graph_session)
419
+
420
+ return drives_object
421
+
422
+ def drive_item(self) -> DriveItems:
423
+ """Used to access the Drive Items Services and metadata.
424
+
425
+ ### Returns
426
+ ---
427
+ DriveItems:
428
+ The `DriveItems` services Object.
429
+ """
430
+
431
+ # Grab the Drive Items Object for the session.
432
+ drive_items_object: Drives = DriveItems(session=self.graph_session)
433
+
434
+ return drive_items_object
435
+
436
+ def groups(self) -> Groups:
437
+ """Used to access the Groups Services and metadata.
438
+
439
+ ### Returns
440
+ ---
441
+ Groups:
442
+ The `Groups` services Object.
443
+ """
444
+
445
+ # Grab the `Groups` Object for the session.
446
+ groups_object: Groups = Groups(session=self.graph_session)
447
+
448
+ return groups_object
449
+
450
+ def notes(self) -> Notes:
451
+ """Used to access the OneNotes Services and metadata.
452
+
453
+ ### Returns
454
+ ---
455
+ Notes:
456
+ The `Notes` services Object.
457
+ """
458
+
459
+ # Grab the `Notes` Object for the session.
460
+ notes_object: Notes = Notes(session=self.graph_session)
461
+
462
+ return notes_object
463
+
464
+ def search(self) -> Search:
465
+ """Used to access the Search Services and metadata.
466
+
467
+ ### Returns
468
+ ---
469
+ Search:
470
+ The `Search` services Object.
471
+ """
472
+
473
+ # Grab the `Search` Object for the session.
474
+ search_object: Search = Search(session=self.graph_session)
475
+
476
+ return search_object
477
+
478
+ def personal_contacts(self) -> PersonalContacts:
479
+ """Used to access the PersonalContacts Services and metadata.
480
+
481
+ ### Returns
482
+ ---
483
+ PersonalContacts:
484
+ The `PersonalContacts` services Object.
485
+ """
486
+
487
+ # Grab the `PersonalContacts` Object for the session.
488
+ personal_contacts_object: PersonalContacts = PersonalContacts(
489
+ session=self.graph_session
490
+ )
491
+
492
+ return personal_contacts_object
493
+
494
+ def mail(self) -> Mail:
495
+ """Used to access the Mail Services and metadata.
496
+
497
+ ### Returns
498
+ ---
499
+ Mail:
500
+ The `Mail` services Object.
501
+ """
502
+
503
+ # Grab the `Mail` Object for the session.
504
+ mail_service: Mail = Mail(session=self.graph_session)
505
+
506
+ return mail_service
507
+
508
+ def workbooks(self) -> Workbooks:
509
+ """Used to access the Workbooks Services and metadata.
510
+
511
+ ### Returns
512
+ ---
513
+ Workbooks:
514
+ The `Workbooks` services Object.
515
+ """
516
+
517
+ # Grab the `Workbooks` Object for the session.
518
+ workbook_service: Workbooks = Workbooks(session=self.graph_session)
519
+
520
+ return workbook_service
521
+
522
+ def range(self) -> Range:
523
+ """Used to access the Range Services and metadata.
524
+
525
+ ### Returns
526
+ ---
527
+ Range:
528
+ The `Range` services Object.
529
+ """
530
+
531
+ # Grab the `Range` Object for the session.
532
+ range_service: Range = Range(session=self.graph_session)
533
+
534
+ return range_service
535
+
536
+ def table(self) -> Table:
537
+ """Used to access the Table Services and metadata.
538
+
539
+ ### Returns
540
+ ---
541
+ Table:
542
+ The `Table` services Object.
543
+ """
544
+
545
+ table_service: Table = Table(session=self.graph_session)
546
+ return table_service