A video indexing task represents a request to upload and index a video. The Resources.Task class provides methods to manage your video indexing tasks.

Methods

Create a video indexing task

Description: This method creates a new video indexing task that uploads and indexes a video.

Function signature and example:

async create(body: CreateTaskParams, options: RequestOptions = {}): Promise<Models.Task> 
import { Task } from 'twelvelabs-js';

const task = await client.task.create({
  indexId: '<YOUR_INDEX_ID>',
  file: '<YOUR_FILE_PATH>',
  transcriptionFile: '<YOUR_TRANSCRIPTION_FILE>'),
});
console.log(`Task ID:${task.id}`);
await task.waitForDone(500, (task: Task) => {
  console.log(`  Status=${task.status}`);
});

if (task.status !== 'ready') {
  throw new Error(`Indexing failed with status ${task.status}`);
}
console.log(`Video ID: ${task.videoId}`);

Parameters:

NameTypeRequiredDescription
bodyCreateTaskParamsYesParameters for creating the new video indexing task.
optionsRequestOptionsNoAdditional options for the request. Defaults to {}.

The CreateTaskParams interface defines the parameters for creating a new video indexing task:

NameTypeRequiredDescription
indexIdstringYesThe unique identifier of the index to which the video will be uploaded.
fileBuffer | NodeJS.ReadableStream | stringNoThe file you want to upload. This parameter can be a Buffer, a ReadableStream, or a string representing the path to the file.
urlstringNoThe publicly accessible URL of the video you want to upload.
transcriptionFileBuffer | NodeJS.ReadableStream | stringNoThe transcription file. This parameter can be a Buffer, a ReadableStream, or a string representing the path to the file.
transcriptionUrlstringNoThe URL of the transcription file.
languagestringNoThe language of the video.
enableVideoStreambooleanNoIndicates if the platform stores the video for streaming.

Return value: Returns a Promise that resolves to a Models.Task instance representing the newly created video indexing task.

📘

Note:

As shown in the example code above, you can use the waitForDone method of the Models.Task class to monitor the status of a video indexing task until it completes.

API Reference: For a description of each field in the request and response, see the Create a video indexing task page.

Related guide: Upload single videos.

Retrieve a video indexing task

Description: This method retrieves the details of a specific video indexing task.

Function signature and example:

async retrieve(id: string, options: RequestOptions = {}): Promise<Models.Task> 
const retrievedTask = await client.task.retrieve("<YOUR_TASK_ID>");
console.log(`Task ID=${retrievedTask.id}`);
console.log(`Index ID: ${retrievedTask.indexId}`);
console.log(`Video ID: ${retrievedTask.videoId}`);
console.log(`Status: ${retrievedTask.status}`);

console.log("System metadata:");
for (const [key, value] of Object.entries(retrievedTask.systemMetadata)) {
  console.log(`  ${key}: ${value}`);
}

if (retrievedTask.hls) {
  console.log("HLS:");
  console.log(`  Video URL: ${retrievedTask.hls.videoUrl}`);
  console.log("  Thumbnail URLs:");
  for (const url of retrievedTask.hls.thumbnailUrls || []) {
    console.log(`    ${url}`);
  }
  console.log(`  Status: ${retrievedTask.hls.status}`);
  console.log(`  Updated at: ${retrievedTask.hls.updatedAt}`);
}

if (retrievedTask.process) {
  console.log("Process:");
  console.log(`  Percentage: ${retrievedTask.process.percentage}%`);
  console.log(`  Remaining Seconds: ${retrievedTask.process.remainSeconds}`);
}

console.log(`Created at: ${retrievedTask.createdAt}`);
console.log(`Updated at: ${retrievedTask.updatedAt}`);

Parameters

NameTypeRequiredDescription
idstringYesThe unique identifier of the task to retrieve.
optionsRequestOptionsNoAdditional options for the request. Defaults to {}.

Return value: Returns a Promise that resolves to a Models.Task instance.

API Reference: For a description of each field in the response, see the Retrieve a video indexing task.

