Code Snippets

 

Node.js – Wrapper Using Node.js v8+

/**
 * This class is a usable wrapper around the Rev API for use in node.js v8+
 */

const fs = require('fs');
const got = require('got');
const url = require('url');
const FormData = require('form-data');

class RevConnection {
    constructor(baseUrl) {
        this.baseUrl = baseUrl;
        // used for authentication
        this.token = null;
    }
    async login(username, password) {
        try {
            const response = await got.post(`${baseUrl}/api/v1/user/login`, {
                query: {username, password},
                json: true
            });

            // save token for later HTTP calls
            this.token = response.body.token;
            // userid is used for logout
            this.userId = response.body.userId;

            return response.body;
        } catch (err) {
            // check if there's more details about error
            if (err.response && err.response.body) {
                err.message += ` ${err.response.body}`;
            }
            throw err;
        }
    }
    async logoff() {
        return this.post('/api/v1/user/logoff', {userId: this.userId});
    }
    // this should get called every 15 minutes or so to extend the connection session
    async extendSession() {
        return this.post(`/api/v1/user/extend-session-timeout`, {userId: this.userId});
    }
    // make a REST request
    async request(method = 'GET', endpoint = '', data = undefined) {
        const requestOptions = {
            method,
            uri: url.resolve(this.baseUrl, endpoint);
            headers: {
                'Authorization': `VBrick ${this.token}`
            },
            json: true
        };

        // add data in body if body type request, otherwise in query string
        if (data) {
            if (['POST', 'PUT', 'PATCH'].includes(method)) {
                requestOptions.body = data;
            } else {
                requestOptions.query = data;
            }
        }

        // OPTIONAL log request and response
        console.log(`Request ${method} ${endpoint}`);

        try {
            const response = await got(uri, requestOptions);
            console.log(`Response ${method} ${path} ${response.statusCode} ${response.statusMessage}`)
            return response.body;
        } catch (err) {
            // on error attempt to get Rev details
            try {
                if (err.response && err.response.body) {
                    const responseBody = err.response.body;
                    err.body = typeof responseBody === 'string' ? JSON.parse(err.response.body) : responseBody;
                    if (err.body && err.body.detail) {
                        err.message = `${err.statusCode} (${err.body.code}) ${err.body.detail}`;
                    }
                }
            } catch (err) {}
            // OPTIONAL log error
            console.error(`Response ${method} ${path} ${err.message}`);
            throw err;
        }

        return response;
    }
    get(...args) {
		// args expands to path, data
		return this.request('GET', ...args);
	}
	post(...args) {
		// args expands to path, data
		return this.request('POST', ...args);
	}
	put(...args) {
		// args expands to path, data
		return this.request('PUT', ...args);
	}
	delete(...args) {
		// args expands to path, data
		return this.request('DELETE', ...args);
	}
    async upload(filepath, metadata = {}) {
        const endpoint = '/api/uploads/videos';

        // prepare payload
        const form = new FormData();
        // at bare minimum the uploader needs to be defined
        if (!metadata.uploader) {
            metadata.uploader = this.username;
        }

        form.append('video', JSON.stringify(metadata));

        // add file to form data as stream
        const fileStream = fs.createReadStream(filepath);
        form.append('VideoFile', fileStream);

        // prepare headers from form, and include VBrick Auth
        const headers = form.getHeaders();
        const totalBytes = await new Promise((resolve, reject) => {
            form.getLength((err, bytes) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(bytes);
                }
            });
        });
        Object.assign(headers, {
            'authorization': `VBrick ${this.token}`,
            'content-length': totalBytes
        });

        const requestOptions = {
            method: 'POST',
            uri: url.resolve(this.baseUrl, endpoint);
            headers,
            json: false,
            body: form
        };

        const request = got(uri, requestOptions);

        // OPTIONAL log request and response
        console.log(`Uploading ${filepath} (${totalBytes} bytes)`);

        // OPTIONAL - log upload progress (got v7.2 and above only)
        request.on('uploadProgress', progress => console.log(`Uploading...${progress.percent}%`));

        // will return {videoId, statusUri} on success
        try {
            const response = await request;
            const result = JSON.parse(response.body);
            console.log(`Uploaded - ID = ${result.videoId}`);
            return result;
        } catch (err) {
            console.error('Upload Failed', err);
            throw err;
        }
    }
}

var revUrl = 'my.rev.instance.vbrick.com';
var username = 'enter.username.here';
var password = 'enter.password.here';
var filename = 'C:\\\\Videos\\my.video.file.mp4';

(async function () {
    const rev = new RevConnection(revUrl);

    try {
        await rev.login(username, password);

        const {videoId, statusUri} = await rev.upload(filename, {
            title: 'Test API Upload',
            description: 'This video was uploaded via the Rev API'
        });

        console.log('Video uploaded');

        // get the status of the video - should be "Processing"
        // see https://www.vbrick.com/help/rev/api/v1/#!/B._Video/getVideoStatus
        const result = await rev.get(`/api/v1/videos/${videoId}/status`);
        console.log(`Video Status is ${result.status}`);

        // rate the video 5 stars
        // https://www.vbrick.com/help/rev/api/v1/#!/B._Video/submitVideoRating
        await rev.put(`/api/v1/videos/${videoId}/rating`, {
            rating: "5"
        });
        console.log('Video rated');
    } catch (err) {
        console.error('Error', err);
        process.exit(1);
    }
})();