0.3.4 • Published 6 months ago

@ixo/matrixclient-sdk v0.3.4

Weekly downloads
-
License
SEE LICENSE IN LI...
Repository
github
Last release
6 months ago

IXO MATRIX CLIENT SDK

ixo GitHub GitHub repo size License: Apache 2.0

Twitter Medium

NodeJSTypeScript

The IXO Matrix Client SDK provides a set of tools for interacting with a Matrix server and associated bot services. With this SDK, developers can query and set Matrix account profiles, manage room details, and work with ACLs and room states using pre-configured or custom home server and bot URLs.

Installation

To install the SDK, add it to your project using npm or yarn:

npm install @ixo/matrixclient-sdk

or

yarn add @ixo/matrixclient-sdk

Getting Started

Once installed, import the SDK components into your project as follows:

import {
  createMatrixApiClient,
  createMatrixRoomBotClient,
  createMatrixStateBotClient,
  createMatrixBidBotClient,
  createMatrixClaimBotClient,
  utils,
} from '@ixo/matrixclient-sdk';

The SDK allows you to create individual clients to interact with different Matrix API and Matrix Bot services. It handles errors by throwing exceptions, so be sure to wrap requests in try...catch blocks.

Matrix API Client

To create a client for interacting with the Matrix API, use the createMatrixApiClient function. This client provides methods for uploading media, managing user profiles and room details.

const matrixApiClient = createMatrixApiClient({
  homeServerUrl: 'https://your-homeserver-url',
  accessToken: 'your-access-token' // optional
});

| Note: The access token is optional but required for protected endpoints. Omitting it will limit functionality to public endpoints.

Account

The account API allows you to query information about your account access token.

  • queryWhoAmI: Get information about the owner the provided access token.
    const whoAmI = await matrixApiClient.account.v1beta1.queryWhoAmI()
    console.log(response)

Event

The event API allows you to query event or threads with all the related details and content. Ensure the provided access token is up-to-date and active. If the room containing the requested event uses end-to-end encrypted, the responses could be returned encrypted with event type of m.room.encrypted.

  • queryEvent: Query a specific event based on its room and event ID.
    const event = await matrixApiClient.event.v1beta1.queryEvent(
      '!roomId:homeserver.url',
      '$1a2b3c...7x8y9z'
    )
    console.log(event)
  • queryChildEvents: Query events in a thread or as a reply to a specific parent event.
    const childEvents = await matrixApiClient.event.v1beta1.queryChildEvents(
      '!roomId:homeserver.url',
      '$1a2b3c...7x8y9z'
    )
    console.log(childEvents)
  • queryChildEventsByRelType: Query events in a thread or as a reply to a specific parent event filtered based on the relation to the parent event.
    const childEvents = await matrixApiClient.event.v1beta1.queryChildEventsByRelType(
      '!roomId:homeserver.url',
      '$1a2b3c...7x8y9z',
      'm.thread', // fetch thread events
    )
    console.log(childEvents)
  • queryChildEventsByRelTypeAndEventType: Query events in a thread or as a reply to a specific parent event filtered based on the relation to the parent event and the specific event type.
    const childEvents = await matrixApiClient.event.v1beta1.queryChildEventsByRelTypeAndEventType(
      '!roomId:homeserver.url',
      '$1a2b3c...7x8y9z',
      'm.thread', // fetch thread events
      'm.room.message', // only message events
    )
    console.log(childEvents)

Media

The media API allows you to upload files such as pdf or images. These files will be public on the homeserver content repository. Here are the main methods:

  • upload: Upload a file.
    const profile = await matrixApiClient.media.v1beta1.upload(
      'profile_image.png', // file name
      'media/png', // content type
      file // file
    );
    console.log(response.content_uri);

| Tip: Use the mxcUrlToHttp utility to convert an MXC URL to an HTTP URL.

Profile

