aboutsummaryrefslogtreecommitdiffstats
path: root/fg21sim/webui/static/js/products.js
blob: f48508774d846ca718aff0c23867d13fd120c74b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
/**
 * Copyright (c) 2016 Weitian LI <liweitianux@live.com>
 * MIT license
 *
 * Web UI of "fg21sim"
 * Manage and manipulate the simulation products
 */

"use strict";


/**
 * Reset the manifest table
 */
var resetManifestTable = function () {
  var table = $("table#products-manifest");
  // Empty table caption, head, and body
  table.children().empty();
};


/**
 * Compose the manifest table cell element for each product
 *
 * @param {Object} data - The metadata of the product
 * @param {Boolean} localhost - Whether the connection from localhost
 */
var makeManifestTableCell = function (data, localhost) {
  var cell = $("<td>").addClass("product");
  cell.data("localhost", localhost)
    .data("frequency", data.frequency)
    .data("healpix-path", data.healpix.path)
    .data("healpix-size", data.healpix.size)
    .data("healpix-md5", data.healpix.md5);
  cell.append($("<span>").attr("title", "Show product information")
              .addClass("info btn btn-small fa fa-info-circle"));
  cell.append($("<span>").attr("title", "Download HEALPix map")
              .data("ptype", "healpix")
              .addClass("healpix healpix-download btn btn-small fa fa-file"));
  if (data.hpx) {
    cell.data("hpx-image", true)
      .data("hpx-path", data.hpx.path)
      .data("hpx-size", data.hpx.size)
      .data("hpx-md5", data.hpx.md5);
    cell.append($("<span>").attr("title", localhost
                                 ? "Open HPX FITS image"
                                 : "Download HPX FITS image")
                .data("ptype", "hpx")
                .addClass("hpx")
                .addClass(localhost ? "hpx-open" : "hpx-download")
                .addClass("btn btn-small fa fa-image"));
  } else {
    cell.data("hpx-image", false);
    cell.append($("<span>").attr("title", "Generate HPX image")
                .addClass("hpx hpx-convert btn btn-small fa fa-image"));
  }
  return cell;
};


/**
 * Load the products manifest into table
 *
 * @param {Object} manifest - The products manifest data
 * @param {Boolean} [localhost=false] - Whether the connection from localhost
 */
var loadManifestToTable = function (manifest, localhost) {
  localhost = typeof localhost !== "undefined" ? localhost : false;

  var frequency, components, table, row, cell, tbody;
  frequency = manifest.frequency;
  components = Object.keys(manifest);
  // Remove the `frequency` element
  components.splice(components.indexOf("frequency"), 1);

  // Reset the table first
  resetManifestTable();

  table = $("table#products-manifest");
  // Table head
  row = $("<tr>");
  row.append($("<th scope='col'>").text("Frequency (" + frequency.unit + ")"));
  components.forEach(function (compID) {
    row.append($("<th scope='col'>").text(compID).data("compID", compID));
  });
  table.children("thead").append(row);

  // Table body
  tbody = table.children("tbody");
  frequency.id.forEach(function (freqID) {
    // One table row for each frequency
    row = $("<tr>");
    row.append($("<th scope='row'>").addClass("frequency freqid-" + freqID)
              .text(frequency.frequencies[freqID])
              .data("freqID", freqID));
    components.forEach(function (compID) {
      cell = makeManifestTableCell(manifest[compID][freqID], localhost);
      cell.data("compID", compID).data("freqID", freqID);
      row.append(cell);
    });
    tbody.append(row);
  });
};


/**
 * Update the content of one single cell in the manifest table
 *
 * @param {Object} cell - The table cell DOM/jQuery object
 */
var updateManifestTableCell = function (cell, data) {
  cell = $(cell);
  var cell_new = makeManifestTableCell(data, cell.data("localhost"));
  cell_new.data("compID", cell.data("compID"))
    .data("freqID", cell.data("freqID"));
  cell.replaceWith(cell_new);
};


/**
 * Request the server to load the specified products manifest
 *
 * @param {String} url - The URL that handles the "products" AJAX requests.
 * @param {String} manifestfile - The (absolute) path to the manifest file.
 */
