-
Notifications
You must be signed in to change notification settings - Fork 8
/
converter.js
270 lines (208 loc) · 8.52 KB
/
converter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
/*! converter.js | (c) 2022 commeta <dcs-spb@ya.ru> Apache 2.0 License | https://github.com/commeta/modxWebpConverter, https://webdevops.ru/blog/webp-converter-plugin-modx.html */
Ext.onReady(function() {
"use strict";
const concurent_tasks= 3; // Setup this value equal to the number of server processor cores -1
const max_count_threads= 4; // Setup this value equal to the number of server processor cores -1
function manual_start(){ // Click in menu link
if(localStorage.getItem('converter_mode') == "clean"){ // Generate report
document.getElementById('converter').innerHTML= "Конвертация закончена";
localStorage.setItem('converter_mode', 'report');
let output= "";
let keys= [];
for(let i= 0, length= localStorage.length; i < length; i++) {
let key= localStorage.key(i);
if(key && key.includes('convert_log') ){
output+= "<li>" + localStorage.getItem(key) + "<hr /></li>";
keys.push(key);
}
}
if(output.length){
for(let i= 0; i < keys.length; i++) {
localStorage.removeItem(keys[i]);
}
Ext.MessageBox.minWidth = parseInt(document.documentElement.clientWidth) / 100 * 70;
Ext.MessageBox.alert('WEBP Конвертер: Журнал','<div style="max-height: 70vh; overflow-y: auto;"><ul>' + output + '<ul></div>');
} else {
document.getElementById('converter').innerHTML= "Журнал пуст";
setTimeout(() => document.getElementById('converter').innerHTML= "Конвертация закончена", 3000);
}
return;
}
let converter_count= localStorage.getItem('converter_count');
if(converter_count && parseInt(converter_count) > 0) {
if(window.count_threads <= (max_count_threads - 1)) { // Max threads!
window.count_threads++;
files_iterator();
}
} else {
if(localStorage.getItem('converter_mode') != "get"){
document.getElementById('converter').innerHTML= "Поиск изображений";
fetch_converter('get');
}
}
}
function files_iterator(){// Converting *.jp[e]g and *.png files to /webp/[*/]*.webp
for(let i= 0, length= localStorage.length; i < length; i++) {
let key= localStorage.key(i);
if(key && key.includes('convert_img') ){
localStorage.setItem(window.converter_token, "active");
let file= localStorage.getItem(key);
localStorage.removeItem(key);
fetch_converter('convert', file);
let converter_count= parseInt(localStorage.getItem('converter_count'));
converter_count--;
localStorage.setItem('converter_count', converter_count);
if(window.count_threads == 1) document.getElementById('converter').innerHTML= converter_count;
else document.getElementById('converter').innerHTML= window.count_threads + 'x ' + converter_count;
return;
}
}
document.getElementById('converter').innerHTML= "Просмотр журнала";
localStorage.setItem(window.converter_token, "stopped");
localStorage.setItem('converter_count', 0);
if(localStorage.getItem('converter_mode') != "clean"){
fetch_converter('clean'); // Clean deleted copy of files into /webp/ directory
window.count_threads= 0;
}
let converter_error= localStorage.getItem('converter_error');
if( converter_error ) document.getElementById('converter').innerHTML= converter_error;
}
function error_catcher(){ // Catch error
let converter_mode= localStorage.getItem('converter_mode');
if(converter_mode) {
if(converter_mode == "get"){
document.getElementById('converter').innerHTML= "Ошибка, попробуйте позже";
localStorage.setItem('converter_mode', 'error');
}
if(converter_mode == "convert"){
files_iterator();
}
if(converter_mode == "clean"){
document.getElementById('converter').innerHTML= "Просмотр журнала";
}
}
}
function fetch_converter(mode, file= false){
let upload = {
"mode": mode,
"file": file,
"cwebp": file ? localStorage.getItem("converter_cwebp") : false
};
let data= new FormData();
data.append("json", JSON.stringify(upload));
localStorage.setItem('converter_mode', mode);
fetch("/connectors/converter/converter.php", {
method: "POST",
body: data
}).then(response => {
if(response.status !== 200) {
return Promise.reject();
}
return response.json();
}).then(function(data) {
if(typeof( data.status ) != "undefined" && data.status == "complete"){
if(data.mode == 'get'){// Get *.jp[e]g and *.png files list, for queue to converting
localStorage.setItem('converter', Date.now());
localStorage.setItem('converter_count', data.count);
localStorage.setItem('converter_cwebp', data.cwebp);
if(typeof( data.execution_time ) != "undefined" && data.execution_time == "exceeded"){
localStorage.setItem('converter_error', 'Ошибка: слишком много файлов');
}
data.images.forEach(function(file, index, created) {
localStorage.setItem('convert_img_'+index, file);
});
window.count_threads++;
files_iterator();
}
if(data.mode == 'convert'){
if(typeof( data.output ) != "undefined" && data.output){
let output= "<b>Source:</b> " + data.source + "<br /><br />";
output+= "<b>Destination:</b> " + data.dest;
if(data.output.length) {
output+= "<br /><br />";
data.output.forEach(function(line, index) {
output+= "<span style='color:red'>" + line + "</span><br />";
});
}
let itemName= '';
do { // Add log message
itemName= 'convert_log_' + rand();
} while(localStorage.getItem(itemName) !== null);
localStorage.setItem(itemName, output);
}
files_iterator();
}
if(data.mode == 'flg'){
document.getElementById('converter').innerHTML= "Поиск изображений";
fetch_converter('get');
}
} else {
if(typeof( data.status ) != "undefined") {
document.getElementById('converter').innerHTML= data.status;
localStorage.setItem('converter_mode', data.status);
if(data.mode == 'get_bin' && typeof( data.output ) != "undefined"){
let output= "";
data.output.forEach(function(line, index, created) {
output+= "<li>" + line + "</li>";
});
Ext.MessageBox.minWidth = parseInt(document.documentElement.clientWidth) / 100 * 70;
Ext.MessageBox.alert(data.status,'<div style="max-height: 70vh; overflow-y: auto;"><ul>' + output + '<ul></div>');
}
} else {
error_catcher();
}
}
}).catch(() => error_catcher());
}
const rand= function() {
return Math.random().toString(12).substr(2); // remove `0.`
};
let token= function() {
return "converter_token_" + rand() + rand(); // to make it longer
};
// Init
let modxUserMenu= document.getElementById('modx-user-menu');
let a= document.createElement("a");
let textUserMenu= document.createTextNode( "WEBP Конвертер" );
a.setAttribute("id", "converter");
a.setAttribute("title", "Очередь изображений для webp конвертера");
a.onclick= manual_start;
a.appendChild( textUserMenu );
let webpConverterLI= document.createElement("li");
webpConverterLI.appendChild(a);
modxUserMenu.insertBefore(webpConverterLI, modxUserMenu.firstChild);
window.count_threads= 0;
let count_parallel_tabs= 0;
// Detect concurent tasks
if(localStorage.length > 0) {
for(let i= 0, length= localStorage.length; i < length; i++) {
let key= localStorage.key(i);
if(key && key.includes('converter_token') ){
let converter_token= localStorage.getItem(key);
if(converter_token == "active"){
count_parallel_tabs++;
}
}
}
}
window.converter_token= token(); // generate token
localStorage.setItem(window.converter_token, "passive");
window.addEventListener("unload", function() { // Delete token on unload
localStorage.removeItem(window.converter_token);
});
// Check reload
let converter= localStorage.getItem('converter') ? localStorage.getItem('converter') : Date.now();
let converter_count= localStorage.getItem('converter_count') ? localStorage.getItem('converter_count') : "0";
if(converter && converter_count) {
converter_count= parseInt(converter_count);
// Autostart max concurent task
if(converter_count > 0 && count_parallel_tabs < concurent_tasks) {
window.count_threads++;
files_iterator();
}
// Autostart after clean cache, === -1 is Off, === 0 is On
if(converter_count === 0){
fetch_converter('flg');
}
}
});