-
Notifications
You must be signed in to change notification settings - Fork 449
Expand file tree
/
Copy pathconnector.py
More file actions
1214 lines (1032 loc) · 51.4 KB
/
Copy pathconnector.py
File metadata and controls
1214 lines (1032 loc) · 51.4 KB
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from datetime import UTC, datetime, timedelta
from pathlib import Path
from typing import Any
from urllib.parse import urlparse
import httpx
from utils.group_acl import unique_acl_principal_labels
from utils.logging_config import get_logger
from ..base import BaseConnector, ConnectorDocument, DocumentACL
from ..microsoft_graph_acl import (
get_current_user_microsoft_group_roles,
get_current_user_microsoft_principal_labels,
get_current_user_microsoft_principals,
get_oauth_access_token,
microsoft_group_principal_label,
microsoft_group_role,
microsoft_user_principal,
microsoft_user_principal_label,
)
from .oauth import SharePointOAuth
logger = get_logger(__name__)
class SharePointConnector(BaseConnector):
"""SharePoint connector using MSAL-based OAuth for authentication"""
# Required BaseConnector class attributes
CLIENT_ID_ENV_VAR = "MICROSOFT_GRAPH_OAUTH_CLIENT_ID"
CLIENT_SECRET_ENV_VAR = "MICROSOFT_GRAPH_OAUTH_CLIENT_SECRET" # pragma: allowlist secret
# Connector metadata
CONNECTOR_TYPE = "sharepoint"
CONNECTOR_KIND = "oauth"
CONNECTOR_NAME = "SharePoint"
CONNECTOR_DESCRIPTION = "Add knowledge from SharePoint"
CONNECTOR_ICON = "sharepoint"
@classmethod
def get_oauth_class(cls):
from .oauth import SharePointOAuth
return SharePointOAuth
def __init__(self, config: dict[str, Any]):
super().__init__(config)
logger.debug(f"SharePoint connector __init__ called with config type: {type(config)}")
logger.debug(f"SharePoint connector __init__ config value: {config}")
# Ensure we always pass a valid config to the base class
if config is None:
logger.debug("Config was None, using empty dict")
config = {}
try:
logger.debug("Calling super().__init__")
super().__init__(config) # Now safe to call with empty dict instead of None
logger.debug("super().__init__ completed successfully")
except Exception as e:
logger.error(f"super().__init__ failed: {e}")
raise
# Initialize with defaults that allow the connector to be listed
self.client_id = None
self.client_secret = None
self.tenant_id = config.get("tenant_id", "common")
# Graph delta link for webhook change tracking (in-memory per instance)
self._delta_link: str | None = None
# base_url is the generic field name, sharepoint_url is kept for backward compatibility
self.sharepoint_url = config.get("base_url") or config.get("sharepoint_url")
logger.debug(
f"SharePoint connector initialized with sharepoint_url from config: {self.sharepoint_url}"
)
self.redirect_uri = config.get("redirect_uri", "http://localhost")
# Try to get credentials, but don't fail if they're missing
try:
logger.debug("Attempting to get client_id")
self.client_id = self.get_client_id()
logger.debug(f"Got client_id: {self.client_id is not None}")
except Exception as e:
logger.debug(f"Failed to get client_id: {e}")
pass # Credentials not available, that's OK for listing
try:
logger.debug("Attempting to get client_secret")
self.client_secret = self.get_client_secret()
logger.debug(f"Got client_secret: {self.client_secret is not None}")
except Exception as e:
logger.debug(f"Failed to get client_secret: {e}")
pass # Credentials not available, that's OK for listing
# Token file setup - use data directory for persistence
from config.paths import get_data_file
token_file = config.get("token_file") or get_data_file("sharepoint_token.json")
Path(token_file).parent.mkdir(parents=True, exist_ok=True)
# Only initialize OAuth if we have credentials
if self.client_id and self.client_secret:
connection_id = config.get("connection_id", "default")
# Use token_file from config if provided, otherwise generate one
if config.get("token_file"):
oauth_token_file = config["token_file"]
else:
oauth_token_file = get_data_file(f"sharepoint_token_{connection_id}.json")
authority = (
f"https://login.microsoftonline.com/{self.tenant_id}"
if self.tenant_id != "common"
else "https://login.microsoftonline.com/common"
)
self.oauth = SharePointOAuth(
client_id=self.client_id,
client_secret=self.client_secret,
token_file=oauth_token_file,
authority=authority,
)
else:
self.oauth = None
# Track subscription ID for webhooks
self._subscription_id: str | None = None
# Set by setup_subscription/renew_subscription; read by the
# connection manager to persist
self.webhook_resource_id: str | None = None
self.webhook_expiration: str | None = None
# Add Graph API defaults similar to Google Drive flags
self._graph_api_version = "v1.0"
self._default_params = {
"$select": "id,name,size,lastModifiedDateTime,createdDateTime,webUrl,file,folder,@microsoft.graph.downloadUrl"
}
# Selective sync support (similar to Google Drive and OneDrive)
self.cfg = type(
"SharePointConfig",
(),
{
"file_ids": config.get("file_ids")
or config.get("selected_files")
or config.get("selected_file_ids"),
"folder_ids": config.get("folder_ids")
or config.get("selected_folders")
or config.get("selected_folder_ids"),
},
)()
# Cache for file metadata including download URLs
# This allows direct download without Graph API for sharing IDs
self._file_infos: dict[str, dict[str, Any]] = {}
@property
def _graph_base_url(self) -> str:
"""Base URL for Microsoft Graph API calls"""
return f"https://graph.microsoft.com/{self._graph_api_version}"
@property
def base_url(self) -> str | None:
"""Generic base URL property (returns sharepoint_url for SharePoint connector)"""
return self.sharepoint_url
@base_url.setter
def base_url(self, value: str):
"""Set base URL (updates sharepoint_url internally)"""
self.sharepoint_url = value
async def get_current_user_group_roles(self) -> list[str]:
"""Return canonical group ACL roles for the connected Microsoft user."""
return await get_current_user_microsoft_group_roles(
self.oauth,
self._graph_base_url,
tenant_id=self.tenant_id,
)
async def get_current_user_principals(self) -> list[str]:
"""Return canonical user ACL principals for the connected Microsoft user."""
return await get_current_user_microsoft_principals(
self.oauth,
self._graph_base_url,
tenant_id=self.tenant_id,
)
async def get_current_user_principal_labels(self) -> list[dict[str, Any]]:
"""Return display labels for current Microsoft user/group ACL principals."""
return await get_current_user_microsoft_principal_labels(
self.oauth,
self._graph_base_url,
tenant_id=self.tenant_id,
)
def set_file_infos(self, file_infos: list[dict[str, Any]]) -> None:
"""
Cache file metadata including download URLs for later use.
This allows direct download without Graph API calls for sharing IDs.
Args:
file_infos: List of file info dicts with {id, name, mimeType, downloadUrl, size}
"""
self._file_infos = {}
for info in file_infos:
file_id = info.get("id")
if file_id:
self._file_infos[file_id] = info
if info.get("downloadUrl"):
logger.debug(f"Cached download URL for file {file_id}: {info.get('name')}")
def get_cached_file_info(self, file_id: str) -> dict[str, Any] | None:
"""Get cached file info by ID."""
return self._file_infos.get(file_id)
def emit(self, doc: ConnectorDocument) -> None:
"""
Emit a ConnectorDocument instance.
"""
logger.debug(f"Emitting SharePoint document: {doc.id} ({doc.filename})")
async def authenticate(self) -> bool:
"""Test authentication - BaseConnector interface"""
logger.debug(f"SharePoint authenticate() called, oauth is None: {self.oauth is None}")
try:
if not self.oauth:
logger.debug("SharePoint authentication failed: OAuth not initialized")
self._authenticated = False
return False
logger.debug("Loading SharePoint credentials...")
# Try to load existing credentials first
load_result = await self.oauth.load_credentials()
logger.debug(f"Load credentials result: {load_result}")
logger.debug("Checking SharePoint authentication status...")
authenticated = await self.oauth.is_authenticated()
logger.debug(f"SharePoint is_authenticated result: {authenticated}")
self._authenticated = authenticated
return authenticated
except Exception:
logger.exception("[CONNECTOR] SharePoint authentication failed")
self._authenticated = False
return False
def get_auth_url(self) -> str:
"""Get OAuth authorization URL"""
if not self.oauth:
raise RuntimeError("SharePoint OAuth not initialized - missing credentials")
return self.oauth.create_authorization_url(self.redirect_uri)
async def handle_oauth_callback(self, auth_code: str) -> dict[str, Any]:
"""Handle OAuth callback"""
if not self.oauth:
raise RuntimeError("SharePoint OAuth not initialized - missing credentials")
try:
success = await self.oauth.handle_authorization_callback(auth_code, self.redirect_uri)
if success:
self._authenticated = True
# Auto-detect base URL from user's drive
detected_url = await self._detect_base_url()
if detected_url:
self.base_url = detected_url
logger.info(f"Auto-detected base URL: {detected_url}")
return {"status": "success", "base_url": self.base_url}
else:
raise ValueError("OAuth callback failed")
except Exception as e:
logger.error(f"OAuth callback failed: {e}")
raise
async def _detect_base_url(self) -> str | None:
"""Override base class method to detect SharePoint URL"""
return await self._detect_sharepoint_url()
async def _detect_sharepoint_url(self) -> str | None:
"""Auto-detect SharePoint URL from Microsoft Graph API"""
logger.info("_detect_sharepoint_url: Starting SharePoint URL detection")
try:
if not self.oauth:
logger.warning("_detect_sharepoint_url: OAuth not initialized")
return None
access_token = self.oauth.get_access_token()
logger.debug(
f"_detect_sharepoint_url: Got access token (length: {len(access_token) if access_token else 0})"
)
headers = {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json",
}
async with httpx.AsyncClient() as client:
# Get user's default drive to extract SharePoint URL
url = f"{self._graph_base_url}/me/drive"
logger.info(f"_detect_sharepoint_url: Calling Graph API: {url}")
response = await client.get(url, headers=headers, timeout=30.0)
logger.info(
f"_detect_sharepoint_url: Graph API response status: {response.status_code}"
)
if response.status_code == 200:
data = response.json()
web_url = data.get("webUrl", "")
logger.info(f"_detect_sharepoint_url: webUrl from response: {web_url}")
# Extract the SharePoint domain from the webUrl
if web_url:
parsed = urlparse(web_url)
sharepoint_url = f"{parsed.scheme}://{parsed.netloc}"
logger.info(
f"_detect_sharepoint_url: Detected SharePoint URL: {sharepoint_url}"
)
return sharepoint_url
else:
logger.warning("_detect_sharepoint_url: webUrl is empty in response")
else:
logger.warning(
"[CONNECTOR] SharePoint detect URL failed", status_code=response.status_code
)
except Exception:
logger.exception("[CONNECTOR] SharePoint URL detection failed")
return None
def sync_once(self) -> None:
"""
Perform a one-shot sync of SharePoint files and emit documents.
This method mirrors the Google Drive connector's sync_once functionality.
"""
import asyncio
async def _async_sync():
try:
# Get list of files
file_list = await self.list_files(max_files=1000) # Adjust as needed
files = file_list.get("files", [])
for file_info in files:
try:
file_id = file_info.get("id")
if not file_id:
continue
# Get full document content
doc = await self.get_file_content(file_id)
self.emit(doc)
except Exception as e:
logger.error(
f"Failed to sync SharePoint file {file_info.get('name', 'unknown')}: {e}"
)
continue
except Exception as e:
logger.error(f"SharePoint sync_once failed: {e}")
raise
# Run the async sync
if hasattr(asyncio, "run"):
asyncio.run(_async_sync())
else:
# Python < 3.7 compatibility
loop = asyncio.get_event_loop()
loop.run_until_complete(_async_sync())
async def setup_subscription(self) -> str:
"""Set up real-time subscription for file changes - BaseConnector interface"""
webhook_url = self.config.get("webhook_url")
if not webhook_url:
logger.warning("No webhook URL configured, skipping SharePoint subscription setup")
return "no-webhook-configured"
try:
# Ensure we're authenticated
if not await self.authenticate():
raise RuntimeError("SharePoint authentication failed during subscription setup")
token = self.oauth.get_access_token()
# Microsoft Graph subscription for SharePoint site
site_info = self._parse_sharepoint_url()
if site_info:
resource = (
f"sites/{site_info['host_name']}:/sites/{site_info['site_name']}:/drive/root"
)
else:
resource = "/me/drive/root"
subscription_data = {
# Graph driveItem subscriptions only support "updated"; creates and
# deletes still surface through the delta query the webhook triggers.
"changeType": "updated",
# webhook_url is already the full endpoint
# ({WEBHOOK_BASE_URL}/connectors/sharepoint/webhook, set at connect time)
"notificationUrl": webhook_url,
"resource": resource,
"expirationDateTime": self._get_subscription_expiry(),
"clientState": f"sharepoint_{self.tenant_id}",
}
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
url = f"{self._graph_base_url}/subscriptions"
async with httpx.AsyncClient() as client:
response = await client.post(
url, json=subscription_data, headers=headers, timeout=30
)
if response.status_code >= 400:
logger.error(
f"Graph subscription request rejected: {response.status_code} {response.text}"
)
response.raise_for_status()
result = response.json()
subscription_id = result.get("id")
if subscription_id:
self._subscription_id = subscription_id
self.webhook_expiration = result.get("expirationDateTime")
logger.info(f"SharePoint subscription created: {subscription_id}")
return subscription_id
else:
raise ValueError("No subscription ID returned from Microsoft Graph")
except Exception as e:
logger.error(f"Failed to setup SharePoint subscription: {e}")
raise
def _get_subscription_expiry(self) -> str:
"""Get subscription expiry time (max 3 days for Graph API)"""
from datetime import datetime, timedelta
expiry = datetime.now(UTC) + timedelta(days=3) # 3 days max for Graph
return expiry.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
def _parse_sharepoint_url(self) -> dict[str, str] | None:
"""Parse SharePoint URL to extract site information for Graph API"""
if not self.sharepoint_url:
return None
try:
parsed = urlparse(self.sharepoint_url)
# Extract hostname and site name from URL like: https://contoso.sharepoint.com/sites/teamsite
host_name = parsed.netloc
path_parts = parsed.path.strip("/").split("/")
if len(path_parts) >= 2 and path_parts[0] == "sites":
site_name = path_parts[1]
return {"host_name": host_name, "site_name": site_name}
except Exception as e:
logger.warning(f"Could not parse SharePoint URL {self.sharepoint_url}: {e}")
return None
async def list_files(
self, page_token: str | None = None, max_files: int | None = None, **kwargs
) -> dict[str, Any]:
"""List all files using Microsoft Graph API - BaseConnector interface"""
try:
# Ensure authentication
if not await self.authenticate():
raise RuntimeError("SharePoint authentication failed during file listing")
# If file_ids or folder_ids are specified in config, use selective sync
if self.cfg.file_ids or self.cfg.folder_ids:
return await self._list_selected_files()
files = []
max_files_value = max_files if max_files is not None else 100
# Build Graph API URL for the site or fallback to user's OneDrive
site_info = self._parse_sharepoint_url()
if site_info:
base_url = f"{self._graph_base_url}/sites/{site_info['host_name']}:/sites/{site_info['site_name']}:/drive/root/children"
else:
base_url = f"{self._graph_base_url}/me/drive/root/children"
params = dict(self._default_params)
params["$top"] = str(max_files_value)
if page_token:
params["$skiptoken"] = page_token
response = await self._make_graph_request(base_url, params=params)
data = response.json()
items = data.get("value", [])
for item in items:
# Only include files, not folders
if item.get("file"):
files.append(
{
"id": item.get("id", ""),
"name": item.get("name", ""),
"path": f"/drive/items/{item.get('id')}",
"size": int(item.get("size", 0)),
"modified": item.get("lastModifiedDateTime"),
"created": item.get("createdDateTime"),
"mime_type": item.get("file", {}).get(
"mimeType", self._get_mime_type(item.get("name", ""))
),
"url": item.get("webUrl", ""),
"download_url": item.get("@microsoft.graph.downloadUrl"),
}
)
# Check for next page
next_page_token = None
next_link = data.get("@odata.nextLink")
if next_link:
from urllib.parse import parse_qs, urlparse
parsed = urlparse(next_link)
query_params = parse_qs(parsed.query)
if "$skiptoken" in query_params:
next_page_token = query_params["$skiptoken"][0]
return {"files": files, "next_page_token": next_page_token}
except Exception as e:
logger.error(f"Failed to list SharePoint files: {e}")
return {"files": [], "next_page_token": None} # Return empty result instead of raising
async def _extract_sharepoint_acl(self, file_id: str, file_metadata: dict) -> DocumentACL:
"""
Extract ACL from SharePoint item.
Queries Microsoft Graph API permissions endpoint to get allowed users and groups.
Args:
file_id: SharePoint item ID
file_metadata: File metadata dict
Returns:
DocumentACL instance with extracted permissions
"""
try:
# Get access token - use same approach as _make_graph_request
access_token = await get_oauth_access_token(self.oauth)
if not access_token:
logger.warning(f"No access token available for ACL extraction: {file_id}")
return DocumentACL()
# Determine the correct path for permissions API call. Mirror
# _get_file_metadata_by_id: a composite "driveId!itemId" id must be
# split into /drives/{driveId}/items/{itemId}. Using the composite id
# verbatim against /drive/items/{id} yields a malformed URL → Graph
# error → empty ACL, which is why shared-user updates never landed.
if "!" in file_id and len(file_id.rsplit("!", 1)) == 2:
drive_id, item_id = file_id.rsplit("!", 1)
permissions_url = (
f"{self._graph_base_url}/drives/{drive_id}/items/{item_id}/permissions"
)
else:
site_info = self._parse_sharepoint_url()
if site_info:
permissions_url = f"{self._graph_base_url}/sites/{site_info['host_name']}:/sites/{site_info['site_name']}:/drive/items/{file_id}/permissions"
else:
# Fallback to user drive
permissions_url = f"{self._graph_base_url}/me/drive/items/{file_id}/permissions"
# Fetch permissions, following pagination so large share lists are
# captured in full (not just the first page).
permissions: list[dict[str, Any]] = []
async with httpx.AsyncClient() as client:
url: str | None = permissions_url
while url:
response = await client.get(
url, headers={"Authorization": f"Bearer {access_token}"}
)
if response.status_code != 200:
logger.warning(
f"Failed to fetch permissions for {file_id}: {response.status_code}"
)
return DocumentACL()
page = response.json()
permissions.extend(page.get("value", []))
url = page.get("@odata.nextLink")
permissions_data = {"value": permissions}
allowed_users = []
allowed_groups = []
allowed_principals = []
allowed_principal_labels = []
owner = None
for perm in permissions_data.get("value", []):
roles = perm.get("roles", []) # ["read", "write", "owner"]
# Granted to user (grantedTo or grantedToV2)
granted_to = perm.get("grantedToV2") or perm.get("grantedTo")
if granted_to:
user_info = granted_to.get("user", {})
email = user_info.get("email")
display_name = user_info.get("displayName")
user_identifier = email or display_name
if user_identifier:
allowed_users.append(user_identifier)
if "owner" in roles:
owner = user_identifier
for identifier in (
user_info.get("id"),
user_info.get("userPrincipalName"),
email,
):
user_principal = microsoft_user_principal(
identifier,
access_token=access_token,
tenant_id=self.tenant_id,
)
if user_principal:
allowed_principals.append(user_principal)
label = microsoft_user_principal_label(
identifier,
access_token=access_token,
tenant_id=self.tenant_id,
display_name=display_name or email,
email=email,
external_id=identifier,
)
if label:
allowed_principal_labels.append(label)
group_info = granted_to.get("group", {})
group_role = microsoft_group_role(
group_info.get("id"),
access_token=access_token,
tenant_id=self.tenant_id,
)
if group_role:
allowed_groups.append(group_role)
allowed_principals.append(group_role)
label = microsoft_group_principal_label(
group_info.get("id"),
access_token=access_token,
tenant_id=self.tenant_id,
display_name=group_info.get("displayName") or group_info.get("email"),
email=group_info.get("email"),
)
if label:
allowed_principal_labels.append(label)
# Granted to identities (can include users and groups)
if "grantedToIdentitiesV2" in perm or "grantedToIdentities" in perm:
identities = (
perm.get("grantedToIdentitiesV2") or perm.get("grantedToIdentities") or []
)
for identity in identities:
# User
if "user" in identity:
user_info = identity["user"]
email = user_info.get("email")
display_name = user_info.get("displayName")
user_identifier = email or display_name
if user_identifier:
allowed_users.append(user_identifier)
if "owner" in roles:
owner = user_identifier
for identifier in (
user_info.get("id"),
user_info.get("userPrincipalName"),
email,
):
user_principal = microsoft_user_principal(
identifier,
access_token=access_token,
tenant_id=self.tenant_id,
)
if user_principal:
allowed_principals.append(user_principal)
# Group
if "group" in identity:
group_info = identity["group"]
group_id = group_info.get("id")
group_role = microsoft_group_role(
group_id,
access_token=access_token,
tenant_id=self.tenant_id,
)
if group_role:
allowed_groups.append(group_role)
allowed_principals.append(group_role)
label = microsoft_group_principal_label(
group_id,
access_token=access_token,
tenant_id=self.tenant_id,
display_name=group_info.get("displayName")
or group_info.get("email"),
email=group_info.get("email"),
)
if label:
allowed_principal_labels.append(label)
return DocumentACL(
owner=owner,
allowed_users=allowed_users,
allowed_groups=allowed_groups,
allowed_principals=allowed_principals,
allowed_principal_labels=unique_acl_principal_labels(allowed_principal_labels),
)
except Exception as e:
logger.warning(f"Failed to extract ACL for SharePoint item {file_id}: {e}")
return DocumentACL()
async def get_file_content(self, file_id: str) -> ConnectorDocument:
"""Get file content and metadata - BaseConnector interface"""
try:
# Ensure authentication
if not await self.authenticate():
raise RuntimeError("SharePoint authentication failed during file content retrieval")
# First, check for cached file info with download URL
# This is used for SharePoint sharing IDs that can't be resolved via Graph API
cached_info = self.get_cached_file_info(file_id)
if cached_info and cached_info.get("downloadUrl"):
logger.info(f"Using cached download URL for file {file_id}")
content = await self._download_file_from_url(cached_info["downloadUrl"])
# Extract ACL even for cached files
acl = await self._extract_sharepoint_acl(file_id, cached_info)
return ConnectorDocument(
id=file_id,
filename=cached_info.get("name", "Unknown"),
mimetype=cached_info.get("mimeType", "application/octet-stream"),
content=content,
source_url=cached_info.get("webUrl", ""),
acl=acl,
modified_time=datetime.now(),
created_time=datetime.now(),
metadata={
"sharepoint_path": "",
"sharepoint_url": self.sharepoint_url,
"size": cached_info.get("size", 0),
},
)
# Fall back to Graph API for regular file IDs
file_metadata = await self._get_file_metadata_by_id(file_id)
if not file_metadata:
raise ValueError(f"File not found: {file_id}")
# Download file content
download_url = file_metadata.get("download_url")
if download_url:
content = await self._download_file_from_url(download_url)
else:
content = await self._download_file_content(file_id)
# Extract ACL from SharePoint item
acl = await self._extract_sharepoint_acl(file_id, file_metadata)
# Parse dates
modified_time = self._parse_graph_date(file_metadata.get("modified"))
created_time = self._parse_graph_date(file_metadata.get("created"))
return ConnectorDocument(
id=file_id,
filename=file_metadata.get("name", ""),
mimetype=file_metadata.get("mime_type", "application/octet-stream"),
content=content,
source_url=file_metadata.get("url", ""),
acl=acl,
modified_time=modified_time,
created_time=created_time,
metadata={
"sharepoint_path": file_metadata.get("path", ""),
"sharepoint_url": self.sharepoint_url,
"size": file_metadata.get("size", 0),
},
)
except Exception as e:
logger.error(f"Failed to get SharePoint file content {file_id}: {e}")
raise
async def _get_file_metadata_by_id(self, file_id: str) -> dict[str, Any] | None:
"""Get file metadata by ID using Graph API"""
try:
# Check if ID contains '!' which indicates driveId!itemId format
if "!" in file_id:
parts = file_id.rsplit("!", 1)
if len(parts) == 2:
drive_id, item_id = parts
url = f"{self._graph_base_url}/drives/{drive_id}/items/{item_id}"
else:
url = f"{self._graph_base_url}/me/drive/items/{file_id}"
else:
site_info = self._parse_sharepoint_url()
if site_info:
url = f"{self._graph_base_url}/sites/{site_info['host_name']}:/sites/{site_info['site_name']}:/drive/items/{file_id}"
else:
url = f"{self._graph_base_url}/me/drive/items/{file_id}"
params = dict(self._default_params)
response = await self._make_graph_request(url, params=params)
item = response.json()
if item.get("file"):
return {
"id": file_id,
"name": item.get("name", ""),
"path": f"/drive/items/{file_id}",
"size": int(item.get("size", 0)),
"modified": item.get("lastModifiedDateTime"),
"created": item.get("createdDateTime"),
"mime_type": item.get("file", {}).get(
"mimeType", self._get_mime_type(item.get("name", ""))
),
"url": item.get("webUrl", ""),
"download_url": item.get("@microsoft.graph.downloadUrl"),
}
# Check if it's a folder
if item.get("folder"):
return {
"id": file_id,
"name": item.get("name", ""),
"isFolder": True,
}
return None
except Exception as e:
logger.error(
f"Failed to get file metadata for {file_id}: {e}. "
f"Site info: {self._parse_sharepoint_url()}, "
f"SharePoint URL: {self.sharepoint_url}"
)
return None
async def _download_file_content(self, file_id: str) -> bytes:
"""Download file content by file ID using Graph API"""
try:
# Check if ID contains '!' which indicates driveId!itemId format
if "!" in file_id:
parts = file_id.rsplit("!", 1)
if len(parts) == 2:
drive_id, item_id = parts
if not item_id.startswith("s"):
url = f"{self._graph_base_url}/drives/{drive_id}/items/{item_id}/content"
else:
url = f"{self._graph_base_url}/me/drive/items/{file_id}/content"
else:
url = f"{self._graph_base_url}/me/drive/items/{file_id}/content"
else:
site_info = self._parse_sharepoint_url()
if site_info:
url = f"{self._graph_base_url}/sites/{site_info['host_name']}:/sites/{site_info['site_name']}:/drive/items/{file_id}/content"
else:
url = f"{self._graph_base_url}/me/drive/items/{file_id}/content"
token = self.oauth.get_access_token()
headers = {"Authorization": f"Bearer {token}"}
async with httpx.AsyncClient() as client:
response = await client.get(url, headers=headers, timeout=60, follow_redirects=True)
response.raise_for_status()
return response.content
except Exception as e:
logger.error(f"Failed to download file content for {file_id}: {e}")
raise
async def _list_selected_files(self) -> dict[str, Any]:
"""List only selected files/folders (selective sync)."""
files: list[dict[str, Any]] = []
# Process selected file IDs
if self.cfg.file_ids:
for file_id in self.cfg.file_ids:
try:
file_meta = await self._get_file_metadata_by_id(file_id)
if file_meta and not file_meta.get("isFolder", False):
files.append(file_meta)
elif file_meta and file_meta.get("isFolder", False):
# If it's a folder, expand its contents
folder_files = await self._list_folder_contents(file_id)
files.extend(folder_files)
except Exception as e:
logger.warning(f"Failed to get file {file_id}: {e}")
continue
# Process selected folder IDs
if self.cfg.folder_ids:
for folder_id in self.cfg.folder_ids:
try:
folder_files = await self._list_folder_contents(folder_id)
files.extend(folder_files)
except Exception as e:
logger.warning(f"Failed to list folder {folder_id}: {e}")
continue
return {"files": files, "next_page_token": None}
async def _list_folder_contents(self, folder_id: str) -> list[dict[str, Any]]:
"""List all files in a folder recursively."""
files: list[dict[str, Any]] = []
try:
drive_id = None
if "!" in folder_id:
parts = folder_id.rsplit("!", 1)
if len(parts) == 2:
potential_drive_id, item_id = parts
if not item_id.startswith("s"):
drive_id = potential_drive_id
url = f"{self._graph_base_url}/drives/{drive_id}/items/{item_id}/children"
if not drive_id:
site_info = self._parse_sharepoint_url()
if site_info:
url = f"{self._graph_base_url}/sites/{site_info['host_name']}:/sites/{site_info['site_name']}:/drive/items/{folder_id}/children"
else:
url = f"{self._graph_base_url}/me/drive/items/{folder_id}/children"
params = dict(self._default_params)
response = await self._make_graph_request(url, params=params)
data = response.json()
items = data.get("value", [])
for item in items:
parent_ref = item.get("parentReference", {})
item_drive_id = parent_ref.get("driveId") or drive_id
item_id = item.get("id")
if item_id and "!" in item_id:
final_item_id = item_id
else:
final_item_id = f"{item_drive_id}!{item_id}" if item_drive_id else item_id
if item.get("file"): # It's a file
file_meta = {
"id": final_item_id,
"name": item.get("name", ""),
"path": f"/drive/items/{item_id}",
"size": int(item.get("size") or 0),
"modified": item.get("lastModifiedDateTime"),
"created": item.get("createdDateTime"),
"mime_type": item.get("file", {}).get(
"mimeType", self._get_mime_type(item.get("name", ""))
),
"url": item.get("webUrl", ""),
"download_url": item.get("@microsoft.graph.downloadUrl"),
}
files.append(file_meta)
elif item.get("folder"): # It's a subfolder, recurse
subfolder_files = await self._list_folder_contents(final_item_id)
files.extend(subfolder_files)
except Exception as e:
import traceback
logger.error(
f"Failed to list folder contents for {folder_id}: {e}\n{traceback.format_exc()}"
)
return files
async def _download_file_from_url(self, download_url: str) -> bytes:
"""Download file content from direct download URL"""
try:
async with httpx.AsyncClient() as client:
response = await client.get(download_url, timeout=60, follow_redirects=True)
response.raise_for_status()
return response.content
except Exception as e:
logger.error(f"Failed to download from URL {download_url}: {e}")
raise
def _parse_graph_date(self, date_str: str | None) -> datetime:
"""Parse Microsoft Graph date string to datetime"""
if not date_str:
return datetime.now()
try:
if date_str.endswith("Z"):
return datetime.fromisoformat(date_str[:-1]).replace(tzinfo=None)
else:
return datetime.fromisoformat(date_str.replace("T", " "))
except (ValueError, AttributeError):
return datetime.now()
async def _make_graph_request(
self,