The profile API allows you to retrieve and modify user profile details, including display names and avatar URLs. Here are the main methods:

  • queryProfile: Fetches the full profile of a user.
    const profile = await matrixApiClient.profile.v1beta1.queryProfile('@user:homeserver.url');
    console.log(profile.displayname, profile.avatar_url);
  • queryDisplayname: Fetches the display name of a user.
    const displayname = await matrixApiClient.profile.v1beta1.queryDisplayname('@user:homeserver.url');
    console.log(displayname);
  • setDisplayname: Sets the display name of a user.
    const displayname = await matrixApiClient.profile.v1beta1.setDisplayname('@user:homeserver.url', 'John Doe');
    console.log(displayname);
  • queryAvatarUrl: Fetches the avatar URL of a user.
    const avatarUrl = await matrixApiClient.profile.v1beta1.queryAvatarUrl('@user:homeserver.url');
    console.log(avatarUrl);
  • setAvatarUrl: Sets the avatar URL of a user.
    const avatarUrl = await matrixApiClient.profile.v1beta1.setAvatarUrl('@user:homeserver.url', 'mxc://matrix.org/abc123');
    console.log(avatarUrl);

| Tip: Use the mxcUrlToHttp utility to convert an MXC URL to an HTTP URL.

Room

The room API provides methods for retrieving and modifying room details and for managing membership:

  • queryId: Retrieves a room's ID using its alias.
    const roomInfo = await matrixApiClient.room.v1beta1.queryId('#roomAlias:homeserver.url');
    console.log(roomInfo.room_id, roomInfo.servers);
  • queryVisibility: Retrieves the visibility status of a room.
    const visibility = await matrixApiClient.room.v1beta1.queryVisibility('!roomId:homeserver.url');
    console.log(visibility);
  • setVisibility: Sets the visibility status of a room.
    const response = await matrixApiClient.room.v1beta1.setVisibility('!roomId:homeserver.url', 'private');
    console.log(response);
  • knock: Knocks on a room to request a join from the room admin.
    const knockResponse = await matrixApiClient.room.v1beta1.knock('!roomId:homeserver.url');
    console.log(knockResponse.room_id);
  • join: Joins a room (requires an invite).
    const joinResponse = await matrixApiClient.room.v1beta1.join('!roomId:homeserver.url');
    console.log(joinResponse.room_id);
  • listJoinedRooms: Lists all rooms the user has joined. This method checks the rooms associated with the provided access token and does not require a user ID or alias.
    const listJoinedRoomsResponse = await matrixApiClient.room.v1beta1.listJoinedRooms();
    console.log(listJoinedRoomsResponse.joined_rooms);
  • listJoinedMembers: Lists all members of a room along with their profile details (display name, avatar). The user making the request must be a member of the room.
    const listJoinedMembersResponse = await matrixApiClient.room.v1beta1.listJoinedMembers('!roomId:homeserver.url');
    console.log(listJoinedMembersResponse.joined);
  • leave: Leaves a room. The user can provide an optional reason.
    const leaveResponse = await matrixApiClient.room.v1beta1.leave('!roomId:homeserver.url', 'leaving');
    console.log(leaveResponse.room_id);
  • kick: Kicks a user from a room if the user issuing the request has the necessary power level.
    const kickResponse = await matrixApiClient.room.v1beta1.kick('!roomId:homeserver.url', '@user:homeserver.url', 'kicking');
    console.log(kickResponse.room_id);

Room Bot Client

The Room Bot client provides additional functionality for automating entity room management through bots. Use the createMatrixRoomBotClient function to create the bot client.

const matrixRoomBotClient = createMatrixRoomBotClient({
  homeServerUrl: 'https://your-homeserver-url',
  botUrl: 'https://your-bot-url',
  accessToken: 'your-access-token'
});

Room