List video indexing tasks with direct pagination

Description: This method returns a paginated list of the video indexing tasks in your account based on the provided parameters. By default, the platform returns your video indexing tasks sorted by creation date, with the newest at the top of the list. Choose this method mainly when the total number of items is manageable, or you must fetch a single page of results.

Function signature and example:

async list(
  { id, createdAt, updatedAt, ...restParams }: ListTaskParams = {},
  options: RequestOptions = {},
): Promise<Models.Task[]>
const listParams = {
  id: '<YOUR_TASK_ID>',
  indexId: '<YOUR_INDEX_ID>',
  filename: '<YOUR_FILENAME>',
  duration: 20,
  width:1920,
  height: 1080,
  sortBy: 'updated_at',
  sortOption: 'asc',
  estimatedTime: '2024-09-17T07:55:22.125Z',
  page: 2,
  pageLimit: 5,
};
const tasks = await client.task.list(listParams)
tasks.forEach(task => {
  console.log(`Task ID=${task.id}`);
  console.log(`Index ID: ${task.indexId}`);
  console.log(`Video ID: ${task.videoId}`);
  console.log(`Status: ${task.status}`);
  
  console.log("System metadata:");
  for (const [key, value] of Object.entries(task.systemMetadata)) {
    console.log(`  ${key}: ${value}`);
  }

  if (task.hls) {
    console.log("HLS:");
    console.log(`  Video URL: ${task.hls.videoUrl}`);
    console.log("  Thumbnail URLs:");
    for (const url of task.hls.thumbnailUrls || []) {
      console.log(`    ${url}`);
    }
    console.log(`  Status: ${task.hls.status}`);
    console.log(`  Updated at: ${task.hls.updatedAt}`);
  }

  if (task.process) {
    console.log("Process:");
    console.log(`  Percentage: ${task.process.percentage}%`);
    console.log(`  Remaining Seconds: ${task.process.remainSeconds}`);
  }

  console.log(`Created at: ${task.createdAt}`);
  console.log(`Updated at: ${task.updatedAt}`);
});

Parameters:

NameTypeRequiredDescription
paramsListTaskParamsNoParameters for filtering the list of tasks. Defaults to {}.
optionsRequestOptionsNoAdditional options for the request. Defaults to {}.

The ListTaskParams interface extends the PageOptions interface and defines the parameters for listing video indexing tasks:

NameTypeRequiredDescription
idstringNoFilter by the unique identifier of a video indexing task.
indexIdstringNoFilter by the unique identifier of an index.
filenamestringNoFilter by the name of a video file.
durationnumberNoFilter by the duration of a video expressed in seconds.
widthnumberNoFilter by the width of a video.
heightnumberNoFilter by the height of a video.
createdAtstring | Record<string, string>NoFilter by the creation date of a video indexing task. This parameter can be a string or an object with string keys and values for range queries.
updatedAtstring | Record<string, string>NoFilter by the last update date of a video indexing task. This parameter can be a string or an object with string keys and values for range queries.

The following properties are inherited from PageOptions:

NameTypeRequiredDescription
pagenumberNoPage number for pagination. Defaults to 1.
pageLimitnumberNoNumber of items per page. Defaults to 10.
sortBy'createdAt' | 'updatedAt'NoField to sort by ("createdAt" or "updatedAt"). Defaults to "createAt".
sortOption'asc' | 'desc'NoSort order ("asc" or "desc"). Defaults to "desc".

Return value: Returns a Promise that resolves to an array of Models.Task instances.

API Reference: For a description of each field in the request and response, see the List video indexing tasks page.

Related guides:

List video indexing tasks with iterative pagination

Description: This method returns a paginated list of the video indexing tasks in your account based on the provided parameters. Choose this method mainly when your application must retrieve a large number of items. By default, the platform returns your video indexing tasks sorted by creation date, with the newest at the top of the list.

Function signature and example:

