github.com/siglens/siglens@v0.0.0-20240328180423-f7ce9ae441ed/static/js/download-logs.js (about)

     1  "use strict";
     2  
     3  let dlgridDiv = null;
     4  let dlRowData = [];
     5  let curChoose = "";
     6  let interval = null;
     7  var progressBar = $("#progressbar");
     8  var progressLabel = $(".progress-label");
     9  let confirmDownload = true;
    10  $(document).ready(() => {
    11      setDownloadLogsDialog();
    12  })
    13  $(function () {
    14    if (typeof interval != "undefined") {
    15      doClearInterval();
    16    } else {
    17      interval = null;
    18    }
    19  });
    20  
    21  var progressWidth = 0;
    22  function beginProgress(t) {
    23    progressWidth = 1;
    24    interval = setInterval("doProgress()", t * 10);
    25  }
    26  function cancelDownload() {
    27    confirmDownload = false;
    28    var popBox = document.getElementById("pop-box");
    29    var popLayer = document.getElementById("pop-layer");
    30    popLayer.style.display = "none";
    31    popBox.style.display = "none";
    32    $("#progressbar").hide();
    33  }
    34  function setProgress(node, width) {
    35    if (node) {
    36      progressBar.progressbar({
    37        value: width,
    38      });
    39      progressLabel.text(width + "%");
    40    }
    41  }
    42  function doProgress() {
    43    if (progressWidth == 98) {
    44      doClearInterval();
    45    }
    46    setProgress(progressBar, progressWidth);
    47    progressWidth++;
    48  }
    49  function doClearInterval() {
    50    clearInterval(interval);
    51  }
    52  
    53  function setDownloadLogsDialog() {
    54    let dialog = null;
    55    let form = null;
    56    let qname = $("#qnameDL");
    57    let description = $("#descriptionR");
    58    let allFields = $([]).add(qname).add(description);
    59    let tips = $("#validateTips");
    60  
    61    function updateTips(t) {
    62      tips.addClass("active");
    63      $("#validateTips").show();
    64      tips.text(t).addClass("ui-state-highlight");
    65    }
    66  
    67    function checkLength(o, n, min, max) {
    68      if (o.val().length > max || o.val().length < min) {
    69        o.addClass("ui-state-error");
    70        updateTips(
    71          "Length of " + n + " must be between " + min + " and " + max + "."
    72        );
    73        return false;
    74      } else {
    75        return true;
    76      }
    77    }
    78  
    79    function checkRegexp(o, regexp, n) {
    80      if (!regexp.test(o.val())) {
    81        o.addClass("ui-state-error");
    82        updateTips(n);
    83        return false;
    84      } else {
    85        return true;
    86      }
    87    }
    88  
    89    function downloadJson(fileName, json) {
    90      const jsonStr = json instanceof Object ? JSON.stringify(json) : json;
    91      const url = window.URL || window.webkitURL || window;
    92      const blob = new Blob([jsonStr]);
    93      const saveLink = document.createElementNS(
    94        "http://www.w3.org/1999/xhtml",
    95        "a"
    96      );
    97      saveLink.href = url.createObjectURL(blob);
    98      saveLink.download = fileName;
    99      saveLink.click();
   100    }
   101    function convertToCSV(json) {
   102      const items = JSON.parse(json);
   103  
   104      // Get column headers from first item in JSON array
   105      const headers = Object.keys(items[0]);
   106  
   107      // Build CSV header row
   108      const csvHeader = headers.join(",");
   109  
   110      // Build CSV body rows
   111      const csvBody = items
   112        .map((item) => {
   113          return headers
   114            .map((header) => {
   115              let col = item[header];
   116              return typeof col !== "string" ? col : `"${col.replace(/"/g, '""')}"`;
   117            })
   118            .join(",");
   119        })
   120        .join("\n");
   121  
   122      // Combine header and body into single CSV string
   123      const csv = `${csvHeader}\n${csvBody}`;
   124  
   125      return csv;
   126    }
   127    function downloadCsv(csvData, fileName) {
   128      const blob = new Blob([csvData], { type: "text/csv" });
   129      const url = URL.createObjectURL(blob);
   130      const downloadLink = document.createElement("a");
   131      downloadLink.href = url;
   132      downloadLink.download = fileName;
   133      document.body.appendChild(downloadLink);
   134      downloadLink.click();
   135      document.body.removeChild(downloadLink);
   136    }
   137    function download() {
   138      confirmDownload = true;
   139      let valid = true;
   140      allFields.removeClass("ui-state-error");
   141      tips.removeClass("ui-state-highlight");
   142      tips.text("");
   143      valid = valid && checkLength(qname, "download name", 3, 16);
   144      valid = valid && checkRegexp(
   145        qname,
   146        /^[a-zA-Z0-9_.-]+$/i,
   147        "Download name may consist of a-z, 0-9, period, dash, underscores."
   148    );
   149    let enteredName = $("#qnameDL").val();
   150    let extension = curChoose;
   151    let name = enteredName;
   152  
   153    if (!enteredName.endsWith(extension)) {
   154      name += extension;
   155    }
   156  
   157      if (valid) {
   158        dialog.dialog("close");
   159        $("#progressbar").show();
   160        //show progress box
   161        var popBox = document.getElementById("pop-box");
   162        var popLayer = document.getElementById("pop-layer");
   163        popLayer.style.width = document.body.scrollWidth + "px";
   164        popLayer.style.height = document.body.scrollHeight + "px";
   165        popLayer.style.display = "block";
   166        popBox.style.display = "block";
   167  
   168        let params = getSearchFilter(false, false);
   169        let searchText = params.searchText;
   170        let n = searchText.indexOf("BY");
   171        let arrNew = [], textArr = [];
   172        if(n != -1){
   173          let textCut = searchText.substring(n + 2, searchText.length);
   174          let arrNew = textCut.split(",");
   175          for (let i = 0; i < arrNew.length; i++) {
   176            arrNew[i] = arrNew[i].trim();
   177          }
   178          textArr = arrNew.sort();
   179        }
   180        $.ajax({
   181          method: "post",
   182          url: "api/search",
   183          headers: {
   184            "Content-Type": "application/json; charset=utf-8",
   185            Accept: "*/*",
   186          },
   187          crossDomain: true,
   188          dataType: "json",
   189          data: JSON.stringify(params),
   190          beforeSend: function () {
   191            beginProgress(10);
   192          },
   193          success: function (res) {
   194            //close progress box
   195            var popBox = document.getElementById("pop-box");
   196            var popLayer = document.getElementById("pop-layer");
   197            popLayer.style.display = "none";
   198            popBox.style.display = "none";
   199            //set progress finished
   200            doClearInterval();
   201            $("#progressbar").hide();
   202            setProgress(progressBar, 100);
   203            if (!confirmDownload) return;
   204            if (res && res.hits && res.hits.records && res.hits.records.length > 0) {
   205              let json = JSON.stringify(res.hits.records);
   206              if (curChoose == ".json") downloadJson(name, json);
   207              else {
   208                const csvData = convertToCSV(json);
   209                downloadCsv(csvData, name);
   210              }
   211            }else if (res && res.aggregations && res.aggregations[""].buckets.length > 0) {
   212              let arr = res.aggregations[""].buckets;
   213              let createNewRecords = [];
   214              for(let i = 0; i < arr.length; i++){
   215                let perInfo = arr[i];
   216                let newPerInfo = {};
   217                for(let key in perInfo){
   218                  if(key != "key" && key != "doc_count") newPerInfo[key] = perInfo[key].value;
   219                  else if(key == "key") {
   220                    for(let j = 0; j < textArr.length; j++){
   221                      newPerInfo[textArr[j]] = perInfo.key[j];
   222                    }
   223                  }
   224                }
   225                createNewRecords.push(newPerInfo);
   226              }
   227              let json = JSON.stringify(createNewRecords);
   228              if (curChoose == ".json") downloadJson(name, json);
   229              else {
   230                const csvData = convertToCSV(json);
   231                downloadCsv(csvData, name);
   232              }
   233            }else{
   234              alert("no data available");
   235            }
   236          },
   237          error: function () {
   238            doClearInterval();
   239          },
   240        });
   241      }
   242    }
   243    dialog = $("#download-info").dialog({
   244      autoOpen: false,
   245      resizable: false,
   246      width: 460,
   247      modal: true,
   248      position: {
   249        my: "center",
   250        at: "center",
   251        of: window,
   252      },
   253      buttons: {
   254        Cancel: {
   255          class: "cancelqButton",
   256          text: "Cancel",
   257          click: function () {
   258            dialog.dialog("close");
   259          },
   260        },
   261        Save: {
   262          class: "saveqButton",
   263          text: "Save",
   264          click: download,
   265        },
   266      },
   267      close: function () {
   268        form[0].reset();
   269        allFields.removeClass("ui-state-error");
   270      },
   271    });
   272  
   273    form = dialog.find("form").on("submit", function (event) {
   274      event.preventDefault();
   275      download();
   276    });
   277    $("#csv-block").on("click", function () {
   278      curChoose = ".csv";
   279      $("#validateTips").hide();
   280      $("#download-info").dialog("open");
   281      $(".ui-widget-overlay").addClass("opacity-75");
   282      return false;
   283    });
   284    $("#json-block").on("click", function () {
   285      curChoose = ".json";
   286      $("#validateTips").hide();
   287      $("#download-info").dialog("open");
   288      $(".ui-widget-overlay").addClass("opacity-75");
   289      return false;
   290    });
   291  }
   292  
   293  // Delete confirmation popup
   294  $(document).ready(function () {
   295    $("#cancel-loading").on("click", cancelDownload);
   296  });