🔍 Code Extractor

function check_all_libraries

Maturity: 47

Discovers and lists all document libraries (drives) in a SharePoint site, displaying their metadata and contents including folders and files.

File:
/tf/active/vicechatdev/SPFCsync/check_libraries.py
Lines:
10 - 103
Complexity:
moderate

Purpose

This function connects to a SharePoint site via Microsoft Graph API to enumerate all available document libraries. For each library, it retrieves and displays metadata (name, ID, type, URL) and inspects the root-level contents, showing the count and names of folders and files. This is useful for SharePoint site exploration, auditing, and understanding the structure of available document repositories.

Source Code

def check_all_libraries():
    """Check all document libraries in the SharePoint site"""
    config = Config()
    
    try:
        client = SharePointGraphClient(
            site_url=config.SHAREPOINT_SITE_URL,
            client_id=config.AZURE_CLIENT_ID,
            client_secret=config.AZURE_CLIENT_SECRET
        )
        
        print("✅ SharePoint Graph client initialized")
        print(f"Site: {config.SHAREPOINT_SITE_URL}")
        print()
        
    except Exception as e:
        print(f"❌ Failed to initialize client: {e}")
        return
    
    print("🔍 CHECKING ALL DOCUMENT LIBRARIES")
    print("=" * 50)
    
    # Get all drives/document libraries
    headers = {
        'Authorization': f'Bearer {client.access_token}',
        'Accept': 'application/json'
    }
    
    try:
        # Get all drives in the site
        drives_url = f"https://graph.microsoft.com/v1.0/sites/{client.site_id}/drives"
        response = requests.get(drives_url, headers=headers)
        
        if response.status_code == 200:
            drives_data = response.json()
            
            if 'value' in drives_data:
                print(f"Found {len(drives_data['value'])} document libraries:")
                print()
                
                for i, drive in enumerate(drives_data['value'], 1):
                    drive_name = drive.get('name', 'Unknown')
                    drive_id = drive.get('id', 'Unknown')
                    web_url = drive.get('webUrl', 'No URL')
                    drive_type = drive.get('driveType', 'unknown')
                    
                    print(f"{i}. Library: {drive_name}")
                    print(f"   ID: {drive_id}")
                    print(f"   Type: {drive_type}")
                    print(f"   URL: {web_url}")
                    
                    # Get root contents of this library
                    if drive_id != client.drive_id:  # Skip the one we already checked
                        print(f"   📁 Checking contents...")
                        root_url = f"https://graph.microsoft.com/v1.0/drives/{drive_id}/root/children"
                        
                        try:
                            root_response = requests.get(root_url, headers=headers)
                            if root_response.status_code == 200:
                                root_data = root_response.json()
                                if 'value' in root_data:
                                    folders = [item for item in root_data['value'] if 'folder' in item]
                                    files = [item for item in root_data['value'] if 'file' in item]
                                    
                                    print(f"   📁 {len(folders)} folders, 📄 {len(files)} files")
                                    
                                    # List folder names
                                    if folders:
                                        print("   Folders:")
                                        for folder in folders[:10]:  # Show first 10
                                            folder_name = folder.get('name', 'Unknown')
                                            print(f"     📁 {folder_name}")
                                        if len(folders) > 10:
                                            print(f"     ... and {len(folders) - 10} more folders")
                                else:
                                    print("   📁 No items found")
                            else:
                                print(f"   ❌ Failed to access: {root_response.status_code}")
                        except Exception as e:
                            print(f"   ❌ Error accessing library: {e}")
                    else:
                        print(f"   📁 This is our main library (already analyzed)")
                    
                    print()
            else:
                print("No document libraries found")
        else:
            print(f"❌ Failed to get document libraries: {response.status_code}")
            print(response.text)
            
    except Exception as e:
        print(f"❌ Error checking document libraries: {e}")
        import traceback
        traceback.print_exc()

Return Value

This function does not return any value (implicitly returns None). It outputs information directly to stdout using print statements, displaying formatted text about discovered document libraries and their contents.

Dependencies

  • requests
  • sharepoint_graph_client
  • config
  • traceback

Required Imports

import requests
from sharepoint_graph_client import SharePointGraphClient
from config import Config

Conditional/Optional Imports

These imports are only needed under specific conditions:

import traceback

Condition: only used when an exception occurs during document library checking to print detailed error information

Optional

Usage Example

# Ensure config.py exists with required settings
# config.py should contain:
# class Config:
#     SHAREPOINT_SITE_URL = 'https://yourtenant.sharepoint.com/sites/yoursite'
#     AZURE_CLIENT_ID = 'your-client-id'
#     AZURE_CLIENT_SECRET = 'your-client-secret'

# Ensure sharepoint_graph_client.py exists with SharePointGraphClient class

from check_all_libraries import check_all_libraries

# Simply call the function - it handles all initialization and output
check_all_libraries()

# Output will be printed to console showing:
# - Initialization status
# - List of all document libraries
# - For each library: name, ID, type, URL
# - Contents of each library (folders and files count)
# - Names of up to 10 folders in each library

Best Practices

  • Ensure Azure AD application has appropriate Microsoft Graph API permissions before running
  • The function prints directly to stdout - consider redirecting output or modifying to return data structures if programmatic access is needed
  • Error handling is implemented but errors are printed rather than raised - wrap in try-except if you need to handle failures programmatically
  • The function limits folder display to 10 items per library to avoid excessive output - modify this limit if needed
  • Access tokens have expiration times - ensure the SharePointGraphClient handles token refresh appropriately
  • The function makes multiple API calls which may be rate-limited by Microsoft Graph - consider implementing retry logic for production use
  • Sensitive credentials (client_id, client_secret) should be stored securely, not hardcoded
  • The function compares drive_id to skip re-analyzing the main library - ensure SharePointGraphClient properly sets this attribute

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function explore_document_libraries 82.7% similar

    Retrieves and displays all document libraries from a SharePoint site using Microsoft Graph API, then explores items within each library.

    From: /tf/active/vicechatdev/SPFCsync/diagnostic_comprehensive.py
  • function explore_all_drives 78.3% similar

    Retrieves and displays all document drives from a SharePoint site using Microsoft Graph API, then explores the root folder of each drive.

    From: /tf/active/vicechatdev/SPFCsync/diagnostic_comprehensive.py
  • function access_main_site_library 75.6% similar

    Authenticates with Microsoft Graph API and attempts to locate and access the main SharePoint site library using multiple discovery approaches, displaying detailed information about sites, drives, and folder structures.

    From: /tf/active/vicechatdev/SPFCsync/find_main_library.py
  • function explore_site_structure 74.0% similar

    Explores and displays the complete structure of a SharePoint site using Microsoft Graph API, including drives, document libraries, lists, and alternative API endpoints.

    From: /tf/active/vicechatdev/SPFCsync/diagnostic_comprehensive.py
  • function explore_library_items 71.6% similar

    Retrieves and displays items from a SharePoint document library using Microsoft Graph API, showing the total count and details of up to 5 items.

    From: /tf/active/vicechatdev/SPFCsync/diagnostic_comprehensive.py
← Back to Browse