Connection

The connection object groups all wrappers to the HTTP requests and Websocket connections.

The connection object comes to help when it comes to fetch or save data from/to the Stagecast backend. The connection object gathers many utility functions to retrieve and manipulate the entities described in the Concepts section.

The entities you are going to be dealing with the most are the Moment and Moment Class. The Moment Class will contain all the settings to allow you so customize you code (themes, colors, language, sponsors, custom properties etc..), while the Moment will give you a unique id and useful information like the creation time (useful for device synchronization).

getMoment(): Promise<Moment>

SDK
  .connection
  .getMoment()
  .then(m => console.log(m))
  .catch(err => console.error(err)); 

The _id and the event fields hold, respectively, the Moment id and the Event id. This two ids combined identify the communication channel the moment will use for messages.

The active field tells if the moment is live (it has the same function of isActive(). The created field is a simple timestamp and it's often used to display countdowns and sync multiple devices.

getMomentClass(): Promise<MomentClass>

This function returns a MomentClass object. This utility function allows to get the custom data model defined by the developer and customized by the event organizer in the web platform configuration page.

SDK
  .connection
  .getMomentClass()
  .then(mc => console.log(mc))
  .catch(err => console.error(err)); 

getMomentGlobalState(): Promise<any>

Call this function to fetch the moment global state. Calling this function when the state is not set returns either undefined or triggers a 404 - Not Found . The moments gets filled as the specific user start saving its state. The populated global state has the following structure.

SDK
 .connection
 .getMomentGlobalState()
 .then(state => console.log(state))
 .catch(err => console.error(err)); 

The global state is an object where each key is a different user email. The user email holds the specific user state. Please note that, for implementation reasons, some special characters in the email might be replaced with their percent code.

Depending on your implementation, the schema for the user state might differ form user to user. Neither the SDK nor the Backend API enforces any structure, so it's up to the developer to check if the saved state is compliant to the application requirements.

getMomentUserState(uId: string): Promise<any>

Fetches the state of a specific user. This function give you the opportunity to retrieve any user state, unless you specify some security mechanisms.

SDK
 .connection
 .getMomentUserState('user@stagecast.io')
 .then(state => console.log(state))
 .catch(err => console.error(err)); 

If the state is not set yet, the function returns undefined or null or triggers a 404 - Not Found error. Until a patch is published, all of these cases must be verified.

If you don't specify the user id, by default, the function will return the state corresponding to the SDK.getUserId()

There is always a user for each Moment. By joining a Moment via join.stagecast.se, even if you don't insert an email, the backend created an anonymous user.

setMomentUserState(state): Promise<any>

// assuming a generic questionnaire on books
const userState = {
  name: 'Alice Tester', 
  favouriteNumber: 25,
  favouriteBooks: [
   'Alice in Wonderland',
   'A Song Of Ice And Fire',
   'The Circle'
  ],
  gender: 'female',
  likesToRead: true
}
  
SDK
 .connection
 .setMomentUserState(userState)
 .then(res => console.log(res))
 .catch(err => console.error(err)); 

Sets the state of the user using authenticated to your HTML-based application. The state can be any javascript object. The MDK serializes the object automatically to JSON.

getUserInfo(): Promise<UserInfo>

Gets the user display information.

SDK
 .connection
 .getUserInfo()
 .then(info => console.log(info))
 .catch(err => console.error(err)); 

getUserPicture(): Promise<Blob>

Downloads the content corresponding to the user profile picture in the form of a base64 blob.

SDK
 .connection
 .getUserProfile()
 .then(res => res.toBlob())
 .then(content => console.log(content))
 .catch(err => console.error(err)); 

NOTE:

If the user is guest to the event, the profile_pic might not be defined.

getContent(contentId: string, thumb: boolean): Promise<Blob>

Params

  • contentId: the id of the content to be fetched;

  • thumb: if the content should be compressed or full size.

SDK
 .connection
 .getContent('1234-5678-9012-3456', true)
 .then(res => res.toBlob())
 .then(content => console.log(content))
 .catch(err => console.error(err)); 

Like getUserPicture(), downloads the content by its id. The returned file is a base64 blob.

fetchContent(contentId: string, thumb: boolean): Promise<Blob>

Params

  • contentId: the id of the content to be fetched;

  • thumb: if the content should be compressed or full size.

SDK
 .connection
 .fetchContent('1234-5678-9012-3456', false)
 .then(res => res.data)
 .then(img => {
   // this is one approach to display the image in the DOM
   let urlCreator = window.URL || window.webkitURL;
   // crate a blob image url to be added to an img src attribute
   let imageUrl = urlCreator.createObjectURL(res);
   
 });

The returned file is an HttpResponse object bearing a base64 blob.

Notes:

  • The default for thumb is true, therefore the content will be rather small thumbnail. Although sometimes the thumbnail is just enough, png images will present a black background, in that case we suggest to fetch the full-size image.

uploadContent(content: Content): Promise<any>

Params

  • content: the content to be uploaded;

    • file: File

    • type: the content type (eg. image/png)

    • tags: a list of tags to be added to the content

// picture is an image or a document as blob file.
function uploadContent(picture) {
  
  const content = {
    file: new File([picture], picture.name),
    type: 'image/jpeg',
    tags: ['everyone'] // everyone is a special tag that allows the content to be seen by anyone
  };

  SDK.connection.uploadContent(content)
    .then(res => console.log(res)))
    .catch(err => console.error(err));
}

