npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@benzinga/benzinga-squawk-sdk

v0.8.0

Published

Benzinga Squawk JavaScript SDKs for Listener and Broadcaster

Downloads

166

Readme

Squawk JavaScript SDK

Squawk JavaScript SDK for consumer and broadcaster service

Installation

  • Using NPM
    • Install the library
      • npm i @benzinga/benzinga-squawk-sdk --save

Using in typescript

  • Import the library
    import SquawkSDK from "@benzinga/benzinga-squawk-sdk"

Using from private CDN

  • Add the script
    <script src="/your_cdn/path/to/squawkjs.min.js"> </script>

Using in react native

The SDK also support react native. In order to use the SDK in our react native application we need to

  • Add react native WebRTC module in our codebase ( The SDK itself is light and depends on the host application to add react native WebRTC SDK )
      npm install react-native-webrtc --save
  • Must call registerGlobals, before initialize the SDK, so that WebRTC specific methods are available to global namespaces for the SDK to use
  • Make sure you have necessary application permissions provided for WebRTC from both Android and iOS

API

  • Create a squawk instance of SquawkJS by calling SquawkSDK with TransportConfig and SDKCallback.

    • Create a Squawk consumer instance

        // if we want to use session based authentication
        new SquawkSDK.Builder(transportConfig: TransportConfig, callback?: SDKCallback)
            .withDebug() // enabling debug will add verbosity in the application. It is suggested not to use debug in production
            .withSession()
            .asListener()
            .build()
          
        // if we want to use api key based authentication
        new SquawkSDK.Builder(transportConfig: TransportConfig, callback?: SDKCallback)
            .withDebug() // enabling debug will add verbosity in the application. It is suggested not to use debug in production
            .withApiKey()
            .asListener()
            .build()
          
        // if we want to use JWT based authentication
        new SquawkSDK.Builder(transportConfig: TransportConfig, callback?: SDKCallback)
            .withDebug() // enabling debug will add verbosity in the application. It is suggested not to use debug in production
            .withJWT()
            .asListener()
            .build()
    • Create a Squawk broadcaster instance

      // if we want to use session based authentication
      new SquawkSDK.Builder(transportConfig: TransportConfig, callback?: SDKCallback)
          .withDebug() // enabling debug will add verbosity in the application. It is suggested not to use debug in production
          .withSession()
          .asBroadcaster()
          .build()
          
      // if we want to use api key based authentication
      new SquawkSDK.Builder(transportConfig: TransportConfig, callback?: SDKCallback)
          .withDebug() // enabling debug will add verbosity in the application. It is suggested not to use debug in production
          .withApiKey()
          .asBroadcaster()
          .build()
          
      // if we want to use JWT based authentication
      new SquawkSDK.Builder(transportConfig: TransportConfig, callback?: SDKCallback)
          .withDebug() // enabling debug will add verbosity in the application. It is suggested not to use debug in production
          .withJWT()
          .asBroadcaster()
          .build()
  • Initialize the transport and establish a connection with API token, and username.

    • It is an async function. It will return success or throw exception upon successfully connected, or failed with the Server
      async initialize(apiKey: string): Promise<any>

Subscriber specific API

  • As a consumer you can use following SDK methods

      - subscribeChannel
      - unsubscribeChannel
      - getTransportState
      - getChannelState
      - getAvailableChannels
      - getExistingPresenters
      - muteChannel
      - unMuteChannel
      - stop
  • Subscribe to a channel

    • It is an async function. Subscribe to a channel with a channel id and audio element. It will return success or throw exception if failed to subscribe the given channel.

      async subscribeChannel(channelId: number): Promise<void>
  • Unsubscribe from a channel

    • It is an async function. Unsubscribe from a channel with a channel id. It will return success or throw exception if failed to un-subscribe from a channel

      async unsubscribeChannel(channelId: number): Promise<void>
  • Query current SDK transport state

    • Calling this function will provide current TransportState of the SDK.

      getTransportState(): TransportState
  • Get a channel state

    • It is an async function. Get a channel state. It will return success with RTCState type or throw exception if failed to fetch channel state

      async getChannelState(channelId: number): Promise<RTCState>
  • Get a list of available channels

    • It is an async function. Get a list of currently available channel. It takes auth key as string and it will return success or throw exception if failed to fetch available channel

      async getAvailableChannels(key: string): Promise<GetStreamResponse>
  • Get a list of existing presenters

    • Get a list of existing presenters. It will return an array of Presenter

      getExistingPresenters(): Presenter[]
  • Mute channel subscriber

    • Mute a subscriber audio. Will throw exception if subscriber with given channel id is not present

      muteChannel(channelId: number)
  • Unmute channel subscriber. Will throw exception if subscriber with given channel id is not present

    • Mute a subscriber audio

      unMuteChannel(channelId: number)
  • Stop and disconnect client and release resource

    • It is an async function. It disconnects transport and client related resource. It will return success or throw exception if failed release transport and client resource

      async stop(): Promise<any>