async listPagination(
  { id, createdAt, updatedAt, ...restParams }: ListTaskParams = {},
  options: RequestOptions = {},
): Promise<Models.TaskListWithPagination>
function printPage(page) {
  page.forEach(task => {
    console.log(`Task ID=${task.id}`);
    console.log(`Index ID: ${task.indexId}`);
    console.log(`Video ID: ${task.videoId}`);
    console.log(`Status: ${task.status}`);
    
    console.log("System metadata:");
    for (const [key, value] of Object.entries(task.systemMetadata)) {
      console.log(`  ${key}: ${value}`);
    }
  
    if (task.hls) {
      console.log("HLS:");
      console.log(`  Video URL: ${task.hls.videoUrl}`);
      console.log("  Thumbnail URLs:");
      for (const url of task.hls.thumbnailUrls || []) {
        console.log(`    ${url}`);
      }
      console.log(`  Status: ${task.hls.status}`);
      console.log(`  Updated at: ${task.hls.updatedAt}`);
    }
  
    if (task.process) {
      console.log("Process:");
      console.log(`  Percentage: ${task.process.percentage}%`);
      console.log(`  Remaining Seconds: ${task.process.remainSeconds}`);
    }
  
    console.log(`Created at: ${task.createdAt}`);
    console.log(`Updated at: ${task.updatedAt}`);
  });
}
const listParams = {
    id: '<YOUR_TASK_ID>',
    indexId: '<YOUR_INDEX_ID>',
    filename: '<YOUR_FILENAME>',
    duration: 20,
    width:1920,
    height: 1080,
    sortBy: 'updated_at',
    sortOption: 'asc',
    createdAt: '2024-09-17T07:53:46.365Z',
    updatedAt: '2024-09-17T07:53:46.365Z',
    page: 2,
    pageLimit: 5,
};

// Fetch the initial page of results
const taskPaginator = await client.task.listPagination(listParams);

// Print the first page of results
printPage(taskPaginator.data);

// Iterate through subsequent pages
while (true) {
const nextTaskPage = await taskPaginator.next();
if (!nextTaskPage) {
    console.log('No more pages of index results available');
    break;
}
printPage(nextTaskPage);
}

Parameters

NameTypeRequiredDescription
paramsListTaskParamsNoParameters for filtering and paginating the list of tasks. Defaults to {}.
optionsRequestOptionsNoAdditional options for the request. Defaults to {}.

The ListTaskParams interface extends the PageOptions interface and defines the parameters for listing video indexing tasks:

NameTypeRequiredDescription
idstringNoFilter by the unique identifier of a video indexing task.
indexIdstringNoFilter by the unique identifier of an index.
filenamestringNoFilter by the name of a video file.
durationnumberNoFilter by the duration of a video expressed in seconds.
widthnumberNoFilter by the width of a video.
heightnumberNoFilter by the height of a video.
createdAtstring | Record<string, string>NoFilter by the creation date of a video indexing task. This parameter can be a string or an object with string keys and values for range queries.
updatedAtstring | Record<string, string>NoFilter by the last update date of a video indexing task. This parameter can be a string or an object with string keys and values for range queries.

The following properties are inherited from PageOptions:

NameTypeRequiredDescription
pagenumberNoPage number for pagination. Defaults to 1.
pageLimitnumberNoNumber of items per page. Defaults to 10.
sortBy'createdAt' | 'updatedAt'NoField to sort by ("createdAt" or "updatedAt"). Defaults to "createdAt".
sortOption'asc' | 'desc'NoSort order ("asc" or "desc"). Defaults to "desc".

Return value: Returns a Promise that resolves to a Models.TaskListWithPagination instance.

📘

Note:

To retrieve subsequent pages of results, use the async iterator protocol:

  1. Invoke the nextmethod of the TaskListWithPagination object.
  2. Repeat this call until the method returns a promise that resolves tonull, indicating no more pages exist.

API Reference: For a description of each field in the request and response, see the List video indexing tasks page.

Related guides:

Delete a video indexing task

Description: This method deletes an existing video indexing task.

Function signature and example:

