Files
liberama/client/api/reader.js
2019-01-13 19:02:42 +07:00

64 lines
2.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import axios from 'axios';
import {sleep} from '../share/utils';
const api = axios.create({
baseURL: '/api/reader'
});
const workerApi = axios.create({
baseURL: '/api/worker'
});
class Reader {
async loadBook(url, callback) {
const refreshPause = 200;
let response = await api.post('/load-book', {type: 'url', url});
const workerId = response.data.workerId;
if (!workerId)
throw new Error('Неверный ответ api');
let i = 0;
while (1) {// eslint-disable-line no-constant-condition
if (callback)
callback(response.data);
if (response.data.state == 'finish') {//воркер закончил работу, можно скачивать
const options = {
onDownloadProgress: progress => {
if (callback)
callback(Object.assign({},
response.data,
{state: 'loading', step: 4, progress: Math.round((progress.loaded*100)/progress.total)}
));
}
}
//загрузка
const book = await axios.get(response.data.path, options);
return Object.assign({}, response.data, {data: book.data});
}
if (response.data.state == 'error') {
let errMes = response.data.error;
if (errMes.indexOf('getaddrinfo') >= 0 ||
errMes.indexOf('ECONNRESET') >= 0 ||
errMes.indexOf('EINVAL') >= 0 ||
errMes.indexOf('404') >= 0)
errMes = `Ресурс не найден по адресу: ${response.data.url}`;
throw new Error(errMes);
}
if (i > 0)
await sleep(refreshPause);
i++;
if (i > 30*1000/refreshPause) {
throw new Error('Слишком долгое время ожидания');
}
//проверка воркера
const prevProgress = response.data.progress;
response = await workerApi.post('/get-state', {workerId});
i = (prevProgress != response.data.progress ? 1 : i);
}
}
}
export default new Reader();