The returned file is a base64 blob.

getContentCdnLocation(contentId: string): string

Returns the current CDN content folder location in the following form: https://<host>/api/content

const location = SDK.connection.getContentCdnLocation('1234-5678');
console.log(location); 

// prints: 
// https://d2cb7i0wbc0znj.cloudfront.net/api/content/1234-5678

NOTE

Please use this function instead of the link printed in the example. The CDN location can change at runtime depending on the environment, or some backend set up.

getCdnHost(): string

Returns the current CDN host in the following form: https://<host>

const location = SDK.connection.getContentCdnHost();
console.log(location); 

// prints: 
// https://d2cb7i0wbc0znj.cloudfront.net

getHost(): string

Returns the current host in the following form: <host>

const location = SDK.connection.getHost();
console.log(location); 

// prints: 
// stagecast.se

wsConnect(): Websocket Connection and Messaging

This method is @deprecated and it will be removed in later releases. We recommend using the ws object instead. Old moments that use this method will still function correctly.

wsConnect() creates a websocket connection that can be either authenticated or not. The connection can be seen as a channel that is unique to the Moment and accessible by all the users of that Moment to send/receive messages and sync on topics.

Thanks to the websocket, the developer could, for example, implement Moments based on distributed logics and chats.

Params:

  • onMessage: the message handler function;

  • onError: the error handler function;

  • additional: WsEventHandlers: (optional) additional event handlers:

    • onOpen?: the on connection open callback;

    • onAuth?: the authentication callback;

    • onClose?: the on close connection callback;

  • authenticate: authenticates the user to the websocket (default true).

const onMessage = (data) => console.log(data);
const onError = (err) => console.error(err.message || err);

const onOpen = (data) => console.log('The connection was opened');
const onAuth = (data) => console.log('The user has authenticated');
const onClose = (data) => console.log('Connection closed');

const add = {
  onOpen: onOpen.bind(this),
  onAuth: onAuth.bind(this),
  onClose: onClose.bind(this)
}
const authenticate = true;

SDK.connection.wsConnect(
  onMessage.bind(this), 
  onError.bind(this),
  add, 
  authenticate
);

IMPORTANT NOTES

  • The websocket connection is unique. In the future we might enable more websocket connections at the same time.

  • If one Moment (ie. a user) creates multiple authenticated connection in parallel from the same instance, only the last one will be authenticated. The user can only be authenticated in one single session.

  • If the user needs to receive direct messages, it must be authenticated (set the flag to true)

sendMessageTo(recipient: string, message: any)

This method is @deprecated and it will be removed in later releases. We recommend using the ws object instead. Old moments that use this method will still function correctly.

Params:

  • recipient: a user id (its email)

  • message: any javascript object. (it will be serialized to JSON by the MDK).

This function allows to send a message to an authenticated user over the websocket. Both users must be authenticated. If a uses logs on multiple sessions, only the last one will be valid. This means that if the same user logs into the Mobile page and the Result page at the same time only one will be authenticated.

SDK.connection.sendMessageTo('friend@stagecast.se', {
  message: 'Hello Friend, let\'s meet at the bar!'
});

NOTES:

  1. The user must be authenticated to the websocket (ie. have set the authentication param as true in wsConnect())

  2. For now, the function is synchronous, meaning that the MDK doesn't take a callback as an argument. The MDK is being actively developed and future implementations will include this functionality.

send(message: any): boolean

This method is @deprecated and it will be removed in later releases. We recommend using the ws object instead. Old moments that use this method will still function correctly.

This function allows to broadcast a message to all the users connected to the Moment. If you wish to send a private message to a specific user, or to the Result page see sendMessageTo().

SDK.connection.send({
  message: [
    'Hello Everybody! ',
    'Let\'s meet at the bar. ',
    'I\'ll offer the first round!'
  ].join();
});

Params:

  • message: any javascript object. (it will be serialized to JSON by the MDK).

NOTE

For now, the function is synchronous, meaning that the MDK doesn't take a callback as an argument. The MDK is being actively developed and future implementations will include this functionality.

close(): boolean

This method is @deprecated and it will be removed in later releases. We recommend using the ws object instead. Old moments that use this method will still function correctly.

Used to close the websocket connection.

try {
  const res = SDK.connection.close();
} catch (err) {
  console.error(err.message || err);
}

Last updated