nc-py-api: Nextcloud Python Framework

repository·main·Indexed 41 days ago

https://github.com/cloud-py-api/nc_py_api

A robust Python framework for interacting with and extending Nextcloud functionality. It provides a standard client for API requests via the Nextcloud class and a specialized NextcloudApp class for building full-fledged applications using AppAPI and FastAPI. Starting with version 0.30.0, the framework is transitioning to a full async API, introducing AsyncNextcloud and AsyncNextcloudApp to replace synchronous wrappers.

Tokens
25.9K
Snippets
89
Records
115
Agent score
97%

What's inside nc-py-api

  1. Choose between Nextcloud and NextcloudApp classes

    main

    The framework provides two primary classes depending on your use case:

    1. Nextcloud: A standard client used to make API requests using a username and password. Use this for simple scripts or automation tasks.
    2. NextcloudApp: Designed for building full-fledged Nextcloud applications. It utilizes AppAPI to provide features like graphical interfaces and the ability to fulfill requests from different users. It offers a broader selection of APIs than the standard client.

    Compatibility Note: Code written for the Nextcloud class can typically be adapted for NextcloudApp, provided it does not rely on calls requiring user password verification.

  2. Create a Nextcloud skeleton app in Python

    main

    To build a Nextcloud application, use AsyncNextcloudApp in conjunction with FastAPI. The framework provides utilities like run_app, set_handlers, and AppAPIAuthMiddleware to handle the application lifecycle and authentication.

    In the skeleton pattern, you define a lifespan context manager to set up handlers and use run_app to start the server.

    from contextlib import asynccontextmanager
    
    from fastapi import FastAPI
    
    from nc_py_api import AsyncNextcloudApp
    from nc_py_api.ex_app import AppAPIAuthMiddleware, LogLvl, run_app, set_handlers
    
    
    @asynccontextmanager
    async def lifespan(app: FastAPI):
        set_handlers(app, enabled_handler)
        yield
    
    
    APP = FastAPI(lifespan=lifespan)
    APP.add_middleware(AppAPIAuthMiddleware)
    
    
    async def enabled_handler(enabled: bool, nc: AsyncNextcloudApp) -> str:
        if enabled:
            await nc.log(LogLvl.WARNING, "Hello from nc_py_api.")
        else:
            await nc.log(LogLvl.WARNING, "Bye bye from nc_py_api.")
        return ""
    
    
    if __name__ == "__main__":
        run_app("main:APP", log_level="trace")
  3. Install the talk_bot_ai example app

    main

    To install the talk_bot_ai example, you must first have the Nextcloud AppAPI installed. Follow these steps:

    1. Install AppAPI: Ensure the AppAPI app is installed on your Nextcloud instance.
    2. Setup Deployment Daemon: Create a deployment daemon following the AppAPI deployment daemon instructions.
    3. Deploy the App: Use the php occ app_api:app:deploy command to deploy the bot as a Docker image.
    4. Register the App: Use the php occ app_api:app:register command to enable the app and automatically accept all required API scopes.
    # 1. Deploy the bot to Docker
    php occ app_api:app:deploy talk_bot_ai "daemon_deploy_name" \
    --info-xml https://raw.githubusercontent.com/cloud-py-api/nc_py_api/main/examples/as_app/talk_bot_ai/appinfo/info.xml
    
    # 2. Register the app and accept all scopes
    php occ app_api:app:register talk_bot_ai "daemon_deploy_name" --force-scopes \
    --info-xml https://raw.githubusercontent.com/cloud-py-api/nc_py_api/main/examples/as_app/talk_bot_ai/appinfo/info.xml
  4. Install the Talk Bot ExApp

    main

    To deploy and install the talk_bot Example App (ExApp), follow these three steps:

    1. Install the AppAPI: Ensure the AppAPI application is installed on your Nextcloud instance.
    2. Create a deployment daemon: Set up a deployment daemon following the official AppAPI instructions.
    3. Register the app: Use the Nextcloud occ command to register the talk_bot app, providing the required scopes and the remote info.xml file.

    Note: The --force-scopes flag is used during registration to ensure all necessary permissions are granted.

    php occ app_api:app:register talk_bot --force-scopes \
    --info-xml https://raw.githubusercontent.com/cloud-py-api/nc_py_api/main/examples/as_app/talk_bot/appinfo/info.xml
  5. Manage Nextcloud applications

    main

    The application management API allows you to interact with installed applications on a Nextcloud server. It provides two distinct sets of functionality depending on the mode: standard application management (for Nextcloud client mode) and external application management (for external apps).

    Note: Methods like enable and disable do not work in NextcloudApp mode; they are intended for Nextcloud client mode.

  6. How NcSession and NcSessionApp differ

    main

    The library provides two main ways to interact with Nextcloud depending on your use case:

    1. NcSession (Standard User/Client): Used for general client applications. It uses standard authentication (like username/password) to interact with the Nextcloud OCS and WebDAV APIs.
    2. NcSessionApp (AppAPI/Server-side App): Used when developing an application that runs on Nextcloud and uses the AppAPI. It uses AppConfig (requiring app_id, app_version, and app_secret) and automatically handles AppAPI-specific headers like EX-APP-ID, EX-APP-VERSION, and AUTHORIZATION-APP-API for secure communication.
  7. Participant permissions and types in Nextcloud Talk

    main

    Nextcloud Talk uses two main enums to define user roles and capabilities within a conversation:

    ParticipantType

    Defines the permission level of the current user in a conversation:

    • OWNER (1): Creator of the conversation.
    • MODERATOR (2): Moderator of the conversation.
    • USER (3): Regular conversation participant.
    • GUEST (4): Participant without a Nextcloud account.
    • USER_SELF_JOINED (5): User following a public link.
    • GUEST_MODERATOR (6): Moderator without a Nextcloud account.

    AttendeePermissions

    An IntFlag representing the final permissions for a participant. Permissions are resolved in order: attendee -> call -> default. The first CUSTOM permission encountered applies.

    Key flags include:

    • START_CALL (2)
    • JOIN_CALL (4)
    • AUDIO (16)
    • VIDEO (32)
    • SHARE_SCREEN (64)
    • OTHER (128): Post chat messages, share items, and reactions.
  8. Conversation types in Nextcloud Talk

    main

    Nextcloud Talk supports several conversation types, which determine the nature of the chat room. Use the ConversationType enum to identify these types:

    • ONE_TO_ONE (1): Direct One to One chat.
    • GROUP (2): Group conversation (group chat).
    • PUBLIC (3): Group conversation opened to all.
    • CHANGELOG (4): Conversation used by apps to inform about changes.
    • FORMER (5): Converted One-to-One rooms (e.g., when a user is deleted).
    • NOTE_TO_SELF (6): Conversation for personal notes.
    from nc_py_api.talk import ConversationType
    
    # Example check
    if conv.conversation_type == ConversationType.GROUP:
        print("This is a group chat")
  9. Initialize a Nextcloud Session

    main

    To connect to a Nextcloud instance, use the NcSession class for synchronous operations or AsyncNcSession for asynchronous operations. You must provide configuration via kwargs. The configuration can be passed directly or via environment variables (e.g., NEXTCLOUD_URL, NC_AUTH_USER, NC_AUTH_PASS).

    Key configuration parameters include:

    • nextcloud_url: The base URL of your Nextcloud instance.
    • nc_auth_user: Username for authentication.
    • nc_auth_pass: Password for authentication.
    • npa_timeout: Timeout for standard requests.
    • npa_timeout_dav: Timeout for WebDAV requests.
    • npa_nc_cert: SSL certificate verification setting.
    from nc_py_api import NcSession
    
    # Synchronous session
    session = NcSession(
        nextcloud_url="https://nextcloud.example.com",
        nc_auth_user="my_user",
        nc_auth_pass="my_password"
    )
  10. Manage Nextcloud Webhooks

    main

    The Webhooks API allows you to register, update, list, and unregister webhooks that trigger on specific Nextcloud PHP events. You can use either the synchronous _WebhooksAPI (for NcSessionBasic) or the asynchronous _AsyncWebhooksAPI (for AsyncNcSessionBasic).

    Key Operations

    • Register a webhook: Use register() to define an HTTP method, target URI, and the event to listen for.
    • List webhooks: Use get_list(uri_filter=...) to retrieve all webhooks, optionally filtering by URI.
    • Update a webhook: Use update(webhook_id, ...) to modify an existing webhook's configuration.
    • Unregister a webhook: Use unregister(webhook_id) to remove a specific webhook, or unregister_all(appid=...) to remove all webhooks associated with a specific application ID.
    # Example: Registering a new webhook (Synchronous)
    # Assuming 'session' is an instance of NcSessionBasic
    webhooks = _WebhooksAPI(session)
    
    new_webhook = webhooks.register(
        http_method="POST",
        uri="https://your-service.com/webhook",
        event="some.nextcloud.event",
        headers={"X-Custom-Header": "value"}
    )
    print(f"Registered webhook ID: {new_webhook.webhook_id}")
  11. Migrate from sync to async API

    main

    Starting with version 0.30.0, the framework is phasing out synchronous wrappers in favor of a full async API. Several modules, including Activity, Notes, User Status, and Weather Status, no longer have sync counterparts.

    To ensure future compatibility, migrate from the sync Nextcloud or NextcloudApp classes to AsyncNextcloud or AsyncNextcloudApp as soon as possible.

  12. Manage bots in conversations

    main

    Manage bot availability. Note that these methods require the spreed.features.bots-v1 capability.

    • list_bots(): Returns a list of all BotInfo installed on the server.
    • conversation_list_bots(conversation): Returns a list of BotInfoBasic bots that can be enabled for a specific conversation.
    • enable_bot(conversation, bot): Enables a bot for a conversation (requires moderator permissions). bot can be a BotInfoBasic object or a bot ID (int).
    • disable_bot(conversation, bot): Disables a bot for a conversation. bot can be a BotInfoBasic object or a bot ID (int).