2018-12-21 17:03:26 +01:00
|
|
|
import MyWorker from './worker.js';
|
2019-04-30 02:21:06 +02:00
|
|
|
//import localforage from 'localforage';
|
2019-04-29 17:22:46 +02:00
|
|
|
import BroadcastChannel from 'broadcast-channel';
|
2018-12-21 17:03:26 +01:00
|
|
|
import uuid4 from 'uuid/v4';
|
|
|
|
import log from './logger.js';
|
|
|
|
|
|
|
|
const sleep = ms => new Promise(res => setTimeout(res, ms));
|
|
|
|
|
2019-02-04 16:06:08 +01:00
|
|
|
/**
|
2019-04-23 11:06:55 +02:00
|
|
|
* TDLib in a browser
|
2019-02-04 16:06:08 +01:00
|
|
|
*
|
2019-04-23 11:06:55 +02:00
|
|
|
* TDLib can be compiled to WebAssembly or asm.js using Emscripten compiler and used in a browser from JavaScript.
|
|
|
|
* This is a convenient wrapper for TDLib in a browser which controls TDLib instance creation, handles interaction
|
2019-04-29 19:06:18 +02:00
|
|
|
* with TDLib and manages a filesystem for persistent TDLib data.
|
2019-04-25 15:46:03 +02:00
|
|
|
* TDLib instance is created in a Web Worker to run it in a separate thread.
|
2019-04-29 19:06:18 +02:00
|
|
|
* TdClient just sends queries to the Web Worker and receives updates and results from it.
|
2019-04-23 11:06:55 +02:00
|
|
|
* <br>
|
|
|
|
* <br>
|
2019-04-29 19:06:18 +02:00
|
|
|
* Differences from the TDLib JSON API:<br>
|
|
|
|
* 1. Added the update <code>updateFatalError error:string = Update;</code> which is sent whenever TDLib encounters a fatal error.<br>
|
2019-04-26 02:22:39 +02:00
|
|
|
* 2. Added the method <code>setJsLogVerbosityLevel new_verbosity_level:string = Ok;</code>, which allows to change the verbosity level of tdweb logging.<br>
|
2019-04-29 19:06:18 +02:00
|
|
|
* 3. Added the possibility to use blobs as input files via the constructor <code>inputFileBlob data:<JavaScript blob> = InputFile;</code>.<br>
|
2019-04-26 02:22:39 +02:00
|
|
|
* 4. The class <code>filePart</code> contains data as a JavaScript blob instead of a base64-encoded string.<br>
|
2019-08-06 01:45:52 +02:00
|
|
|
* 5. The methods <code>getStorageStatistics</code>, <code>getStorageStatisticsFast</code>, <code>optimizeStorage</code>, <code>addProxy</code> and <code>getFileDownloadedPrefixSize</code> are not supported.<br>
|
2019-02-04 16:06:08 +01:00
|
|
|
* <br>
|
|
|
|
*/
|
2018-12-21 17:03:26 +01:00
|
|
|
class TdClient {
|
2019-02-04 16:06:08 +01:00
|
|
|
/**
|
2019-04-23 11:06:55 +02:00
|
|
|
* @callback TdClient~updateCallback
|
2019-04-23 14:07:36 +02:00
|
|
|
* @param {Object} update The update.
|
2019-02-04 16:06:08 +01:00
|
|
|
*/
|
|
|
|
|
|
|
|
/**
|
2019-04-23 11:06:55 +02:00
|
|
|
* Create TdClient.
|
2019-04-29 19:06:18 +02:00
|
|
|
* @param {Object} options - Options for TDLib instance creation.
|
|
|
|
* @param {TdClient~updateCallback} options.onUpdate - Callback for all incoming updates.
|
|
|
|
* @param {string} [options.instanceName=tdlib] - Name of the TDLib instance. Currently only one instance of TdClient with a given name is allowed. All but one instances with the same name will be automatically closed. Usually, the newest non-background instance is kept alive. Files will be stored in an IndexedDb table with the same name.
|
2019-04-23 11:06:55 +02:00
|
|
|
* @param {boolean} [options.isBackground=false] - Pass true, if the instance is opened from the background.
|
2019-04-24 21:05:09 +02:00
|
|
|
* @param {string} [options.jsLogVerbosityLevel=info] - The initial verbosity level of the JavaScript part of the code (one of 'error', 'warning', 'info', 'log', 'debug').
|
2019-04-29 19:06:18 +02:00
|
|
|
* @param {number} [options.logVerbosityLevel=2] - The initial verbosity level for the TDLib internal logging (0-1023).
|
|
|
|
* @param {boolean} [options.useDatabase=true] - Pass false to use TDLib without database and secret chats. It will significantly improve loading time, but some functionality will be unavailable.
|
2019-04-24 13:00:02 +02:00
|
|
|
* @param {boolean} [options.readOnly=false] - For debug only. Pass true to open TDLib database in read-only mode
|
2019-04-24 21:05:09 +02:00
|
|
|
* @param {string} [options.mode=auto] - For debug only. The type of the TDLib build to use. 'asmjs' for asm.js and 'wasm' for WebAssembly. If mode == 'auto' WebAbassembly will be used if supported by browser, asm.js otherwise.
|
2019-02-04 16:06:08 +01:00
|
|
|
*/
|
2018-12-21 17:03:26 +01:00
|
|
|
constructor(options) {
|
2019-02-14 15:25:38 +01:00
|
|
|
log.setVerbosity(options.jsLogVerbosityLevel);
|
2018-12-21 17:03:26 +01:00
|
|
|
this.worker = new MyWorker();
|
2019-04-24 13:00:02 +02:00
|
|
|
this.worker.onmessage = e => {
|
2019-04-29 17:22:46 +02:00
|
|
|
this.onResponse(e.data);
|
2018-12-21 17:03:26 +01:00
|
|
|
};
|
|
|
|
this.query_id = 0;
|
|
|
|
this.query_callbacks = new Map();
|
2019-02-04 16:06:08 +01:00
|
|
|
if ('onUpdate' in options) {
|
|
|
|
this.onUpdate = options.onUpdate;
|
|
|
|
delete options.onUpdate;
|
|
|
|
}
|
2019-04-24 13:00:02 +02:00
|
|
|
options.instanceName = options.instanceName || 'tdlib';
|
2019-05-10 15:47:39 +02:00
|
|
|
this.fileManager = new FileManager(options.instanceName, this);
|
2018-12-21 17:03:26 +01:00
|
|
|
this.worker.postMessage({ '@type': 'init', options: options });
|
|
|
|
this.closeOtherClients(options);
|
|
|
|
}
|
|
|
|
|
2019-02-04 16:06:08 +01:00
|
|
|
/**
|
2019-04-23 11:06:55 +02:00
|
|
|
* Send a query to TDLib.
|
2019-02-04 16:06:08 +01:00
|
|
|
*
|
2019-04-29 19:06:18 +02:00
|
|
|
* If the query contains the field '@extra', the same field will be added into the result.
|
2019-02-04 16:06:08 +01:00
|
|
|
*
|
2019-04-23 11:06:55 +02:00
|
|
|
* @param {Object} query - The query for TDLib. See the [td_api.tl]{@link https://github.com/tdlib/td/blob/master/td/generate/scheme/td_api.tl} scheme or
|
|
|
|
* the automatically generated [HTML documentation]{@link https://core.telegram.org/tdlib/docs/td__api_8h.html}
|
|
|
|
* for a list of all available TDLib [methods]{@link https://core.telegram.org/tdlib/docs/classtd_1_1td__api_1_1_function.html} and
|
|
|
|
* [classes]{@link https://core.telegram.org/tdlib/docs/classtd_1_1td__api_1_1_object.html}.
|
|
|
|
* @returns {Promise} Promise object represents the result of the query.
|
2019-02-04 16:06:08 +01:00
|
|
|
*/
|
|
|
|
send(query) {
|
2019-04-29 17:22:46 +02:00
|
|
|
return this.doSend(query, true);
|
|
|
|
}
|
|
|
|
|
|
|
|
/** @private */
|
|
|
|
sendInternal(query) {
|
|
|
|
return this.doSend(query, false);
|
|
|
|
}
|
|
|
|
/** @private */
|
|
|
|
doSend(query, isExternal) {
|
2019-02-04 16:06:08 +01:00
|
|
|
this.query_id++;
|
|
|
|
if (query['@extra']) {
|
|
|
|
query['@extra'] = {
|
2019-04-29 17:22:46 +02:00
|
|
|
'@old_extra': JSON.parse(JSON.stringify(query['@extra'])),
|
2019-02-04 16:06:08 +01:00
|
|
|
query_id: this.query_id
|
|
|
|
};
|
|
|
|
} else {
|
|
|
|
query['@extra'] = {
|
|
|
|
query_id: this.query_id
|
|
|
|
};
|
|
|
|
}
|
2019-02-14 15:25:38 +01:00
|
|
|
if (query['@type'] === 'setJsLogVerbosityLevel') {
|
|
|
|
log.setVerbosity(query.new_verbosity_level);
|
2019-02-04 16:06:08 +01:00
|
|
|
}
|
|
|
|
|
2019-02-14 15:25:38 +01:00
|
|
|
log.debug('send to worker: ', query);
|
2019-04-29 17:22:46 +02:00
|
|
|
const res = new Promise((resolve, reject) => {
|
2019-02-04 16:06:08 +01:00
|
|
|
this.query_callbacks.set(this.query_id, [resolve, reject]);
|
|
|
|
});
|
2019-04-29 17:22:46 +02:00
|
|
|
if (isExternal) {
|
|
|
|
this.externalPostMessage(query);
|
|
|
|
} else {
|
|
|
|
this.worker.postMessage(query);
|
|
|
|
}
|
2019-04-24 13:00:02 +02:00
|
|
|
return res;
|
|
|
|
}
|
|
|
|
|
|
|
|
/** @private */
|
|
|
|
externalPostMessage(query) {
|
2019-04-29 17:22:46 +02:00
|
|
|
const unsupportedMethods = [
|
2019-04-24 13:00:02 +02:00
|
|
|
'getStorageStatistics',
|
|
|
|
'getStorageStatisticsFast',
|
|
|
|
'optimizeStorage',
|
|
|
|
'addProxy',
|
|
|
|
'init',
|
|
|
|
'start'
|
|
|
|
];
|
|
|
|
if (unsupportedMethods.includes(query['@type'])) {
|
|
|
|
this.onResponse({
|
|
|
|
'@type': 'error',
|
|
|
|
'@extra': query['@extra'],
|
|
|
|
code: 400,
|
2019-04-24 21:05:09 +02:00
|
|
|
message: "Method '" + query['@type'] + "' is not supported"
|
2019-04-24 13:00:02 +02:00
|
|
|
});
|
|
|
|
return;
|
|
|
|
}
|
2019-04-30 02:21:06 +02:00
|
|
|
if (query['@type'] === 'readFile' || query['@type'] === 'readFilePart') {
|
2019-04-24 17:44:12 +02:00
|
|
|
this.readFile(query);
|
|
|
|
return;
|
|
|
|
}
|
2019-04-29 17:22:46 +02:00
|
|
|
if (query['@type'] === 'deleteFile') {
|
|
|
|
this.deleteFile(query);
|
|
|
|
return;
|
|
|
|
}
|
2019-04-24 13:00:02 +02:00
|
|
|
this.worker.postMessage(query);
|
|
|
|
}
|
|
|
|
|
2019-04-24 17:44:12 +02:00
|
|
|
/** @private */
|
|
|
|
async readFile(query) {
|
2019-04-29 17:22:46 +02:00
|
|
|
const response = await this.fileManager.readFile(query);
|
|
|
|
this.onResponse(response);
|
|
|
|
}
|
|
|
|
|
|
|
|
/** @private */
|
|
|
|
async deleteFile(query) {
|
|
|
|
const response = this.fileManager.deleteFile(query);
|
|
|
|
try {
|
|
|
|
if (response.idb_key) {
|
|
|
|
await this.sendInternal({
|
|
|
|
'@type': 'deleteIdbKey',
|
|
|
|
idb_key: response.idb_key
|
|
|
|
});
|
|
|
|
delete response.idb_key;
|
|
|
|
}
|
|
|
|
await this.sendInternal({
|
|
|
|
'@type': 'deleteFile',
|
|
|
|
file_id: query.file_id
|
|
|
|
});
|
|
|
|
} catch (e) {}
|
2019-04-24 17:44:12 +02:00
|
|
|
this.onResponse(response);
|
|
|
|
}
|
|
|
|
|
2019-04-24 13:00:02 +02:00
|
|
|
/** @private */
|
|
|
|
onResponse(response) {
|
|
|
|
log.debug(
|
|
|
|
'receive from worker: ',
|
|
|
|
JSON.parse(
|
|
|
|
JSON.stringify(response, (key, value) => {
|
2020-10-09 18:40:13 +02:00
|
|
|
if (key === 'arr' || key === 'data') {
|
2019-04-24 13:00:02 +02:00
|
|
|
return undefined;
|
|
|
|
}
|
|
|
|
return value;
|
|
|
|
})
|
|
|
|
)
|
|
|
|
);
|
2019-04-24 17:44:12 +02:00
|
|
|
|
|
|
|
// for FileManager
|
|
|
|
response = this.prepareResponse(response);
|
|
|
|
|
2019-04-24 13:00:02 +02:00
|
|
|
if ('@extra' in response) {
|
2019-04-29 17:22:46 +02:00
|
|
|
const query_id = response['@extra'].query_id;
|
|
|
|
const [resolve, reject] = this.query_callbacks.get(query_id);
|
2019-04-24 13:00:02 +02:00
|
|
|
this.query_callbacks.delete(query_id);
|
|
|
|
if ('@old_extra' in response['@extra']) {
|
|
|
|
response['@extra'] = response['@extra']['@old_extra'];
|
|
|
|
}
|
|
|
|
if (resolve) {
|
|
|
|
if (response['@type'] === 'error') {
|
|
|
|
reject(response);
|
|
|
|
} else {
|
|
|
|
resolve(response);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if (response['@type'] === 'inited') {
|
|
|
|
this.onInited();
|
|
|
|
return;
|
|
|
|
}
|
2019-04-25 20:50:26 +02:00
|
|
|
if (response['@type'] === 'fsInited') {
|
|
|
|
this.onFsInited();
|
|
|
|
return;
|
|
|
|
}
|
2019-04-24 13:00:02 +02:00
|
|
|
if (
|
|
|
|
response['@type'] === 'updateAuthorizationState' &&
|
|
|
|
response.authorization_state['@type'] === 'authorizationStateClosed'
|
|
|
|
) {
|
|
|
|
this.onClosed();
|
|
|
|
}
|
|
|
|
this.onUpdate(response);
|
|
|
|
}
|
2019-02-04 16:06:08 +01:00
|
|
|
}
|
|
|
|
|
2019-04-24 17:44:12 +02:00
|
|
|
/** @private */
|
|
|
|
prepareFile(file) {
|
|
|
|
return this.fileManager.registerFile(file);
|
|
|
|
}
|
|
|
|
|
|
|
|
/** @private */
|
|
|
|
prepareResponse(response) {
|
|
|
|
if (response['@type'] === 'file') {
|
2019-04-29 17:22:46 +02:00
|
|
|
if (false && Math.random() < 0.1) {
|
|
|
|
(async () => {
|
|
|
|
log.warn('DELETE FILE', response.id);
|
|
|
|
try {
|
|
|
|
await this.send({ '@type': 'deleteFile', file_id: response.id });
|
|
|
|
} catch (e) {}
|
|
|
|
})();
|
|
|
|
}
|
2019-04-24 17:44:12 +02:00
|
|
|
return this.prepareFile(response);
|
|
|
|
}
|
2019-04-29 17:22:46 +02:00
|
|
|
for (const key in response) {
|
|
|
|
const field = response[key];
|
2020-10-09 18:40:13 +02:00
|
|
|
if (
|
|
|
|
field &&
|
|
|
|
typeof field === 'object' &&
|
|
|
|
key !== 'data' &&
|
|
|
|
key !== 'arr'
|
|
|
|
) {
|
2019-04-24 17:44:12 +02:00
|
|
|
response[key] = this.prepareResponse(field);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return response;
|
|
|
|
}
|
|
|
|
|
2019-02-04 16:06:08 +01:00
|
|
|
/** @private */
|
2018-12-21 17:03:26 +01:00
|
|
|
onBroadcastMessage(e) {
|
2019-04-29 17:22:46 +02:00
|
|
|
//const message = e.data;
|
|
|
|
const message = e;
|
2019-04-25 20:50:26 +02:00
|
|
|
if (message.uid === this.uid) {
|
|
|
|
log.info('ignore self broadcast message: ', message);
|
|
|
|
return;
|
|
|
|
}
|
2018-12-21 17:03:26 +01:00
|
|
|
log.info('got broadcast message: ', message);
|
|
|
|
if (message.isBackground && !this.isBackground) {
|
|
|
|
// continue
|
|
|
|
} else if (
|
|
|
|
(!message.isBackground && this.isBackground) ||
|
|
|
|
message.timestamp > this.timestamp
|
|
|
|
) {
|
|
|
|
this.close();
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (message.state === 'closed') {
|
|
|
|
this.waitSet.delete(message.uid);
|
|
|
|
if (this.waitSet.size === 0) {
|
|
|
|
log.info('onWaitSetEmpty');
|
|
|
|
this.onWaitSetEmpty();
|
|
|
|
this.onWaitSetEmpty = () => {};
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
this.waitSet.add(message.uid);
|
|
|
|
if (message.state !== 'closing') {
|
|
|
|
this.postState();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-02-04 16:06:08 +01:00
|
|
|
/** @private */
|
2018-12-21 17:03:26 +01:00
|
|
|
postState() {
|
2019-04-29 17:22:46 +02:00
|
|
|
const state = {
|
|
|
|
uid: this.uid,
|
2018-12-21 17:03:26 +01:00
|
|
|
state: this.state,
|
|
|
|
timestamp: this.timestamp,
|
|
|
|
isBackground: this.isBackground
|
|
|
|
};
|
|
|
|
log.info('Post state: ', state);
|
|
|
|
this.channel.postMessage(state);
|
|
|
|
}
|
|
|
|
|
2019-02-04 16:06:08 +01:00
|
|
|
/** @private */
|
2018-12-21 17:03:26 +01:00
|
|
|
onWaitSetEmpty() {
|
|
|
|
// nop
|
|
|
|
}
|
|
|
|
|
2019-04-25 20:50:26 +02:00
|
|
|
/** @private */
|
|
|
|
onFsInited() {
|
|
|
|
this.fileManager.init();
|
|
|
|
}
|
|
|
|
|
2019-02-04 16:06:08 +01:00
|
|
|
/** @private */
|
2018-12-21 17:03:26 +01:00
|
|
|
onInited() {
|
|
|
|
this.isInited = true;
|
|
|
|
this.doSendStart();
|
|
|
|
}
|
2019-02-04 16:06:08 +01:00
|
|
|
|
|
|
|
/** @private */
|
2018-12-21 17:03:26 +01:00
|
|
|
sendStart() {
|
|
|
|
this.wantSendStart = true;
|
|
|
|
this.doSendStart();
|
|
|
|
}
|
|
|
|
|
2019-02-04 16:06:08 +01:00
|
|
|
/** @private */
|
2018-12-21 17:03:26 +01:00
|
|
|
doSendStart() {
|
|
|
|
if (!this.isInited || !this.wantSendStart || this.state !== 'start') {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
this.wantSendStart = false;
|
|
|
|
this.state = 'active';
|
2019-04-29 17:22:46 +02:00
|
|
|
const query = { '@type': 'start' };
|
2018-12-21 17:03:26 +01:00
|
|
|
log.info('send to worker: ', query);
|
|
|
|
this.worker.postMessage(query);
|
|
|
|
}
|
|
|
|
|
2019-02-04 16:06:08 +01:00
|
|
|
/** @private */
|
2018-12-21 17:03:26 +01:00
|
|
|
onClosed() {
|
|
|
|
this.isClosing = true;
|
|
|
|
this.worker.terminate();
|
|
|
|
log.info('worker is terminated');
|
|
|
|
this.state = 'closed';
|
|
|
|
this.postState();
|
|
|
|
}
|
|
|
|
|
2019-02-04 16:06:08 +01:00
|
|
|
/** @private */
|
2018-12-21 17:03:26 +01:00
|
|
|
close() {
|
|
|
|
if (this.isClosing) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
this.isClosing = true;
|
|
|
|
|
|
|
|
log.info('close state: ', this.state);
|
|
|
|
|
|
|
|
if (this.state === 'start') {
|
|
|
|
this.onClosed();
|
|
|
|
this.onUpdate({
|
|
|
|
'@type': 'updateAuthorizationState',
|
|
|
|
authorization_state: {
|
|
|
|
'@type': 'authorizationStateClosed'
|
|
|
|
}
|
|
|
|
});
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2019-04-29 17:22:46 +02:00
|
|
|
const query = { '@type': 'close' };
|
2018-12-21 17:03:26 +01:00
|
|
|
log.info('send to worker: ', query);
|
|
|
|
this.worker.postMessage(query);
|
|
|
|
|
|
|
|
this.state = 'closing';
|
|
|
|
this.postState();
|
|
|
|
}
|
|
|
|
|
2019-02-04 16:06:08 +01:00
|
|
|
/** @private */
|
2018-12-21 17:03:26 +01:00
|
|
|
async closeOtherClients(options) {
|
|
|
|
this.uid = uuid4();
|
|
|
|
this.state = 'start';
|
|
|
|
this.isBackground = !!options.isBackground;
|
|
|
|
this.timestamp = Date.now();
|
|
|
|
this.waitSet = new Set();
|
|
|
|
|
|
|
|
log.info('close other clients');
|
2019-04-29 17:22:46 +02:00
|
|
|
this.channel = new BroadcastChannel(options.instanceName, {
|
|
|
|
webWorkerSupport: false
|
|
|
|
});
|
2018-12-21 17:03:26 +01:00
|
|
|
|
|
|
|
this.postState();
|
|
|
|
|
|
|
|
this.channel.onmessage = message => {
|
2019-04-29 17:22:46 +02:00
|
|
|
this.onBroadcastMessage(message);
|
2018-12-21 17:03:26 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
await sleep(300);
|
|
|
|
if (this.waitSet.size !== 0) {
|
|
|
|
await new Promise(resolve => {
|
2019-04-29 17:22:46 +02:00
|
|
|
this.onWaitSetEmpty = resolve;
|
2018-12-21 17:03:26 +01:00
|
|
|
});
|
|
|
|
}
|
|
|
|
this.sendStart();
|
|
|
|
}
|
|
|
|
|
2019-02-04 16:06:08 +01:00
|
|
|
/** @private */
|
2019-04-24 21:05:09 +02:00
|
|
|
onUpdate(update) {
|
2018-12-21 17:03:26 +01:00
|
|
|
log.info('ignore onUpdate');
|
|
|
|
//nop
|
|
|
|
}
|
|
|
|
}
|
2019-04-24 17:44:12 +02:00
|
|
|
|
2019-04-29 17:22:46 +02:00
|
|
|
/** @private */
|
|
|
|
class ListNode {
|
|
|
|
constructor(value) {
|
|
|
|
this.value = value;
|
|
|
|
this.clear();
|
|
|
|
}
|
|
|
|
|
|
|
|
erase() {
|
|
|
|
this.prev.connect(this.next);
|
|
|
|
this.clear();
|
|
|
|
}
|
|
|
|
clear() {
|
|
|
|
this.prev = this;
|
|
|
|
this.next = this;
|
|
|
|
}
|
|
|
|
|
|
|
|
connect(other) {
|
|
|
|
this.next = other;
|
|
|
|
other.prev = this;
|
|
|
|
}
|
|
|
|
|
|
|
|
onUsed(other) {
|
|
|
|
other.usedAt = Date.now();
|
2019-06-19 15:05:10 +02:00
|
|
|
other.erase();
|
2019-04-29 17:22:46 +02:00
|
|
|
other.connect(this.next);
|
|
|
|
log.debug('LRU: used file_id: ', other.value);
|
|
|
|
this.connect(other);
|
|
|
|
}
|
|
|
|
|
|
|
|
getLru() {
|
|
|
|
if (this === this.next) {
|
|
|
|
throw new Error('popLru from empty list');
|
|
|
|
}
|
|
|
|
return this.prev;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-24 17:44:12 +02:00
|
|
|
/** @private */
|
|
|
|
class FileManager {
|
2019-05-10 15:47:39 +02:00
|
|
|
constructor(instanceName, client) {
|
2019-04-25 20:50:26 +02:00
|
|
|
this.instanceName = instanceName;
|
2019-04-24 17:44:12 +02:00
|
|
|
this.cache = new Map();
|
2019-04-25 20:50:26 +02:00
|
|
|
this.pending = [];
|
|
|
|
this.transaction_id = 0;
|
2019-04-29 17:22:46 +02:00
|
|
|
this.totalSize = 0;
|
|
|
|
this.lru = new ListNode(-1);
|
2019-05-10 15:47:39 +02:00
|
|
|
this.client = client;
|
2019-04-25 20:50:26 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
init() {
|
2019-04-24 17:44:12 +02:00
|
|
|
this.idb = new Promise((resolve, reject) => {
|
2019-12-24 11:39:52 +01:00
|
|
|
const request = indexedDB.open(this.instanceName);
|
2019-04-24 17:44:12 +02:00
|
|
|
request.onsuccess = () => resolve(request.result);
|
|
|
|
request.onerror = () => reject(request.error);
|
|
|
|
});
|
|
|
|
//this.store = localforage.createInstance({
|
|
|
|
//name: instanceName
|
|
|
|
//});
|
2019-04-25 20:50:26 +02:00
|
|
|
this.isInited = true;
|
2019-04-24 17:44:12 +02:00
|
|
|
}
|
|
|
|
|
2019-04-29 17:22:46 +02:00
|
|
|
unload(info) {
|
|
|
|
if (info.arr) {
|
|
|
|
log.debug(
|
|
|
|
'LRU: delete file_id: ',
|
|
|
|
info.node.value,
|
|
|
|
' with arr.length: ',
|
|
|
|
info.arr.length
|
|
|
|
);
|
|
|
|
this.totalSize -= info.arr.length;
|
|
|
|
delete info.arr;
|
|
|
|
}
|
|
|
|
if (info.node) {
|
|
|
|
info.node.erase();
|
|
|
|
delete info.node;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-24 17:44:12 +02:00
|
|
|
registerFile(file) {
|
|
|
|
if (file.idb_key || file.arr) {
|
2019-06-14 21:03:19 +02:00
|
|
|
file.local.is_downloading_completed = true;
|
|
|
|
} else {
|
|
|
|
file.local.is_downloading_completed = false;
|
2019-05-10 15:47:39 +02:00
|
|
|
}
|
|
|
|
let info = {};
|
|
|
|
const cached_info = this.cache.get(file.id);
|
|
|
|
if (cached_info) {
|
|
|
|
info = cached_info;
|
|
|
|
} else {
|
|
|
|
this.cache.set(file.id, info);
|
|
|
|
}
|
|
|
|
if (file.idb_key) {
|
|
|
|
info.idb_key = file.idb_key;
|
2019-06-14 21:03:19 +02:00
|
|
|
delete file.idb_key;
|
2019-05-10 15:47:39 +02:00
|
|
|
} else {
|
|
|
|
delete info.idb_key;
|
|
|
|
}
|
|
|
|
if (file.arr) {
|
|
|
|
const now = Date.now();
|
2019-07-25 17:27:03 +02:00
|
|
|
while (this.totalSize > 100000000) {
|
2019-05-10 15:47:39 +02:00
|
|
|
const node = this.lru.getLru();
|
2019-07-25 17:27:03 +02:00
|
|
|
// immunity for 60 seconds
|
|
|
|
if (node.usedAt + 60 * 1000 > now) {
|
2019-05-10 15:47:39 +02:00
|
|
|
break;
|
2019-04-29 17:22:46 +02:00
|
|
|
}
|
2019-05-10 15:47:39 +02:00
|
|
|
const lru_info = this.cache.get(node.value);
|
|
|
|
this.unload(lru_info);
|
|
|
|
}
|
2019-04-29 17:22:46 +02:00
|
|
|
|
2019-05-10 15:47:39 +02:00
|
|
|
if (info.arr) {
|
|
|
|
log.warn('Got file.arr at least twice for the same file');
|
|
|
|
this.totalSize -= info.arr.length;
|
2019-04-24 17:44:12 +02:00
|
|
|
}
|
2019-05-10 15:47:39 +02:00
|
|
|
info.arr = file.arr;
|
|
|
|
delete file.arr;
|
|
|
|
this.totalSize += info.arr.length;
|
|
|
|
if (!info.node) {
|
|
|
|
log.debug(
|
|
|
|
'LRU: create file_id: ',
|
|
|
|
file.id,
|
|
|
|
' with arr.length: ',
|
|
|
|
info.arr.length
|
|
|
|
);
|
|
|
|
info.node = new ListNode(file.id);
|
|
|
|
}
|
|
|
|
this.lru.onUsed(info.node);
|
|
|
|
log.info('Total file.arr size: ', this.totalSize);
|
2019-04-24 17:44:12 +02:00
|
|
|
}
|
2019-05-10 15:47:39 +02:00
|
|
|
info.file = file;
|
2019-04-24 17:44:12 +02:00
|
|
|
return file;
|
|
|
|
}
|
|
|
|
|
|
|
|
async flushLoad() {
|
2019-04-29 17:22:46 +02:00
|
|
|
const pending = this.pending;
|
2019-04-24 17:44:12 +02:00
|
|
|
this.pending = [];
|
2019-04-29 17:22:46 +02:00
|
|
|
const idb = await this.idb;
|
|
|
|
const transaction_id = this.transaction_id++;
|
|
|
|
const read = idb
|
2019-04-24 17:44:12 +02:00
|
|
|
.transaction(['keyvaluepairs'], 'readonly')
|
|
|
|
.objectStore('keyvaluepairs');
|
|
|
|
log.debug('Load group of files from idb', pending.length);
|
|
|
|
for (const query of pending) {
|
|
|
|
const request = read.get(query.key);
|
|
|
|
request.onsuccess = event => {
|
|
|
|
const blob = event.target.result;
|
|
|
|
if (blob) {
|
2019-05-10 15:47:39 +02:00
|
|
|
if (blob.size === 0) {
|
2019-05-01 16:15:54 +02:00
|
|
|
log.error('Got empty blob from db ', query.key);
|
|
|
|
}
|
2019-04-25 20:50:26 +02:00
|
|
|
query.resolve({ data: blob, transaction_id: transaction_id });
|
2019-04-24 17:44:12 +02:00
|
|
|
} else {
|
|
|
|
query.reject();
|
|
|
|
}
|
|
|
|
};
|
2019-07-25 17:27:03 +02:00
|
|
|
request.onerror = () => query.reject(request.error);
|
2019-04-24 17:44:12 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
load(key, resolve, reject) {
|
|
|
|
if (this.pending.length === 0) {
|
|
|
|
setTimeout(() => {
|
2019-04-29 17:22:46 +02:00
|
|
|
this.flushLoad();
|
2019-04-24 17:44:12 +02:00
|
|
|
}, 1);
|
|
|
|
}
|
|
|
|
this.pending.push({ key: key, resolve: resolve, reject: reject });
|
|
|
|
}
|
|
|
|
|
2019-05-10 15:47:39 +02:00
|
|
|
async doLoadFull(info) {
|
2019-04-24 17:44:12 +02:00
|
|
|
if (info.arr) {
|
2019-04-25 20:50:26 +02:00
|
|
|
return { data: new Blob([info.arr]), transaction_id: -1 };
|
2019-04-24 17:44:12 +02:00
|
|
|
}
|
2019-05-10 15:47:39 +02:00
|
|
|
if (info.idb_key) {
|
|
|
|
const idb_key = info.idb_key;
|
|
|
|
//return this.store.getItem(idb_key);
|
|
|
|
return await new Promise((resolve, reject) => {
|
|
|
|
this.load(idb_key, resolve, reject);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
throw new Error('File is not loaded');
|
|
|
|
}
|
|
|
|
async doLoad(info, offset, size) {
|
|
|
|
if (!info.arr && !info.idb_key && info.file.local.path) {
|
|
|
|
try {
|
|
|
|
const count = await this.client.sendInternal({
|
|
|
|
'@type': 'getFileDownloadedPrefixSize',
|
|
|
|
file_id: info.file.id,
|
|
|
|
offset: offset
|
|
|
|
});
|
2020-10-08 15:14:46 +02:00
|
|
|
//log.error(count, size);
|
2019-05-10 15:47:39 +02:00
|
|
|
if (!size) {
|
|
|
|
size = count.count;
|
|
|
|
} else if (size > count.count) {
|
|
|
|
throw new Error('File not loaded yet');
|
|
|
|
}
|
|
|
|
const res = await this.client.sendInternal({
|
|
|
|
'@type': 'readFilePart',
|
|
|
|
path: info.file.local.path,
|
|
|
|
offset: offset,
|
2020-04-07 23:59:55 +02:00
|
|
|
count: size
|
2019-05-10 15:47:39 +02:00
|
|
|
});
|
|
|
|
res.data = new Blob([res.data]);
|
|
|
|
res.transaction_id = -2;
|
2020-10-08 15:14:46 +02:00
|
|
|
//log.error(res);
|
2019-05-10 15:47:39 +02:00
|
|
|
return res;
|
|
|
|
} catch (e) {
|
|
|
|
log.info('readFilePart failed', info, offset, size, e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const res = await this.doLoadFull(info);
|
|
|
|
|
|
|
|
// return slice(size, offset + size)
|
|
|
|
const data_size = res.data.size;
|
|
|
|
if (!size) {
|
|
|
|
size = data_size;
|
|
|
|
}
|
|
|
|
if (offset > data_size) {
|
|
|
|
offset = data_size;
|
|
|
|
}
|
|
|
|
res.data = res.data.slice(offset, offset + size);
|
|
|
|
return res;
|
2019-04-24 17:44:12 +02:00
|
|
|
}
|
|
|
|
|
2019-04-29 17:22:46 +02:00
|
|
|
doDelete(info) {
|
|
|
|
this.unload(info);
|
|
|
|
return info.idb_key;
|
|
|
|
}
|
|
|
|
|
2019-04-24 17:44:12 +02:00
|
|
|
async readFile(query) {
|
|
|
|
try {
|
2019-04-25 20:50:26 +02:00
|
|
|
if (!this.isInited) {
|
|
|
|
throw new Error('FileManager is not inited');
|
|
|
|
}
|
2019-04-29 17:22:46 +02:00
|
|
|
const info = this.cache.get(query.file_id);
|
2019-04-24 17:44:12 +02:00
|
|
|
if (!info) {
|
|
|
|
throw new Error('File is not loaded');
|
|
|
|
}
|
2019-04-29 17:22:46 +02:00
|
|
|
if (info.node) {
|
|
|
|
this.lru.onUsed(info.node);
|
|
|
|
}
|
2019-05-10 15:47:39 +02:00
|
|
|
query.offset = query.offset || 0;
|
2020-04-07 23:59:55 +02:00
|
|
|
query.size = query.count || query.size || 0;
|
2019-05-10 15:47:39 +02:00
|
|
|
const response = await this.doLoad(info, query.offset, query.size);
|
2019-04-24 17:44:12 +02:00
|
|
|
return {
|
2019-04-29 17:22:46 +02:00
|
|
|
'@type': 'filePart',
|
2019-04-24 17:44:12 +02:00
|
|
|
'@extra': query['@extra'],
|
2019-04-25 20:50:26 +02:00
|
|
|
data: response.data,
|
|
|
|
transaction_id: response.transaction_id
|
2019-04-24 17:44:12 +02:00
|
|
|
};
|
|
|
|
} catch (e) {
|
|
|
|
return {
|
|
|
|
'@type': 'error',
|
|
|
|
'@extra': query['@extra'],
|
|
|
|
code: 400,
|
|
|
|
message: e
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
2019-04-29 17:22:46 +02:00
|
|
|
|
|
|
|
deleteFile(query) {
|
|
|
|
const res = {
|
|
|
|
'@type': 'ok',
|
|
|
|
'@extra': query['@extra']
|
|
|
|
};
|
|
|
|
try {
|
|
|
|
if (!this.isInited) {
|
|
|
|
throw new Error('FileManager is not inited');
|
|
|
|
}
|
|
|
|
const info = this.cache.get(query.file_id);
|
|
|
|
if (!info) {
|
|
|
|
throw new Error('File is not loaded');
|
|
|
|
}
|
|
|
|
const idb_key = this.doDelete(info);
|
|
|
|
if (idb_key) {
|
|
|
|
res.idb_key = idb_key;
|
|
|
|
}
|
|
|
|
} catch (e) {}
|
|
|
|
return res;
|
|
|
|
}
|
2019-04-24 17:44:12 +02:00
|
|
|
}
|
|
|
|
|
2018-12-21 17:03:26 +01:00
|
|
|
export default TdClient;
|