Skip to content

Microsoft sharepoint

SharePointReader #

Bases: BasePydanticReader, ResourcesReaderMixin, FileSystemReaderMixin

SharePoint reader.

Reads folders from the SharePoint site from a folder under documents.

Parameters:

Name Type Description Default
client_id str

The Application ID for the app registered in Microsoft Azure Portal. The application must also be configured with MS Graph permissions "Files.ReadAll", "Sites.ReadAll" and BrowserSiteLists.Read.All.

required
client_secret str

The application secret for the app registered in Azure.

required
tenant_id str

Unique identifier of the Azure Active Directory Instance.

required
sharepoint_site_name Optional[str]

The name of the SharePoint site to download from.

None
sharepoint_folder_path Optional[str]

The path of the SharePoint folder to download from.

None
sharepoint_folder_id Optional[str]

The ID of the SharePoint folder to download from. Overrides sharepoint_folder_path.

None
drive_name Optional[str]

The name of the drive to download from.

None
drive_id Optional[str]

The ID of the drive to download from. Overrides drive_name.

None
file_extractor Optional[Dict[str, BaseReader]]

A mapping of file extension to a BaseReader class that specifies how to convert that file to text. See SimpleDirectoryReader for more details.

None
attach_permission_metadata bool

If True, the reader will attach permission metadata to the documents. Set to False if your vector store only supports flat metadata (i.e. no nested fields or lists), or to avoid the additional API calls.

required
Source code in llama-index-integrations/readers/llama-index-readers-microsoft-sharepoint/llama_index/readers/microsoft_sharepoint/base.py
 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