var loadServerManifest = function (url, manifestfile) {
  if (typeof manifestfile === "undefined") {
    manifestfile = $("input#products-manifest").val();
  };
  var data = {action: "load", manifestfile: manifestfile};
  return $.postJSON(url, data)
    .fail(function (jqxhr) {
      showModal({
        icon: "times-circle",
        contents: "Failed to load the products manifest!",
        code: jqxhr.status,
        reason: jqxhr.statusText
      });
    });
};


/**
 * Save the current products manifest to file
 *
 * @param {Boolean} [clobber=false] - Whether overwrite the existing file.
 */
var saveServerManifest = function (url, clobber) {
  clobber = typeof clobber !== "undefined" ? clobber : false;
  var outfile = $("input#products-manifest").val();
  var data = {
    action: "save",
    outfile: outfile,
    clobber: clobber
  };
  return $.postJSON(url, data)
    .done(function () {
      showModal({
        icon: "check-circle",
        contents: "Current products manifest saved."
      });
    })
    .fail(function (jqxhr) {
      showModal({
        icon: "times-circle",
        contents: "Failed to save current products manifest!",
        code: jqxhr.status,
        reason: jqxhr.statusText
      });
    });
};


/**
 * Get the products manifest from server
 */
var getServerManifest = function (url) {
  return $.getJSONUncached(url)
    .fail(function (jqxhr) {
      showModal({
        icon: "times-circle",
        contents: "Failed to load the products manifest!",
        code: jqxhr.status,
        reason: jqxhr.statusText
      });
    });
};


/**
 * Locate the command in the `$PATH` on the server, which checks
 * whether the command can be called.
 *
 * @param {String} cmd - The command name or path.
 */
var whichExecutable = function (url, cmd) {
  return $.getJSONUncached(url, {action: "which", cmd: JSON.stringify(cmd)});
};


/**
 * Reset the products manifest on both the server side and client side
 */
var resetManifest = function (url) {
  return $.postJSON(url, {action: "reset"})
    .done(function () {
      resetManifestTable();
      showModal({
        icon: "check-circle",
        contents: "Reset the products manifest."
      });
    })
    .fail(function (jqxhr) {
      showModal({
        icon: "times-circle",
        contents: "Failed to reset the products manifest on server!",
        code: jqxhr.status,
        reason: jqxhr.statusText
      });
    });
};


/**
 * Convert a product from HEALPix map to HPX projected FITS image
 *
 * @param {String} compID - ID of the foreground component
 * @param {Integer} freqID - Frequency ID
 */
var convertProductHPX = function (url, compID, freqID) {
  return $.postJSON(url, {action: "convert", compID: compID, freqID: freqID})
    .fail(function (jqxhr) {
      showModal({
        icon: "times-circle",
        contents: "Failed to convert the HEALPix map to HPX image!",
        code: jqxhr.status,
        reason: jqxhr.statusText
      });
    });
};


/**
 * Open the HPX FITS image of the specified product
 *
 * NOTE: This request is only allowed when using the Web UI on the localhost
 *
 * @param {String} viewer - The command name or path for the FITS viewer.
 */
var openProductHPX = function (url, compID, freqID, viewer) {
  var data = {
    action: "open",
    compID: JSON.stringify(compID),
    freqID: JSON.stringify(freqID),
    viewer: JSON.stringify(viewer)
  };
  return $.getJSONUncached(url, data)
    .fail(function (jqxhr) {
      showModal({
        icon: "times-circle",
        contents: "Failed to open the HPX image!",
        code: jqxhr.status,
        reason: jqxhr.statusText
      });
    });
};


