Calculate qBittorrent selected torrents size

Calculates setected torrents size and displays a total in the toolbar

// ==UserScript==
// @name         Calculate qBittorrent selected torrents size
// @namespace    http://tampermonkey.net/
// @version      v0.5
// @description  Calculates setected torrents size and displays a total in the toolbar
// @author       me
// @match        http://localhost:8080/
// @icon         https://www.google.com/s2/favicons?sz=64&domain=undefined.localhost
// @grant        none
// @license      MIT

// ==/UserScript==
(function() {
    'use strict';

    var previousSelectedRows = [];
    var totalSpanId = 'totalSpan';

    // ========== Localization ================
    // Get the UI element value
    var uiElementValue = document.querySelector("#desktopNavbar > ul > li:nth-child(5) > a").innerHTML;

    // Autodetect language based on UI top menu help button
    var languageMappings = {
        "Help": "en",
        "Ajutor": "ro",
        "Aide": "fr",
        "Ayuda": "es",
        "Справка": "ru",
        "Aiuto": "it",
        "帮助": "zh",
        "Hilfe": "de",
        "Βοήθεια": "el",
        "Ajuda": "pt",
        "日本語": "ja",
        // Add more mappings as needed
    };

    // Use the value to look up the corresponding language code
    var userLanguage = languageMappings[uiElementValue];

    // Define localization sizes based on language
    var localizationValArr = {
        "en": ["KiB", "MiB", "GiB", "TiB", "Selected Torrents Total Size:"],
        "ro": ["KiO", "MiO", "GiO", "TiO", "Marimea Totala a Torrentelor Selectate:"],
        "fr": ["Kio", "Mio", "Gio", "Tio", "Taille totale des torrents sélectionnés:"],
        "es": ["KiB", "MiB", "GiB", "TiB", "Tamaño total de los torrents seleccionados:"],
        "ru": ["КиБ", "МиБ", "ГиБ", "ТиБ", "Общий размер выбранных торрентов:"],
        "it": ["KiB", "MiB", "GiB", "TiB", "Dimensione totale dei torrent selezionati:"],
        "zh": ["KiB", "MiB", "GiB", "TiB", "所选种子的总大小:"],
        "de": ["KiB", "MiB", "GiB", "TiB", "Gesamtgröße der ausgewählten Torrents:"],
        "nl": ["KiB", "MiB", "GiB", "TiB", "Totale Grootte van Geselecteerde Torrents:"],
        "el": ["KiB", "MiB", "GiB", "TiB", "Συνολικό Μέγεθος Επιλεγμένων Torrents:"],
        "pt": ["KiB", "MiB", "GiB", "TiB", "Tamanho Total dos Torrents Selecionados:"],
        "ja": ["KiB", "MiB", "GiB", "TiB", "選択したトレントの合計サイズ:"],
        // Add more languages as needed
    };

    // Function to get the correct size array based on language
    function getSizeArray(language) {
        return localizationValArr[language] || localizationValArr["en"]; // Default to English if the language is not defined
    }

    // ========== End Localization logic =======================

    // creating footer bar elements with slight delay for web ui to load
    setTimeout(function() {
        var trElement = document.querySelector("#desktopFooter > table > tbody > tr")

        var selectedSizeTotalElement = document.createElement("td");
        selectedSizeTotalElement.id = "selectedSizeTotal";
        selectedSizeTotalElement.textContent = getSizeArray(userLanguage)[4] + " 0.00";

        var statusBarSeparatorElement = document.createElement("td");
        statusBarSeparatorElement.className = "statusBarSeparator";

        // Insert the new elements before the existing ones
        trElement.insertBefore(selectedSizeTotalElement, trElement.firstElementChild);
        trElement.insertBefore(statusBarSeparatorElement, trElement.firstElementChild.nextSibling);

    }, 1000);

    // Calculates Selected torrents total size and inserts the values in the footer bar
    function calculateTotal() {
        var kib = 0;
        var mib = 0;
        var gib = 0;
        var tib = 0;
        var total = "";

        var selectedRows = document.querySelectorAll("tr.torrentsTableContextMenuTarget.selected");

        // Get the correct size array based on user language
        var fileAttrSizeArr = getSizeArray(userLanguage);

        // Check if selectedRows array is bigger than 0
        if (selectedRows.length > 0) {
            // Check if selectedRows has changed
            if (!arraysAreEqual(previousSelectedRows, selectedRows)) {
                selectedRows.forEach(function(row) {
                    var tSize = row.childNodes[3].innerHTML.split(" ");

                    if (fileAttrSizeArr[0].includes(tSize[1])) {
                        kib += parseFloat(tSize[0]);
                    } else if (fileAttrSizeArr[1].includes(tSize[1])) {
                        mib += parseFloat(tSize[0]);
                    } else if (fileAttrSizeArr[2].includes(tSize[1])) {
                        gib += parseFloat(tSize[0]);
                    } else if (fileAttrSizeArr[3].includes(tSize[1])) {
                        tib += parseFloat(tSize[0]);
                    }
                });

                var localTotal = kib + mib * 1024 + gib * 1048576 + tib * 1073741824;

                // Check if total has changed
                if (localTotal.toFixed(2) !== total) {
                    if (localTotal < 1024) {
                        total = localTotal.toFixed(2) + " " + fileAttrSizeArr[0];
                    } else if (localTotal < 1024000) {
                        total = (localTotal / 1024).toFixed(2) + " " + fileAttrSizeArr[1];
                    } else if (localTotal < 1048576000) {
                        total = (localTotal / 1048576).toFixed(2) + " " + fileAttrSizeArr[2];
                    } else {
                        total = (localTotal / 1073741824).toFixed(2) + " " + fileAttrSizeArr[3];
                    }


                    var selectedSizeTotal = document.getElementById("selectedSizeTotal");
                    selectedSizeTotal.innerHTML = fileAttrSizeArr[4] + " " + total;

                }

                // Update previousSelectedRows
                previousSelectedRows = Array.from(selectedRows);
            }
        }
    }


    // Run the function every 1 second
    var intervalId = setInterval(calculateTotal, 1000);

    // Helper function to compare two arrays
    function arraysAreEqual(array1, array2) {
        return array1.length === array2.length && array1.every((value, index) => value === array2[index]);
    }

})();