class SharePointReader(BasePydanticReader, ResourcesReaderMixin, FileSystemReaderMixin):
    """
    SharePoint reader.


    Reads folders from the SharePoint site from a folder under documents.

    Args:
        client_id (str): The Application ID for the app registered in Microsoft Azure Portal.
            The application must also be configured with MS Graph permissions "Files.ReadAll", "Sites.ReadAll" and BrowserSiteLists.Read.All.
        client_secret (str): The application secret for the app registered in Azure.
        tenant_id (str): Unique identifier of the Azure Active Directory Instance.
        sharepoint_site_name (Optional[str]): The name of the SharePoint site to download from.
        sharepoint_folder_path (Optional[str]): The path of the SharePoint folder to download from.
        sharepoint_folder_id (Optional[str]): The ID of the SharePoint folder to download from. Overrides sharepoint_folder_path.
        drive_name (Optional[str]): The name of the drive to download from.
        drive_id (Optional[str]): The ID of the drive to download from. Overrides drive_name.
        file_extractor (Optional[Dict[str, BaseReader]]): A mapping of file extension to a BaseReader class that specifies how to convert that
                                                          file to text. See `SimpleDirectoryReader` for more details.
        attach_permission_metadata (bool): If True, the reader will attach permission metadata to the documents. Set to False if your vector store
                                           only supports flat metadata (i.e. no nested fields or lists), or to avoid the additional API calls.
    """

    client_id: str = None
    client_secret: str = None
    tenant_id: str = None
    sharepoint_site_name: Optional[str] = None
    sharepoint_site_id: Optional[str] = None
    sharepoint_folder_path: Optional[str] = None
    sharepoint_folder_id: Optional[str] = None
    file_extractor: Optional[Dict[str, Union[str, BaseReader]]] = Field(
        default=None, exclude=True
    )
    attach_permission_metadata: bool = True
    drive_name: Optional[str] = None
    drive_id: Optional[str] = None

    _authorization_headers = PrivateAttr()
    _site_id_with_host_name = PrivateAttr()
    _drive_id_endpoint = PrivateAttr()
    _drive_id = PrivateAttr()

    def __init__(
        self,
        client_id: str,
        client_secret: str,
        tenant_id: str,
        sharepoint_site_name: Optional[str] = None,
        sharepoint_folder_path: Optional[str] = None,
        sharepoint_folder_id: Optional[str] = None,
        file_extractor: Optional[Dict[str, Union[str, BaseReader]]] = None,
        drive_name: Optional[str] = None,
        drive_id: Optional[str] = None,
        **kwargs: Any,
    ) -> None:
        super().__init__(
            client_id=client_id,
            client_secret=client_secret,
            tenant_id=tenant_id,
            sharepoint_site_name=sharepoint_site_name,
            sharepoint_folder_path=sharepoint_folder_path,
            sharepoint_folder_id=sharepoint_folder_id,
            file_extractor=file_extractor,
            drive_name=drive_name,
            drive_id=drive_id,
            **kwargs,
        )

    @classmethod
    def class_name(cls) -> str:
        return "SharePointReader"

    def _get_access_token(self) -> str:
        """
        Gets the access_token for accessing file from SharePoint.

        Returns:
            str: The access_token for accessing the file.

        Raises:
            ValueError: If there is an error in obtaining the access_token.
        """
        authority = f"https://login.microsoftonline.com/{self.tenant_id}/oauth2/token"

        payload = {
            "grant_type": "client_credentials",
            "client_id": self.client_id,
            "client_secret": self.client_secret,
            "resource": "https://graph.microsoft.com/",
        }

        response = requests.post(
            url=authority,
            data=payload,
        )

        if response.status_code == 200 and "access_token" in response.json():
            return response.json()["access_token"]

        else:
            logger.error(response.json()["error"])
            raise ValueError(response.json()["error_description"])

    def _get_site_id_with_host_name(
        self, access_token, sharepoint_site_name: Optional[str]
    ) -> str:
        """
        Retrieves the site ID of a SharePoint site using the provided site name.

        Args:
            sharepoint_site_name (str): The name of the SharePoint site.

        Returns:
            str: The ID of the SharePoint site.

        Raises:
            Exception: If the specified SharePoint site is not found.
        """
        if hasattr(self, "_site_id_with_host_name"):
            return self._site_id_with_host_name

        self._authorization_headers = {"Authorization": f"Bearer {access_token}"}

        if self.sharepoint_site_id:
            return self.sharepoint_site_id

        if not (sharepoint_site_name):
            raise ValueError("The SharePoint site name or ID must be provided.")

        site_information_endpoint = f"https://graph.microsoft.com/v1.0/sites"

        while site_information_endpoint:
            response = requests.get(
                url=site_information_endpoint,
                headers=self._authorization_headers,
            )

            json_response = response.json()
            if response.status_code == 200 and "value" in json_response:
                if (
                    len(json_response["value"]) > 0
                    and "id" in json_response["value"][0]
                ):
                    # find the site with the specified name
                    for site in json_response["value"]:
                        if (
                            "name" in site
                            and site["name"].lower() == sharepoint_site_name.lower()
                        ):
                            return site["id"]
                    site_information_endpoint = json_response.get(
                        "@odata.nextLink", None
                    )
                else:
                    raise ValueError(
                        f"The specified sharepoint site {sharepoint_site_name} is not found."
                    )
            else:
                if "error_description" in json_response:
                    logger.error(json_response["error"])
                    raise ValueError(json_response["error_description"])
                raise ValueError(json_response["error"])

        raise ValueError(
            f"The specified sharepoint site {sharepoint_site_name} is not found."
        )

    def _get_drive_id(self) -> str:
        """
        Retrieves the drive ID of the SharePoint site.

        Returns:
            str: The ID of the SharePoint site drive.

        Raises:
            ValueError: If there is an error in obtaining the drive ID.
        """
        if hasattr(self, "_drive_id"):
            return self._drive_id

        if self.drive_id:
            return self.drive_id

        self._drive_id_endpoint = f"https://graph.microsoft.com/v1.0/sites/{self._site_id_with_host_name}/drives"

        response = requests.get(
            url=self._drive_id_endpoint,
            headers=self._authorization_headers,
        )

        if response.status_code == 200 and "value" in response.json():
            if len(response.json()["value"]) > 0 and self.drive_name is not None:
                for drive in response.json()["value"]:
                    if drive["name"].lower() == self.drive_name.lower():
                        return drive["id"]
                raise ValueError(f"The specified drive {self.drive_name} is not found.")

            if (
                len(response.json()["value"]) > 0
                and "id" in response.json()["value"][0]
            ):
                return response.json()["value"][0]["id"]
            else:
                raise ValueError(
                    "Error occurred while fetching the drives for the sharepoint site."
                )
        else:
            logger.error(response.json()["error"])
            raise ValueError(response.json()["error_description"])

    def _get_sharepoint_folder_id(self, folder_path: str) -> str:
        """
        Retrieves the folder ID of the SharePoint site.

        Args:
            folder_path (str): The path of the folder in the SharePoint site.

        Returns:
            str: The ID of the SharePoint site folder.
        """
        folder_id_endpoint = (
            f"{self._drive_id_endpoint}/{self._drive_id}/root:/{folder_path}"
        )

        response = requests.get(
            url=folder_id_endpoint,
            headers=self._authorization_headers,
        )

        if response.status_code == 200 and "id" in response.json():
            return response.json()["id"]
        else:
            raise ValueError(response.json()["error"])

    def _download_files_and_extract_metadata(
        self,
        folder_id: str,
        download_dir: str,
        include_subfolders: bool = False,
    ) -> Dict[str, str]:
        """
        Downloads files from the specified folder ID and extracts metadata.

        Args:
            folder_id (str): The ID of the folder from which the files should be downloaded.
            download_dir (str): The directory where the files should be downloaded.
            include_subfolders (bool): If True, files from all subfolders are downloaded.

        Returns:
            Dict[str, str]: A dictionary containing the metadata of the downloaded files.

        Raises:
            ValueError: If there is an error in downloading the files.
        """
        files_path = self.list_resources(
            sharepoint_site_name=self.sharepoint_site_name,
            sharepoint_site_id=self.sharepoint_site_id,
            sharepoint_folder_id=folder_id,
        )

        metadata = {}

        for file_path in files_path:
            item = self._get_item_from_path(file_path)
            metadata.update(self._download_file(item, download_dir))

        return metadata

    def _get_file_content_by_url(self, item: Dict[str, Any]) -> bytes:
        """
        Retrieves the content of the file from the provided URL.

        Args:
            item (Dict[str, Any]): Dictionary containing file metadata.

        Returns:
            bytes: The content of the file.
        """
        file_download_url = item["@microsoft.graph.downloadUrl"]
        response = requests.get(file_download_url)
        if response.status_code != 200:
            logger.error(response.json()["error"])
            raise ValueError(response.json()["error_description"])

        return response.content

    def _download_file_by_url(self, item: Dict[str, Any], download_dir: str) -> str:
        """
        Downloads the file from the provided URL.

        Args:
            item (Dict[str, Any]): Dictionary containing file metadata.
            download_dir (str): The directory where the files should be downloaded.

        Returns:
            str: The path of the downloaded file in the temporary directory.
        """
        # Get the download URL for the file.
        file_name = item["name"]

        content = self._get_file_content_by_url(item)

        # Create the directory if it does not exist and save the file.
        if not os.path.exists(download_dir):
            os.makedirs(download_dir)
        file_path = os.path.join(download_dir, file_name)
        with open(file_path, "wb") as f:
            f.write(content)

        return file_path

    def _get_permissions_info(self, item: Dict[str, Any]) -> Dict[str, str]:
        """
        Extracts the permissions information for the file. For more information, see:
        https://learn.microsoft.com/en-us/graph/api/resources/permission?view=graph-rest-1.0.

        Args:
            item (Dict[str, Any]): Dictionary containing file metadata.

        Returns:
            Dict[str, str]: A dictionary containing the extracted permissions information.
        """
        item_id = item.get("id")
        permissions_info_endpoint = (
            f"{self._drive_id_endpoint}/{self._drive_id}/items/{item_id}/permissions"
        )
        response = requests.get(
            url=permissions_info_endpoint,
            headers=self._authorization_headers,
        )
        permissions = response.json()

        identity_sets = []
        for permission in permissions["value"]:
            # user type permissions
            granted_to = permission.get("grantedToV2", None)
            if granted_to:
                identity_sets.append(granted_to)

            # link type permissions
            granted_to_identities = permission.get("grantedToIdentitiesV2", [])
            for identity in granted_to_identities:
                identity_sets.append(identity)

        # Extract the identity information from each identity set
        # they can be 'application', 'device', 'user', 'group', 'siteUser' or 'siteGroup'
        # 'siteUser' and 'siteGroup' are site-specific, 'group' is for Microsoft 365 groups
        permissions_dict = {}
        for identity_set in identity_sets:
            for identity, identity_info in identity_set.items():
                id = identity_info.get("id")
                display_name = identity_info.get("displayName")
                ids_key = f"allowed_{identity}_ids"
                display_names_key = f"allowed_{identity}_display_names"

                if ids_key not in permissions_dict:
                    permissions_dict[ids_key] = []
                if display_names_key not in permissions_dict:
                    permissions_dict[display_names_key] = []

                permissions_dict[ids_key].append(id)
                permissions_dict[display_names_key].append(display_name)

        # sort to get consistent results, if possible
        for key in permissions_dict:
            try:
                permissions_dict[key] = sorted(permissions_dict[key])
            except TypeError:
                pass

        return permissions_dict

    def _extract_metadata_for_file(self, item: Dict[str, Any]) -> Dict[str, str]:
        """
        Extracts metadata related to the file.

        Parameters:
        - item (Dict[str, str]): Dictionary containing file metadata.

        Returns:
        - Dict[str, str]: A dictionary containing the extracted metadata.
        """
        # Extract the required metadata for file.
        if self.attach_permission_metadata:
            metadata = self._get_permissions_info(item)
        else:
            metadata = {}

        metadata.update(
            {
                "file_id": item.get("id"),
                "file_name": item.get("name"),
                "url": item.get("webUrl"),
                "file_path": item.get("file_path"),
            }
        )

        return metadata

    def _download_file(
        self,
        item: Dict[str, Any],
        download_dir: str,
    ):
        metadata = {}

        file_path = self._download_file_by_url(item, download_dir)

        metadata[file_path] = self._extract_metadata_for_file(item)
        return metadata

    def _download_files_from_sharepoint(
        self,
        download_dir: str,
        sharepoint_site_name: Optional[str],
        sharepoint_folder_path: Optional[str],
        sharepoint_folder_id: Optional[str],
        recursive: bool,
    ) -> Dict[str, str]:
        """
        Downloads files from the specified folder and returns the metadata for the downloaded files.

        Args:
            download_dir (str): The directory where the files should be downloaded.
            sharepoint_site_name (str): The name of the SharePoint site.
            sharepoint_folder_path (str): The path of the folder in the SharePoint site.
            recursive (bool): If True, files from all subfolders are downloaded.

        Returns:
            Dict[str, str]: A dictionary containing the metadata of the downloaded files.

        """
        access_token = self._get_access_token()

        self._site_id_with_host_name = self._get_site_id_with_host_name(
            access_token, sharepoint_site_name
        )

        self._drive_id = self._get_drive_id()

        if not sharepoint_folder_id and sharepoint_folder_path:
            sharepoint_folder_id = self._get_sharepoint_folder_id(
                sharepoint_folder_path
            )

        return self._download_files_and_extract_metadata(
            sharepoint_folder_id,
            download_dir,
            recursive,
        )

    def _exclude_access_control_metadata(
        self, documents: List[Document]
    ) -> List[Document]:
        """
        Excludes the access control metadata from the documents for embedding and LLM calls.

        Args:
            documents (List[Document]): A list of documents.

        Returns:
            List[Document]: A list of documents with access control metadata excluded.
        """
        for doc in documents:
            access_control_keys = [
                key for key in doc.metadata if key.startswith("allowed_")
            ]

            doc.excluded_embed_metadata_keys.extend(access_control_keys)
            doc.excluded_llm_metadata_keys.extend(access_control_keys)

        return documents

    def _load_documents_with_metadata(
        self,
        files_metadata: Dict[str, Any],
        download_dir: str,
        recursive: bool,
    ) -> List[Document]:
        """
        Loads the documents from the downloaded files.

        Args:
            files_metadata (Dict[str,Any]): A dictionary containing the metadata of the downloaded files.
            download_dir (str): The directory where the files should be downloaded.
            recursive (bool): If True, files from all subfolders are downloaded.

        Returns:
            List[Document]: A list containing the documents with metadata.
        """

        def get_metadata(filename: str) -> Any:
            return files_metadata[filename]

        simple_loader = SimpleDirectoryReader(
            download_dir,
            file_extractor=self.file_extractor,
            file_metadata=get_metadata,
            recursive=recursive,
        )
        docs = simple_loader.load_data()
        if self.attach_permission_metadata:
            docs = self._exclude_access_control_metadata(docs)
        return docs

    def load_data(
        self,
        sharepoint_site_name: Optional[str] = None,
        sharepoint_folder_path: Optional[str] = None,
        sharepoint_folder_id: Optional[str] = None,
        recursive: bool = True,
    ) -> List[Document]:
        """
        Loads the files from the specified folder in the SharePoint site.

        Args:
            sharepoint_site_name (Optional[str]): The name of the SharePoint site.
            sharepoint_folder_path (Optional[str]): The path of the folder in the SharePoint site.
            recursive (bool): If True, files from all subfolders are downloaded.

        Returns:
            List[Document]: A list containing the documents with metadata.

        Raises:
            Exception: If an error occurs while accessing SharePoint site.
        """
        # If no arguments are provided to load_data, default to the object attributes
        if not sharepoint_site_name:
            sharepoint_site_name = self.sharepoint_site_name

        if not sharepoint_folder_path:
            sharepoint_folder_path = self.sharepoint_folder_path

        if not sharepoint_folder_id:
            sharepoint_folder_id = self.sharepoint_folder_id

        # TODO: make both of these values optional — and just default to the client ID defaults
        if not (sharepoint_site_name or self.sharepoint_site_id):
            raise ValueError("sharepoint_site_name must be provided.")

        try:
            with tempfile.TemporaryDirectory() as temp_dir:
                files_metadata = self._download_files_from_sharepoint(
                    temp_dir,
                    sharepoint_site_name,
                    sharepoint_folder_path,
                    sharepoint_folder_id,
                    recursive,
                )

                # return self.files_metadata
                return self._load_documents_with_metadata(
                    files_metadata, temp_dir, recursive
                )

        except Exception as exp:
            logger.error("An error occurred while accessing SharePoint: %s", exp)

    def _list_folder_contents(
        self, folder_id: str, recursive: bool, current_path: str
    ) -> List[Path]:
        """
        Helper method to fetch the contents of a folder.

        Args:
            folder_id (str): ID of the folder whose contents are to be listed.
            recursive (bool): Whether to include subfolders recursively.

        Returns:
            List[Path]: List of file paths.
        """
        folder_contents_endpoint = (
            f"{self._drive_id_endpoint}/{self._drive_id}/items/{folder_id}/children"
        )
        response = requests.get(
            url=folder_contents_endpoint,
            headers=self._authorization_headers,
        )
        items = response.json().get("value", [])
        file_paths = []
        for item in items:
            if "folder" in item and recursive:
                # Recursive call for subfolder
                subfolder_id = item["id"]
                subfolder_paths = self._list_folder_contents(
                    subfolder_id, recursive, os.path.join(current_path, item["name"])
                )
                file_paths.extend(subfolder_paths)
            elif "file" in item:
                # Append file path
                file_path = Path(os.path.join(current_path, item["name"]))
                file_paths.append(file_path)

        return file_paths

    def _list_drive_contents(self) -> List[Path]:
        """
        Helper method to fetch the contents of the drive.

        Returns:
            List[Path]: List of file paths.
        """
        drive_contents_endpoint = (
            f"{self._drive_id_endpoint}/{self._drive_id}/root/children"
        )
        response = requests.get(
            url=drive_contents_endpoint,
            headers=self._authorization_headers,
        )
        items = response.json().get("value", [])

        file_paths = []
        for item in items:
            if "folder" in item:
                # Append folder path
                folder_paths = self._list_folder_contents(
                    item["id"], recursive=True, current_path=item["name"]
                )
                file_paths.extend(folder_paths)
            elif "file" in item:
                # Append file path
                file_path = Path(item["name"])
                file_paths.append(file_path)

        return file_paths

    def list_resources(
        self,
        sharepoint_site_name: Optional[str] = None,
        sharepoint_folder_path: Optional[str] = None,
        sharepoint_folder_id: Optional[str] = None,
        sharepoint_site_id: Optional[str] = None,
        recursive: bool = True,
    ) -> List[Path]:
        """
        Lists the files in the specified folder in the SharePoint site.

        Args:
            **kwargs: Additional keyword arguments.

        Returns:
            List[Path]: A list of paths of the files in the specified folder.

        Raises:
            Exception: If an error occurs while accessing SharePoint site.
        """
        # If no arguments are provided to load_data, default to the object attributes
        if not sharepoint_site_name:
            sharepoint_site_name = self.sharepoint_site_name

        if not sharepoint_folder_path:
            sharepoint_folder_path = self.sharepoint_folder_path

        if not sharepoint_folder_id:
            sharepoint_folder_id = self.sharepoint_folder_id

        if not sharepoint_site_id:
            sharepoint_site_id = self.sharepoint_site_id

        if not (sharepoint_site_name or sharepoint_site_id):
            raise ValueError(
                "sharepoint_site_name or sharepoint_site_id must be provided."
            )

        file_paths = []
        try:
            access_token = self._get_access_token()
            self._site_id_with_host_name = self._get_site_id_with_host_name(
                access_token, sharepoint_site_name
            )
            self._drive_id = self._get_drive_id()

            if sharepoint_folder_path:
                if not sharepoint_folder_id:
                    sharepoint_folder_id = self._get_sharepoint_folder_id(
                        sharepoint_folder_path
                    )
                # Fetch folder contents
                folder_contents = self._list_folder_contents(
                    sharepoint_folder_id,
                    recursive,
                    os.path.join(sharepoint_site_name, sharepoint_folder_path),
                )
                file_paths.extend(folder_contents)
            else:
                # Fetch drive contents
                drive_contents = self._list_drive_contents()
                file_paths.extend(drive_contents)
        except Exception as exp:
            logger.error("An error occurred while listing files in SharePoint: %s", exp)
            raise

        return file_paths

    def _get_item_from_path(self, input_file: Path) -> Dict[str, Any]:
        """
        Retrieves the item details for a specified file in SharePoint.

        Args:
            input_file (Path): The path of the file in SharePoint.
                Should include the SharePoint site name and the folder path. e.g. "site_name/folder_path/file_name".

        Returns:
            Dict[str, Any]: Dictionary containing the item details.
        """
        # Get the file ID
        # remove the site_name prefix
        parts = [part for part in input_file.parts if part != self.sharepoint_site_name]
        file_path = "/".join(parts)
        endpoint = f"{self._drive_id_endpoint}/{self._drive_id}/root:/{file_path}"

        response = requests.get(
            url=endpoint,
            headers=self._authorization_headers,
        )

        return response.json()

    def get_resource_info(self, resource_id: str, **kwargs) -> Dict:
        """
        Retrieves metadata for a specified file in SharePoint without downloading it.

        Args:
            input_file (Path): The path of the file in SharePoint. The path should include
                                the SharePoint site name and the folder path. e.g. "site_name/folder_path/file_name".
        """
        try:
            item = self._get_item_from_path(Path(resource_id))

            info_dict = {
                "file_path": resource_id,
                "size": item.get("size"),
                "created_at": item.get("createdDateTime"),
                "modified_at": item.get("lastModifiedDateTime"),
                "etag": item.get("eTag"),
            }

            if (
                self.attach_permission_metadata
            ):  # changes in access control should trigger a reingestion of the file
                permissions = self._get_permissions_info(item)
                info_dict.update(permissions)

            return {
                meta_key: meta_value
                for meta_key, meta_value in info_dict.items()
                if meta_value is not None
            }

        except Exception as exp:
            logger.error(
                "An error occurred while fetching file information from SharePoint: %s",
                exp,
            )
            raise

    def load_resource(self, resource_id: str, **kwargs) -> List[Document]:
        try:
            access_token = self._get_access_token()
            self._site_id_with_host_name = self._get_site_id_with_host_name(
                access_token, self.sharepoint_site_name
            )
            self._drive_id = self._get_drive_id()

            path = Path(resource_id)

            item = self._get_item_from_path(path)

            input_file_dir = path.parent

            with tempfile.TemporaryDirectory() as temp_dir:
                metadata = self._download_file(item, temp_dir, input_file_dir)
                return self._load_documents_with_metadata(
                    metadata, temp_dir, recursive=False
                )

        except Exception as exp:
            logger.error(
                "An error occurred while reading file from SharePoint: %s", exp
            )
            raise

    def read_file_content(self, input_file: Path, **kwargs) -> bytes:
        try:
            access_token = self._get_access_token()
            self._site_id_with_host_name = self._get_site_id_with_host_name(
                access_token, self.sharepoint_site_name
            )
            self._drive_id = self._get_drive_id()

            item = self._get_item_from_path(input_file)
            return self._get_file_content_by_url(item)

        except Exception as exp:
            logger.error(
                "An error occurred while reading file content from SharePoint: %s", exp
            )
            raise

