WebUI: Improve accuracy of trackers list
[qBittorrent.git] / src / webui / www / private / scripts / dynamicTable.js
blob923d42a23a0a5a66bde0e603103efe3ef6750cbe
1 /*
2 * MIT License
3 * Copyright (c) 2008 Ishan Arora <ishan@qbittorrent.org> & Christophe Dumez <chris@qbittorrent.org>
5 * Permission is hereby granted, free of charge, to any person obtaining a copy
6 * of this software and associated documentation files (the "Software"), to deal
7 * in the Software without restriction, including without limitation the rights
8 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 * copies of the Software, and to permit persons to whom the Software is
10 * furnished to do so, subject to the following conditions:
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 * THE SOFTWARE.
24 /**************************************************************
26 Script : Dynamic Table
27 Version : 0.5
28 Authors : Ishan Arora & Christophe Dumez
29 Desc : Programmable sortable table
30 Licence : Open Source MIT Licence
32 **************************************************************/
34 'use strict';
36 if (window.qBittorrent === undefined) {
37 window.qBittorrent = {};
40 window.qBittorrent.DynamicTable = (function() {
41 const exports = function() {
42 return {
43 TorrentsTable: TorrentsTable,
44 TorrentPeersTable: TorrentPeersTable,
45 SearchResultsTable: SearchResultsTable,
46 SearchPluginsTable: SearchPluginsTable,
47 TorrentTrackersTable: TorrentTrackersTable,
48 BulkRenameTorrentFilesTable: BulkRenameTorrentFilesTable,
49 TorrentFilesTable: TorrentFilesTable,
50 LogMessageTable: LogMessageTable,
51 LogPeerTable: LogPeerTable,
52 RssFeedTable: RssFeedTable,
53 RssArticleTable: RssArticleTable,
54 RssDownloaderRulesTable: RssDownloaderRulesTable,
55 RssDownloaderFeedSelectionTable: RssDownloaderFeedSelectionTable,
56 RssDownloaderArticlesTable: RssDownloaderArticlesTable
60 const compareNumbers = (val1, val2) => {
61 if (val1 < val2)
62 return -1;
63 if (val1 > val2)
64 return 1;
65 return 0;
68 let DynamicTableHeaderContextMenuClass = null;
69 let ProgressColumnWidth = -1;
71 const DynamicTable = new Class({
73 initialize: function() {},
75 setup: function(dynamicTableDivId, dynamicTableFixedHeaderDivId, contextMenu) {
76 this.dynamicTableDivId = dynamicTableDivId;
77 this.dynamicTableFixedHeaderDivId = dynamicTableFixedHeaderDivId;
78 this.fixedTableHeader = $(dynamicTableFixedHeaderDivId).getElements('tr')[0];
79 this.hiddenTableHeader = $(dynamicTableDivId).getElements('tr')[0];
80 this.tableBody = $(dynamicTableDivId).getElements('tbody')[0];
81 this.rows = new Hash();
82 this.selectedRows = [];
83 this.columns = [];
84 this.contextMenu = contextMenu;
85 this.sortedColumn = LocalPreferences.get('sorted_column_' + this.dynamicTableDivId, 0);
86 this.reverseSort = LocalPreferences.get('reverse_sort_' + this.dynamicTableDivId, '0');
87 this.initColumns();
88 this.loadColumnsOrder();
89 this.updateTableHeaders();
90 this.setupCommonEvents();
91 this.setupHeaderEvents();
92 this.setupHeaderMenu();
93 this.setSortedColumnIcon(this.sortedColumn, null, (this.reverseSort === '1'));
96 setupCommonEvents: function() {
97 const scrollFn = function() {
98 $(this.dynamicTableFixedHeaderDivId).getElements('table')[0].style.left = -$(this.dynamicTableDivId).scrollLeft + 'px';
99 }.bind(this);
101 $(this.dynamicTableDivId).addEvent('scroll', scrollFn);
103 // if the table exists within a panel
104 if ($(this.dynamicTableDivId).getParent('.panel')) {
105 const resizeFn = function() {
106 const panel = $(this.dynamicTableDivId).getParent('.panel');
107 let h = panel.getBoundingClientRect().height - $(this.dynamicTableFixedHeaderDivId).getBoundingClientRect().height;
108 $(this.dynamicTableDivId).style.height = h + 'px';
110 // Workaround due to inaccurate calculation of elements heights by browser
112 let n = 2;
114 // is panel vertical scrollbar visible or does panel content not fit?
115 while (((panel.clientWidth != panel.offsetWidth) || (panel.clientHeight != panel.scrollHeight)) && (n > 0)) {
116 --n;
117 h -= 0.5;
118 $(this.dynamicTableDivId).style.height = h + 'px';
121 this.lastPanelHeight = panel.getBoundingClientRect().height;
122 }.bind(this);
124 $(this.dynamicTableDivId).getParent('.panel').addEvent('resize', resizeFn);
126 this.lastPanelHeight = 0;
128 // Workaround. Resize event is called not always (for example it isn't called when browser window changes it's size)
130 const checkResizeFn = function() {
131 const tableDiv = $(this.dynamicTableDivId);
133 // dynamicTableDivId is not visible on the UI
134 if (!tableDiv) {
135 return;
138 const panel = tableDiv.getParent('.panel');
139 if (this.lastPanelHeight != panel.getBoundingClientRect().height) {
140 this.lastPanelHeight = panel.getBoundingClientRect().height;
141 panel.fireEvent('resize');
143 }.bind(this);
145 setInterval(checkResizeFn, 500);
149 setupHeaderEvents: function() {
150 this.currentHeaderAction = '';
151 this.canResize = false;
153 const resetElementBorderStyle = function(el, side) {
154 if (side === 'left' || side !== 'right') {
155 el.setStyle('border-left-style', '');
156 el.setStyle('border-left-color', '');
157 el.setStyle('border-left-width', '');
159 if (side === 'right' || side !== 'left') {
160 el.setStyle('border-right-style', '');
161 el.setStyle('border-right-color', '');
162 el.setStyle('border-right-width', '');
166 const mouseMoveFn = function(e) {
167 const brect = e.target.getBoundingClientRect();
168 const mouseXRelative = e.event.clientX - brect.left;
169 if (this.currentHeaderAction === '') {
170 if (brect.width - mouseXRelative < 5) {
171 this.resizeTh = e.target;
172 this.canResize = true;
173 e.target.getParent("tr").style.cursor = 'col-resize';
175 else if ((mouseXRelative < 5) && e.target.getPrevious('[class=""]')) {
176 this.resizeTh = e.target.getPrevious('[class=""]');
177 this.canResize = true;
178 e.target.getParent("tr").style.cursor = 'col-resize';
180 else {
181 this.canResize = false;
182 e.target.getParent("tr").style.cursor = '';
185 if (this.currentHeaderAction === 'drag') {
186 const previousVisibleSibling = e.target.getPrevious('[class=""]');
187 let borderChangeElement = previousVisibleSibling;
188 let changeBorderSide = 'right';
190 if (mouseXRelative > brect.width / 2) {
191 borderChangeElement = e.target;
192 this.dropSide = 'right';
194 else {
195 this.dropSide = 'left';
198 e.target.getParent("tr").style.cursor = 'move';
200 if (!previousVisibleSibling) { // right most column
201 borderChangeElement = e.target;
203 if (mouseXRelative <= brect.width / 2)
204 changeBorderSide = 'left';
207 borderChangeElement.setStyle('border-' + changeBorderSide + '-style', 'solid');
208 borderChangeElement.setStyle('border-' + changeBorderSide + '-color', '#e60');
209 borderChangeElement.setStyle('border-' + changeBorderSide + '-width', 'initial');
211 resetElementBorderStyle(borderChangeElement, changeBorderSide === 'right' ? 'left' : 'right');
213 borderChangeElement.getSiblings('[class=""]').each(function(el) {
214 resetElementBorderStyle(el);
217 this.lastHoverTh = e.target;
218 this.lastClientX = e.event.clientX;
219 }.bind(this);
221 const mouseOutFn = function(e) {
222 resetElementBorderStyle(e.target);
223 }.bind(this);
225 const onBeforeStart = function(el) {
226 this.clickedTh = el;
227 this.currentHeaderAction = 'start';
228 this.dragMovement = false;
229 this.dragStartX = this.lastClientX;
230 }.bind(this);
232 const onStart = function(el, event) {
233 if (this.canResize) {
234 this.currentHeaderAction = 'resize';
235 this.startWidth = this.resizeTh.getStyle('width').toFloat();
237 else {
238 this.currentHeaderAction = 'drag';
239 el.setStyle('background-color', '#C1D5E7');
241 }.bind(this);
243 const onDrag = function(el, event) {
244 if (this.currentHeaderAction === 'resize') {
245 let width = this.startWidth + (event.page.x - this.dragStartX);
246 if (width < 16)
247 width = 16;
248 this.columns[this.resizeTh.columnName].width = width;
249 this.updateColumn(this.resizeTh.columnName);
251 }.bind(this);
253 const onComplete = function(el, event) {
254 resetElementBorderStyle(this.lastHoverTh);
255 el.setStyle('background-color', '');
256 if (this.currentHeaderAction === 'resize')
257 LocalPreferences.set('column_' + this.resizeTh.columnName + '_width_' + this.dynamicTableDivId, this.columns[this.resizeTh.columnName].width);
258 if ((this.currentHeaderAction === 'drag') && (el !== this.lastHoverTh)) {
259 this.saveColumnsOrder();
260 const val = LocalPreferences.get('columns_order_' + this.dynamicTableDivId).split(',');
261 val.erase(el.columnName);
262 let pos = val.indexOf(this.lastHoverTh.columnName);
263 if (this.dropSide === 'right')
264 ++pos;
265 val.splice(pos, 0, el.columnName);
266 LocalPreferences.set('columns_order_' + this.dynamicTableDivId, val.join(','));
267 this.loadColumnsOrder();
268 this.updateTableHeaders();
269 while (this.tableBody.firstChild)
270 this.tableBody.removeChild(this.tableBody.firstChild);
271 this.updateTable(true);
273 if (this.currentHeaderAction === 'drag') {
274 resetElementBorderStyle(el);
275 el.getSiblings('[class=""]').each(function(el) {
276 resetElementBorderStyle(el);
279 this.currentHeaderAction = '';
280 }.bind(this);
282 const onCancel = function(el) {
283 this.currentHeaderAction = '';
284 this.setSortedColumn(el.columnName);
285 }.bind(this);
287 const onTouch = function(e) {
288 const column = e.target.columnName;
289 this.currentHeaderAction = '';
290 this.setSortedColumn(column);
291 }.bind(this);
293 const ths = this.fixedTableHeader.getElements('th');
295 for (let i = 0; i < ths.length; ++i) {
296 const th = ths[i];
297 th.addEvent('mousemove', mouseMoveFn);
298 th.addEvent('mouseout', mouseOutFn);
299 th.addEvent('touchend', onTouch);
300 th.makeResizable({
301 modifiers: {
302 x: '',
303 y: ''
305 onBeforeStart: onBeforeStart,
306 onStart: onStart,
307 onDrag: onDrag,
308 onComplete: onComplete,
309 onCancel: onCancel
314 setupDynamicTableHeaderContextMenuClass: function() {
315 if (!DynamicTableHeaderContextMenuClass) {
316 DynamicTableHeaderContextMenuClass = new Class({
317 Extends: window.qBittorrent.ContextMenu.ContextMenu,
318 updateMenuItems: function() {
319 for (let i = 0; i < this.dynamicTable.columns.length; ++i) {
320 if (this.dynamicTable.columns[i].caption === '')
321 continue;
322 if (this.dynamicTable.columns[i].visible !== '0')
323 this.setItemChecked(this.dynamicTable.columns[i].name, true);
324 else
325 this.setItemChecked(this.dynamicTable.columns[i].name, false);
332 showColumn: function(columnName, show) {
333 this.columns[columnName].visible = show ? '1' : '0';
334 LocalPreferences.set('column_' + columnName + '_visible_' + this.dynamicTableDivId, show ? '1' : '0');
335 this.updateColumn(columnName);
338 setupHeaderMenu: function() {
339 this.setupDynamicTableHeaderContextMenuClass();
341 const menuId = this.dynamicTableDivId + '_headerMenu';
343 // reuse menu if already exists
344 const ul = $(menuId) ?? new Element('ul', {
345 id: menuId,
346 class: 'contextMenu scrollableMenu'
349 const createLi = function(columnName, text) {
350 const html = '<a href="#' + columnName + '" ><img src="images/checked-completed.svg"/>' + window.qBittorrent.Misc.escapeHtml(text) + '</a>';
351 return new Element('li', {
352 html: html
356 const actions = {};
358 const onMenuItemClicked = function(element, ref, action) {
359 this.showColumn(action, this.columns[action].visible === '0');
360 }.bind(this);
362 // recreate child nodes when reusing (enables the context menu to work correctly)
363 if (ul.hasChildNodes()) {
364 while (ul.firstChild) {
365 ul.removeChild(ul.lastChild);
369 for (let i = 0; i < this.columns.length; ++i) {
370 const text = this.columns[i].caption;
371 if (text === '')
372 continue;
373 ul.appendChild(createLi(this.columns[i].name, text));
374 actions[this.columns[i].name] = onMenuItemClicked;
377 ul.inject(document.body);
379 this.headerContextMenu = new DynamicTableHeaderContextMenuClass({
380 targets: '#' + this.dynamicTableFixedHeaderDivId + ' tr',
381 actions: actions,
382 menu: menuId,
383 offsets: {
384 x: -15,
385 y: 2
389 this.headerContextMenu.dynamicTable = this;
392 initColumns: function() {},
394 newColumn: function(name, style, caption, defaultWidth, defaultVisible) {
395 const column = {};
396 column['name'] = name;
397 column['title'] = name;
398 column['visible'] = LocalPreferences.get('column_' + name + '_visible_' + this.dynamicTableDivId, defaultVisible ? '1' : '0');
399 column['force_hide'] = false;
400 column['caption'] = caption;
401 column['style'] = style;
402 column['width'] = LocalPreferences.get('column_' + name + '_width_' + this.dynamicTableDivId, defaultWidth);
403 column['dataProperties'] = [name];
404 column['getRowValue'] = function(row, pos) {
405 if (pos === undefined)
406 pos = 0;
407 return row['full_data'][this.dataProperties[pos]];
409 column['compareRows'] = function(row1, row2) {
410 const value1 = this.getRowValue(row1);
411 const value2 = this.getRowValue(row2);
412 if ((typeof(value1) === 'number') && (typeof(value2) === 'number'))
413 return compareNumbers(value1, value2);
414 return window.qBittorrent.Misc.naturalSortCollator.compare(value1, value2);
416 column['updateTd'] = function(td, row) {
417 const value = this.getRowValue(row);
418 td.set('text', value);
419 td.set('title', value);
421 column['onResize'] = null;
422 this.columns.push(column);
423 this.columns[name] = column;
425 this.hiddenTableHeader.appendChild(new Element('th'));
426 this.fixedTableHeader.appendChild(new Element('th'));
429 loadColumnsOrder: function() {
430 const columnsOrder = [];
431 const val = LocalPreferences.get('columns_order_' + this.dynamicTableDivId);
432 if (val === null || val === undefined)
433 return;
434 val.split(',').forEach(function(v) {
435 if ((v in this.columns) && (!columnsOrder.contains(v)))
436 columnsOrder.push(v);
437 }.bind(this));
439 for (let i = 0; i < this.columns.length; ++i)
440 if (!columnsOrder.contains(this.columns[i].name))
441 columnsOrder.push(this.columns[i].name);
443 for (let i = 0; i < this.columns.length; ++i)
444 this.columns[i] = this.columns[columnsOrder[i]];
447 saveColumnsOrder: function() {
448 let val = '';
449 for (let i = 0; i < this.columns.length; ++i) {
450 if (i > 0)
451 val += ',';
452 val += this.columns[i].name;
454 LocalPreferences.set('columns_order_' + this.dynamicTableDivId, val);
457 updateTableHeaders: function() {
458 this.updateHeader(this.hiddenTableHeader);
459 this.updateHeader(this.fixedTableHeader);
462 updateHeader: function(header) {
463 const ths = header.getElements('th');
465 for (let i = 0; i < ths.length; ++i) {
466 const th = ths[i];
467 th._this = this;
468 th.setAttribute('title', this.columns[i].caption);
469 th.set('text', this.columns[i].caption);
470 th.setAttribute('style', 'width: ' + this.columns[i].width + 'px;' + this.columns[i].style);
471 th.columnName = this.columns[i].name;
472 th.addClass('column_' + th.columnName);
473 if ((this.columns[i].visible == '0') || this.columns[i].force_hide)
474 th.addClass('invisible');
475 else
476 th.removeClass('invisible');
480 getColumnPos: function(columnName) {
481 for (let i = 0; i < this.columns.length; ++i)
482 if (this.columns[i].name == columnName)
483 return i;
484 return -1;
487 updateColumn: function(columnName) {
488 const pos = this.getColumnPos(columnName);
489 const visible = ((this.columns[pos].visible != '0') && !this.columns[pos].force_hide);
490 const ths = this.hiddenTableHeader.getElements('th');
491 const fths = this.fixedTableHeader.getElements('th');
492 const trs = this.tableBody.getElements('tr');
493 const style = 'width: ' + this.columns[pos].width + 'px;' + this.columns[pos].style;
495 ths[pos].setAttribute('style', style);
496 fths[pos].setAttribute('style', style);
498 if (visible) {
499 ths[pos].removeClass('invisible');
500 fths[pos].removeClass('invisible');
501 for (let i = 0; i < trs.length; ++i)
502 trs[i].getElements('td')[pos].removeClass('invisible');
504 else {
505 ths[pos].addClass('invisible');
506 fths[pos].addClass('invisible');
507 for (let j = 0; j < trs.length; ++j)
508 trs[j].getElements('td')[pos].addClass('invisible');
510 if (this.columns[pos].onResize !== null) {
511 this.columns[pos].onResize(columnName);
515 getSortedColumn: function() {
516 return LocalPreferences.get('sorted_column_' + this.dynamicTableDivId);
520 * @param {string} column name to sort by
521 * @param {string|null} reverse defaults to implementation-specific behavior when not specified. Should only be passed when restoring previous state.
523 setSortedColumn: function(column, reverse = null) {
524 if (column != this.sortedColumn) {
525 const oldColumn = this.sortedColumn;
526 this.sortedColumn = column;
527 this.reverseSort = reverse ?? '0';
528 this.setSortedColumnIcon(column, oldColumn, false);
530 else {
531 // Toggle sort order
532 this.reverseSort = reverse ?? (this.reverseSort === '0' ? '1' : '0');
533 this.setSortedColumnIcon(column, null, (this.reverseSort === '1'));
535 LocalPreferences.set('sorted_column_' + this.dynamicTableDivId, column);
536 LocalPreferences.set('reverse_sort_' + this.dynamicTableDivId, this.reverseSort);
537 this.updateTable(false);
540 setSortedColumnIcon: function(newColumn, oldColumn, isReverse) {
541 const getCol = function(headerDivId, colName) {
542 const colElem = $$("#" + headerDivId + " .column_" + colName);
543 if (colElem.length == 1)
544 return colElem[0];
545 return null;
548 const colElem = getCol(this.dynamicTableFixedHeaderDivId, newColumn);
549 if (colElem !== null) {
550 colElem.addClass('sorted');
551 if (isReverse)
552 colElem.addClass('reverse');
553 else
554 colElem.removeClass('reverse');
556 const oldColElem = getCol(this.dynamicTableFixedHeaderDivId, oldColumn);
557 if (oldColElem !== null) {
558 oldColElem.removeClass('sorted');
559 oldColElem.removeClass('reverse');
563 getSelectedRowId: function() {
564 if (this.selectedRows.length > 0)
565 return this.selectedRows[0];
566 return '';
569 isRowSelected: function(rowId) {
570 return this.selectedRows.contains(rowId);
573 altRow: function() {
574 if (!MUI.ieLegacySupport)
575 return;
577 const trs = this.tableBody.getElements('tr');
578 trs.each(function(el, i) {
579 if (i % 2) {
580 el.addClass('alt');
582 else {
583 el.removeClass('alt');
585 }.bind(this));
588 selectAll: function() {
589 this.deselectAll();
591 const trs = this.tableBody.getElements('tr');
592 for (let i = 0; i < trs.length; ++i) {
593 const tr = trs[i];
594 this.selectedRows.push(tr.rowId);
595 if (!tr.hasClass('selected'))
596 tr.addClass('selected');
600 deselectAll: function() {
601 this.selectedRows.empty();
604 selectRow: function(rowId) {
605 this.selectedRows.push(rowId);
606 this.setRowClass();
607 this.onSelectedRowChanged();
610 deselectRow: function(rowId) {
611 this.selectedRows.erase(rowId);
612 this.setRowClass();
613 this.onSelectedRowChanged();
616 selectRows: function(rowId1, rowId2) {
617 this.deselectAll();
618 if (rowId1 === rowId2) {
619 this.selectRow(rowId1);
620 return;
623 let select = false;
624 const that = this;
625 this.tableBody.getElements('tr').each(function(tr) {
626 if ((tr.rowId == rowId1) || (tr.rowId == rowId2)) {
627 select = !select;
628 that.selectedRows.push(tr.rowId);
630 else if (select) {
631 that.selectedRows.push(tr.rowId);
634 this.setRowClass();
635 this.onSelectedRowChanged();
638 reselectRows: function(rowIds) {
639 this.deselectAll();
640 this.selectedRows = rowIds.slice();
641 this.tableBody.getElements('tr').each(function(tr) {
642 if (rowIds.indexOf(tr.rowId) > -1)
643 tr.addClass('selected');
647 setRowClass: function() {
648 const that = this;
649 this.tableBody.getElements('tr').each(function(tr) {
650 if (that.isRowSelected(tr.rowId))
651 tr.addClass('selected');
652 else
653 tr.removeClass('selected');
657 onSelectedRowChanged: function() {},
659 updateRowData: function(data) {
660 // ensure rowId is a string
661 const rowId = `${data['rowId']}`;
662 let row;
664 if (!this.rows.has(rowId)) {
665 row = {
666 'full_data': {},
667 'rowId': rowId
669 this.rows.set(rowId, row);
671 else
672 row = this.rows.get(rowId);
674 row['data'] = data;
675 for (const x in data)
676 row['full_data'][x] = data[x];
679 getFilteredAndSortedRows: function() {
680 const filteredRows = [];
682 const rows = this.rows.getValues();
684 for (let i = 0; i < rows.length; ++i) {
685 filteredRows.push(rows[i]);
686 filteredRows[rows[i].rowId] = rows[i];
689 filteredRows.sort(function(row1, row2) {
690 const column = this.columns[this.sortedColumn];
691 const res = column.compareRows(row1, row2);
692 if (this.reverseSort === '0')
693 return res;
694 else
695 return -res;
696 }.bind(this));
697 return filteredRows;
700 getTrByRowId: function(rowId) {
701 const trs = this.tableBody.getElements('tr');
702 for (let i = 0; i < trs.length; ++i)
703 if (trs[i].rowId == rowId)
704 return trs[i];
705 return null;
708 updateTable: function(fullUpdate = false) {
709 const rows = this.getFilteredAndSortedRows();
711 for (let i = 0; i < this.selectedRows.length; ++i)
712 if (!(this.selectedRows[i] in rows)) {
713 this.selectedRows.splice(i, 1);
714 --i;
717 const trs = this.tableBody.getElements('tr');
719 for (let rowPos = 0; rowPos < rows.length; ++rowPos) {
720 const rowId = rows[rowPos]['rowId'];
721 let tr_found = false;
722 for (let j = rowPos; j < trs.length; ++j)
723 if (trs[j]['rowId'] == rowId) {
724 tr_found = true;
725 if (rowPos == j)
726 break;
727 trs[j].inject(trs[rowPos], 'before');
728 const tmpTr = trs[j];
729 trs.splice(j, 1);
730 trs.splice(rowPos, 0, tmpTr);
731 break;
733 if (tr_found) // row already exists in the table
734 this.updateRow(trs[rowPos], fullUpdate);
735 else { // else create a new row in the table
736 const tr = new Element('tr');
737 // set tabindex so element receives keydown events
738 // more info: https://developer.mozilla.org/en-US/docs/Web/API/Element/keydown_event
739 tr.setProperty("tabindex", "-1");
741 const rowId = rows[rowPos]['rowId'];
742 tr.setProperty("data-row-id", rowId);
743 tr['rowId'] = rowId;
745 tr._this = this;
746 tr.addEvent('contextmenu', function(e) {
747 if (!this._this.isRowSelected(this.rowId)) {
748 this._this.deselectAll();
749 this._this.selectRow(this.rowId);
751 return true;
753 tr.addEvent('click', function(e) {
754 e.stop();
755 if (e.control || e.meta) {
756 // CTRL/CMD ⌘ key was pressed
757 if (this._this.isRowSelected(this.rowId))
758 this._this.deselectRow(this.rowId);
759 else
760 this._this.selectRow(this.rowId);
762 else if (e.shift && (this._this.selectedRows.length == 1)) {
763 // Shift key was pressed
764 this._this.selectRows(this._this.getSelectedRowId(), this.rowId);
766 else {
767 // Simple selection
768 this._this.deselectAll();
769 this._this.selectRow(this.rowId);
771 return false;
773 tr.addEvent('touchstart', function(e) {
774 if (!this._this.isRowSelected(this.rowId)) {
775 this._this.deselectAll();
776 this._this.selectRow(this.rowId);
778 return false;
780 tr.addEvent('keydown', function(event) {
781 switch (event.key) {
782 case "up":
783 this._this.selectPreviousRow();
784 return false;
785 case "down":
786 this._this.selectNextRow();
787 return false;
791 this.setupTr(tr);
793 for (let k = 0; k < this.columns.length; ++k) {
794 const td = new Element('td');
795 if ((this.columns[k].visible == '0') || this.columns[k].force_hide)
796 td.addClass('invisible');
797 td.injectInside(tr);
800 // Insert
801 if (rowPos >= trs.length) {
802 tr.inject(this.tableBody);
803 trs.push(tr);
805 else {
806 tr.inject(trs[rowPos], 'before');
807 trs.splice(rowPos, 0, tr);
810 // Update context menu
811 if (this.contextMenu)
812 this.contextMenu.addTarget(tr);
814 this.updateRow(tr, true);
818 let rowPos = rows.length;
820 while ((rowPos < trs.length) && (trs.length > 0)) {
821 trs.pop().destroy();
825 setupTr: function(tr) {},
827 updateRow: function(tr, fullUpdate) {
828 const row = this.rows.get(tr.rowId);
829 const data = row[fullUpdate ? 'full_data' : 'data'];
831 const tds = tr.getElements('td');
832 for (let i = 0; i < this.columns.length; ++i) {
833 if (Object.hasOwn(data, this.columns[i].dataProperties[0]))
834 this.columns[i].updateTd(tds[i], row);
836 row['data'] = {};
839 removeRow: function(rowId) {
840 this.selectedRows.erase(rowId);
841 const tr = this.getTrByRowId(rowId);
842 if (tr !== null) {
843 tr.destroy();
844 this.rows.erase(rowId);
845 return true;
847 return false;
850 clear: function() {
851 this.deselectAll();
852 this.rows.empty();
853 const trs = this.tableBody.getElements('tr');
854 while (trs.length > 0) {
855 trs.pop().destroy();
859 selectedRowsIds: function() {
860 return this.selectedRows.slice();
863 getRowIds: function() {
864 return this.rows.getKeys();
867 selectNextRow: function() {
868 const visibleRows = $(this.dynamicTableDivId).getElements("tbody tr").filter(e => e.getStyle("display") !== "none");
869 const selectedRowId = this.getSelectedRowId();
871 let selectedIndex = -1;
872 for (let i = 0; i < visibleRows.length; ++i) {
873 const row = visibleRows[i];
874 if (row.getProperty("data-row-id") === selectedRowId) {
875 selectedIndex = i;
876 break;
880 const isLastRowSelected = (selectedIndex >= (visibleRows.length - 1));
881 if (!isLastRowSelected) {
882 this.deselectAll();
884 const newRow = visibleRows[selectedIndex + 1];
885 this.selectRow(newRow.getProperty("data-row-id"));
889 selectPreviousRow: function() {
890 const visibleRows = $(this.dynamicTableDivId).getElements("tbody tr").filter(e => e.getStyle("display") !== "none");
891 const selectedRowId = this.getSelectedRowId();
893 let selectedIndex = -1;
894 for (let i = 0; i < visibleRows.length; ++i) {
895 const row = visibleRows[i];
896 if (row.getProperty("data-row-id") === selectedRowId) {
897 selectedIndex = i;
898 break;
902 const isFirstRowSelected = selectedIndex <= 0;
903 if (!isFirstRowSelected) {
904 this.deselectAll();
906 const newRow = visibleRows[selectedIndex - 1];
907 this.selectRow(newRow.getProperty("data-row-id"));
912 const TorrentsTable = new Class({
913 Extends: DynamicTable,
915 initColumns: function() {
916 this.newColumn('priority', '', '#', 30, true);
917 this.newColumn('state_icon', 'cursor: default', '', 22, true);
918 this.newColumn('name', '', 'QBT_TR(Name)QBT_TR[CONTEXT=TransferListModel]', 200, true);
919 this.newColumn('size', '', 'QBT_TR(Size)QBT_TR[CONTEXT=TransferListModel]', 100, true);
920 this.newColumn('total_size', '', 'QBT_TR(Total Size)QBT_TR[CONTEXT=TransferListModel]', 100, false);
921 this.newColumn('progress', '', 'QBT_TR(Done)QBT_TR[CONTEXT=TransferListModel]', 85, true);
922 this.newColumn('status', '', 'QBT_TR(Status)QBT_TR[CONTEXT=TransferListModel]', 100, true);
923 this.newColumn('num_seeds', '', 'QBT_TR(Seeds)QBT_TR[CONTEXT=TransferListModel]', 100, true);
924 this.newColumn('num_leechs', '', 'QBT_TR(Peers)QBT_TR[CONTEXT=TransferListModel]', 100, true);
925 this.newColumn('dlspeed', '', 'QBT_TR(Down Speed)QBT_TR[CONTEXT=TransferListModel]', 100, true);
926 this.newColumn('upspeed', '', 'QBT_TR(Up Speed)QBT_TR[CONTEXT=TransferListModel]', 100, true);
927 this.newColumn('eta', '', 'QBT_TR(ETA)QBT_TR[CONTEXT=TransferListModel]', 100, true);
928 this.newColumn('ratio', '', 'QBT_TR(Ratio)QBT_TR[CONTEXT=TransferListModel]', 100, true);
929 this.newColumn('category', '', 'QBT_TR(Category)QBT_TR[CONTEXT=TransferListModel]', 100, true);
930 this.newColumn('tags', '', 'QBT_TR(Tags)QBT_TR[CONTEXT=TransferListModel]', 100, true);
931 this.newColumn('added_on', '', 'QBT_TR(Added On)QBT_TR[CONTEXT=TransferListModel]', 100, true);
932 this.newColumn('completion_on', '', 'QBT_TR(Completed On)QBT_TR[CONTEXT=TransferListModel]', 100, false);
933 this.newColumn('tracker', '', 'QBT_TR(Tracker)QBT_TR[CONTEXT=TransferListModel]', 100, false);
934 this.newColumn('dl_limit', '', 'QBT_TR(Down Limit)QBT_TR[CONTEXT=TransferListModel]', 100, false);
935 this.newColumn('up_limit', '', 'QBT_TR(Up Limit)QBT_TR[CONTEXT=TransferListModel]', 100, false);
936 this.newColumn('downloaded', '', 'QBT_TR(Downloaded)QBT_TR[CONTEXT=TransferListModel]', 100, false);
937 this.newColumn('uploaded', '', 'QBT_TR(Uploaded)QBT_TR[CONTEXT=TransferListModel]', 100, false);
938 this.newColumn('downloaded_session', '', 'QBT_TR(Session Download)QBT_TR[CONTEXT=TransferListModel]', 100, false);
939 this.newColumn('uploaded_session', '', 'QBT_TR(Session Upload)QBT_TR[CONTEXT=TransferListModel]', 100, false);
940 this.newColumn('amount_left', '', 'QBT_TR(Remaining)QBT_TR[CONTEXT=TransferListModel]', 100, false);
941 this.newColumn('time_active', '', 'QBT_TR(Time Active)QBT_TR[CONTEXT=TransferListModel]', 100, false);
942 this.newColumn('save_path', '', 'QBT_TR(Save path)QBT_TR[CONTEXT=TransferListModel]', 100, false);
943 this.newColumn('completed', '', 'QBT_TR(Completed)QBT_TR[CONTEXT=TransferListModel]', 100, false);
944 this.newColumn('max_ratio', '', 'QBT_TR(Ratio Limit)QBT_TR[CONTEXT=TransferListModel]', 100, false);
945 this.newColumn('seen_complete', '', 'QBT_TR(Last Seen Complete)QBT_TR[CONTEXT=TransferListModel]', 100, false);
946 this.newColumn('last_activity', '', 'QBT_TR(Last Activity)QBT_TR[CONTEXT=TransferListModel]', 100, false);
947 this.newColumn('availability', '', 'QBT_TR(Availability)QBT_TR[CONTEXT=TransferListModel]', 100, false);
948 this.newColumn('reannounce', '', 'QBT_TR(Reannounce In)QBT_TR[CONTEXT=TransferListModel]', 100, false);
950 this.columns['state_icon'].onclick = '';
951 this.columns['state_icon'].dataProperties[0] = 'state';
953 this.columns['num_seeds'].dataProperties.push('num_complete');
954 this.columns['num_leechs'].dataProperties.push('num_incomplete');
955 this.columns['time_active'].dataProperties.push('seeding_time');
957 this.initColumnsFunctions();
960 initColumnsFunctions: function() {
962 // state_icon
963 this.columns['state_icon'].updateTd = function(td, row) {
964 let state = this.getRowValue(row);
965 let img_path;
966 // normalize states
967 switch (state) {
968 case "forcedDL":
969 case "metaDL":
970 case "forcedMetaDL":
971 case "downloading":
972 state = "downloading";
973 img_path = "images/downloading.svg";
974 break;
975 case "forcedUP":
976 case "uploading":
977 state = "uploading";
978 img_path = "images/upload.svg";
979 break;
980 case "stalledUP":
981 state = "stalledUP";
982 img_path = "images/stalledUP.svg";
983 break;
984 case "stalledDL":
985 state = "stalledDL";
986 img_path = "images/stalledDL.svg";
987 break;
988 case "stoppedDL":
989 state = "torrent-stop";
990 img_path = "images/stopped.svg";
991 break;
992 case "stoppedUP":
993 state = "checked-completed";
994 img_path = "images/checked-completed.svg";
995 break;
996 case "queuedDL":
997 case "queuedUP":
998 state = "queued";
999 img_path = "images/queued.svg";
1000 break;
1001 case "checkingDL":
1002 case "checkingUP":
1003 case "queuedForChecking":
1004 case "checkingResumeData":
1005 state = "force-recheck";
1006 img_path = "images/force-recheck.svg";
1007 break;
1008 case "moving":
1009 state = "moving";
1010 img_path = "images/set-location.svg";
1011 break;
1012 case "error":
1013 case "unknown":
1014 case "missingFiles":
1015 state = "error";
1016 img_path = "images/error.svg";
1017 break;
1018 default:
1019 break; // do nothing
1022 if (td.getChildren('img').length > 0) {
1023 const img = td.getChildren('img')[0];
1024 if (img.src.indexOf(img_path) < 0) {
1025 img.set('src', img_path);
1026 img.set('title', state);
1029 else {
1030 td.adopt(new Element('img', {
1031 'src': img_path,
1032 'class': 'stateIcon',
1033 'title': state
1034 }));
1038 // status
1039 this.columns['status'].updateTd = function(td, row) {
1040 const state = this.getRowValue(row);
1041 if (!state)
1042 return;
1044 let status;
1045 switch (state) {
1046 case "downloading":
1047 status = "QBT_TR(Downloading)QBT_TR[CONTEXT=TransferListDelegate]";
1048 break;
1049 case "stalledDL":
1050 status = "QBT_TR(Stalled)QBT_TR[CONTEXT=TransferListDelegate]";
1051 break;
1052 case "metaDL":
1053 status = "QBT_TR(Downloading metadata)QBT_TR[CONTEXT=TransferListDelegate]";
1054 break;
1055 case "forcedMetaDL":
1056 status = "QBT_TR([F] Downloading metadata)QBT_TR[CONTEXT=TransferListDelegate]";
1057 break;
1058 case "forcedDL":
1059 status = "QBT_TR([F] Downloading)QBT_TR[CONTEXT=TransferListDelegate]";
1060 break;
1061 case "uploading":
1062 case "stalledUP":
1063 status = "QBT_TR(Seeding)QBT_TR[CONTEXT=TransferListDelegate]";
1064 break;
1065 case "forcedUP":
1066 status = "QBT_TR([F] Seeding)QBT_TR[CONTEXT=TransferListDelegate]";
1067 break;
1068 case "queuedDL":
1069 case "queuedUP":
1070 status = "QBT_TR(Queued)QBT_TR[CONTEXT=TransferListDelegate]";
1071 break;
1072 case "checkingDL":
1073 case "checkingUP":
1074 status = "QBT_TR(Checking)QBT_TR[CONTEXT=TransferListDelegate]";
1075 break;
1076 case "queuedForChecking":
1077 status = "QBT_TR(Queued for checking)QBT_TR[CONTEXT=TransferListDelegate]";
1078 break;
1079 case "checkingResumeData":
1080 status = "QBT_TR(Checking resume data)QBT_TR[CONTEXT=TransferListDelegate]";
1081 break;
1082 case "stoppedDL":
1083 status = "QBT_TR(Stopped)QBT_TR[CONTEXT=TransferListDelegate]";
1084 break;
1085 case "stoppedUP":
1086 status = "QBT_TR(Completed)QBT_TR[CONTEXT=TransferListDelegate]";
1087 break;
1088 case "moving":
1089 status = "QBT_TR(Moving)QBT_TR[CONTEXT=TransferListDelegate]";
1090 break;
1091 case "missingFiles":
1092 status = "QBT_TR(Missing Files)QBT_TR[CONTEXT=TransferListDelegate]";
1093 break;
1094 case "error":
1095 status = "QBT_TR(Errored)QBT_TR[CONTEXT=TransferListDelegate]";
1096 break;
1097 default:
1098 status = "QBT_TR(Unknown)QBT_TR[CONTEXT=HttpServer]";
1101 td.set('text', status);
1102 td.set('title', status);
1105 // priority
1106 this.columns['priority'].updateTd = function(td, row) {
1107 const queuePos = this.getRowValue(row);
1108 const formattedQueuePos = (queuePos < 1) ? '*' : queuePos;
1109 td.set('text', formattedQueuePos);
1110 td.set('title', formattedQueuePos);
1113 this.columns['priority'].compareRows = function(row1, row2) {
1114 let row1_val = this.getRowValue(row1);
1115 let row2_val = this.getRowValue(row2);
1116 if (row1_val < 1)
1117 row1_val = 1000000;
1118 if (row2_val < 1)
1119 row2_val = 1000000;
1120 return compareNumbers(row1_val, row2_val);
1123 // name, category, tags
1124 this.columns['name'].compareRows = function(row1, row2) {
1125 const row1Val = this.getRowValue(row1);
1126 const row2Val = this.getRowValue(row2);
1127 return row1Val.localeCompare(row2Val, undefined, { numeric: true, sensitivity: 'base' });
1129 this.columns['category'].compareRows = this.columns['name'].compareRows;
1130 this.columns['tags'].compareRows = this.columns['name'].compareRows;
1132 // size, total_size
1133 this.columns['size'].updateTd = function(td, row) {
1134 const size = window.qBittorrent.Misc.friendlyUnit(this.getRowValue(row), false);
1135 td.set('text', size);
1136 td.set('title', size);
1138 this.columns['total_size'].updateTd = this.columns['size'].updateTd;
1140 // progress
1141 this.columns['progress'].updateTd = function(td, row) {
1142 const progress = this.getRowValue(row);
1143 let progressFormatted = (progress * 100).round(1);
1144 if (progressFormatted == 100.0 && progress != 1.0)
1145 progressFormatted = 99.9;
1147 if (td.getChildren('div').length > 0) {
1148 const div = td.getChildren('div')[0];
1149 if (td.resized) {
1150 td.resized = false;
1151 div.setWidth(ProgressColumnWidth - 5);
1153 if (div.getValue() != progressFormatted)
1154 div.setValue(progressFormatted);
1156 else {
1157 if (ProgressColumnWidth < 0)
1158 ProgressColumnWidth = td.offsetWidth;
1159 td.adopt(new window.qBittorrent.ProgressBar.ProgressBar(progressFormatted.toFloat(), {
1160 'width': ProgressColumnWidth - 5
1161 }));
1162 td.resized = false;
1166 this.columns['progress'].onResize = function(columnName) {
1167 const pos = this.getColumnPos(columnName);
1168 const trs = this.tableBody.getElements('tr');
1169 ProgressColumnWidth = -1;
1170 for (let i = 0; i < trs.length; ++i) {
1171 const td = trs[i].getElements('td')[pos];
1172 if (ProgressColumnWidth < 0)
1173 ProgressColumnWidth = td.offsetWidth;
1174 td.resized = true;
1175 this.columns[columnName].updateTd(td, this.rows.get(trs[i].rowId));
1177 }.bind(this);
1179 // num_seeds
1180 this.columns['num_seeds'].updateTd = function(td, row) {
1181 const num_seeds = this.getRowValue(row, 0);
1182 const num_complete = this.getRowValue(row, 1);
1183 let value = num_seeds;
1184 if (num_complete != -1)
1185 value += ' (' + num_complete + ')';
1186 td.set('text', value);
1187 td.set('title', value);
1189 this.columns['num_seeds'].compareRows = function(row1, row2) {
1190 const num_seeds1 = this.getRowValue(row1, 0);
1191 const num_complete1 = this.getRowValue(row1, 1);
1193 const num_seeds2 = this.getRowValue(row2, 0);
1194 const num_complete2 = this.getRowValue(row2, 1);
1196 const result = compareNumbers(num_complete1, num_complete2);
1197 if (result !== 0)
1198 return result;
1199 return compareNumbers(num_seeds1, num_seeds2);
1202 // num_leechs
1203 this.columns['num_leechs'].updateTd = this.columns['num_seeds'].updateTd;
1204 this.columns['num_leechs'].compareRows = this.columns['num_seeds'].compareRows;
1206 // dlspeed
1207 this.columns['dlspeed'].updateTd = function(td, row) {
1208 const speed = window.qBittorrent.Misc.friendlyUnit(this.getRowValue(row), true);
1209 td.set('text', speed);
1210 td.set('title', speed);
1213 // upspeed
1214 this.columns['upspeed'].updateTd = this.columns['dlspeed'].updateTd;
1216 // eta
1217 this.columns['eta'].updateTd = function(td, row) {
1218 const eta = window.qBittorrent.Misc.friendlyDuration(this.getRowValue(row), window.qBittorrent.Misc.MAX_ETA);
1219 td.set('text', eta);
1220 td.set('title', eta);
1223 // ratio
1224 this.columns['ratio'].updateTd = function(td, row) {
1225 const ratio = this.getRowValue(row);
1226 const string = (ratio === -1) ? '∞' : window.qBittorrent.Misc.toFixedPointString(ratio, 2);
1227 td.set('text', string);
1228 td.set('title', string);
1231 // added on
1232 this.columns['added_on'].updateTd = function(td, row) {
1233 const date = new Date(this.getRowValue(row) * 1000).toLocaleString();
1234 td.set('text', date);
1235 td.set('title', date);
1238 // completion_on
1239 this.columns['completion_on'].updateTd = function(td, row) {
1240 const val = this.getRowValue(row);
1241 if ((val === 0xffffffff) || (val < 0)) {
1242 td.set('text', '');
1243 td.set('title', '');
1245 else {
1246 const date = new Date(this.getRowValue(row) * 1000).toLocaleString();
1247 td.set('text', date);
1248 td.set('title', date);
1252 // dl_limit, up_limit
1253 this.columns['dl_limit'].updateTd = function(td, row) {
1254 const speed = this.getRowValue(row);
1255 if (speed === 0) {
1256 td.set('text', '∞');
1257 td.set('title', '∞');
1259 else {
1260 const formattedSpeed = window.qBittorrent.Misc.friendlyUnit(speed, true);
1261 td.set('text', formattedSpeed);
1262 td.set('title', formattedSpeed);
1266 this.columns['up_limit'].updateTd = this.columns['dl_limit'].updateTd;
1268 // downloaded, uploaded, downloaded_session, uploaded_session, amount_left
1269 this.columns['downloaded'].updateTd = this.columns['size'].updateTd;
1270 this.columns['uploaded'].updateTd = this.columns['size'].updateTd;
1271 this.columns['downloaded_session'].updateTd = this.columns['size'].updateTd;
1272 this.columns['uploaded_session'].updateTd = this.columns['size'].updateTd;
1273 this.columns['amount_left'].updateTd = this.columns['size'].updateTd;
1275 // time active
1276 this.columns['time_active'].updateTd = function(td, row) {
1277 const activeTime = this.getRowValue(row, 0);
1278 const seedingTime = this.getRowValue(row, 1);
1279 const time = (seedingTime > 0)
1280 ? ('QBT_TR(%1 (seeded for %2))QBT_TR[CONTEXT=TransferListDelegate]'
1281 .replace('%1', window.qBittorrent.Misc.friendlyDuration(activeTime))
1282 .replace('%2', window.qBittorrent.Misc.friendlyDuration(seedingTime)))
1283 : window.qBittorrent.Misc.friendlyDuration(activeTime);
1284 td.set('text', time);
1285 td.set('title', time);
1288 // completed
1289 this.columns['completed'].updateTd = this.columns['size'].updateTd;
1291 // max_ratio
1292 this.columns['max_ratio'].updateTd = this.columns['ratio'].updateTd;
1294 // seen_complete
1295 this.columns['seen_complete'].updateTd = this.columns['completion_on'].updateTd;
1297 // last_activity
1298 this.columns['last_activity'].updateTd = function(td, row) {
1299 const val = this.getRowValue(row);
1300 if (val < 1) {
1301 td.set('text', '∞');
1302 td.set('title', '∞');
1304 else {
1305 const formattedVal = 'QBT_TR(%1 ago)QBT_TR[CONTEXT=TransferListDelegate]'.replace('%1', window.qBittorrent.Misc.friendlyDuration((new Date()) / 1000 - val));
1306 td.set('text', formattedVal);
1307 td.set('title', formattedVal);
1311 // availability
1312 this.columns['availability'].updateTd = function(td, row) {
1313 const value = window.qBittorrent.Misc.toFixedPointString(this.getRowValue(row), 3);
1314 td.set('text', value);
1315 td.set('title', value);
1318 // reannounce
1319 this.columns['reannounce'].updateTd = function(td, row) {
1320 const time = window.qBittorrent.Misc.friendlyDuration(this.getRowValue(row));
1321 td.set('text', time);
1322 td.set('title', time);
1326 applyFilter: function(row, filterName, categoryHash, tagHash, trackerHash, filterTerms) {
1327 const state = row['full_data'].state;
1328 const name = row['full_data'].name.toLowerCase();
1329 let inactive = false;
1330 let r;
1332 switch (filterName) {
1333 case 'downloading':
1334 if ((state != 'downloading') && (state.indexOf('DL') === -1))
1335 return false;
1336 break;
1337 case 'seeding':
1338 if (state != 'uploading' && state != 'forcedUP' && state != 'stalledUP' && state != 'queuedUP' && state != 'checkingUP')
1339 return false;
1340 break;
1341 case 'completed':
1342 if ((state != 'uploading') && (state.indexOf('UP') === -1))
1343 return false;
1344 break;
1345 case 'stopped':
1346 if (state.indexOf('stopped') === -1)
1347 return false;
1348 break;
1349 case 'running':
1350 if (state.indexOf('stopped') > -1)
1351 return false;
1352 break;
1353 case 'stalled':
1354 if ((state != 'stalledUP') && (state != 'stalledDL'))
1355 return false;
1356 break;
1357 case 'stalled_uploading':
1358 if (state != 'stalledUP')
1359 return false;
1360 break;
1361 case 'stalled_downloading':
1362 if (state != 'stalledDL')
1363 return false;
1364 break;
1365 case 'inactive':
1366 inactive = true;
1367 // fallthrough
1368 case 'active':
1369 if (state == 'stalledDL')
1370 r = (row['full_data'].upspeed > 0);
1371 else
1372 r = state == 'metaDL' || state == 'forcedMetaDL' || state == 'downloading' || state == 'forcedDL' || state == 'uploading' || state == 'forcedUP';
1373 if (r == inactive)
1374 return false;
1375 break;
1376 case 'checking':
1377 if (state !== 'checkingUP' && state !== 'checkingDL' && state !== 'checkingResumeData')
1378 return false;
1379 break;
1380 case 'moving':
1381 if (state !== 'moving')
1382 return false;
1383 break;
1384 case 'errored':
1385 if (state != 'error' && state != "unknown" && state != "missingFiles")
1386 return false;
1387 break;
1390 switch (categoryHash) {
1391 case CATEGORIES_ALL:
1392 break; // do nothing
1393 case CATEGORIES_UNCATEGORIZED:
1394 if (row['full_data'].category.length !== 0)
1395 return false;
1396 break; // do nothing
1397 default:
1398 if (!useSubcategories) {
1399 if (categoryHash !== window.qBittorrent.Client.genHash(row['full_data'].category))
1400 return false;
1402 else {
1403 const selectedCategoryName = category_list.get(categoryHash).name + "/";
1404 const torrentCategoryName = row['full_data'].category + "/";
1405 if (!torrentCategoryName.startsWith(selectedCategoryName))
1406 return false;
1408 break;
1411 switch (tagHash) {
1412 case TAGS_ALL:
1413 break; // do nothing
1415 case TAGS_UNTAGGED:
1416 if (row['full_data'].tags.length !== 0)
1417 return false;
1418 break; // do nothing
1420 default: {
1421 const tagHashes = row['full_data'].tags.split(', ').map(tag => window.qBittorrent.Client.genHash(tag));
1422 if (!tagHashes.contains(tagHash))
1423 return false;
1424 break;
1428 const trackerHashInt = Number.parseInt(trackerHash, 10);
1429 switch (trackerHashInt) {
1430 case TRACKERS_ALL:
1431 break; // do nothing
1432 case TRACKERS_TRACKERLESS:
1433 if (row['full_data'].trackers_count !== 0)
1434 return false;
1435 break;
1436 default: {
1437 const tracker = trackerList.get(trackerHashInt);
1438 if (tracker) {
1439 let found = false;
1440 for (const torrents of tracker.trackerTorrentMap.values()) {
1441 if (torrents.includes(row['full_data'].rowId)) {
1442 found = true;
1443 break;
1446 if (!found)
1447 return false;
1449 break;
1453 if ((filterTerms !== undefined) && (filterTerms !== null)) {
1454 if (filterTerms instanceof RegExp) {
1455 if (!filterTerms.test(name))
1456 return false;
1458 else {
1459 if ((filterTerms.length > 0) && !window.qBittorrent.Misc.containsAllTerms(name, filterTerms))
1460 return false;
1464 return true;
1467 getFilteredTorrentsNumber: function(filterName, categoryHash, tagHash, trackerHash) {
1468 let cnt = 0;
1469 const rows = this.rows.getValues();
1471 for (let i = 0; i < rows.length; ++i) {
1472 if (this.applyFilter(rows[i], filterName, categoryHash, tagHash, trackerHash, null))
1473 ++cnt;
1475 return cnt;
1478 getFilteredTorrentsHashes: function(filterName, categoryHash, tagHash, trackerHash) {
1479 const rowsHashes = [];
1480 const rows = this.rows.getValues();
1482 for (let i = 0; i < rows.length; ++i) {
1483 if (this.applyFilter(rows[i], filterName, categoryHash, tagHash, trackerHash, null))
1484 rowsHashes.push(rows[i]['rowId']);
1487 return rowsHashes;
1490 getFilteredAndSortedRows: function() {
1491 const filteredRows = [];
1493 const rows = this.rows.getValues();
1494 const useRegex = $('torrentsFilterRegexBox').checked;
1495 const filterText = $('torrentsFilterInput').value.trim().toLowerCase();
1496 const filterTerms = (filterText.length > 0)
1497 ? (useRegex ? new RegExp(filterText) : filterText.split(" "))
1498 : null;
1500 for (let i = 0; i < rows.length; ++i) {
1501 if (this.applyFilter(rows[i], selected_filter, selected_category, selectedTag, selectedTracker, filterTerms)) {
1502 filteredRows.push(rows[i]);
1503 filteredRows[rows[i].rowId] = rows[i];
1507 filteredRows.sort(function(row1, row2) {
1508 const column = this.columns[this.sortedColumn];
1509 const res = column.compareRows(row1, row2);
1510 if (this.reverseSort === '0')
1511 return res;
1512 else
1513 return -res;
1514 }.bind(this));
1515 return filteredRows;
1518 setupTr: function(tr) {
1519 tr.addEvent('dblclick', function(e) {
1520 e.stop();
1521 this._this.deselectAll();
1522 this._this.selectRow(this.rowId);
1523 const row = this._this.rows.get(this.rowId);
1524 const state = row['full_data'].state;
1525 if (state.indexOf('stopped') > -1)
1526 startFN();
1527 else
1528 stopFN();
1529 return true;
1531 tr.addClass("torrentsTableContextMenuTarget");
1534 getCurrentTorrentID: function() {
1535 return this.getSelectedRowId();
1538 onSelectedRowChanged: function() {
1539 updatePropertiesPanel();
1543 const TorrentPeersTable = new Class({
1544 Extends: DynamicTable,
1546 initColumns: function() {
1547 this.newColumn('country', '', 'QBT_TR(Country/Region)QBT_TR[CONTEXT=PeerListWidget]', 22, true);
1548 this.newColumn('ip', '', 'QBT_TR(IP)QBT_TR[CONTEXT=PeerListWidget]', 80, true);
1549 this.newColumn('port', '', 'QBT_TR(Port)QBT_TR[CONTEXT=PeerListWidget]', 35, true);
1550 this.newColumn('connection', '', 'QBT_TR(Connection)QBT_TR[CONTEXT=PeerListWidget]', 50, true);
1551 this.newColumn('flags', '', 'QBT_TR(Flags)QBT_TR[CONTEXT=PeerListWidget]', 50, true);
1552 this.newColumn('client', '', 'QBT_TR(Client)QBT_TR[CONTEXT=PeerListWidget]', 140, true);
1553 this.newColumn('peer_id_client', '', 'QBT_TR(Peer ID Client)QBT_TR[CONTEXT=PeerListWidget]', 60, false);
1554 this.newColumn('progress', '', 'QBT_TR(Progress)QBT_TR[CONTEXT=PeerListWidget]', 50, true);
1555 this.newColumn('dl_speed', '', 'QBT_TR(Down Speed)QBT_TR[CONTEXT=PeerListWidget]', 50, true);
1556 this.newColumn('up_speed', '', 'QBT_TR(Up Speed)QBT_TR[CONTEXT=PeerListWidget]', 50, true);
1557 this.newColumn('downloaded', '', 'QBT_TR(Downloaded)QBT_TR[CONTEXT=PeerListWidget]', 50, true);
1558 this.newColumn('uploaded', '', 'QBT_TR(Uploaded)QBT_TR[CONTEXT=PeerListWidget]', 50, true);
1559 this.newColumn('relevance', '', 'QBT_TR(Relevance)QBT_TR[CONTEXT=PeerListWidget]', 30, true);
1560 this.newColumn('files', '', 'QBT_TR(Files)QBT_TR[CONTEXT=PeerListWidget]', 100, true);
1562 this.columns['country'].dataProperties.push('country_code');
1563 this.columns['flags'].dataProperties.push('flags_desc');
1564 this.initColumnsFunctions();
1567 initColumnsFunctions: function() {
1569 // country
1570 this.columns['country'].updateTd = function(td, row) {
1571 const country = this.getRowValue(row, 0);
1572 const country_code = this.getRowValue(row, 1);
1574 if (!country_code) {
1575 if (td.getChildren('img').length > 0)
1576 td.getChildren('img')[0].destroy();
1577 return;
1580 const img_path = 'images/flags/' + country_code + '.svg';
1582 if (td.getChildren('img').length > 0) {
1583 const img = td.getChildren('img')[0];
1584 img.set('src', img_path);
1585 img.set('class', 'flags');
1586 img.set('alt', country);
1587 img.set('title', country);
1589 else
1590 td.adopt(new Element('img', {
1591 'src': img_path,
1592 'class': 'flags',
1593 'alt': country,
1594 'title': country
1595 }));
1598 // ip
1599 this.columns['ip'].compareRows = function(row1, row2) {
1600 const ip1 = this.getRowValue(row1);
1601 const ip2 = this.getRowValue(row2);
1603 const a = ip1.split(".");
1604 const b = ip2.split(".");
1606 for (let i = 0; i < 4; ++i) {
1607 if (a[i] != b[i])
1608 return a[i] - b[i];
1611 return 0;
1614 // flags
1615 this.columns['flags'].updateTd = function(td, row) {
1616 td.set('text', this.getRowValue(row, 0));
1617 td.set('title', this.getRowValue(row, 1));
1620 // progress
1621 this.columns['progress'].updateTd = function(td, row) {
1622 const progress = this.getRowValue(row);
1623 let progressFormatted = (progress * 100).round(1);
1624 if (progressFormatted == 100.0 && progress != 1.0)
1625 progressFormatted = 99.9;
1626 progressFormatted += "%";
1627 td.set('text', progressFormatted);
1628 td.set('title', progressFormatted);
1631 // dl_speed, up_speed
1632 this.columns['dl_speed'].updateTd = function(td, row) {
1633 const speed = this.getRowValue(row);
1634 if (speed === 0) {
1635 td.set('text', '');
1636 td.set('title', '');
1638 else {
1639 const formattedSpeed = window.qBittorrent.Misc.friendlyUnit(speed, true);
1640 td.set('text', formattedSpeed);
1641 td.set('title', formattedSpeed);
1644 this.columns['up_speed'].updateTd = this.columns['dl_speed'].updateTd;
1646 // downloaded, uploaded
1647 this.columns['downloaded'].updateTd = function(td, row) {
1648 const downloaded = window.qBittorrent.Misc.friendlyUnit(this.getRowValue(row), false);
1649 td.set('text', downloaded);
1650 td.set('title', downloaded);
1652 this.columns['uploaded'].updateTd = this.columns['downloaded'].updateTd;
1654 // relevance
1655 this.columns['relevance'].updateTd = this.columns['progress'].updateTd;
1657 // files
1658 this.columns['files'].updateTd = function(td, row) {
1659 const value = this.getRowValue(row, 0);
1660 td.set('text', value.replace(/\n/g, ';'));
1661 td.set('title', value);
1667 const SearchResultsTable = new Class({
1668 Extends: DynamicTable,
1670 initColumns: function() {
1671 this.newColumn('fileName', '', 'QBT_TR(Name)QBT_TR[CONTEXT=SearchResultsTable]', 500, true);
1672 this.newColumn('fileSize', '', 'QBT_TR(Size)QBT_TR[CONTEXT=SearchResultsTable]', 100, true);
1673 this.newColumn('nbSeeders', '', 'QBT_TR(Seeders)QBT_TR[CONTEXT=SearchResultsTable]', 100, true);
1674 this.newColumn('nbLeechers', '', 'QBT_TR(Leechers)QBT_TR[CONTEXT=SearchResultsTable]', 100, true);
1675 this.newColumn('siteUrl', '', 'QBT_TR(Search engine)QBT_TR[CONTEXT=SearchResultsTable]', 250, true);
1677 this.initColumnsFunctions();
1680 initColumnsFunctions: function() {
1681 const displaySize = function(td, row) {
1682 const size = window.qBittorrent.Misc.friendlyUnit(this.getRowValue(row), false);
1683 td.set('text', size);
1684 td.set('title', size);
1686 const displayNum = function(td, row) {
1687 const value = this.getRowValue(row);
1688 const formattedValue = (value === "-1") ? "Unknown" : value;
1689 td.set('text', formattedValue);
1690 td.set('title', formattedValue);
1693 this.columns['fileSize'].updateTd = displaySize;
1694 this.columns['nbSeeders'].updateTd = displayNum;
1695 this.columns['nbLeechers'].updateTd = displayNum;
1698 getFilteredAndSortedRows: function() {
1699 const getSizeFilters = function() {
1700 let minSize = (window.qBittorrent.Search.searchSizeFilter.min > 0.00) ? (window.qBittorrent.Search.searchSizeFilter.min * Math.pow(1024, window.qBittorrent.Search.searchSizeFilter.minUnit)) : 0.00;
1701 let maxSize = (window.qBittorrent.Search.searchSizeFilter.max > 0.00) ? (window.qBittorrent.Search.searchSizeFilter.max * Math.pow(1024, window.qBittorrent.Search.searchSizeFilter.maxUnit)) : 0.00;
1703 if ((minSize > maxSize) && (maxSize > 0.00)) {
1704 const tmp = minSize;
1705 minSize = maxSize;
1706 maxSize = tmp;
1709 return {
1710 min: minSize,
1711 max: maxSize
1715 const getSeedsFilters = function() {
1716 let minSeeds = (window.qBittorrent.Search.searchSeedsFilter.min > 0) ? window.qBittorrent.Search.searchSeedsFilter.min : 0;
1717 let maxSeeds = (window.qBittorrent.Search.searchSeedsFilter.max > 0) ? window.qBittorrent.Search.searchSeedsFilter.max : 0;
1719 if ((minSeeds > maxSeeds) && (maxSeeds > 0)) {
1720 const tmp = minSeeds;
1721 minSeeds = maxSeeds;
1722 maxSeeds = tmp;
1725 return {
1726 min: minSeeds,
1727 max: maxSeeds
1731 let filteredRows = [];
1732 const rows = this.rows.getValues();
1733 const searchTerms = window.qBittorrent.Search.searchText.pattern.toLowerCase().split(" ");
1734 const filterTerms = window.qBittorrent.Search.searchText.filterPattern.toLowerCase().split(" ");
1735 const sizeFilters = getSizeFilters();
1736 const seedsFilters = getSeedsFilters();
1737 const searchInTorrentName = $('searchInTorrentName').get('value') === "names";
1739 if (searchInTorrentName || (filterTerms.length > 0) || (window.qBittorrent.Search.searchSizeFilter.min > 0.00) || (window.qBittorrent.Search.searchSizeFilter.max > 0.00)) {
1740 for (let i = 0; i < rows.length; ++i) {
1741 const row = rows[i];
1743 if (searchInTorrentName && !window.qBittorrent.Misc.containsAllTerms(row.full_data.fileName, searchTerms))
1744 continue;
1745 if ((filterTerms.length > 0) && !window.qBittorrent.Misc.containsAllTerms(row.full_data.fileName, filterTerms))
1746 continue;
1747 if ((sizeFilters.min > 0.00) && (row.full_data.fileSize < sizeFilters.min))
1748 continue;
1749 if ((sizeFilters.max > 0.00) && (row.full_data.fileSize > sizeFilters.max))
1750 continue;
1751 if ((seedsFilters.min > 0) && (row.full_data.nbSeeders < seedsFilters.min))
1752 continue;
1753 if ((seedsFilters.max > 0) && (row.full_data.nbSeeders > seedsFilters.max))
1754 continue;
1756 filteredRows.push(row);
1759 else {
1760 filteredRows = rows;
1763 filteredRows.sort(function(row1, row2) {
1764 const column = this.columns[this.sortedColumn];
1765 const res = column.compareRows(row1, row2);
1766 if (this.reverseSort === '0')
1767 return res;
1768 else
1769 return -res;
1770 }.bind(this));
1772 return filteredRows;
1775 setupTr: function(tr) {
1776 tr.addClass("searchTableRow");
1780 const SearchPluginsTable = new Class({
1781 Extends: DynamicTable,
1783 initColumns: function() {
1784 this.newColumn('fullName', '', 'QBT_TR(Name)QBT_TR[CONTEXT=SearchPluginsTable]', 175, true);
1785 this.newColumn('version', '', 'QBT_TR(Version)QBT_TR[CONTEXT=SearchPluginsTable]', 100, true);
1786 this.newColumn('url', '', 'QBT_TR(Url)QBT_TR[CONTEXT=SearchPluginsTable]', 175, true);
1787 this.newColumn('enabled', '', 'QBT_TR(Enabled)QBT_TR[CONTEXT=SearchPluginsTable]', 100, true);
1789 this.initColumnsFunctions();
1792 initColumnsFunctions: function() {
1793 this.columns['enabled'].updateTd = function(td, row) {
1794 const value = this.getRowValue(row);
1795 if (value) {
1796 td.set('text', 'QBT_TR(Yes)QBT_TR[CONTEXT=SearchPluginsTable]');
1797 td.set('title', 'QBT_TR(Yes)QBT_TR[CONTEXT=SearchPluginsTable]');
1798 td.getParent("tr").addClass("green");
1799 td.getParent("tr").removeClass("red");
1801 else {
1802 td.set('text', 'QBT_TR(No)QBT_TR[CONTEXT=SearchPluginsTable]');
1803 td.set('title', 'QBT_TR(No)QBT_TR[CONTEXT=SearchPluginsTable]');
1804 td.getParent("tr").addClass("red");
1805 td.getParent("tr").removeClass("green");
1810 setupTr: function(tr) {
1811 tr.addClass("searchPluginsTableRow");
1815 const TorrentTrackersTable = new Class({
1816 Extends: DynamicTable,
1818 initColumns: function() {
1819 this.newColumn('tier', '', 'QBT_TR(Tier)QBT_TR[CONTEXT=TrackerListWidget]', 35, true);
1820 this.newColumn('url', '', 'QBT_TR(URL)QBT_TR[CONTEXT=TrackerListWidget]', 250, true);
1821 this.newColumn('status', '', 'QBT_TR(Status)QBT_TR[CONTEXT=TrackerListWidget]', 125, true);
1822 this.newColumn('peers', '', 'QBT_TR(Peers)QBT_TR[CONTEXT=TrackerListWidget]', 75, true);
1823 this.newColumn('seeds', '', 'QBT_TR(Seeds)QBT_TR[CONTEXT=TrackerListWidget]', 75, true);
1824 this.newColumn('leeches', '', 'QBT_TR(Leeches)QBT_TR[CONTEXT=TrackerListWidget]', 75, true);
1825 this.newColumn('downloaded', '', 'QBT_TR(Times Downloaded)QBT_TR[CONTEXT=TrackerListWidget]', 100, true);
1826 this.newColumn('message', '', 'QBT_TR(Message)QBT_TR[CONTEXT=TrackerListWidget]', 250, true);
1830 const BulkRenameTorrentFilesTable = new Class({
1831 Extends: DynamicTable,
1833 filterTerms: [],
1834 prevFilterTerms: [],
1835 prevRowsString: null,
1836 prevFilteredRows: [],
1837 prevSortedColumn: null,
1838 prevReverseSort: null,
1839 fileTree: new window.qBittorrent.FileTree.FileTree(),
1841 populateTable: function(root) {
1842 this.fileTree.setRoot(root);
1843 root.children.each(function(node) {
1844 this._addNodeToTable(node, 0);
1845 }.bind(this));
1848 _addNodeToTable: function(node, depth) {
1849 node.depth = depth;
1851 if (node.isFolder) {
1852 const data = {
1853 rowId: node.rowId,
1854 fileId: -1,
1855 checked: node.checked,
1856 path: node.path,
1857 original: node.original,
1858 renamed: node.renamed
1861 node.data = data;
1862 node.full_data = data;
1863 this.updateRowData(data);
1865 else {
1866 node.data.rowId = node.rowId;
1867 node.full_data = node.data;
1868 this.updateRowData(node.data);
1871 node.children.each(function(child) {
1872 this._addNodeToTable(child, depth + 1);
1873 }.bind(this));
1876 getRoot: function() {
1877 return this.fileTree.getRoot();
1880 getNode: function(rowId) {
1881 return this.fileTree.getNode(rowId);
1884 getRow: function(node) {
1885 const rowId = this.fileTree.getRowId(node);
1886 return this.rows.get(rowId);
1889 getSelectedRows: function() {
1890 const nodes = this.fileTree.toArray();
1892 return nodes.filter(x => x.checked == 0);
1895 initColumns: function() {
1896 // Blocks saving header width (because window width isn't saved)
1897 LocalPreferences.remove('column_' + "checked" + '_width_' + this.dynamicTableDivId);
1898 LocalPreferences.remove('column_' + "original" + '_width_' + this.dynamicTableDivId);
1899 LocalPreferences.remove('column_' + "renamed" + '_width_' + this.dynamicTableDivId);
1900 this.newColumn('checked', '', '', 50, true);
1901 this.newColumn('original', '', 'QBT_TR(Original)QBT_TR[CONTEXT=TrackerListWidget]', 270, true);
1902 this.newColumn('renamed', '', 'QBT_TR(Renamed)QBT_TR[CONTEXT=TrackerListWidget]', 220, true);
1904 this.initColumnsFunctions();
1908 * Toggles the global checkbox and all checkboxes underneath
1910 toggleGlobalCheckbox: function() {
1911 const checkbox = $('rootMultiRename_cb');
1912 const checkboxes = $$('input.RenamingCB');
1914 for (let i = 0; i < checkboxes.length; ++i) {
1915 const node = this.getNode(i);
1917 if (checkbox.checked || checkbox.indeterminate) {
1918 let cb = checkboxes[i];
1919 cb.checked = true;
1920 cb.indeterminate = false;
1921 cb.state = "checked";
1922 node.checked = 0;
1923 node.full_data.checked = node.checked;
1925 else {
1926 let cb = checkboxes[i];
1927 cb.checked = false;
1928 cb.indeterminate = false;
1929 cb.state = "unchecked";
1930 node.checked = 1;
1931 node.full_data.checked = node.checked;
1935 this.updateGlobalCheckbox();
1938 toggleNodeTreeCheckbox: function(rowId, checkState) {
1939 const node = this.getNode(rowId);
1940 node.checked = checkState;
1941 node.full_data.checked = checkState;
1942 const checkbox = $(`cbRename${rowId}`);
1943 checkbox.checked = node.checked == 0;
1944 checkbox.state = checkbox.checked ? "checked" : "unchecked";
1946 for (let i = 0; i < node.children.length; ++i) {
1947 this.toggleNodeTreeCheckbox(node.children[i].rowId, checkState);
1951 updateGlobalCheckbox: function() {
1952 const checkbox = $('rootMultiRename_cb');
1953 const checkboxes = $$('input.RenamingCB');
1954 const isAllChecked = function() {
1955 for (let i = 0; i < checkboxes.length; ++i) {
1956 if (!checkboxes[i].checked)
1957 return false;
1959 return true;
1961 const isAllUnchecked = function() {
1962 for (let i = 0; i < checkboxes.length; ++i) {
1963 if (checkboxes[i].checked)
1964 return false;
1966 return true;
1968 if (isAllChecked()) {
1969 checkbox.state = "checked";
1970 checkbox.indeterminate = false;
1971 checkbox.checked = true;
1973 else if (isAllUnchecked()) {
1974 checkbox.state = "unchecked";
1975 checkbox.indeterminate = false;
1976 checkbox.checked = false;
1978 else {
1979 checkbox.state = "partial";
1980 checkbox.indeterminate = true;
1981 checkbox.checked = false;
1985 initColumnsFunctions: function() {
1986 const that = this;
1988 // checked
1989 this.columns['checked'].updateTd = function(td, row) {
1990 const id = row.rowId;
1991 const value = this.getRowValue(row);
1993 const treeImg = new Element('img', {
1994 src: 'images/L.gif',
1995 styles: {
1996 'margin-bottom': -2
1999 const checkbox = new Element('input');
2000 checkbox.set('type', 'checkbox');
2001 checkbox.set('id', 'cbRename' + id);
2002 checkbox.set('data-id', id);
2003 checkbox.set('class', 'RenamingCB');
2004 checkbox.addEvent('click', function(e) {
2005 const node = that.getNode(id);
2006 node.checked = e.target.checked ? 0 : 1;
2007 node.full_data.checked = node.checked;
2008 that.updateGlobalCheckbox();
2009 that.onRowSelectionChange(node);
2010 e.stopPropagation();
2012 checkbox.checked = value == 0;
2013 checkbox.state = checkbox.checked ? "checked" : "unchecked";
2014 checkbox.indeterminate = false;
2015 td.adopt(treeImg, checkbox);
2018 // original
2019 this.columns['original'].updateTd = function(td, row) {
2020 const id = row.rowId;
2021 const fileNameId = 'filesTablefileName' + id;
2022 const node = that.getNode(id);
2024 if (node.isFolder) {
2025 const value = this.getRowValue(row);
2026 const dirImgId = 'renameTableDirImg' + id;
2027 if ($(dirImgId)) {
2028 // just update file name
2029 $(fileNameId).set('text', value);
2031 else {
2032 const span = new Element('span', {
2033 text: value,
2034 id: fileNameId
2036 const dirImg = new Element('img', {
2037 src: 'images/directory.svg',
2038 styles: {
2039 'width': 15,
2040 'padding-right': 5,
2041 'margin-bottom': -3,
2042 'margin-left': (node.depth * 20)
2044 id: dirImgId
2046 const html = dirImg.outerHTML + span.outerHTML;
2047 td.set('html', html);
2050 else { // is file
2051 const value = this.getRowValue(row);
2052 const span = new Element('span', {
2053 text: value,
2054 id: fileNameId,
2055 styles: {
2056 'margin-left': ((node.depth + 1) * 20)
2059 td.set('html', span.outerHTML);
2063 // renamed
2064 this.columns['renamed'].updateTd = function(td, row) {
2065 const id = row.rowId;
2066 const fileNameRenamedId = 'filesTablefileRenamed' + id;
2067 const value = this.getRowValue(row);
2069 const span = new Element('span', {
2070 text: value,
2071 id: fileNameRenamedId,
2073 td.set('html', span.outerHTML);
2077 onRowSelectionChange: function(row) {},
2079 selectRow: function() {
2080 return;
2083 reselectRows: function(rowIds) {
2084 const that = this;
2085 this.deselectAll();
2086 this.tableBody.getElements('tr').each(function(tr) {
2087 if (rowIds.indexOf(tr.rowId) > -1) {
2088 const node = that.getNode(tr.rowId);
2089 node.checked = 0;
2090 node.full_data.checked = 0;
2092 const checkbox = tr.children[0].getElement('input');
2093 checkbox.state = "checked";
2094 checkbox.indeterminate = false;
2095 checkbox.checked = true;
2099 this.updateGlobalCheckbox();
2102 altRow: function() {
2103 let addClass = false;
2104 const trs = this.tableBody.getElements('tr');
2105 trs.each(function(tr) {
2106 if (tr.hasClass("invisible"))
2107 return;
2109 if (addClass) {
2110 tr.addClass("alt");
2111 tr.removeClass("nonAlt");
2113 else {
2114 tr.removeClass("alt");
2115 tr.addClass("nonAlt");
2117 addClass = !addClass;
2118 }.bind(this));
2121 _sortNodesByColumn: function(nodes, column) {
2122 nodes.sort(function(row1, row2) {
2123 // list folders before files when sorting by name
2124 if (column.name === "original") {
2125 const node1 = this.getNode(row1.data.rowId);
2126 const node2 = this.getNode(row2.data.rowId);
2127 if (node1.isFolder && !node2.isFolder)
2128 return -1;
2129 if (node2.isFolder && !node1.isFolder)
2130 return 1;
2133 const res = column.compareRows(row1, row2);
2134 return (this.reverseSort === '0') ? res : -res;
2135 }.bind(this));
2137 nodes.each(function(node) {
2138 if (node.children.length > 0)
2139 this._sortNodesByColumn(node.children, column);
2140 }.bind(this));
2143 _filterNodes: function(node, filterTerms, filteredRows) {
2144 if (node.isFolder) {
2145 const childAdded = node.children.reduce(function(acc, child) {
2146 // we must execute the function before ORing w/ acc or we'll stop checking child nodes after the first successful match
2147 return (this._filterNodes(child, filterTerms, filteredRows) || acc);
2148 }.bind(this), false);
2150 if (childAdded) {
2151 const row = this.getRow(node);
2152 filteredRows.push(row);
2153 return true;
2157 if (window.qBittorrent.Misc.containsAllTerms(node.original, filterTerms)) {
2158 const row = this.getRow(node);
2159 filteredRows.push(row);
2160 return true;
2163 return false;
2166 setFilter: function(text) {
2167 const filterTerms = text.trim().toLowerCase().split(' ');
2168 if ((filterTerms.length === 1) && (filterTerms[0] === ''))
2169 this.filterTerms = [];
2170 else
2171 this.filterTerms = filterTerms;
2174 getFilteredAndSortedRows: function() {
2175 if (this.getRoot() === null)
2176 return [];
2178 const generateRowsSignature = function(rows) {
2179 const rowsData = rows.map(function(row) {
2180 return row.full_data;
2182 return JSON.stringify(rowsData);
2185 const getFilteredRows = function() {
2186 if (this.filterTerms.length === 0) {
2187 const nodeArray = this.fileTree.toArray();
2188 const filteredRows = nodeArray.map(function(node) {
2189 return this.getRow(node);
2190 }.bind(this));
2191 return filteredRows;
2194 const filteredRows = [];
2195 this.getRoot().children.each(function(child) {
2196 this._filterNodes(child, this.filterTerms, filteredRows);
2197 }.bind(this));
2198 filteredRows.reverse();
2199 return filteredRows;
2200 }.bind(this);
2202 const hasRowsChanged = function(rowsString, prevRowsStringString) {
2203 const rowsChanged = (rowsString !== prevRowsStringString);
2204 const isFilterTermsChanged = this.filterTerms.reduce(function(acc, term, index) {
2205 return (acc || (term !== this.prevFilterTerms[index]));
2206 }.bind(this), false);
2207 const isFilterChanged = ((this.filterTerms.length !== this.prevFilterTerms.length)
2208 || ((this.filterTerms.length > 0) && isFilterTermsChanged));
2209 const isSortedColumnChanged = (this.prevSortedColumn !== this.sortedColumn);
2210 const isReverseSortChanged = (this.prevReverseSort !== this.reverseSort);
2212 return (rowsChanged || isFilterChanged || isSortedColumnChanged || isReverseSortChanged);
2213 }.bind(this);
2215 const rowsString = generateRowsSignature(this.rows);
2216 if (!hasRowsChanged(rowsString, this.prevRowsString)) {
2217 return this.prevFilteredRows;
2220 // sort, then filter
2221 const column = this.columns[this.sortedColumn];
2222 this._sortNodesByColumn(this.getRoot().children, column);
2223 const filteredRows = getFilteredRows();
2225 this.prevFilterTerms = this.filterTerms;
2226 this.prevRowsString = rowsString;
2227 this.prevFilteredRows = filteredRows;
2228 this.prevSortedColumn = this.sortedColumn;
2229 this.prevReverseSort = this.reverseSort;
2230 return filteredRows;
2233 setIgnored: function(rowId, ignore) {
2234 const row = this.rows.get(rowId);
2235 if (ignore)
2236 row.full_data.remaining = 0;
2237 else
2238 row.full_data.remaining = (row.full_data.size * (1.0 - (row.full_data.progress / 100)));
2241 setupTr: function(tr) {
2242 tr.addEvent('keydown', function(event) {
2243 switch (event.key) {
2244 case "left":
2245 qBittorrent.PropFiles.collapseFolder(this._this.getSelectedRowId());
2246 return false;
2247 case "right":
2248 qBittorrent.PropFiles.expandFolder(this._this.getSelectedRowId());
2249 return false;
2255 const TorrentFilesTable = new Class({
2256 Extends: DynamicTable,
2258 filterTerms: [],
2259 prevFilterTerms: [],
2260 prevRowsString: null,
2261 prevFilteredRows: [],
2262 prevSortedColumn: null,
2263 prevReverseSort: null,
2264 fileTree: new window.qBittorrent.FileTree.FileTree(),
2266 populateTable: function(root) {
2267 this.fileTree.setRoot(root);
2268 root.children.each(function(node) {
2269 this._addNodeToTable(node, 0);
2270 }.bind(this));
2273 _addNodeToTable: function(node, depth) {
2274 node.depth = depth;
2276 if (node.isFolder) {
2277 const data = {
2278 rowId: node.rowId,
2279 size: node.size,
2280 checked: node.checked,
2281 remaining: node.remaining,
2282 progress: node.progress,
2283 priority: window.qBittorrent.PropFiles.normalizePriority(node.priority),
2284 availability: node.availability,
2285 fileId: -1,
2286 name: node.name
2289 node.data = data;
2290 node.full_data = data;
2291 this.updateRowData(data);
2293 else {
2294 node.data.rowId = node.rowId;
2295 node.full_data = node.data;
2296 this.updateRowData(node.data);
2299 node.children.each(function(child) {
2300 this._addNodeToTable(child, depth + 1);
2301 }.bind(this));
2304 getRoot: function() {
2305 return this.fileTree.getRoot();
2308 getNode: function(rowId) {
2309 return this.fileTree.getNode(rowId);
2312 getRow: function(node) {
2313 const rowId = this.fileTree.getRowId(node);
2314 return this.rows.get(rowId);
2317 initColumns: function() {
2318 this.newColumn('checked', '', '', 50, true);
2319 this.newColumn('name', '', 'QBT_TR(Name)QBT_TR[CONTEXT=TrackerListWidget]', 300, true);
2320 this.newColumn('size', '', 'QBT_TR(Total Size)QBT_TR[CONTEXT=TrackerListWidget]', 75, true);
2321 this.newColumn('progress', '', 'QBT_TR(Progress)QBT_TR[CONTEXT=TrackerListWidget]', 100, true);
2322 this.newColumn('priority', '', 'QBT_TR(Download Priority)QBT_TR[CONTEXT=TrackerListWidget]', 150, true);
2323 this.newColumn('remaining', '', 'QBT_TR(Remaining)QBT_TR[CONTEXT=TrackerListWidget]', 75, true);
2324 this.newColumn('availability', '', 'QBT_TR(Availability)QBT_TR[CONTEXT=TrackerListWidget]', 75, true);
2326 this.initColumnsFunctions();
2329 initColumnsFunctions: function() {
2330 const that = this;
2331 const displaySize = function(td, row) {
2332 const size = window.qBittorrent.Misc.friendlyUnit(this.getRowValue(row), false);
2333 td.set('text', size);
2334 td.set('title', size);
2336 const displayPercentage = function(td, row) {
2337 const value = window.qBittorrent.Misc.friendlyPercentage(this.getRowValue(row));
2338 td.set('text', value);
2339 td.set('title', value);
2342 // checked
2343 this.columns['checked'].updateTd = function(td, row) {
2344 const id = row.rowId;
2345 const value = this.getRowValue(row);
2347 if (window.qBittorrent.PropFiles.isDownloadCheckboxExists(id)) {
2348 window.qBittorrent.PropFiles.updateDownloadCheckbox(id, value);
2350 else {
2351 const treeImg = new Element('img', {
2352 src: 'images/L.gif',
2353 styles: {
2354 'margin-bottom': -2
2357 td.adopt(treeImg, window.qBittorrent.PropFiles.createDownloadCheckbox(id, row.full_data.fileId, value));
2361 // name
2362 this.columns['name'].updateTd = function(td, row) {
2363 const id = row.rowId;
2364 const fileNameId = 'filesTablefileName' + id;
2365 const node = that.getNode(id);
2367 if (node.isFolder) {
2368 const value = this.getRowValue(row);
2369 const collapseIconId = 'filesTableCollapseIcon' + id;
2370 const dirImgId = 'filesTableDirImg' + id;
2371 if ($(dirImgId)) {
2372 // just update file name
2373 $(fileNameId).set('text', value);
2375 else {
2376 const collapseIcon = new Element('img', {
2377 src: 'images/go-down.svg',
2378 styles: {
2379 'margin-left': (node.depth * 20)
2381 class: "filesTableCollapseIcon",
2382 id: collapseIconId,
2383 "data-id": id,
2384 onclick: "qBittorrent.PropFiles.collapseIconClicked(this)"
2386 const span = new Element('span', {
2387 text: value,
2388 id: fileNameId
2390 const dirImg = new Element('img', {
2391 src: 'images/directory.svg',
2392 styles: {
2393 'width': 15,
2394 'padding-right': 5,
2395 'margin-bottom': -3
2397 id: dirImgId
2399 const html = collapseIcon.outerHTML + dirImg.outerHTML + span.outerHTML;
2400 td.set('html', html);
2403 else {
2404 const value = this.getRowValue(row);
2405 const span = new Element('span', {
2406 text: value,
2407 id: fileNameId,
2408 styles: {
2409 'margin-left': ((node.depth + 1) * 20)
2412 td.set('html', span.outerHTML);
2416 // size
2417 this.columns['size'].updateTd = displaySize;
2419 // progress
2420 this.columns['progress'].updateTd = function(td, row) {
2421 const id = row.rowId;
2422 const value = this.getRowValue(row);
2424 const progressBar = $('pbf_' + id);
2425 if (progressBar === null) {
2426 td.adopt(new window.qBittorrent.ProgressBar.ProgressBar(value.toFloat(), {
2427 id: 'pbf_' + id,
2428 width: 80
2429 }));
2431 else {
2432 progressBar.setValue(value.toFloat());
2436 // priority
2437 this.columns['priority'].updateTd = function(td, row) {
2438 const id = row.rowId;
2439 const value = this.getRowValue(row);
2441 if (window.qBittorrent.PropFiles.isPriorityComboExists(id))
2442 window.qBittorrent.PropFiles.updatePriorityCombo(id, value);
2443 else
2444 td.adopt(window.qBittorrent.PropFiles.createPriorityCombo(id, row.full_data.fileId, value));
2447 // remaining, availability
2448 this.columns['remaining'].updateTd = displaySize;
2449 this.columns['availability'].updateTd = displayPercentage;
2452 altRow: function() {
2453 let addClass = false;
2454 const trs = this.tableBody.getElements('tr');
2455 trs.each(function(tr) {
2456 if (tr.hasClass("invisible"))
2457 return;
2459 if (addClass) {
2460 tr.addClass("alt");
2461 tr.removeClass("nonAlt");
2463 else {
2464 tr.removeClass("alt");
2465 tr.addClass("nonAlt");
2467 addClass = !addClass;
2468 }.bind(this));
2471 _sortNodesByColumn: function(nodes, column) {
2472 nodes.sort(function(row1, row2) {
2473 // list folders before files when sorting by name
2474 if (column.name === "name") {
2475 const node1 = this.getNode(row1.data.rowId);
2476 const node2 = this.getNode(row2.data.rowId);
2477 if (node1.isFolder && !node2.isFolder)
2478 return -1;
2479 if (node2.isFolder && !node1.isFolder)
2480 return 1;
2483 const res = column.compareRows(row1, row2);
2484 return (this.reverseSort === '0') ? res : -res;
2485 }.bind(this));
2487 nodes.each(function(node) {
2488 if (node.children.length > 0)
2489 this._sortNodesByColumn(node.children, column);
2490 }.bind(this));
2493 _filterNodes: function(node, filterTerms, filteredRows) {
2494 if (node.isFolder) {
2495 const childAdded = node.children.reduce(function(acc, child) {
2496 // we must execute the function before ORing w/ acc or we'll stop checking child nodes after the first successful match
2497 return (this._filterNodes(child, filterTerms, filteredRows) || acc);
2498 }.bind(this), false);
2500 if (childAdded) {
2501 const row = this.getRow(node);
2502 filteredRows.push(row);
2503 return true;
2507 if (window.qBittorrent.Misc.containsAllTerms(node.name, filterTerms)) {
2508 const row = this.getRow(node);
2509 filteredRows.push(row);
2510 return true;
2513 return false;
2516 setFilter: function(text) {
2517 const filterTerms = text.trim().toLowerCase().split(' ');
2518 if ((filterTerms.length === 1) && (filterTerms[0] === ''))
2519 this.filterTerms = [];
2520 else
2521 this.filterTerms = filterTerms;
2524 getFilteredAndSortedRows: function() {
2525 if (this.getRoot() === null)
2526 return [];
2528 const generateRowsSignature = function(rows) {
2529 const rowsData = rows.map(function(row) {
2530 return row.full_data;
2532 return JSON.stringify(rowsData);
2535 const getFilteredRows = function() {
2536 if (this.filterTerms.length === 0) {
2537 const nodeArray = this.fileTree.toArray();
2538 const filteredRows = nodeArray.map(function(node) {
2539 return this.getRow(node);
2540 }.bind(this));
2541 return filteredRows;
2544 const filteredRows = [];
2545 this.getRoot().children.each(function(child) {
2546 this._filterNodes(child, this.filterTerms, filteredRows);
2547 }.bind(this));
2548 filteredRows.reverse();
2549 return filteredRows;
2550 }.bind(this);
2552 const hasRowsChanged = function(rowsString, prevRowsStringString) {
2553 const rowsChanged = (rowsString !== prevRowsStringString);
2554 const isFilterTermsChanged = this.filterTerms.reduce(function(acc, term, index) {
2555 return (acc || (term !== this.prevFilterTerms[index]));
2556 }.bind(this), false);
2557 const isFilterChanged = ((this.filterTerms.length !== this.prevFilterTerms.length)
2558 || ((this.filterTerms.length > 0) && isFilterTermsChanged));
2559 const isSortedColumnChanged = (this.prevSortedColumn !== this.sortedColumn);
2560 const isReverseSortChanged = (this.prevReverseSort !== this.reverseSort);
2562 return (rowsChanged || isFilterChanged || isSortedColumnChanged || isReverseSortChanged);
2563 }.bind(this);
2565 const rowsString = generateRowsSignature(this.rows);
2566 if (!hasRowsChanged(rowsString, this.prevRowsString)) {
2567 return this.prevFilteredRows;
2570 // sort, then filter
2571 const column = this.columns[this.sortedColumn];
2572 this._sortNodesByColumn(this.getRoot().children, column);
2573 const filteredRows = getFilteredRows();
2575 this.prevFilterTerms = this.filterTerms;
2576 this.prevRowsString = rowsString;
2577 this.prevFilteredRows = filteredRows;
2578 this.prevSortedColumn = this.sortedColumn;
2579 this.prevReverseSort = this.reverseSort;
2580 return filteredRows;
2583 setIgnored: function(rowId, ignore) {
2584 const row = this.rows.get(rowId);
2585 if (ignore)
2586 row.full_data.remaining = 0;
2587 else
2588 row.full_data.remaining = (row.full_data.size * (1.0 - (row.full_data.progress / 100)));
2591 setupTr: function(tr) {
2592 tr.addEvent('keydown', function(event) {
2593 switch (event.key) {
2594 case "left":
2595 qBittorrent.PropFiles.collapseFolder(this._this.getSelectedRowId());
2596 return false;
2597 case "right":
2598 qBittorrent.PropFiles.expandFolder(this._this.getSelectedRowId());
2599 return false;
2605 const RssFeedTable = new Class({
2606 Extends: DynamicTable,
2607 initColumns: function() {
2608 this.newColumn('state_icon', '', '', 30, true);
2609 this.newColumn('name', '', 'QBT_TR(RSS feeds)QBT_TR[CONTEXT=FeedListWidget]', -1, true);
2611 this.columns['state_icon'].dataProperties[0] = '';
2613 // map name row to "[name] ([unread])"
2614 this.columns['name'].dataProperties.push('unread');
2615 this.columns['name'].updateTd = function(td, row) {
2616 const name = this.getRowValue(row, 0);
2617 const unreadCount = this.getRowValue(row, 1);
2618 let value = name + ' (' + unreadCount + ')';
2619 td.set('text', value);
2620 td.set('title', value);
2623 setupHeaderMenu: function() {},
2624 setupHeaderEvents: function() {},
2625 getFilteredAndSortedRows: function() {
2626 return this.rows.getValues();
2628 selectRow: function(rowId) {
2629 this.selectedRows.push(rowId);
2630 this.setRowClass();
2631 this.onSelectedRowChanged();
2633 const rows = this.rows.getValues();
2634 let path = '';
2635 for (let i = 0; i < rows.length; ++i) {
2636 if (rows[i].rowId === rowId) {
2637 path = rows[i].full_data.dataPath;
2638 break;
2641 window.qBittorrent.Rss.showRssFeed(path);
2643 setupTr: function(tr) {
2644 tr.addEvent('dblclick', function(e) {
2645 if (this.rowId !== 0) {
2646 window.qBittorrent.Rss.moveItem(this._this.rows.get(this.rowId).full_data.dataPath);
2647 return true;
2651 updateRow: function(tr, fullUpdate) {
2652 const row = this.rows.get(tr.rowId);
2653 const data = row[fullUpdate ? 'full_data' : 'data'];
2655 const tds = tr.getElements('td');
2656 for (let i = 0; i < this.columns.length; ++i) {
2657 if (Object.hasOwn(data, this.columns[i].dataProperties[0]))
2658 this.columns[i].updateTd(tds[i], row);
2660 row['data'] = {};
2661 tds[0].style.overflow = 'visible';
2662 let indentation = row.full_data.indentation;
2663 tds[0].style.paddingLeft = (indentation * 32 + 4) + 'px';
2664 tds[1].style.paddingLeft = (indentation * 32 + 4) + 'px';
2666 updateIcons: function() {
2667 // state_icon
2668 this.rows.each(row => {
2669 let img_path;
2670 switch (row.full_data.status) {
2671 case 'default':
2672 img_path = 'images/application-rss.svg';
2673 break;
2674 case 'hasError':
2675 img_path = 'images/task-reject.svg';
2676 break;
2677 case 'isLoading':
2678 img_path = 'images/spinner.gif';
2679 break;
2680 case 'unread':
2681 img_path = 'images/mail-inbox.svg';
2682 break;
2683 case 'isFolder':
2684 img_path = 'images/folder-documents.svg';
2685 break;
2687 let td;
2688 for (let i = 0; i < this.tableBody.rows.length; ++i) {
2689 if (this.tableBody.rows[i].rowId === row.rowId) {
2690 td = this.tableBody.rows[i].children[0];
2691 break;
2694 if (td.getChildren('img').length > 0) {
2695 const img = td.getChildren('img')[0];
2696 if (img.src.indexOf(img_path) < 0) {
2697 img.set('src', img_path);
2698 img.set('title', status);
2701 else {
2702 td.adopt(new Element('img', {
2703 'src': img_path,
2704 'class': 'stateIcon',
2705 'height': '22px',
2706 'width': '22px'
2707 }));
2711 newColumn: function(name, style, caption, defaultWidth, defaultVisible) {
2712 const column = {};
2713 column['name'] = name;
2714 column['title'] = name;
2715 column['visible'] = defaultVisible;
2716 column['force_hide'] = false;
2717 column['caption'] = caption;
2718 column['style'] = style;
2719 if (defaultWidth !== -1) {
2720 column['width'] = defaultWidth;
2723 column['dataProperties'] = [name];
2724 column['getRowValue'] = function(row, pos) {
2725 if (pos === undefined)
2726 pos = 0;
2727 return row['full_data'][this.dataProperties[pos]];
2729 column['compareRows'] = function(row1, row2) {
2730 const value1 = this.getRowValue(row1);
2731 const value2 = this.getRowValue(row2);
2732 if ((typeof(value1) === 'number') && (typeof(value2) === 'number'))
2733 return compareNumbers(value1, value2);
2734 return window.qBittorrent.Misc.naturalSortCollator.compare(value1, value2);
2736 column['updateTd'] = function(td, row) {
2737 const value = this.getRowValue(row);
2738 td.set('text', value);
2739 td.set('title', value);
2741 column['onResize'] = null;
2742 this.columns.push(column);
2743 this.columns[name] = column;
2745 this.hiddenTableHeader.appendChild(new Element('th'));
2746 this.fixedTableHeader.appendChild(new Element('th'));
2748 setupCommonEvents: function() {
2749 const scrollFn = function() {
2750 $(this.dynamicTableFixedHeaderDivId).getElements('table')[0].style.left = -$(this.dynamicTableDivId).scrollLeft + 'px';
2751 }.bind(this);
2753 $(this.dynamicTableDivId).addEvent('scroll', scrollFn);
2757 const RssArticleTable = new Class({
2758 Extends: DynamicTable,
2759 initColumns: function() {
2760 this.newColumn('name', '', 'QBT_TR(Torrents: (double-click to download))QBT_TR[CONTEXT=RSSWidget]', -1, true);
2762 setupHeaderMenu: function() {},
2763 setupHeaderEvents: function() {},
2764 getFilteredAndSortedRows: function() {
2765 return this.rows.getValues();
2767 selectRow: function(rowId) {
2768 this.selectedRows.push(rowId);
2769 this.setRowClass();
2770 this.onSelectedRowChanged();
2772 const rows = this.rows.getValues();
2773 let articleId = '';
2774 let feedUid = '';
2775 for (let i = 0; i < rows.length; ++i) {
2776 if (rows[i].rowId === rowId) {
2777 articleId = rows[i].full_data.dataId;
2778 feedUid = rows[i].full_data.feedUid;
2779 this.tableBody.rows[rows[i].rowId].removeClass('unreadArticle');
2780 break;
2783 window.qBittorrent.Rss.showDetails(feedUid, articleId);
2785 setupTr: function(tr) {
2786 tr.addEvent('dblclick', function(e) {
2787 showDownloadPage([this._this.rows.get(this.rowId).full_data.torrentURL]);
2788 return true;
2790 tr.addClass('torrentsTableContextMenuTarget');
2792 updateRow: function(tr, fullUpdate) {
2793 const row = this.rows.get(tr.rowId);
2794 const data = row[fullUpdate ? 'full_data' : 'data'];
2795 if (!row.full_data.isRead)
2796 tr.addClass('unreadArticle');
2797 else
2798 tr.removeClass('unreadArticle');
2800 const tds = tr.getElements('td');
2801 for (let i = 0; i < this.columns.length; ++i) {
2802 if (Object.hasOwn(data, this.columns[i].dataProperties[0]))
2803 this.columns[i].updateTd(tds[i], row);
2805 row['data'] = {};
2807 newColumn: function(name, style, caption, defaultWidth, defaultVisible) {
2808 const column = {};
2809 column['name'] = name;
2810 column['title'] = name;
2811 column['visible'] = defaultVisible;
2812 column['force_hide'] = false;
2813 column['caption'] = caption;
2814 column['style'] = style;
2815 if (defaultWidth !== -1) {
2816 column['width'] = defaultWidth;
2819 column['dataProperties'] = [name];
2820 column['getRowValue'] = function(row, pos) {
2821 if (pos === undefined)
2822 pos = 0;
2823 return row['full_data'][this.dataProperties[pos]];
2825 column['compareRows'] = function(row1, row2) {
2826 const value1 = this.getRowValue(row1);
2827 const value2 = this.getRowValue(row2);
2828 if ((typeof(value1) === 'number') && (typeof(value2) === 'number'))
2829 return compareNumbers(value1, value2);
2830 return window.qBittorrent.Misc.naturalSortCollator.compare(value1, value2);
2832 column['updateTd'] = function(td, row) {
2833 const value = this.getRowValue(row);
2834 td.set('text', value);
2835 td.set('title', value);
2837 column['onResize'] = null;
2838 this.columns.push(column);
2839 this.columns[name] = column;
2841 this.hiddenTableHeader.appendChild(new Element('th'));
2842 this.fixedTableHeader.appendChild(new Element('th'));
2844 setupCommonEvents: function() {
2845 const scrollFn = function() {
2846 $(this.dynamicTableFixedHeaderDivId).getElements('table')[0].style.left = -$(this.dynamicTableDivId).scrollLeft + 'px';
2847 }.bind(this);
2849 $(this.dynamicTableDivId).addEvent('scroll', scrollFn);
2853 const RssDownloaderRulesTable = new Class({
2854 Extends: DynamicTable,
2855 initColumns: function() {
2856 this.newColumn('checked', '', '', 30, true);
2857 this.newColumn('name', '', '', -1, true);
2859 this.columns['checked'].updateTd = function(td, row) {
2860 if ($('cbRssDlRule' + row.rowId) === null) {
2861 const checkbox = new Element('input');
2862 checkbox.set('type', 'checkbox');
2863 checkbox.set('id', 'cbRssDlRule' + row.rowId);
2864 checkbox.checked = row.full_data.checked;
2866 checkbox.addEvent('click', function(e) {
2867 window.qBittorrent.RssDownloader.rssDownloaderRulesTable.updateRowData({
2868 rowId: row.rowId,
2869 checked: this.checked
2871 window.qBittorrent.RssDownloader.modifyRuleState(row.full_data.name, 'enabled', this.checked);
2872 e.stopPropagation();
2875 td.append(checkbox);
2877 else {
2878 $('cbRssDlRule' + row.rowId).checked = row.full_data.checked;
2882 setupHeaderMenu: function() {},
2883 setupHeaderEvents: function() {},
2884 getFilteredAndSortedRows: function() {
2885 return this.rows.getValues();
2887 setupTr: function(tr) {
2888 tr.addEvent('dblclick', function(e) {
2889 window.qBittorrent.RssDownloader.renameRule(this._this.rows.get(this.rowId).full_data.name);
2890 return true;
2893 newColumn: function(name, style, caption, defaultWidth, defaultVisible) {
2894 const column = {};
2895 column['name'] = name;
2896 column['title'] = name;
2897 column['visible'] = defaultVisible;
2898 column['force_hide'] = false;
2899 column['caption'] = caption;
2900 column['style'] = style;
2901 if (defaultWidth !== -1) {
2902 column['width'] = defaultWidth;
2905 column['dataProperties'] = [name];
2906 column['getRowValue'] = function(row, pos) {
2907 if (pos === undefined)
2908 pos = 0;
2909 return row['full_data'][this.dataProperties[pos]];
2911 column['compareRows'] = function(row1, row2) {
2912 const value1 = this.getRowValue(row1);
2913 const value2 = this.getRowValue(row2);
2914 if ((typeof(value1) === 'number') && (typeof(value2) === 'number'))
2915 return compareNumbers(value1, value2);
2916 return window.qBittorrent.Misc.naturalSortCollator.compare(value1, value2);
2918 column['updateTd'] = function(td, row) {
2919 const value = this.getRowValue(row);
2920 td.set('text', value);
2921 td.set('title', value);
2923 column['onResize'] = null;
2924 this.columns.push(column);
2925 this.columns[name] = column;
2927 this.hiddenTableHeader.appendChild(new Element('th'));
2928 this.fixedTableHeader.appendChild(new Element('th'));
2930 selectRow: function(rowId) {
2931 this.selectedRows.push(rowId);
2932 this.setRowClass();
2933 this.onSelectedRowChanged();
2935 const rows = this.rows.getValues();
2936 let name = '';
2937 for (let i = 0; i < rows.length; ++i) {
2938 if (rows[i].rowId === rowId) {
2939 name = rows[i].full_data.name;
2940 break;
2943 window.qBittorrent.RssDownloader.showRule(name);
2947 const RssDownloaderFeedSelectionTable = new Class({
2948 Extends: DynamicTable,
2949 initColumns: function() {
2950 this.newColumn('checked', '', '', 30, true);
2951 this.newColumn('name', '', '', -1, true);
2953 this.columns['checked'].updateTd = function(td, row) {
2954 if ($('cbRssDlFeed' + row.rowId) === null) {
2955 const checkbox = new Element('input');
2956 checkbox.set('type', 'checkbox');
2957 checkbox.set('id', 'cbRssDlFeed' + row.rowId);
2958 checkbox.checked = row.full_data.checked;
2960 checkbox.addEvent('click', function(e) {
2961 window.qBittorrent.RssDownloader.rssDownloaderFeedSelectionTable.updateRowData({
2962 rowId: row.rowId,
2963 checked: this.checked
2965 e.stopPropagation();
2968 td.append(checkbox);
2970 else {
2971 $('cbRssDlFeed' + row.rowId).checked = row.full_data.checked;
2975 setupHeaderMenu: function() {},
2976 setupHeaderEvents: function() {},
2977 getFilteredAndSortedRows: function() {
2978 return this.rows.getValues();
2980 newColumn: function(name, style, caption, defaultWidth, defaultVisible) {
2981 const column = {};
2982 column['name'] = name;
2983 column['title'] = name;
2984 column['visible'] = defaultVisible;
2985 column['force_hide'] = false;
2986 column['caption'] = caption;
2987 column['style'] = style;
2988 if (defaultWidth !== -1) {
2989 column['width'] = defaultWidth;
2992 column['dataProperties'] = [name];
2993 column['getRowValue'] = function(row, pos) {
2994 if (pos === undefined)
2995 pos = 0;
2996 return row['full_data'][this.dataProperties[pos]];
2998 column['compareRows'] = function(row1, row2) {
2999 const value1 = this.getRowValue(row1);
3000 const value2 = this.getRowValue(row2);
3001 if ((typeof(value1) === 'number') && (typeof(value2) === 'number'))
3002 return compareNumbers(value1, value2);
3003 return window.qBittorrent.Misc.naturalSortCollator.compare(value1, value2);
3005 column['updateTd'] = function(td, row) {
3006 const value = this.getRowValue(row);
3007 td.set('text', value);
3008 td.set('title', value);
3010 column['onResize'] = null;
3011 this.columns.push(column);
3012 this.columns[name] = column;
3014 this.hiddenTableHeader.appendChild(new Element('th'));
3015 this.fixedTableHeader.appendChild(new Element('th'));
3017 selectRow: function() {}
3020 const RssDownloaderArticlesTable = new Class({
3021 Extends: DynamicTable,
3022 initColumns: function() {
3023 this.newColumn('name', '', '', -1, true);
3025 setupHeaderMenu: function() {},
3026 setupHeaderEvents: function() {},
3027 getFilteredAndSortedRows: function() {
3028 return this.rows.getValues();
3030 newColumn: function(name, style, caption, defaultWidth, defaultVisible) {
3031 const column = {};
3032 column['name'] = name;
3033 column['title'] = name;
3034 column['visible'] = defaultVisible;
3035 column['force_hide'] = false;
3036 column['caption'] = caption;
3037 column['style'] = style;
3038 if (defaultWidth !== -1) {
3039 column['width'] = defaultWidth;
3042 column['dataProperties'] = [name];
3043 column['getRowValue'] = function(row, pos) {
3044 if (pos === undefined)
3045 pos = 0;
3046 return row['full_data'][this.dataProperties[pos]];
3048 column['compareRows'] = function(row1, row2) {
3049 const value1 = this.getRowValue(row1);
3050 const value2 = this.getRowValue(row2);
3051 if ((typeof(value1) === 'number') && (typeof(value2) === 'number'))
3052 return compareNumbers(value1, value2);
3053 return window.qBittorrent.Misc.naturalSortCollator.compare(value1, value2);
3055 column['updateTd'] = function(td, row) {
3056 const value = this.getRowValue(row);
3057 td.set('text', value);
3058 td.set('title', value);
3060 column['onResize'] = null;
3061 this.columns.push(column);
3062 this.columns[name] = column;
3064 this.hiddenTableHeader.appendChild(new Element('th'));
3065 this.fixedTableHeader.appendChild(new Element('th'));
3067 selectRow: function() {},
3068 updateRow: function(tr, fullUpdate) {
3069 const row = this.rows.get(tr.rowId);
3070 const data = row[fullUpdate ? 'full_data' : 'data'];
3072 if (row.full_data.isFeed) {
3073 tr.addClass('articleTableFeed');
3074 tr.removeClass('articleTableArticle');
3076 else {
3077 tr.removeClass('articleTableFeed');
3078 tr.addClass('articleTableArticle');
3081 const tds = tr.getElements('td');
3082 for (let i = 0; i < this.columns.length; ++i) {
3083 if (Object.hasOwn(data, this.columns[i].dataProperties[0]))
3084 this.columns[i].updateTd(tds[i], row);
3086 row['data'] = {};
3090 const LogMessageTable = new Class({
3091 Extends: DynamicTable,
3093 filterText: '',
3095 filteredLength: function() {
3096 return this.tableBody.getElements('tr').length;
3099 initColumns: function() {
3100 this.newColumn('rowId', '', 'QBT_TR(ID)QBT_TR[CONTEXT=ExecutionLogWidget]', 50, true);
3101 this.newColumn('message', '', 'QBT_TR(Message)QBT_TR[CONTEXT=ExecutionLogWidget]', 350, true);
3102 this.newColumn('timestamp', '', 'QBT_TR(Timestamp)QBT_TR[CONTEXT=ExecutionLogWidget]', 150, true);
3103 this.newColumn('type', '', 'QBT_TR(Log Type)QBT_TR[CONTEXT=ExecutionLogWidget]', 100, true);
3104 this.initColumnsFunctions();
3107 initColumnsFunctions: function() {
3108 this.columns['timestamp'].updateTd = function(td, row) {
3109 const date = new Date(this.getRowValue(row) * 1000).toLocaleString();
3110 td.set({ 'text': date, 'title': date });
3113 this.columns['type'].updateTd = function(td, row) {
3114 //Type of the message: Log::NORMAL: 1, Log::INFO: 2, Log::WARNING: 4, Log::CRITICAL: 8
3115 let logLevel, addClass;
3116 switch (this.getRowValue(row).toInt()) {
3117 case 1:
3118 logLevel = 'QBT_TR(Normal)QBT_TR[CONTEXT=ExecutionLogWidget]';
3119 addClass = 'logNormal';
3120 break;
3121 case 2:
3122 logLevel = 'QBT_TR(Info)QBT_TR[CONTEXT=ExecutionLogWidget]';
3123 addClass = 'logInfo';
3124 break;
3125 case 4:
3126 logLevel = 'QBT_TR(Warning)QBT_TR[CONTEXT=ExecutionLogWidget]';
3127 addClass = 'logWarning';
3128 break;
3129 case 8:
3130 logLevel = 'QBT_TR(Critical)QBT_TR[CONTEXT=ExecutionLogWidget]';
3131 addClass = 'logCritical';
3132 break;
3133 default:
3134 logLevel = 'QBT_TR(Unknown)QBT_TR[CONTEXT=ExecutionLogWidget]';
3135 addClass = 'logUnknown';
3136 break;
3138 td.set({ 'text': logLevel, 'title': logLevel });
3139 td.getParent('tr').set('class', 'logTableRow ' + addClass);
3143 getFilteredAndSortedRows: function() {
3144 let filteredRows = [];
3145 const rows = this.rows.getValues();
3146 this.filterText = window.qBittorrent.Log.getFilterText();
3147 const filterTerms = (this.filterText.length > 0) ? this.filterText.toLowerCase().split(' ') : [];
3148 const logLevels = window.qBittorrent.Log.getSelectedLevels();
3149 if (filterTerms.length > 0 || logLevels.length < 4) {
3150 for (let i = 0; i < rows.length; ++i) {
3151 if (logLevels.indexOf(rows[i].full_data.type.toString()) == -1)
3152 continue;
3154 if (filterTerms.length > 0 && !window.qBittorrent.Misc.containsAllTerms(rows[i].full_data.message, filterTerms))
3155 continue;
3157 filteredRows.push(rows[i]);
3160 else {
3161 filteredRows = rows;
3164 filteredRows.sort(function(row1, row2) {
3165 const column = this.columns[this.sortedColumn];
3166 const res = column.compareRows(row1, row2);
3167 return (this.reverseSort == '0') ? res : -res;
3168 }.bind(this));
3170 return filteredRows;
3173 setupCommonEvents: function() {},
3175 setupTr: function(tr) {
3176 tr.addClass('logTableRow');
3180 const LogPeerTable = new Class({
3181 Extends: LogMessageTable,
3183 initColumns: function() {
3184 this.newColumn('rowId', '', 'QBT_TR(ID)QBT_TR[CONTEXT=ExecutionLogWidget]', 50, true);
3185 this.newColumn('ip', '', 'QBT_TR(IP)QBT_TR[CONTEXT=ExecutionLogWidget]', 150, true);
3186 this.newColumn('timestamp', '', 'QBT_TR(Timestamp)QBT_TR[CONTEXT=ExecutionLogWidget]', 150, true);
3187 this.newColumn('blocked', '', 'QBT_TR(Status)QBT_TR[CONTEXT=ExecutionLogWidget]', 150, true);
3188 this.newColumn('reason', '', 'QBT_TR(Reason)QBT_TR[CONTEXT=ExecutionLogWidget]', 150, true);
3190 this.columns['timestamp'].updateTd = function(td, row) {
3191 const date = new Date(this.getRowValue(row) * 1000).toLocaleString();
3192 td.set({ 'text': date, 'title': date });
3195 this.columns['blocked'].updateTd = function(td, row) {
3196 let status, addClass;
3197 if (this.getRowValue(row)) {
3198 status = 'QBT_TR(Blocked)QBT_TR[CONTEXT=ExecutionLogWidget]';
3199 addClass = 'peerBlocked';
3201 else {
3202 status = 'QBT_TR(Banned)QBT_TR[CONTEXT=ExecutionLogWidget]';
3203 addClass = 'peerBanned';
3205 td.set({ 'text': status, 'title': status });
3206 td.getParent('tr').set('class', 'logTableRow ' + addClass);
3210 getFilteredAndSortedRows: function() {
3211 let filteredRows = [];
3212 const rows = this.rows.getValues();
3213 this.filterText = window.qBittorrent.Log.getFilterText();
3214 const filterTerms = (this.filterText.length > 0) ? this.filterText.toLowerCase().split(' ') : [];
3215 if (filterTerms.length > 0) {
3216 for (let i = 0; i < rows.length; ++i) {
3217 if (filterTerms.length > 0 && !window.qBittorrent.Misc.containsAllTerms(rows[i].full_data.ip, filterTerms))
3218 continue;
3220 filteredRows.push(rows[i]);
3223 else {
3224 filteredRows = rows;
3227 filteredRows.sort(function(row1, row2) {
3228 const column = this.columns[this.sortedColumn];
3229 const res = column.compareRows(row1, row2);
3230 return (this.reverseSort == '0') ? res : -res;
3231 }.bind(this));
3233 return filteredRows;
3237 return exports();
3238 })();
3240 Object.freeze(window.qBittorrent.DynamicTable);
3242 /*************************************************************/