$(document).ready(function () {
  // URL to handle the "products" AJAX requests
  var ajax_url = "/ajax/products";
  // URL to download the products (NOTE the trailing slash "/")
  var download_url = "/products/download/";

  // Update the products manifest file path
  $("#conf-form input[name='workdir'], " +
    "#conf-form input[name='common/manifest']")
    .on("change", function (e) {
      var workdir = $("#conf-form input[name='workdir']").val();
      var manifest = $("#conf-form input[name='output/manifest']").val();
      $("input#products-manifest").val(joinPath(workdir, manifest));
  });

  // Validate the FITS viewer executable on change
  $("input#products-fitsviewer").on("change", function () {
    var target = $(this);
    var cmd = target.val();
    whichExecutable(ajax_url, cmd)
      .done(function (response) {
        target[0].setCustomValidity("");
        target.removeClass("error").data("validity", true);
      })
      .fail(function (jqxhr) {
        target[0].setCustomValidity(jqxhr.statusText);
        target.addClass("error").data("validity", false);
      });
  }).trigger("change");  // Manually trigger the "change" after loading

  // Get and load products manifest into table
  $("#load-products").on("click", function () {
    loadServerManifest(ajax_url)
      .then(function () { return getServerManifest(ajax_url); })
      .done(function (response) {
        console.log("GET products response:", response);
        if ($.isEmptyObject(response.manifest)) {
          showModal({
            icon: "warning",
            contents: "Products manifest not loaded on the server."
          });
        } else {
          loadManifestToTable(response.manifest, response.localhost);
          showModal({
            icon: "check-circle",
            contents: "Loaded products manifest to table."
          });
        }
      });
  });

  // Save current products manifest
  $("#save-products").on("click", function () {
    saveServerManifest(ajax_url, true);
  });

  // Show product information (metadata)
  // NOTE:
  // Since the table cell are dynamically built, so "click" event handler
  // should be bound to the "document" with the proper selector.
  $(document).on("click", "td.product > .info", function () {
    var product = $(this).closest("td");
    var modalData = {
      icon: "info-circle",
      title: ("Product: " + product.data("compID") + " @ " +
              product.data("frequency") + " (#" + product.data("freqID") + ")"),
      contents: [
        ("<strong>HEALPix map:</strong> " + product.data("healpix-path") +
         ", size: " + (product.data("healpix-size")/1024/1024).toFixed(1) +
         " MB, MD5: " + product.data("healpix-md5"))
      ]
    };
    if (product.data("hpx-image")) {
      var p = ("<strong>HPX image:</strong> " + product.data("hpx-path") +
               ", size: " + (product.data("hpx-size")/1024/1024).toFixed(1) +
               " MB, MD5: " + product.data("hpx-md5"));
      modalData.contents.push(p);
    }
    showModal(modalData);
  });

  // Convert HEALPix map of a product to HPX projected FITS image.
  $(document).on("click", "td.product > .hpx.hpx-convert", function () {
    var cell = $(this).closest("td");
    var compID = cell.data("compID");
    var freqID = cell.data("freqID");
    // Replace the icon with a spinner when converting
    $(this).removeClass("fa-image").addClass("fa-spinner fa-pulse")
      .fadeTo("fast", 1.0).css({"font-size": "2em"})
      .attr("title", "Generating HPX image ...");
    convertProductHPX(ajax_url, compID, freqID)
      .done(function (response) {
        updateManifestTableCell(cell, response.data);
        showModal({
          icon: "check-circle",
          contents: "Generated HPX projected FITS image."
        });
      });
  });

  // Open the HPX FITS image
  // NOTE: Only allowed when accessing the Web UI from localhost
  $(document).on("click", "td.product > .hpx.hpx-open", function () {
    var cell = $(this).closest("td");
    var compID = cell.data("compID");
    var freqID = cell.data("freqID");
    var input_viewer = $("input#products-fitsviewer");
    var viewer;
    if (input_viewer.data("validity")) {
      viewer = input_viewer.val();
      openProductHPX(ajax_url, compID, freqID, viewer)
        .done(function (response) {
          showModal({
            icon: "check-circle",
            contents: "Opened HPX FITS image. (PID: " + response.pid + ")"
          });
        });
    } else {
      showModal({
        icon: "times-circle",
        contents: "Invalid name/path for the FITS viewer executable!"
      });
    }
  });

  // Download the HEALPix maps and HPX images
  $(document).on(
    "click",
    ("td.product > .healpix.healpix-download, " +
     "td.product > .hpx.hpx-download"),
    function () {
      var cell = $(this).closest("td");
      var ptype = $(this).data("ptype");
      var filepath = cell.data(ptype + "-path");
      var url = download_url + filepath;
      console.log("Download", ptype, "product at URL:", url);
      // Open the download URL in a new window
      window.open(url, "_blank");
  });
});