load_data #

load_data(sharepoint_site_name: Optional[str] = None, sharepoint_folder_path: Optional[str] = None, sharepoint_folder_id: Optional[str] = None, recursive: bool = True) -> List[Document]

Loads the files from the specified folder in the SharePoint site.

Parameters:

Name Type Description Default
sharepoint_site_name Optional[str]

The name of the SharePoint site.

None
sharepoint_folder_path Optional[str]

The path of the folder in the SharePoint site.

None
recursive bool

If True, files from all subfolders are downloaded.

True

Returns:

Type Description
List[Document]

List[Document]: A list containing the documents with metadata.

Raises:

Type Description
Exception

If an error occurs while accessing SharePoint site.

Source code in llama-index-integrations/readers/llama-index-readers-microsoft-sharepoint/llama_index/readers/microsoft_sharepoint/base.py
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
def load_data(
    self,
    sharepoint_site_name: Optional[str] = None,
    sharepoint_folder_path: Optional[str] = None,
    sharepoint_folder_id: Optional[str] = None,
    recursive: bool = True,
) -> List[Document]:
    """
    Loads the files from the specified folder in the SharePoint site.

    Args:
        sharepoint_site_name (Optional[str]): The name of the SharePoint site.
        sharepoint_folder_path (Optional[str]): The path of the folder in the SharePoint site.
        recursive (bool): If True, files from all subfolders are downloaded.

    Returns:
        List[Document]: A list containing the documents with metadata.

    Raises:
        Exception: If an error occurs while accessing SharePoint site.
    """
    # If no arguments are provided to load_data, default to the object attributes
    if not sharepoint_site_name:
        sharepoint_site_name = self.sharepoint_site_name

    if not sharepoint_folder_path:
        sharepoint_folder_path = self.sharepoint_folder_path

    if not sharepoint_folder_id:
        sharepoint_folder_id = self.sharepoint_folder_id

    # TODO: make both of these values optional — and just default to the client ID defaults
    if not (sharepoint_site_name or self.sharepoint_site_id):
        raise ValueError("sharepoint_site_name must be provided.")

    try:
        with tempfile.TemporaryDirectory() as temp_dir:
            files_metadata = self._download_files_from_sharepoint(
                temp_dir,
                sharepoint_site_name,
                sharepoint_folder_path,
                sharepoint_folder_id,
                recursive,
            )

            # return self.files_metadata
            return self._load_documents_with_metadata(
                files_metadata, temp_dir, recursive
            )

    except Exception as exp:
        logger.error("An error occurred while accessing SharePoint: %s", exp)