Broadcaster specific API

  • As a broadcaster you can use following SDK methods

      - startBroadcasting
      - stopBroadcasting
      - getTransportState
      - getChannelState
      - getAvailableChannels
      - getExistingPresenters
      - muteChannel
      - unMuteChannel
      - stop
  • Start broadcasting to a channel

    • It is an async function. Calling this method will start broadcasting to given channel or if throw error if failed.

      async startBroadcasting(channelId: number): Promise<void>
  • Stop broadcasting to a channel

    • It is an async function. Calling this method will stop broadcasting to the given channel or if throw error if failed.

      async stopBroadcasting(channelId: number): Promise<void>
  • Query current SDK transport state

    • Calling this function will provide current TransportState of the SDK.

      getTransportState(): TransportState
  • Get a channel state

    • It is an async function. Get a channel state. It will return success with RTCState type or throw exception if failed to fetch channel state

      async getChannelState(channelId: number): Promise<RTCState>
  • Mute channel broadcaster

    • Mute a broadcaster audio. Will throw exception if subscriber with given channel id is not present

      muteChannel(channelId: number)
  • Unmute channel broadcaster. Will throw exception if subscriber with given channel id is not present

    • Mute a broadcaster audio

      unMuteChannel(channelId: number)
  • Get a list of available channel

    • It is an async function. Get a list of currently available channel. It takes auth key as string and it will return success or throw exception if failed to fetch available channel

      async getAvailableChannels(key: string): Promise<GetStreamResponse>
  • Get a list of existing presenters

    • Get a list of existing presenters. It will return an array of Presenter

      getExistingPresenters(): Presenter[]
  • Stop and disconnect client and release resource

    • It is an async function. It disconnects transport and client related resource. It will return success or throw exception if failed release transport and client resource

      async stop(): Promise<any>

Example codebase

Please keep request timeout( requestTimeoutInMs ) less than or equal to connection timeout ( connectionTimeoutInMs ) in order to keep the application behaviour consistent


// create a transport config object
const transportConfig = {
  serverAddress: 'wss://squawk-lb.zingbot.bz/ws/v4/squawk',
  connectionTimeoutInMs: 5000 + 10000, // 15 second
  requestTimeoutInMs: 10000, // 10 second
  maxRetry: 5,
} as TransportConfig
 

// Create a listener or broadcaster specific callback
// SDK callback object is used to listen squawk RTC realted service related callback

// Listener callback if you are using listener 
const sdkCallBack = {
    onMediaOverride(channelId: number): void {
      // implementation here
    },
    onPresenterStateChange(presenterState: PresenterState, channelId: number): void {
      // implementation here
    },
    onRTCStateChange(rtcState: RTCState, channelId: number): void {
      // implementation here
    },
    onRemoteStream(e: MediaStream | undefined, channelId: number): void {
      // implementation here
    },
    onTransportStateChange(transportState: TransportState): void {
      // implementation here
    }
} as ListenerCallback

// Broadcaster callback if you are using broadcaster
const sdkCallBack = {
    onBroadcastOverride(): void {
      // implementation here
    },
    onBroadcasterLeft(name: string, streamId: number, userId: string): void {
      // implementation here
    },
    onLocalStream(e: MediaStream | undefined): void {
      // implementation here
    },
    onNewBroadcaster(name: string, streamId: number, userId: string): void {
      // implementation here
    },
    onRTCStateChange(rtcState: RTCState, channelId: number): void {
      // implementation here
    },
    onTransportStateChange(transportState: TransportState): void {
      // implementation here
    }
} as PublisherCallback

// Create a squawkJs instance

// Create a squawkJs listener instance based on session key
const squawkClient = new SquawkSDK.Builder(transportConfig, sdkCallBack).asListener().withSession().build()
// Or create a squawkJs broadcaster instance based on session key
const squawkClient = new SquawkSDK.Builder(transportConfig, sdkCallBack).asBroadcaster().withSession().build()
      