Room Bot methods include managing entity rooms and invitations:

  • sourceRoom: Sources an entity room by its IID document (DID). If the room does not exist, it will be created. This method will also invite the user to the entity room if they have not been invited before.
    const sourceRoomResponse = await matrixRoomBotClient.room.v1beta1.sourceRoom('did:ixo:entity:abc...xyz');
    console.log(sourceRoomResponse.room_id);
  • sourceRoomAndJoin: Similar to sourceRoom but also joins the entity room if the user is not already a member.
    const sourceRoomAndJoinResponse = await matrixRoomBotClient.room.v1beta1.sourceRoomAndJoin('did:ixo:entity:abc...xyz');
    console.log(sourceRoomAndJoinResponse.room_id);
  • roomInvite: Invites the user to the entity room if the room exists, regardless of whether the user has been invited to the room before.
    const roomInviteResponse = await matrixRoomBotClient.room.v1beta1.roomInvite('did:ixo:entity:abc...xyz');
    console.log(roomInviteResponse.room_id);
  • roomInviteAndJoin: Similar to roomInvite but also joins the room if the user is not already a member.
    const roomInviteAndJoinResponse = await matrixRoomBotClient.room.v1beta1.roomInviteAndJoin('did:ixo:entity:abc...xyz');
    console.log(roomInviteAndJoinResponse.room_id);

State Bot Client

The State Bot client allows managing room state and ACLs. Create the client using the createMatrixStateBotClient function:

const matrixStateBotClient = createMatrixStateBotClient({
  botUrl: 'https://your-bot-url',
  accessToken: 'your-access-token' // optional
});

ACL

The state bot ACL methods allow you to retrieve access control lists (ACLs) for rooms, which specify what users or groups can access or edit certain parts of the room. The state bot fetches the acl for a given key and optional path. If no path is provided (path = ''), the acl for the overall state object under the key is returned.

  • queryAcl: Fetches the ACL data for a room. Note that '*' means all users.
    const aclData = await matrixStateBotClient.acl.v1beta1.queryAcl(
      '!roomId:homeserver.url',
      'impactsX',
      'profile'
    );
    console.log(aclData.data);
  • setAcl: Sets the ACL data for a room. Note that '*' means all users.
    const setAclResponse = await matrixStateBotClient.acl.v1beta1.setAcl(
      '!roomId:homeserver.url',
      'impactsX',
      'profile',
      JSON.stringify({
        "/": {
          canAccess: ['*'],
          canEdit: [],
        }
      })
    );
    console.log(setAclResponse.data);

Bot

The bot methods provide functionality to interact with the state bot such as inviting it to a room to manage state and ACLs.

  • invite: Invites the state bot to a specified room and adjusts its power level to ensure it has the necessary permissions to manage state events.
    const response = await matrixStateBotClient.bot.v1beta1.invite(
      '!roomId:homeserver.url',
    );
    console.log(response);

Note: This request will still succeed even if bot is already part of the room or has the necessary power levels, so it is safe to call in those cases.

State

The state methods provide functionality to query the state of a room. The state bot fetches the state for a given key and optional path. If no path is provided (path = ''), the entire state object under the key is returned.

  • queryState: Fetches the state data for a room.
    const stateData = await matrixStateBotClient.state.v1beta1.queryState(
      '!roomId:homeserver.url',
      'impactsX',
      'profile'
    );
    console.log(stateData.data);
  • setState: Sets the state data for a room.
    const setStateResponse = await matrixStateBotClient.state.v1beta1.setState(
      '!roomId:homeserver.url',
      'impactsX',
      'profile',
      JSON.stringify({
        displayName: 'John Doe',
        avatar_url: 'mxc://matrix.org/abc123',
      })
    );
    console.log(setStateResponse.data);

IMPORTANT: Always check whether a state object exists before setting and potentially overwriting it. This is especially important when setting important state values such as credentials or private information.

Bid Bot Client

The Bid Bot client provides functionality for managing bids within collections. This includes the fetching, submission and evaluation of bids and blocking users' access to prevent spamming. Access and permissions are determined mainly by appropriate blockchain authorizations (authz). Create the client using the createMatrixBidBotClient function:

const matrixBidBotClient = createMatrixBidBotClient({
  botUrl: 'https://your-bot-url',
  accessToken: 'your-access-token'
});

Bid

The bid methods allow you to manage bids within collections:

  • queryBids: Fetches all active bids for a collection with optional pagination.

    const bids = await matrixBidBotClient.bid.v1beta1.queryBids(
      'collection', // claim collection id
      { nextPageToken: 'optional-token' }
    );
    console.log(bids.data); // Array of bids
  • queryBidsByDid: Fetches all active bids for a specific DID within a collection.

    const bids = await matrixBidBotClient.bid.v1beta1.queryBidsByDid(
      'collection', // claim collection id
      'did:ixo:123'
    );
    console.log(bids.data); // Array of bids
  • submitBid: Submits a new bid to a collection (only 1 bid per user per collection).

    const response = await matrixBidBotClient.bid.v1beta1.submitBid(
      'collection', // claim collection id
      '{"name":"John","surname":"Doe"}'
      'SA',
    );
    console.log(response.id); // The new bid ID
  • approveBid: Approves a bid in a collection.

    const response = await matrixBidBotClient.bid.v1beta1.approveBid(
      'bidId',
      'collection', // claim collection id
      'did:ixo:123'
    );
    console.log(response.id);
  • rejectBid: Rejects a bid in a collection with a reason.

    const response = await matrixBidBotClient.bid.v1beta1.rejectBid(
      'bidId',
      'collection', // claim collection id
      'did:ixo:123',
      'Rejection reason'
    );
    console.log(response.id);
  • queryDidIsBlocked: Checks if a DID is blocked from submitting bids in a collection.

    const response = await matrixBidBotClient.bid.v1beta1.queryDidIsBlocked(
      'collection', // claim collection id
      'did:ixo:123'
    );
    console.log(response.blocked); // true or false
  • didBlock: Blocks a DID from submitting bids in a collection.

    const response = await matrixBidBotClient.bid.v1beta1.didBlock(
      'collection', // claim collection id
      'did:ixo:123'
    );
    console.log(response.blocked); // true
  • didUnblock: Unblocks a DID from submitting bids in a collection.

    const response = await matrixBidBotClient.bid.v1beta1.didUnblock(
      'collection', // claim collection id
      'did:ixo:123'
    );
    console.log(response.blocked); // false

Bot

The bot methods provide functionality to interact with the bid bot:

  • invite: Invites the bid bot to a room.

    const response = await matrixBidBotClient.bot.v1beta1.invite('!roomId:homeserver.url');
    console.log(response.message);
  • invited: Checks if the bid bot is a member of a room.

    const response = await matrixBidBotClient.bot.v1beta1.invited('!roomId:homeserver.url');
    console.log(response.isInvited)

Claim Bot Client

The Claim Bot client provides functionality for managing claims within collections. Access and permissions are determined mainly by appropriate blockchain authorizations (authz). Create the client using the createMatrixClaimBotClient function:

const matrixClaimBotClient = createMatrixClaimBotClient({
  botUrl: 'https://your-bot-url',
  accessToken: 'your-access-token' // optional
});

Claim

The claim methods allow you to manage claims within collections:

  • queryClaim: Fetches a claim by its CID from a collection.

    const claim = await matrixClaimBotClient.claim.v1beta1.queryClaim(
      'collection', // claim collection id
      'claimCid'
    );
    console.log(claim.data);
  • saveClaim: Saves a new claim to a collection.

    const response = await matrixClaimBotClient.claim.v1beta1.saveClaim(
      'collection', // claim collection id
      '{"name":"John","surname":"Doe"}'
    );
    console.log(response.data.cid); // The CID of the saved claim

Bot