list_resources #

list_resources(sharepoint_site_name: Optional[str] = None, sharepoint_folder_path: Optional[str] = None, sharepoint_folder_id: Optional[str] = None, sharepoint_site_id: Optional[str] = None, recursive: bool = True) -> List[Path]

Lists the files in the specified folder in the SharePoint site.

Parameters:

Name Type Description Default
**kwargs

Additional keyword arguments.

required

Returns:

Type Description
List[Path]

List[Path]: A list of paths of the files in the specified folder.

Raises:

Type Description
Exception

If an error occurs while accessing SharePoint site.

Source code in llama-index-integrations/readers/llama-index-readers-microsoft-sharepoint/llama_index/readers/microsoft_sharepoint/base.py
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
def list_resources(
    self,
    sharepoint_site_name: Optional[str] = None,
    sharepoint_folder_path: Optional[str] = None,
    sharepoint_folder_id: Optional[str] = None,
    sharepoint_site_id: Optional[str] = None,
    recursive: bool = True,
) -> List[Path]:
    """
    Lists the files in the specified folder in the SharePoint site.

    Args:
        **kwargs: Additional keyword arguments.

    Returns:
        List[Path]: A list of paths of the files in the specified folder.

    Raises:
        Exception: If an error occurs while accessing SharePoint site.
    """
    # If no arguments are provided to load_data, default to the object attributes
    if not sharepoint_site_name:
        sharepoint_site_name = self.sharepoint_site_name

    if not sharepoint_folder_path:
        sharepoint_folder_path = self.sharepoint_folder_path

    if not sharepoint_folder_id:
        sharepoint_folder_id = self.sharepoint_folder_id

    if not sharepoint_site_id:
        sharepoint_site_id = self.sharepoint_site_id

    if not (sharepoint_site_name or sharepoint_site_id):
        raise ValueError(
            "sharepoint_site_name or sharepoint_site_id must be provided."
        )

    file_paths = []
    try:
        access_token = self._get_access_token()
        self._site_id_with_host_name = self._get_site_id_with_host_name(
            access_token, sharepoint_site_name
        )
        self._drive_id = self._get_drive_id()

        if sharepoint_folder_path:
            if not sharepoint_folder_id:
                sharepoint_folder_id = self._get_sharepoint_folder_id(
                    sharepoint_folder_path
                )
            # Fetch folder contents
            folder_contents = self._list_folder_contents(
                sharepoint_folder_id,
                recursive,
                os.path.join(sharepoint_site_name, sharepoint_folder_path),
            )
            file_paths.extend(folder_contents)
        else:
            # Fetch drive contents
            drive_contents = self._list_drive_contents()
            file_paths.extend(drive_contents)
    except Exception as exp:
        logger.error("An error occurred while listing files in SharePoint: %s", exp)
        raise

    return file_paths

