wombo-dream-api
Version:
Unofficial API for Wombo Dream
702 lines (701 loc) • 29.7 kB
JavaScript
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WomboDream = exports.DEFAULT_CHECK_FREQ = exports.DEFAULT_DISPLAY_FREQ = void 0;
var axios_1 = __importDefault(require("axios"));
var sprintf_js_1 = require("sprintf-js");
var sleep_promise_1 = __importDefault(require("sleep-promise"));
exports.DEFAULT_DISPLAY_FREQ = 10;
exports.DEFAULT_CHECK_FREQ = 1000;
var WomboDream = /** @class */ (function () {
function WomboDream(authentifier, apiTaskUrl, apiUserSuffix, apiTaskSuffix, apiShopSuffix, apiStyleSuffix, apiGallerySuffix, originUrl, uploadUrl) {
this.authentifier = authentifier;
this.apiTaskUrl = apiTaskUrl;
this.apiUserSuffix = apiUserSuffix;
this.apiTaskSuffix = apiTaskSuffix;
this.apiShopSuffix = apiShopSuffix;
this.apiStyleSuffix = apiStyleSuffix;
this.apiGallerySuffix = apiGallerySuffix;
this.originUrl = originUrl;
this.uploadUrl = uploadUrl;
}
WomboDream.prototype.buildApiTaskUrl = function (taskId) {
return (0, sprintf_js_1.sprintf)(this.apiTaskUrl, {
suffix: (0, sprintf_js_1.sprintf)(this.apiTaskSuffix, { taskId: taskId }),
});
};
WomboDream.prototype.buildRawApiTaskUrl = function () {
return this.buildApiTaskUrl('');
};
WomboDream.prototype.buildUploadUrl = function () {
return this.uploadUrl;
};
WomboDream.prototype.buildApiStyleUrl = function () {
return (0, sprintf_js_1.sprintf)(this.apiTaskUrl, {
suffix: this.apiStyleSuffix,
});
};
WomboDream.prototype.buildApiTaskShopUrl = function (taskId) {
return (0, sprintf_js_1.sprintf)(this.apiTaskUrl, {
suffix: (0, sprintf_js_1.sprintf)(this.apiShopSuffix, { taskId: taskId }),
});
};
WomboDream.prototype.buildApiGalleryUrl = function (taskId) {
return (0, sprintf_js_1.sprintf)(this.apiTaskUrl, {
suffix: (0, sprintf_js_1.sprintf)(this.apiGallerySuffix, { taskId: taskId }),
});
};
WomboDream.prototype.buildRawApiGalleryUrl = function () {
return this.buildApiGalleryUrl('');
};
/**
* Create a new HTTP request agent with custom headers for dream API
* @example
* ```ts
* const agent = await dreamInstance.buildHttpRequestAgentForDreamApi();
* agent.get('https://app.wombo.art').then(res => console.log(res.data));
* ```
*/
WomboDream.prototype.buildHttpRequestAgentForDreamApi = function () {
return __awaiter(this, void 0, void 0, function () {
var _a, _b;
var _c, _d;
return __generator(this, function (_e) {
switch (_e.label) {
case 0:
_a = this.buildHttpRequestAgent;
_c = {
baseURL: this.buildRawApiTaskUrl()
};
_d = {
Origin: this.originUrl,
Referer: this.originUrl
};
_b = "Bearer ".concat;
return [4 /*yield*/, this.authentifier.obtainAuthorisationToken()];
case 1: return [2 /*return*/, _a.apply(this, [(_c.headers = (_d.Authorization = _b.apply("Bearer ", [_e.sent()]),
_d.service = 'Dream',
_d),
_c)])];
}
});
});
};
/**
* Create a new HTTP request agent with custom headers for user API
* @example
* ```ts
* const agent = await dreamInstance.buildHttpRequestAgentForApiUser();
* agent.post('https://app.wombo.art/api/users', {username: "myusername"}).then(res => console.log(res.data));
* ```
*/
WomboDream.prototype.buildHttpRequestAgentForUserAPI = function () {
return __awaiter(this, void 0, void 0, function () {
var _a, _b;
var _c, _d;
return __generator(this, function (_e) {
switch (_e.label) {
case 0:
_a = this.buildHttpRequestAgent;
_c = {
baseURL: this.originUrl
};
_d = {
Origin: this.originUrl,
Referer: this.originUrl + '/'
};
_b = "bearer ".concat;
return [4 /*yield*/, this.authentifier.obtainAuthorisationToken()];
case 1: return [2 /*return*/, _a.apply(this, [(_c.headers = (_d.Authorization = _b.apply("bearer ", [_e.sent()]),
_d),
_c)])];
}
});
});
};
/**
* Create a new HTTP request agent with custom headers
* @example
* ```ts
* const agent = await dreamInstance.buildHttpRequestAgentForApiUser({baseURL: "https://app.wombo.art", headers: {Authorization: "Bearer 12345"}});
* agent.get('https://app.wombo.art').then(res => console.log(res.data));
* ```
*/
WomboDream.prototype.buildHttpRequestAgent = function (config) {
return __awaiter(this, void 0, void 0, function () {
var requestAgent;
return __generator(this, function (_a) {
try {
requestAgent = axios_1.default.create(config);
return [2 /*return*/, requestAgent];
}
catch (error) {
throw { reason: 'Failed to create request agent', error: error };
}
return [2 /*return*/];
});
});
};
/**
* Initialize new Task
*
* The Task wont start until it is configured
*
* @example
* ```ts
* dreamInstance.initTask().then(console.log);
* ```
*/
WomboDream.prototype.initTask = function () {
return __awaiter(this, void 0, void 0, function () {
var requestAgent, initializedTask, error_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.buildHttpRequestAgentForDreamApi()];
case 1:
requestAgent = _a.sent();
_a.label = 2;
case 2:
_a.trys.push([2, 4, , 5]);
return [4 /*yield*/, requestAgent.post(this.buildRawApiTaskUrl(), {})];
case 3:
initializedTask = _a.sent();
return [2 /*return*/, initializedTask.data];
case 4:
error_1 = _a.sent();
throw {
reason: 'Failed to initialize task',
error: error_1,
};
case 5: return [2 /*return*/];
}
});
});
};
/**
* Configure an existing Task
*
* @param input_image use an image as input
* @param display_freq how often the task makes intermediate renders
*
* @warning must be done with the same account as the task was created
*
* @example
* ```ts
* const task:Task;
* dreamInstance.configureTask(task, "kitten", 34).then(console.log);
* ```
*/
WomboDream.prototype.configureTask = function (task, prompt, style, input_image, display_freq) {
if (display_freq === void 0) { display_freq = exports.DEFAULT_DISPLAY_FREQ; }
return __awaiter(this, void 0, void 0, function () {
var requestAgent, configuredTask, error_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.buildHttpRequestAgentForDreamApi()];
case 1:
requestAgent = _a.sent();
_a.label = 2;
case 2:
_a.trys.push([2, 4, , 5]);
return [4 /*yield*/, requestAgent.put(this.buildApiTaskUrl(task.id), {
input_spec: {
display_freq: display_freq,
prompt: prompt,
style: style,
input_image: input_image,
},
}, {
headers: {
'Access-Control-Request-Method': 'PUT',
},
})];
case 3:
configuredTask = _a.sent();
return [2 /*return*/, configuredTask.data];
case 4:
error_2 = _a.sent();
throw {
reason: 'Failed to configure task',
error: error_2,
};
case 5: return [2 /*return*/];
}
});
});
};
/**
* Create and configure an existing Task
*
* @param input_image use an image as input
* @param display_freq how often the task makes intermediate renders
*
* @example
* ```ts
* dreamInstance.createTask("kitten", 34).then(console.log);
* ```
*/
WomboDream.prototype.createTask = function (prompt, style, input_image, display_freq) {
if (display_freq === void 0) { display_freq = exports.DEFAULT_DISPLAY_FREQ; }
return __awaiter(this, void 0, void 0, function () {
var initializedTask, configuredTask, error_3;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 3, , 4]);
return [4 /*yield*/, this.initTask()];
case 1:
initializedTask = _a.sent();
return [4 /*yield*/, this.configureTask(initializedTask, prompt, style, input_image, display_freq)];
case 2:
configuredTask = _a.sent();
return [2 /*return*/, configuredTask];
case 3:
error_3 = _a.sent();
throw {
reason: 'Failed to create task',
error: error_3,
};
case 4: return [2 /*return*/];
}
});
});
};
/**
* Fetch the current infos of a Task
*
* @warning must be done with the same account as the task was created
*
* @example
* ```ts
* const taskId:string;
* dreamInstance.fetchTaskInfos(taskId).then(console.log);
* ```
*/
WomboDream.prototype.fetchTaskInfos = function (taskId) {
return __awaiter(this, void 0, void 0, function () {
var requestAgent, task, error_4;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.buildHttpRequestAgentForDreamApi()];
case 1:
requestAgent = _a.sent();
_a.label = 2;
case 2:
_a.trys.push([2, 4, , 5]);
return [4 /*yield*/, requestAgent.get(this.buildApiTaskUrl(taskId))];
case 3:
task = _a.sent();
return [2 /*return*/, task.data];
case 4:
error_4 = _a.sent();
throw { reason: 'Failed to fetch task info', error: error_4 };
case 5: return [2 /*return*/];
}
});
});
};
/**
* Create a new task and generate a picture
*
* @param progressCallback a callback function that will be called with the progress of the Task
* @param input_image use an image as input
* @param display_freq how often the task makes intermediate renders
*
* @example
* ```ts
* dreamInstance.generatePicture('kitten', 34, (task) => {
* console.log(task.state, 'stage', task.photo_url_list.length);
* })
* .then((task) => console.log(task?.result.final))
* .catch(console.error);
* ```
*/
WomboDream.prototype.generatePicture = function (prompt, style, progressCallback, input_image, checkFrequency, display_freq) {
if (progressCallback === void 0) { progressCallback = function () { }; }
if (checkFrequency === void 0) { checkFrequency = exports.DEFAULT_CHECK_FREQ; }
if (display_freq === void 0) { display_freq = exports.DEFAULT_DISPLAY_FREQ; }
return __awaiter(this, void 0, void 0, function () {
var task, error_5;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.createTask(prompt, style, input_image, display_freq)];
case 1:
task = _a.sent();
_a.label = 2;
case 2:
_a.trys.push([2, 7, , 8]);
_a.label = 3;
case 3:
if (!(task.state !== 'completed')) return [3 /*break*/, 6];
return [4 /*yield*/, this.fetchTaskInfos(task.id)];
case 4:
task = _a.sent();
progressCallback(task);
if (task.state === 'failed')
throw new Error();
return [4 /*yield*/, (0, sleep_promise_1.default)(checkFrequency)];
case 5:
_a.sent();
return [3 /*break*/, 3];
case 6: return [2 /*return*/, task];
case 7:
error_5 = _a.sent();
progressCallback(__assign(__assign({}, task), { state: 'failed' }));
throw {
reason: 'Failed to generate picture',
error: error_5,
};
case 8: return [2 /*return*/];
}
});
});
};
/**
* Upload an image for later use
*
* @warning jpg/jpeg are the only supported image formats
*
* @example
* ```ts
* dreamInstance.uploadImage(fs.readFileSync('./image.jpg')).then(console.log);
* ```
*/
WomboDream.prototype.uploadImage = function (bufferedImage) {
var _a;
return __awaiter(this, void 0, void 0, function () {
var requestAgent, resourceUploadInfos, error_6;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, this.buildHttpRequestAgentForDreamApi()];
case 1:
requestAgent = _b.sent();
_b.label = 2;
case 2:
_b.trys.push([2, 5, , 6]);
return [4 /*yield*/, requestAgent.post(this.buildUploadUrl(), {
media_expiry: 'HOURS_72',
media_suffix: 'jpeg',
num_uploads: 1,
})];
case 3:
resourceUploadInfos = (_a = (_b.sent()).data) === null || _a === void 0 ? void 0 : _a.shift();
return [4 /*yield*/, requestAgent.put(resourceUploadInfos.media_url, bufferedImage, {
headers: {
'Content-Type': 'image/jpeg',
'Content-Length': bufferedImage.length,
},
})];
case 4:
_b.sent();
return [2 /*return*/, resourceUploadInfos];
case 5:
error_6 = _b.sent();
throw {
reason: 'Failed to upload image',
error: error_6,
};
case 6: return [2 /*return*/];
}
});
});
};
/**
* Fetch all available styles
*
* @example
* ```ts
* dreamInstance.fetchStyles().then(console.log);
* ```
*/
WomboDream.prototype.fetchStyles = function () {
return __awaiter(this, void 0, void 0, function () {
var requestAgent, styles, error_7;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.buildHttpRequestAgentForDreamApi()];
case 1:
requestAgent = _a.sent();
_a.label = 2;
case 2:
_a.trys.push([2, 4, , 5]);
return [4 /*yield*/, requestAgent.get(this.buildApiStyleUrl())];
case 3:
styles = _a.sent();
return [2 /*return*/, styles.data];
case 4:
error_7 = _a.sent();
throw { reason: 'Failed to fetch styles', error: error_7 };
case 5: return [2 /*return*/];
}
});
});
};
/**
* Fetch shop url from task id
*
* @warning must be done with the same account as the task was created
*
* @example
* ```ts
* const taskId:string;
* dreamInstance.fetchTaskShopUrl(taskId).then(console.log);
* ```
*/
WomboDream.prototype.fetchTaskShopUrl = function (taskId) {
return __awaiter(this, void 0, void 0, function () {
var requestAgent, taskShopUrl, error_8;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.buildHttpRequestAgentForDreamApi()];
case 1:
requestAgent = _a.sent();
_a.label = 2;
case 2:
_a.trys.push([2, 4, , 5]);
return [4 /*yield*/, requestAgent.get(this.buildApiTaskShopUrl(taskId))];
case 3:
taskShopUrl = _a.sent();
return [2 /*return*/, taskShopUrl.data.url];
case 4:
error_8 = _a.sent();
throw { reason: 'Failed to fetch task shop url', error: error_8 };
case 5: return [2 /*return*/];
}
});
});
};
/**
* Save task to the gallery
*
* @warning must be done with the same account as the task was created
* @warning you must be logged as a user to use it
*
* @example
* ```ts
* const taskId:string;
* dreamInstance.saveTaskToGallery(taskId, "wonderful kitty").then(console.log);
* ```
*/
WomboDream.prototype.saveTaskToGallery = function (taskId, name, isPublic, isPromptVisible) {
if (name === void 0) { name = ''; }
if (isPublic === void 0) { isPublic = false; }
if (isPromptVisible === void 0) { isPromptVisible = true; }
return __awaiter(this, void 0, void 0, function () {
var requestAgent, savedTask, error_9;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.buildHttpRequestAgentForDreamApi()];
case 1:
requestAgent = _a.sent();
_a.label = 2;
case 2:
_a.trys.push([2, 4, , 5]);
return [4 /*yield*/, requestAgent.post(this.buildRawApiGalleryUrl(), {
task_id: taskId,
name: name,
is_public: isPublic,
is_prompt_visible: isPromptVisible,
})];
case 3:
savedTask = _a.sent();
return [2 /*return*/, savedTask.data];
case 4:
error_9 = _a.sent();
throw { reason: 'Failed to save task to gallery', error: error_9 };
case 5: return [2 /*return*/];
}
});
});
};
/**
* Fetch a gallery saved task
*
* @warning task_id != task_gallery_id
* @warning you must be logged as a user to use it
*
* @example
* ```ts
* const taskGalleryId:number;
* dreamInstance.fetchGalleryTask(taskGalleryId).then(console.log);
* ```
*/
WomboDream.prototype.fetchGalleryTask = function (taskGalleryId) {
return __awaiter(this, void 0, void 0, function () {
var requestAgent, galleryTask, error_10;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.buildHttpRequestAgentForDreamApi()];
case 1:
requestAgent = _a.sent();
_a.label = 2;
case 2:
_a.trys.push([2, 4, , 5]);
return [4 /*yield*/, requestAgent.get(this.buildApiGalleryUrl("".concat(taskGalleryId)))];
case 3:
galleryTask = _a.sent();
return [2 /*return*/, galleryTask.data];
case 4:
error_10 = _a.sent();
throw { reason: 'Failed to fetch gallery task', error: error_10 };
case 5: return [2 /*return*/];
}
});
});
};
/**
* Fetch gallery saved tasks
*
* @warning you must be logged as a user to use it
*
* @example
* ```ts
* dreamInstance.fetchGalleryTasks().then(console.log);
* ```
*/
WomboDream.prototype.fetchGalleryTasks = function () {
return __awaiter(this, void 0, void 0, function () {
var requestAgent, galleryTask, error_11;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.buildHttpRequestAgentForDreamApi()];
case 1:
requestAgent = _a.sent();
_a.label = 2;
case 2:
_a.trys.push([2, 4, , 5]);
return [4 /*yield*/, requestAgent.get(this.buildRawApiGalleryUrl())];
case 3:
galleryTask = _a.sent();
return [2 /*return*/, galleryTask.data.items];
case 4:
error_11 = _a.sent();
throw { reason: 'failed to fetch gallery tasks', error: error_11 };
case 5: return [2 /*return*/];
}
});
});
};
/**
* Fetch a gallery saved task
*
* @warning task_id != task_gallery_id
* @warning you must be logged as a user to use it
*
* @example
* ```ts
* const taskGalleryId:number;
* dreamInstance.deleteGalleryTask(taskGalleryId);
* ```
*/
WomboDream.prototype.deleteGalleryTask = function (taskGalleryId) {
return __awaiter(this, void 0, void 0, function () {
var requestAgent, galleryTask, error_12;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.buildHttpRequestAgentForDreamApi()];
case 1:
requestAgent = _a.sent();
_a.label = 2;
case 2:
_a.trys.push([2, 4, , 5]);
return [4 /*yield*/, requestAgent.delete(this.buildApiGalleryUrl("".concat(taskGalleryId)))];
case 3:
galleryTask = _a.sent();
return [2 /*return*/, galleryTask.data];
case 4:
error_12 = _a.sent();
throw { reason: 'Failed to delete gallery task', error: error_12 };
case 5: return [2 /*return*/];
}
});
});
};
/**
* Set account username
*
* @warning YOU NEED TO SET A USERNAME TO INTERRACT WITH GALLERY
*
* @example
* ```ts
* dreamInstance.setUsername("myusername");
* ```
*/
WomboDream.prototype.setUsername = function (username) {
return __awaiter(this, void 0, void 0, function () {
var requestAgent, user, error_13;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.buildHttpRequestAgentForUserAPI()];
case 1:
requestAgent = _a.sent();
_a.label = 2;
case 2:
_a.trys.push([2, 4, , 5]);
return [4 /*yield*/, requestAgent.post(this.apiUserSuffix, {
username: username,
})];
case 3:
user = _a.sent();
return [2 /*return*/, user.data];
case 4:
error_13 = _a.sent();
throw { reason: 'Failed to set username', error: error_13 };
case 5: return [2 /*return*/];
}
});
});
};
return WomboDream;
}());
exports.WomboDream = WomboDream;
exports.default = WomboDream;