This is a javascript client library for interacting with the Vbrick Rev API. It should work in node.js 20+, browsers, and deno.
This library is intended for use with VBrick Rev.
The compiled library is at dist/rev-client.js.
npm install @vbrick/rev-client- Browser - This library is in ESM module format - it assumes use of an evergreen browser that has
fetch,AbortController, etc. - node.js - Node.js 18 or above required. This package includes commonjs (
require) and ES Module (import) versions. By default it uses the (node-fetch) polyfill unless you import using the@vbrick/rev-client/native-fetchnamed export (which uses nativefetch). - deno - Should be compatible, though testing is limited. You'll need
--allow-netpermissions at minimum.
By default CORS (Cross Origin Resource Sharing) is disabled for Rev Cloud tenants. This means this library will not work out of the box in the browser. You should open a ticket with Vbrick Support if this feature isn't yet configured.
To verify if CORS is enabled for your account check the headers response from https://YOUR_REV_TENANT_URL/api/v2/accounts/branding-settings - it doesn't require authentication.
If you need to use this library behind a proxy (and you're using Node.js) then the proxy method to use depends on which fetch library you're using.
- If you use the
node-fetchpolyfill (@vbrick/rev-clientor@vbrick/rev-client/node-fetch) then you should use a proxy that sets thehttps.Agent(likeglobal-agent). - If you use the native fetch (which is based on
undici) then you'll need a proxy implementation that sets the undici global agent dispatcher - Alternatively, you can override to use you're own fetch compatible library by using
utils.setPolyfills()
On-Prem note: this library targets the latest version of Rev. Some API endpoints may not be available or work as expected in older versions of Rev On-Prem.
import {RevClient} from '/path/to/rev-client.js';
// create client object
const rev = new RevClient({
url: 'https://my.rev.url',
apiKey: 'my.user.apikey',
secret: 'my.user.secret',
// or can login via username + password
// username: 'my.username',
// password: 'my.password',
logEnabled: true, // turn on debug logging
keepAlive: true // automatically extend session
rateLimits: true // automatically enforce rate limiting (avoid 429 error responses)
});
(async () => {
// call login api and start session. will throw error if invalid login
await rev.connect();
// create a category
const {categoryId} = await rev.category.create({ name: 'Created Via API' });
// get details about this category
const categoryDetails = await rev.category.details(categoryId);
console.log('category details: ', categoryDetails);
// get the account media contributor role
const mediaContributorRole = await rev.admin.getRoleByName('Media Contributor');
// create a new user, with the media contributor role
const userId = await rev.user.create({
username: 'new.user',
firstname: 'new',
lastname: 'user',
roleIds: [mediaContributorRole.id]
});
// upload a video, and assign 'new.user' as the owner of that video, and add to the category created above
// if browser instead of node.js - pass in a File object instead of the filepath
const videoId = await rev.upload.video("/path/to/local/video.mp4", {
uploader: 'new.user',
title: 'video uploaded via the API',
categories: [categoryDetails.name], // ['Created Via API']
unlisted: true,
isActive: true
/// ...any additional metadata
});
console.log('Video uploaded!', videoId);
await rev.disconnect();
})();NOTE Unless otherwise noted all methods of RevClient are async (they return a Promise)
-
url: REQUIRED - URL of Rev instance (exhttps://company.rev.vbrick.com) -
keepAlive:true/false(Default:true) - If true then automatically extend the Rev session at regular intervals (untilrev.disconnect()is called). If false then you must manually callextendSession()to maintain a valid token. -
rateLimits:true/false/RateLimitOptions(Default:false) - Automatically throttle requests client-side to fit within Vbrick's API Request Rate Limits. Note that the default values (when value istrue) is set to the account maximum - see belowRate Limitssection for how to customize. -
logEnabled:true/false(Default:false) - Enable/disable debug logging -
log:(logLevel, ...args) => void- Custom log function. Default is to log to console
And one of following login options (apiKey+secret, username+password, oauthConfig+code+codeVerifier, jwtToken, guestRegistrationToken+webcastId, publicOnly):
-
User API Key:
apiKey: User API Key of Rev Usersecret: User Secret of Rev User
-
Username/Password login:
username: Username of Rev user.password: Password of Rev user.
-
Legacy OAuth session (NOTE: This is for OAuth 2.0 browser-redirect flow to create sessions, it's not intended for server-side only login).
oauthConfig: OAuth configuration objectoauthConfig.oauthApiKey: API key from Rev Admin -> Security. This is a DIFFERENT value from the User Token used for API login/extend sessionoauthConfig.oauthSecret: API secret from Rev Admin -> Security. This is a DIFFERENT value from a user'ssecret. DEPRECATED - only for Legacy OAuth loginoauthConfig.redirectUri: The local URL Rev should redirect user to after logging in. This must match EXACTLY what's specified in Rev Admin -> Security for the specified API keyauthCode: the Auth Code returned from the OAuth redirect response as a query parameter
- OAuth2 session (NOTE: This is for OAuth 2.0 browser-redirect flow to create sessions, it's not intended for server-side only login - use User API Key / JWT logins instead for this use case).
oauthConfig: OAuth configuration objectoauthConfig.oauthApiKey: API key from Rev Admin -> Security. This is a DIFFERENT value from the User Token used for API login/extend sessionoauthConfig.redirectUri: The local URL Rev should redirect user to after logging in. This must match EXACTLY what's specified in Rev Admin -> Security for the specified API keycode: the Code returned from the OAuth redirect response as a query parametercodeVerifier: the Code Verifier used when initially generating the OAuth2 authorization URL. userev.auth.buildOAuth2Authentication()to generate an OAuth2 authorization URL and corresponding codeVerifier.
-
JWT session:
jwtToken: The JWT Token
-
Guest Registration session:
guestRegistrationToken: The Token returned when creating a guest registration.webcastId: ID of the webcast in question
-
Access Token (existing sessions)
session.token: The Access Token previously received via some login method (see below)session.expiration: The expiration time of the session.
-
Public Only usage (no authentication)
publicOnly: Don't use any authentication. This limits use to endpoints that don't require authentication.
You can pass in an existing session to the constructor to reuse a session token (assuming it isn't expired). When you include session the additional credential values aren't necessary, however if not included you won't be able to re-login, just extend the session.
const initialRev = new RevClient({ url, apiKey, secret });
await initialRev.connect();
// store state for use elasewhere (like /tmp/ storage in a serverless environment)
// has { token, expiration }
let savedState = rev.sessionState;
// ... time passes ...
const revWithReusedSession = new RevClient({ url, apiKey, sessionState: savedState })
// or set after initial configuration
revWithReusedSession.sessionState = savedState;isConnected - Boolean value that indicates if connect() has been called and the session isn't expired
Make a request to a specific API endpoint. get,post,put,patch and delete are helpers to set the method value of the main request call
method- HTTP Verb to useendpoint- Path for call to make. This will be relative to theurlset inRevClientdata- Query parameters forget/deleterequests, Body forput/post/patchrequests.options- Additional request parameters to pass tofetch.options.responseType-json|text|blob|stream- specify how to decode the response. Default is to autodetect based on the response.streammeans pass through without decoding.
statusCode- HTTP Status Codeheaders- Headers objectbody- Response payload, already decoded based onoptions.responseTyperesponse- rawfetchResponse object
Custom Error with the following additional properties:
status- HTTP Status Codeurl- Request URLcode?- Rev-specific error codedetail?- Rev-specific detail message;
rev = new RevClient({ url: "https://my.rev.url", ...credentials });
await rev.request('get', '/api/v2/users/my.username', { type: 'username' });
// HTTP GET https://my.rev.url/api/v2/users/my.username?type=usernameMake HTTP requests with the specified verb (get/post/patch/etc). Unlike request() these calls return the body directly.
endpoint- Path for call to make. This will be relative to theurlset inRevClientdata- Query parameters forget/deleterequests, Body forput/post/patchrequests.options- Additional request parameters to pass tofetch.options.responseType-json|text|blob|stream- specify how to decode the response. Default is to autodetect based on the response.streammeans pass through without decoding.
The Response payload, already decoded based on options.responseType
See the Vbrick documentation for information on Rate Limit behavior.
If you have multiple users / agents using the Public API for a Vbrick account then you may need to set lower rate limits. These values are set Per Minute, so 30 means "30 calls per minute".
// example using default options
const rev = new RevClient({
url: 'https://my.rev.url',
apiKey: 'key', secret: 'secret',
rateLimits: {
get: 24000,
post: 3600,
searchVideos: 120,
videoDetails: 2000,
uploadVideo: 30,
auditEndpoint: 60,
updateVideo: 30,
loginReport: 10,
attendeesRealtime: 2
}
// rateLimits: true // equivalent option
});For background usage you may consider using lower values to ensure the service doesn't impact other agents using the API:
// example of overriding the limits for a service account that makes background requests
const rev = new RevClient({
url: 'https://my.rev.url',
apiKey: 'key', secret: 'secret',
rateLimits: {
searchVideos: 10, // only make 10 search calls per minute
videoDetails: 100,
// other values use default
}
})RevClient also wraps API functionality into separate namespaces. They mostly follow the API Documentation categorization.
Refer to the autogenerated documentation for full listing
admin.getRoleByName(name) - Get a specific Role { id: string, name: string } based on the Role's name (i.e. 'Media Viewer')
These calls are called automatically by the RevClient instance, but they're included here for completeness.
auth.buildOAuth2Authentication(config, state?) - returns Promise<{ url, codeVerifier }>. Sign and format an OAuth2 Authorication URL. Make sure to store the codeVerifier for making a call to get an Access Token.
auth.buildOAuthAuthenticateURL(config, state?) - returns Promise<string>. DEPRECATED Sign and format an OAuth Authorization URL (for browser login flow)
auth.parseOAuthRedirectResponse(url) - DEPRECATED Synchronous, returns { isSuccess, authCode, state, error} based on returned information
Wrapper around the Search Users,Groups and Channels API. If options.assignable: true then restrict to only assignable entities. options.type defaults to Channel to just return channels
Wrapper around the Use the Get User Location Service to get a user's IP Address for zoning purposes.
NOTE: The response from this endpoint is remapped from the raw API results - it returns camelCase instead of PascalCase ({id: string, name: string, entityType: string } instead of {Id: string, Name: string, EntityType: string}
All upload functions take in a file argument and an options argument.
file: The actual upload data. The possible input options are:
| Type | Browser | Node | Notes |
|---|---|---|---|
File / Blob |
âś” | âś” | |
"data:" / "blob:" urls |
Passed to fetch() |
âś” | Treated like a Blob |
"file:" urls |
Passed to fetch() |
Read using fs.createReadStream() |
Follows browser/user agent fetch() security policy |
"http:" / "https:" urls |
❌ | ✔ | On node.js these are passed to fetch(), so could load remote resources |
relative/absolute path (string) |
❌ | Read using fs.createReadStream() |
Follows filesystem permissions |
Web Stream (Readable Stream), fetch Response |
converted to Blob |
âś” | On browsers entire stream is read into memory. For node.js the stream is piped |
Node.js Streams (including http.IncomingResponse) |
N/A | âś” | Piped through to request. |
options:- Any
fetchoptions (most importantlysignalfor passing in anAbortSignal) filename?:string- the filename used in theContent-Dispositionfield header.contentType?:string- the content type of the filecontentLength?:number- the known content length of the file. This is rarely needed, but can be used if passing along a HTTP StreamuseChunkedTransfer?:boolean- tell upload to not calculate a content length automatically, and just send asTransfer-Encoding: chunkeddisableExternalResources?:boolean- iftruethen reject anystringargument that would read from the network/disk (onlyblob:ordata:URLs allowed). Default isfalsefor backwards compatibility
- Any
SECURITY REMINDER - Passing in strings has the chance to trigger a remote request, and on node.js/deno/bun could read arbitrary files on the disk. Be sure to sanitize your inputs. Optionally, use the options.disableExternalResources to only allow data: and blob: URLs.
Note: Rev expects the file extension and content-type to agree. This library will attempt to automatically fix the filename/content-type as needed.
videoId: string, videoId of the video in questionchapters: array of Chapter objects. At least one oftitleorimageFilemust be specifiedtime: (required)stringtitle:stringimageFile:string,stream.ReadableorBlobif using node.js.Fileif browser. Seefilein the Shared Options section above.
action: One of two string values (default:replace):"append": Update Video Chapters)"replace": Upload Video Chapters
options: Additionalfetchoptions
file:string,stream.ReadableorBlobif using node.js.Fileif browser. Seefilein the Shared Options section above.metadata: Video metadata - see API docs. Note that at minimumuploaderMUST be included.options: See Shared Options section above.
The ID of the video
upload.transcription(videoId, file, language?, options?) - Upload a transcription / close captions file
NOTE: The response from this endpoint is remapped from the raw API results - it returns camelCase instead of PascalCase ({userId: string, firstname: string, profileImageUri: string, entityType: string } instead of {Id: string, FirstName: string, ProfileImageUri: string, EntityType: string}.
NOTE: set options.assignable to true to use the "Search assignable Users/Groups/Channels" instead of searching for all users
NOTE: The API only allows searching for 12 months of data at a time. This wrapper function will split up the requests to allow for a larger range of days.
query: See API Docs for available search optionsoptions: Optional, Additional options for requestoptions.maxResults: number, set the maximum number of results to return.options.onProgress:(items: <array>, current, total) => void- callback for each time a page is queried from Rev.options.onScrollExpired:(err: ScrollError) => void- Search results use a scrollID cursor that expires after 1-5 minutes from first request. If the scrollID expires then onScrollExpired will be called with a ScrollError. Default behavior is to throw the error.
This method returns a SearchRequest object, that includes the following methods:
.exec()- Get all results as an array.nextPage()-{ current, total, items, done }- Get the search results one page at a time[async iterator]- The class also implementsAsyncIterator, so can be used as aStreamor usingfor await
// get the 10 most recent videos that match 'puppy' in the tags/keywords field
const request = rev.video.search({ q: 'puppies', searchField: 'tags', sortField: 'whenUploaded', sortDirection: 'desc' }, { maxResults: 10 });
const results = await request.exec();
// get ALL videos in the account and report their title, reporting progress and ignoring errors
const request = rev.video.search(undefined, {
onProgress(items, current, total) {
console.log(`PROGRESS: ${current}-${current + items.length} of ${total}`);
},
onScrollExpired(err) {
console.warn('Error while getting video results, ignoring: ', err);
}
});
for await (let video of request) {
console.log(`Video ${video.id}: ${video.title} | duration: ${video.duration}`);
}video.listDeleted(query?, options?) - Get Deleted Videos
The library exposes some additional utilities:
The Rev API includes rate limiting for some API endpoints. If you exceed the limit then you'll receive a 429 error response. This function can help to automatically avoid that threshold.
See the API Documentation on Rate Limiting for current limits.
fn: function to be rate-limitedoptions:fn: function to be rate-limited (if not set as first argument)perSecond: set limit toXexecutions per secondperMinute: set limit toXexecutions per minuteperHour: set limit toXexecutions per hourlimit: allowlimitexecutions perintervalmillisecondsinterval: allowlimitexecutions perintervalmillisecondssignal:AbortSignalto cancel all pending executions.
Wrapped function with same arguments as passed in fn, with added:
.abort()- cancel all pending executions
import { RevClient, rateLimit } from '@vbrick/rev-client';
const rev = new RevClient(options);
// assumes this tool is only tool in the account using API uploads
const throttledUpload = rateLimit({
fn: (...args) => rev.upload.video(...args),
perMinute: 30
});
const numberOfVideos = 100;
for (let i = 0; i < numberOfVideos; i++) {
// same arguments as rev.upload.video
const videoId = await throttledUpload(file, {title: `video ${i}`, uploader: `my.username` });
}Get the expected extension for a mime-type supported by Rev for upload. If none found it will return the defaultExtension (or .mp4 if none specified)
Get the expected mime-type for the specified extension (.ext). If none found it will return the defaultType (or video/mp4 if none specified)
Allows overriding the underlying network primitives used by this library, in particular fetch. This function expects a callback that is called before the first network request is made, to allow lazy load of any dependencies.
import {RevClient, utils} from '@vbrick/rev-client';
utils.setPolyfills(async (polyfills) => {
console.log('Overriding polyfills');
// dynamic import, which works in ESM or commonjs modules
const {fetch} = await import('undici');
Object.assign(polyfills, {
fetch
});
});
const rev = new RevClient(...args);
await rev.connect(); // setpolyfills triggered hereCustom error returned for error status code responses
status:number- http status codeurl:string- original URL of requestcode:string- Rev-specified error string, for exampleMalformedRequest,RequiredFieldMissingorInvalidFileTypedetail:string- Additional details about error (if passed).
Custom error returned if a paged search request has expired (usually because more than 1 minute has passed between requests for more pages of data)
This code is distributed "as is", with no warranty expressed or implied, and no guarantee for accuracy or applicability to your purpose.