get_resource_info #

get_resource_info(resource_id: str, **kwargs) -> Dict

Retrieves metadata for a specified file in SharePoint without downloading it.

Parameters:

Name Type Description Default
input_file Path

The path of the file in SharePoint. The path should include the SharePoint site name and the folder path. e.g. "site_name/folder_path/file_name".

required
Source code in llama-index-integrations/readers/llama-index-readers-microsoft-sharepoint/llama_index/readers/microsoft_sharepoint/base.py
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
def get_resource_info(self, resource_id: str, **kwargs) -> Dict:
    """
    Retrieves metadata for a specified file in SharePoint without downloading it.

    Args:
        input_file (Path): The path of the file in SharePoint. The path should include
                            the SharePoint site name and the folder path. e.g. "site_name/folder_path/file_name".
    """
    try:
        item = self._get_item_from_path(Path(resource_id))

        info_dict = {
            "file_path": resource_id,
            "size": item.get("size"),
            "created_at": item.get("createdDateTime"),
            "modified_at": item.get("lastModifiedDateTime"),
            "etag": item.get("eTag"),
        }

        if (
            self.attach_permission_metadata
        ):  # changes in access control should trigger a reingestion of the file
            permissions = self._get_permissions_info(item)
            info_dict.update(permissions)

        return {
            meta_key: meta_value
            for meta_key, meta_value in info_dict.items()
            if meta_value is not None
        }

    except Exception as exp:
        logger.error(
            "An error occurred while fetching file information from SharePoint: %s",
            exp,
        )
        raise