The bot methods provide functionality to interact with the claim bot:

  • invite: Invites the claim bot to a room.

    const response = await matrixClaimBotClient.bot.v1beta1.invite('!roomId:homeserver.url');
    console.log(response.message);
  • invited: Checks if the claim bot is a member of a room.

    const response = await matrixClaimBotClient.bot.v1beta1.invited('!roomId:homeserver.url');
    console.log(response.isInvited)

Utilities

The SDK includes several utility functions for handling MXC URLs and validating inputs.

MXC Utilities

The mxc utilities allow you to convert Matrix Content (MXC) URLs to standard HTTP URLs.

  • mxcUrlToHttp: Converts an MXC URL to an HTTP URL.
    const httpUrl = utils.mxc.mxcUrlToHttp(
      'https://your-homeserver-url', // homeServerUrl
      'mxc://matrix.org/abc123', // the mxc url
      300, // width
      300, // height
      'crop' // resizeMethod
    );
    console.log(httpUrl); // Outputs the HTTP URL

Validators

The validators namespace provides a set of utility functions for validating user IDs and room IDs.

  • isValidUserId: Validates whether a string is a properly formatted user ID. Note that all user IDs are prefixed with an '@'.
    const isValid = utils.validators.isValidUserId('@user:homeserver.url');
    console.log(isValid); // true or false
  • isValidRoomId: Validates whether a string is a properly formatted room ID. Note that all room IDs are prefixed with an '!'.
    const isValid = utils.validators.isValidRoomId('!roomId:homeserver.url');
    console.log(isValid); // true or false
  • isValidRoomAlias: Validates whether a string is a properly formatted room alias. Note that all room aliases are prefixed with an '#'.
    const isValid = utils.validators.isValidRoomAlias('#roomAlias:homeserver.url');
    console.log(isValid); // true or false
  • isValidMxcLink: Validates whether a string is a properly formatted mxc link. Note that all mxc links are prefixed with an 'mxc://'.
    const isValid = utils.validators.isValidMxcLink('mxc://matrix.org/abc123');
    console.log(isValid); // true or false
  • isValidEventId: Validates whether a string is a properly formatted matrix event id. Note that matrix event ids are typically prefixed with '$'.
    const isValid = utils.validators.isValidEventId('$3v3nt...1d');
    console.log(isValid) // true or false
  • isValidEventType: Validates whether a string is a properly formatted matrix event type.
    const isValid = utils.validators.isValidEventType('m.room.message');
    console.log(isValid) // true or false
  • isValidCollectionId: Validates whether a string is a properly formatted collection id. Note that collection ids are typically stringified integers.
    const isValid = utils.validators.isValidCollectionId('1')
    console.log(isValid) // true or false
  • isValidDid: Validates whether a string is a properly formatted IXO user DID. Note that some matrix bots only permits the new DID format (did:ixo:ixo1a2...b3c) but this validator also permits legacy DIDs (did:x:1a2...3g4).
    const isValid = utils.validators.isValidDid('did:ixo:ixo1a2...b3c')
    console.log(isValid) // true or false
  • isValidAddress: Validates whether a string is a properly formatted IXO blockchain address.
    const isValid = utils.validators.isValidAddress('ixo1a2...b3c')
    console.log(isValid) // true or false
  • isValidBid: Validates whether a string is properly formatted (stringified) bid data.
    const isValid = utils.validators.isValidBid('{"request": "validate bid data"}')
    console.log(isValid) // true or false
  • isValidBidRole: Validates whether a string is a valid agent role. These roles include owners (PO), evaluators (EA), service providers (SA) and investors (IA).
    const isValid = utils.validators.isValidBidRole('SA')
    console.log(isValid) // true or false
0.3.0

7 months ago

0.3.2

6 months ago

0.3.1

7 months ago

0.3.4

6 months ago

0.3.3

6 months ago

0.1.0

1 year ago

0.2.1

1 year ago

0.2.0

1 year ago

0.0.2

1 year ago

0.0.1

1 year ago