// initialize client
await squawkClient.initialize('your-api.key')
  • Listener specific examples

    // subscribe to channel
    await squawkClient.subscribeChannel(1)
    // when using in react native
    await squawkClient.subscribeChannel(1)
      
    // unsubscribe from channel
    await squawkClient.unsubscribeChannel(1)
      
    // get available channel
    const availableChannel = await squawkClient.getAvailableChannels("my test auth key")
      
    // get channel status
    const channelState = await squawkClient.getChannelState(1)
      
    // stop and release client
    await squawkClient.stop()
  • Publisher specific examples

    // broadcast to channel
    await squawkClient.startBroadcasting(1)
    // when using in react native
    await squawkClient.startBroadcasting(1)
      
    // stop broadcasting to a channel
    await squawkClient.stopBroadcasting(1)
      
    // get available channel
    const availableChannel = await squawkClient.getAvailableChannels("my test auth key")
      
    // get channel status
    const channelState = await squawkClient.getChannelState(1)
      
    // stop and release client
    await squawkClient.stop()

Squawk SDK Error Code

Squawk SDK throws an error which is an instance of SquawkError when some error occured during async SDK calls. SquawkError has an error message ( msg ), and error coded ( code ) that you can use in your application to write your SDK error handling logic. Scope of error message are quite broad. So, using error code is encouraged for logic handling.

Error code is a type of Squawk ErrorType which is an enum of type(s)
  • INITIALIZING_SDK
    • If there is an error happened during initialization
  • NOT_ALLOWED
    • If a listener or broadcasted is not allowed listen or broadcast to a channel
  • ALREADY_SUBSCRIBED
    • If a listener is already subscribed to the given channel
  • ALREADY_BROADCASTING
    • If a broadcaster is already broadcasting to the given channel
  • SUBSCRIBING_CHANNEL
    • If some other generic error occurred while subscribing to the given channel
  • BROADCASTING_CHANNEL
    • If some other generic error occured while broadcasting to the given channel
  • CHANNEL_NOT_FOUND
    • If given channel is not accociated to the listener or publisher
  • UNSUBSCRIBING_CHANNEL
    • If error occurred during unsubscribe to the channel
  • STOPPING_BROADCAST
    • If error occurred while stopping a broadcaster
  • FETCHING_CHANNELS
    • If error occurred while querying available channel list

Useful public interface, type and values

  • maxRetry in TransportConfig
    • Application has a default max and min retry policy. Values greater than 30 and less than 5 will be ignored
  • onRemoteStream callback from ListenerCallback
    • We have to attach the Media stream with an HTML audio element, so that the audio can be played by the browser(s).
      • Note - Some browser(s) can have default audio playout restriction that required a user interaction to play audio.
interface TransportConfig {
  connectionTimeoutInMs: number
  requestTimeoutInMs: number
  maxRetry: number
  serverAddress: string
}

interface ClientCallback {
    onTransportStateChange(transportState: TransportState): void;
    onRTCStateChange(rtcState: RTCState, channelId: number): void;
}

interface ListenerCallback extends ClientCallback {
    onRemoteStream(e: MediaStream | undefined, channelId: number): void;
    onPresenterStateChange(presenterState: PresenterState, channelId: number): void;
    onMediaOverride(channelId: number): void;
}

interface PublisherCallback extends ClientCallback {
    onLocalStream(e: MediaStream | undefined): void;
    onBroadcastOverride(): void;
    onNewBroadcaster(name: string, streamId: number, userId: string): void;
    onBroadcasterLeft(name: string, streamId: number, userId: string): void;
}
  
enum TransportState {
  connected = 'CONNECTED',
  disconnected = 'DISCONNECTED',
  neutral = 'NEUTRAL',
}

enum RTCState {
  connected = 'CONNECTED',
  closed = 'CLOSED',
  failed = 'FAILED',
  neutral = 'NEUTRAL',
}

enum PresenterState {
  streaming = 'STREAMING',
  neutral = 'NEUTRAL',
}

type Stream = {
  id: number
  type: string
  description: string
  allowedBroadcasting: boolean
  allowedListening: boolean
  metadata: string
}

type GetStreamResponse = {
  streams: Stream[]
  id: number
  type: 'getAvailableStreamsResponse'
}