d6e46f69af2b560c0bad72f36ca804c2aecc02ff
[unfold.git] / engine / static / js / manifold-async.js
1 manifold_async_debug=false;
2
3 // Helper functions for asynchronous requests
4
5 var api_url = '/manifold/api/json/'
6
7 // Executes all async. queries contained in manifold_async_query_array, which is
8 // an array of hash (action, method, ts, filter, fields)
9 //
10 function manifold_async_exec(arr)
11 {
12     if (manifold_async_debug) console.log('manifold_async_exec length='+ arr.length);
13     // start spinners
14     // xxx todo - I don't have the spinner jquery plugin yet
15 //    jQuery('.loading').spin();
16
17     // We use js function closure to be able to pass the query (array) to the
18     // callback function used when data is received
19     var manifold_async_success_closure = function(query, id) {
20         return function(data, textStatus) {manifold_async_success(data, query, id);}
21     };
22
23     // Loop through query array and issue XML/RPC queries
24     jQuery.each(arr, function(index, elt) {
25         hash=elt.query.to_hash();
26         if (manifold_async_debug) console.log ('sending POST on ' + api_url + " iterating on " + hash);
27         jQuery.post(api_url, {'query': hash}, manifold_async_success_closure(elt.query, elt.id));
28     })
29 }
30
31 function manifold_async_error(str) {
32     var out = '<div class="error"><h2>Error</h2><dl id="system-message"><dt class="error">Notice</dt><dd class="error message"><ul><li>' + jQuery('<div />').text(str).html() + '</li></ul></dd></dl></div>';
33     jQuery('#manifold_message').html(out);
34     //onObjectAvailable('Spinners', function(){ Spinners.get('.loading').remove(); }, this, true);
35     jQuery('.loading').spin();
36 }
37
38 /* what the hell is this doing here ?
39 function apply_format(key, value, type, method) {
40     // type = type, key = 
41     var link = {
42         'platform': {'_all': 'platforms'},
43         'src_hostname': {'traceroute': 'agents', '_other': 'hostname'},
44         'dst_hostname': {'traceroute': 'agents', '_other': 'hostname'},
45         'src_ip': {'traceroute': 'agents', '_other': 'ip'},
46         'dst_ip': {'traceroute': 'agents', '_other': 'ip'},
47         'as_name': {'_all': 'as'},
48         'asn': {'_all': 'as'},
49         'city': {'_all': 'cities'},
50         'continent': {'_all': 'continents'},
51         'continent_code': {'_all': 'continents'},
52         'country': {'_all': 'countries'},
53         'country_code': {'_all': 'countries'},
54         'hostname': {'agents': 'agents', 'nodes': 'node', '_other': 'hostname'},
55         'ip': {'agents': 'agents', '_other': 'ip'},
56         'network_hrn': {'_all': 'network'},
57         'region': {'_all': 'regions'},
58         'region_code': {'_all': 'regions'},
59         'slice_hrn': {'_all': 'slice'},
60     };
61     if (link[type]) {
62         // creates problems sorting ?
63         if (link[type]['_all']) {
64             var urlpart = link[type]['_all'];
65         } else {
66             if (link[type][method]) {
67                 var urlpart = link[type][method];
68             } else {
69                 if (link[type]['_other']) {
70                     var urlpart = link[type]['_other'];
71                 } else {
72                     return key;
73                 }
74             }
75         }
76         return '<a href="/view/' + urlpart + '/' + key +'">' + value + '</a>';
77     } else {
78         return key;
79     }
80 }
81 */
82
83 function manifold_html_a(key, value, type) {
84     if (type == 'network_hrn') {
85         return "<a href='/view/network/" + key + "'>" + value + '</a>';
86     } else if (type == 'slice_hrn') {
87         return "<a href='/view/slice/" + key + "'>" + value + '</a>';
88     } else {
89
90     }
91 }
92
93 function manifold_html_li(type, value, is_cached) {
94     var cached = '';
95     if (is_cached)
96         cached='<div class="cache"><span><b>Cached information from the database</b><br/>Timestamp: XX/XX/XX XX:XX:XX<br/><br/><i>Refresh in progress...</i></span></div>';
97     if (type == 'slice_hrn') {
98         return "<li class='icn icn-play'>" + value + cached + "</li>";
99     } else if (type == 'network_hrn') {
100         return "<li class='icn icn-play'>" + value + cached + "</li>";
101     } else {
102         return "<li>" + value + "</li>";
103     }
104 }
105
106
107 function manifold_html_ul(data, key, value, type, method, is_cached) {
108     var out = "<ul>";
109     for (var i = 0; i < data.length; i++) {
110         out += manifold_html_li(key, apply_format(data[i][key], data[i][value], key, method), is_cached);
111         //out += manifold_html_li(key, manifold_html_a(data[i][key], data[i][value], key), is_cached);
112     }
113     out += "</ul>";
114
115     return out;
116 }
117
118 function manifold_update_template(data) 
119 {
120     jQuery.each(data, function(key, value) {
121         if ((typeof value == 'string') || (typeof value == 'number') || (typeof value == 'boolean')) {
122             // Simple field
123             jQuery('#manifold__' + key).html(value);
124         } else if (value == null) {
125             jQuery('#manifold__' + key).html("N/A");
126         } else { 
127             manifold_update_table('#manifold__' + key, value);
128         }
129     });
130 }
131
132 function manifold_async_success(data, query, id) {
133     if (data) {
134
135         if (!!id) {
136             /* Directly inform the requestor */
137             jQuery('#' + id).trigger('results', [data]);
138         } else {
139             /* Publish an update announce */
140             jQuery.publish("/results/" + query.uuid + "/changed", [data, query]);
141         }
142
143         // Is there a linked query ?
144         //if ((query.done == 'now') && (query.ts == 'latest')) {
145         //    var new_query = [query_json.replace("latest", "now")];
146         //    manifold_async_exec(new_query);
147         //}
148     }
149 }
150
151 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
152 //make sure to expose csrf in our outcoming ajax/post requests
153 $.ajaxSetup({ 
154      beforeSend: function(xhr, settings) {
155          function getCookie(name) {
156              var cookieValue = null;
157              if (document.cookie && document.cookie != '') {
158                  var cookies = document.cookie.split(';');
159                  for (var i = 0; i < cookies.length; i++) {
160                      var cookie = jQuery.trim(cookies[i]);
161                      // Does this cookie string begin with the name we want?
162                  if (cookie.substring(0, name.length + 1) == (name + '=')) {
163                      cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
164                      break;
165                  }
166              }
167          }
168          return cookieValue;
169          }
170          if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
171              // Only send the token to relative URLs i.e. locally.
172              xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
173          }
174      } 
175 });