sideara-image

Lorem ipsum dolor sit . Proin gravida nibh vel vealiquete sollicitudin, lorem quis bibendum auctonisilin sequat. Nam nec tellus a odio tincidunt auctor ornare.

Stay Connected & Follow us

What are you looking for?

Simply enter your keyword and we will help you find what you need.

Connecting with Kaltura from NodeJs using Kaltura TypeScript Client

Introduction

Recently when I was working on a project, I found myself looking for a better way to upload a video on Kaltura from a NodeJs project. Of course, there is a Kaltura npm library that can be used to upload videos and do other things on Kaltura, but it didn’t work out for us, so we switched to Kaltura TypeScript client.

Motivation

Our main objective was to be able to create a media entry on Kaltura and upload a video on that entry using a URL. And while creating the media entry, we will provide some video metadata like title, description, etc. And these metadata may contain some Danish characters.

We are using TypeScript as our coding language, so I was looking for a typed Kaltura client library to use for our objective. But unfortunately at that time, we didn’t find the Kaltura TypeScript client library, so we made work with the npm library. It was doing fine until we found that if we try to create an entry that contains any Danish characters, it fails in the code giving some errors. At first, we thought it was a problem with Kaltura API, but after some debugging and some chat with Kaltura support, we realized that the error was in the npm library. So I started looking for an alternative and that is when I found the Kaltura TypeScript client on the Kaltura native libraries page.

Source code

You can get the full project code in this GitHub project. The initial project code is in the master branch and a full working code that connects to Kaltura lies in the develop branch. You can download the code and use it as a reference to get going.

Code Setup

For this demonstration, I’ll create a new NodeJs project. Initially, the project structure is like this:

You can grab the project from the GitHub repo. The master branch contains the initial project structure shown in the image above.

Adding the Kaltura Library

To use the Kaltura TypeScript client, first, clone the library from GitHub. After that go to the project directory and run the following commands:

$ npm install
$ npm run deploy

This will create a folder in the working directory named dist, where the main TypeScript library can be found, which is named like:
kaltura-typescript-client-<version_name>.tgz

Generated Kaltura TypeScript library (Red marked)

Now we need to place this file in the project that we created before. I’ll put the file in the lib directory of the project. For simplicity, I’ll rename the file to kaltura-typescript-client-7.0.1.tgz. But you can leave it as it is.

Kaltura TypeScript library added and renamed

Now open the package.json file and add the following into the “dependencies” block:

"kaltura-typescript-client": "file:lib/kaltura-typescript-client-7.0.1.tgz"
Add the library located inside the dependencies block in the package.json file

After that just open any terminal, go to the project root and execute:

$ npm install

That’s it, you have successfully added the Kaltura TypeScript library into your NodeJs project. All that’s left is to apply it in code and connect to Kaltura and do whatever you want to do.

Connecting to Kaltura

To test that our library integration is working, it’s best to connect to the Kaltura developer account and get the session token.

First, let’s add a new file named kalturaService.ts in the src > util folder. In this file, we will add the necessary methods to connect to the Kaltura API.

Paste the following code into the kalturaService.ts file.


import { KalturaClient } from "kaltura-typescript-client";
import { KalturaSessionType } from "kaltura-typescript-client/api/types/KalturaSessionType";
import { SessionStartAction } from "kaltura-typescript-client/api/types/SessionStartAction";

global.XMLHttpRequest = require("xhr2");

const config = {
  clientTag: "Kaltura_typescript_testing",
  endpointUrl: "http://www.kaltura.com",
};
const client = new KalturaClient(config);

export const startKalturaSession = async (
  adminSecret: string,
  userSecret: string,
  partnerId: number
): Promise<boolean> => {
  try {
    const session = await client.request(
      new SessionStartAction({
        partnerId,
        secret: adminSecret,
        userId: userSecret,
        type: KalturaSessionType.admin,
      })
    );

    if (!session) {
      console.log("Failed to start kaltura session");

      return false;
    }

    client.setDefaultRequestOptions({ ks: session });

    console.log(`Kaltura session:\n${session}`);

    return true;
  } catch (error) {
    console.log(`Kaltura session error: \n ${error}`);
    return false;
  }
};

Here, give extra attention in the following line in the code:

global.XMLHttpRequest = require("xhr2");

This line set’s the XMLHttpRequest from xhr2 npm library, because in the Kaltura TypeScript library, it uses XMLHttpRequest to connect to Kaltura API. If you don’t add this line you might get an error: ReferenceError: XMLHttpRequest is not defined. To avoid that, add xhr2 npm library by running the following command on the terminal from the project root. And while we are at it, we will be needing another npm library, dotenvwhich will be used to get the Kaltura account credentials from the .env file, which we will create just after a little bit.

$ npm install -D xhr2 dotenv

Now it’s time for using the file we just created to get the session token of Kaltura. Copy the following code and paste it into the index.ts file.

import { startKalturaSession } from "./util/kalturaService";

import * as env from 'dotenv';

const run = async () => {
  console.log("This project is for testing the Kaltura TypeScript library");

  env.config();

  const adminSecret = process.env.adminSecret;
  const userSecret = process.env.userSecret;
  const partnerId = process.env.partnerId;

  if (!adminSecret || !userSecret || !partnerId) {
    console.log(
      "Please check your Kaltura credentials in .env file and try again"
    );
    return;
  }

  const sessionStarted = await startKalturaSession(
    adminSecret,
    userSecret,
    Number(partnerId)
  );

  if (sessionStarted) {
    console.log("Successfully got the kaltura session");
  } else {
    console.log("Failed to get the kaltura session token");
  }
};

run();

Here we are getting the adminSecret, userSecret, partnerId that we need to connect to the Kaltura API. You can find these credential info by following these steps:

  1. Login to the Kaltura management console. If you don’t have an account, just create a new one from here.
  2. Click the Settings icon or click here to directly go to the settings page.

3. Select the INTEGRATIONtab, or click here to directly open the page. There you will find all the necessary info needed for this testing.

Kaltura Integration settings page where all necessary credentials are placed.

Now just copy the .env.example file from the GitHub project or copy the content of the file from here and then create a new file named .env and paste the copied code in the .env file.

That’s it, now you are ready to run the code! Just hit npm start from the terminal or cmd and you should get a success message: “Successfully got the Kaltura session” with the Kaltura session token! You now do whatever you want on Kaltura using this TypeScript library. To get to know what you can do and how to do it, visit the Kaltura API documentation, where you will also find the code snippet for your desired work.

That’s all for now. I hope this will help you to get up and running with the Kaltura TypeScript library. Happy coding!!

author avatar
Asif Imtiaz Shaafi
No Comments

Sorry, the comment form is closed at this time.