async delete(id: string, options: RequestOptions = {}): Promise<void>
await client.task.delete('<YOUR_TASK_ID>');

Parameters:

NameTypeRequiredDescription
idstringYesThe unique identifier of the video indexing task to delete.
optionsRequestOptionsNoAdditional options for the request. Defaults to {}.

Return value: Returns a Promise that resolves to void. This method doesn't return any data upon successful completion.

API Refference: Delete a video indexing task.

Import videos

Description: An import represents the process of uploading and indexing all videos from the specified integration. This method initiates an asynchronous import.

Function signature and example:

async importVideos(
  { integrationId, ...restParams }: TransferImportParams,
  options: RequestOptions = {},
): Promise<Models.TransferImportResponse> 
const res = await client.task.transfers.importVideos({'<YOUR_INTEGRATION_ID>', '<YOUR_INDEX_ID>' });
res.videos.forEach((v) => {
  console.log(`video: ${v.videoId} ${v.filename}`);
});
res.failedFiles?.forEach((f) => {
  console.log(`failed file: ${f.filename} ${f.errorMessage}`);
});

Parameters:

NameTypeRequiredDescription
integrationIdstringYesThe unique identifier of the integration for which you want to import videos.
indexIdstringYesThe unique identifier of the index to which the videos are being uploaded.
optionsRequestOptionsNoAdditional options for the request. Defaults to {}.

Return value: Returns a Models.TransferImportResponse object containing two lists:

  • Videos that will be imported.
  • Videos that will not be imported, typically due to unmet prerequisites .

API Refference: Import videos.

Related guide: Cloud-to-cloud integrations.

Retrieve import status

Description: This method retrieves the current status for each video from a specified integration and index.

Function signature and example:

async importStatus(
  integrationId: string,
  indexId: string,
  options: RequestOptions = {},
): Promise<Models.TransferImportStatusResponse>
const status = await client.task.transfers.importStatus('<YOUR_INTEGRATION_ID>', '<YOUR_INDEX_ID>');
status.ready.forEach((v) => {
  console.log(`ready: ${v.videoId} ${v.filename} ${v.createdAt}`);
});
status.failed.forEach((f) => {
  console.log(`failed: ${f.filename} ${f.errorMessage}`);
});

Parameters:

NameTypeRequiredDescription
integrationIdstringYesThe unique identifier of the integration for which you want to retrieve the status of your imported videos.
indexIdstringYesThe unique identifier of the index for which you want to retrieve the status of your imported videos.
optionsRequestOptionsNoAdditional options for the request. Defaults to {}.

Return value: Returns a Models.TransferImportStatusResponse object containing lists of videos grouped by status. See the Task object page for details on each status.

API Reference: Retrieve import status.

Related guide: Cloud-to-cloud integrations.

Retrieve import logs

Description: This method returns a chronological list of import operations for the specified integration.

Function signature and example:

async importLogs(integrationId: string, options: RequestOptions = {}): Promise<Models.TransferImportLog[]>
const logs = await client.task.transfers.importLogs('<YOUR_INTEGRATION_ID>');
logs.forEach((l) => {
  console.log(
    `indexId: ${l.indexId} indexName: ${l.indexName} createdAt: ${l.createdAt} endedAt: ${l.endedAt} videoStatus: ${l.videoStatus}`,
  );
  l.failedFiles?.forEach((f) => {
    console.log(`failed file: ${f.filename} ${f.errorMessage}`);
  });
});

Parameters:

NameTypeRequiredDescription
integrationIdstringYesThe unique identifier of the integration for which you want to retrieve the import logs.
optionsRequestOptionsNoAdditional options for the request. Defaults to {}.

Return value: Returns a Models.TransferImportLog object containing a chronological list of import operations for the specified integration. The list is sorted by creation date, with the oldest imports first. Each item in the list contains:

  • The number of videos in each status
  • Detailed error information for failed uploads, including filenames and error messages.

API Reference: Retrieve import logs.

Related guide: Cloud-to-cloud integrations.