Megalodon Fediverse API Client

repository·master·Indexed 43 days ago

https://github.com/h3poteto/megalodon

A Fediverse API client library for Node.js and browsers (version 10.3.0) providing a unified interface for interacting with servers such as Mastodon, Pleroma, Friendica, Firefish, GoToSocial, and Pixelfed. It supports REST APIs, WebSocket streaming, and automatic server software detection via the detector() function.

Tokens
14.9K
Snippets
50
Records
71
Agent score
52%

What's inside Megalodon

  1. Use the generator and detector functions to handle multiple SNS

    master

    Megalodon v3.0.0 uses a generator function as the default export to create Client API instances for specific SNS platforms (mastodon, pleroma, or misskey). To handle multiple SNS types dynamically, use the detector function to identify the SNS type from a URL, then pass that type to the generator.

    1. detector(url): Returns the SNS name ('mastodon', 'pleroma', or 'misskey') based on the provided URL.
    2. generator(sns_name, url, access_token): Generates a Client API instance for the specified SNS.
    import generator, { detector } from 'megalodon'
    
    // 1. Detect the SNS type from the URL
    const sns = await detector(url)
    
    // 2. Generate the client using the detected SNS type
    const client = generator(sns, url, access_token)
    
    // 3. Use the client
    client.getHomeTimeline()
  2. Migrate from v2.x to v3.0.0

    master
    Upgrading from version 2.x to 3.0.0 introduces breaking changes due to the addition of Misskey support. Key changes include moving Mastodon class methods to instance methods, deprecating direct API calls (like .get()) in favor of named methods, and changing the default export to a generator function.
  3. Register an application and obtain an access token

    master

    If you do not have an access token, you can programmatically register an application and perform the OAuth flow.

    1. Register the App: Use client.registerApp(name: string, options: object) to get a client_id and client_secret. This returns an authorization URL.
    2. Authorize: Open the generated URL in a browser and authorize the app to receive an authorization code.
    3. Fetch Token: Use client.fetchAccessToken(clientId, clientSecret, code) with the code obtained from the browser to get the final access_token and refresh_token.
    import generator, { OAuth } from 'megalodon'
    
    const client = generator('mastodon', 'https://mastodon.social')
    
    // 1. Register
    client.registerApp('Test App', {}).then(appData => {
      const clientId = appData.client_id
      const clientSecret = appData.client_secret
      console.log('Authorize here:', appData.url)
    
      // 2. After getting 'code' from browser...
      const code = '...' 
      
      // 3. Fetch Token
      client.fetchAccessToken(clientId, clientSecret, code)
        .then((tokenData: OAuth.TokenData) => {
          console.log(tokenData.access_token)
          console.log(tokenData.refresh_token)
        })
    })
  4. Set up environment variables for Megalodon development

    master

    Before building or running the project, you must set the following environment variables to connect to a Mastodon instance:

    • MASTODON_URL: The WebSocket URL of your Mastodon instance (e.g., wss://mastodon.social).
    • MASTODON_ACCESS_TOKEN: Your Mastodon access token.

    Use export in your terminal to set these for the current session.

    $ export MASTODON_URL=wss://mastodon.social
    $ export MASTODON_ACCESS_TOKEN=foobar
  5. Replace direct API calls with named methods in v3.0.0

    master

    In v3.0.0, direct API call methods like .get() are deprecated and are no longer exported from the megalodon package. Instead, you must use the specific named methods provided for each Mastodon API endpoint (e.g., getHomeTimeline() instead of .get('/api/v1/timelines/home')).

    import { Mastodon } from 'megalodon'
    
    const client = new Mastodon(...)
    
    // Use named methods instead of .get()
    client.getHomeTimeline()
  6. Install Megalodon via npm, pnpm, or yarn

    master

    Install the megalodon package using your preferred package manager to start interfacing with Fediverse servers.

    # npm
    npm install -S megalodon
    
    # pnpm
    pnpm add megalodon
    
    # yarn
    yarn add megalodon
  7. Use instance methods for Mastodon authentication in v3.0.0

    master

    In v3.0.0, several authentication-related methods have been moved and changed to instance methods on the Mastodon class. You can no longer call them as static methods or via the previous pattern. The affected methods are:

    • registerApp
    • createApp
    • generateAuthUrl
    • fetchAccessToken
    • refreshToken
    import { Mastodon } from 'megalodon'
    
    const client = new Mastodon(...)
    client.registerApp('TestApp')
  8. Build and run Megalodon using Webpack

    master

    To build the core megalodon package and the browser application, and then start the development server using Webpack, execute the following commands in order using yarn workspace:

    1. Build the megalodon workspace.
    2. Build the browser workspace.
    3. Start the browser workspace.

    Once running, the application will be available at http://127.0.0.1:8000.

    $ yarn workspace megalodon build
    $ yarn workspace browser build
    $ yarn workspace browser start
  9. Convert Friendica entities to Megalodon format

    master

    The FriendicaAPI.Converter namespace provides utility functions to transform Friendica-specific API responses into the standard MegalodonEntity format used by the rest of the library. This ensures compatibility across different federated protocols.

    Key conversion functions include:

    • account(a: Entity.Account): Converts a Friendica account object.
    • status(s: Entity.Status): Converts a Friendica status object, including visibility and media attachments.
    • notification(n: Entity.Notification): Converts a notification, handling type decoding.
    • instance(i: Entity.Instance): Converts instance metadata.
    • results(r: Entity.Results): Converts search/list results.
    • visibility(v: Entity.StatusVisibility): Maps Friendica visibility strings to Megalodon visibility types.
  10. Understand OAuth AppData and TokenData types

    master

    When working with OAuth in Megalodon, you will encounter two primary data structures: AppData and TokenData.

    AppData represents the application's configuration and credentials returned during the OAuth process. It includes sensitive fields like client_id, client_secret, and session_token.

    TokenData represents the authentication tokens used to authorize requests. It includes the access_token, token_type, and optionally a refresh_token for obtaining new access tokens when the current one expires.

    // AppData structure
    type AppData = {
      id: string
      name: string
      website: string | null
      redirect_uri: string | null
      client_id: string
      client_secret: string
      url: string | null
      session_token: string | null
    }
    
    // TokenData structure
    type TokenData = {
      access_token: string
      token_type: string
      scope: string | null
      created_at: number | null
      expires_in: number | null
      refresh_token: string | null
    }
  11. Convert Gotosocial entities to Megalodon entities

    master

    The GotosocialAPI.Converter namespace provides utility functions to transform raw Gotosocial API responses into standardized MegalodonEntity formats. This ensures compatibility with the rest of the Megalodon ecosystem.

    Key conversion functions include:

    • account(a): Converts a Gotosocial account to a Megalodon account.
    • status(s): Converts a Gotosocial status to a Megalodon status.
    • notification(n): Converts a Gotosocial notification, handling type decoding via decodeNotificationType.
    • instance(i): Converts a Gotosocial instance to a Megalodon instance.
    • attachment(a): Converts an attachment.
    • results(r): Converts a results object (containing accounts, statuses, and hashtags).

    These converters are essential when consuming raw data from the Client methods to ensure the data matches the expected MegalodonEntity types used by other parts of the library.

  12. Initialize the Mastodon Client

    master

    The MastodonAPI.Client class is used to interact with a Mastodon instance's REST API. You can provide a baseUrl, an accessToken for authenticated requests, and an optional userAgent. You can also provide a custom axiosInstance if you need to use custom adapters.

    By default, the client uses https://mastodon.social as the base URL and includes an AbortController to allow canceling all ongoing requests via the .cancel() method.

    import MastodonAPI from 'megalodon/src/mastodon/api_client.js';
    
    const client = new MastodonAPI.Client(
      'https://your-instance.social',
      'YOUR_ACCESS_TOKEN',
      'MyMegalodonApp/1.0.0'
    );