2 function debug_dict_keys (msg, o) {
4 for (var k in o) keys.push(k);
5 messages.debug ("debug_dict_keys: " + msg + " keys= " + keys);
7 function debug_dict (msg, o) {
8 for (var k in o) messages.debug ("debug_dict: " + msg + " [" + k + "]=" + o[k]);
10 function debug_value (msg, value) {
11 messages.debug ("debug_value: " + msg + " " + value);
13 function debug_query (msg, query) {
14 if (query === undefined) messages.debug ("debug_query: " + msg + " -> undefined");
15 else if (query == null) messages.debug ("debug_query: " + msg + " -> null");
16 else if ('query_uuid' in query) messages.debug ("debug_query: " + msg + query.__repr());
17 else messages.debug ("debug_query: " + msg + " query= " + query);
20 /* ------------------------------------------------------------ */
22 // Constants that should be somehow moved to a plugin.js file
24 var FILTER_REMOVED = 2;
25 var CLEAR_FILTERS = 3;
27 var FIELD_REMOVED = 5;
30 var CLEAR_RECORDS = 8;
32 var IN_PROGRESS = 101;
35 /* Update requests from plugins */
37 var SET_REMOVED = 202;
40 var STATUS_NONE = 500; // Query has not been started yet
41 var STATUS_GET_IN_PROGRESS = 501; // Query has been sent, no result has been received
42 var STATUS_GET_RECEIVED = 502; // Success
43 var STATUS_GET_ERROR = 503; // Error
44 var STATUS_UPDATE_PENDING = 504;
45 var STATUS_UPDATE_IN_PROGRESS = 505;
46 var STATUS_UPDATE_RECEIVED = 506;
47 var STATUS_UPDATE_ERROR = 507;
50 // A structure for storing queries
54 function QueryExt(query, parent_query, main_query) {
57 if (typeof query == "undefined")
58 throw "Must pass a query in QueryExt constructor";
60 this.parent_query = (typeof parent_query == "undefined") ? false : parent_query
61 this.main_query = (typeof main_query == "undefined") ? false : main_query
65 this.update_query = null; // null unless we are a main_query (aka parent_query == null); only main_query_fields can be updated...
68 function QueryStore() {
70 this.main_queries = {};
71 this.analyzed_queries = {};
75 this.insert = function(query)
77 if (query.analyzed_query == null) {
78 query.analyze_subqueries();
81 query_ext = new QueryExt(query, null, null)
82 manifold.query_store.main_queries[query.query_uuid] = query_ext;
84 // We also need to insert all queries and subqueries from the analyzed_query
85 query.iter_subqueries(function(sq, data, parent_query) {
87 parent_query_ext = manifold.query_store.find_analyzed_query_ext(parent_query.query_uuid);
89 parent_query_ext = null;
90 sq_ext = new QueryExt(sq, parent_query_ext, query_ext)
91 manifold.query_store.analyzed_queries[sq.query_uuid] = sq_ext;
97 this.find_query_ext = function(query_uuid)
99 return this.main_queries[query_uuid];
102 this.find_query = function(query_uuid)
104 return this.find_query_ext(query_uuid).query;
107 this.find_analyzed_query_ext = function(query_uuid)
109 return this.analyzed_queries[query_uuid];
112 this.find_analyzed_query = function(query_uuid)
114 return this.find_analyzed_query_ext(query_uuid).query;
119 * This namespace holds functions for globally managing query objects
124 /**************************************************************************
126 **************************************************************************/
130 spin: function(locator, active /*= true */) {
131 active = typeof active !== 'undefined' ? active : true;
134 $(locator).spin(manifold.spin_presets);
136 $(locator).spin(false);
138 } catch (err) { messages.debug("Cannot turn spins on/off " + err); }
141 /**************************************************************************
143 **************************************************************************/
145 query_store: new QueryStore(),
147 // XXX Remaining functions are deprecated since they are replaced by the query store
150 * Associative array storing the set of queries active on the page
156 * Insert a query in the global hash table associating uuids to queries.
157 * If the query has no been analyzed yet, let's do it.
158 * \fn insert_query(query)
160 * \param ManifoldQuery query Query to be added
162 insert_query : function (query) {
164 manifold.query_store.insert(query);
167 if (query.analyzed_query == null) {
168 query.analyze_subqueries();
170 manifold.all_queries[query.query_uuid]=query;
174 * Returns the query associated to a UUID
175 * \fn find_query(query_uuid)
177 * \param string query_uuid The UUID of the query to be returned
179 find_query : function (query_uuid) {
180 return manifold.all_queries[query_uuid];
183 /**************************************************************************
185 **************************************************************************/
187 // trigger a query asynchroneously
188 proxy_url : '/manifold/proxy/json/',
190 asynchroneous_debug : true,
193 * \brief We use js function closure to be able to pass the query (array)
194 * to the callback function used when data is received
196 success_closure: function(query, publish_uuid, callback /*domid*/)
198 return function(data, textStatus) {
199 manifold.asynchroneous_success(data, query, publish_uuid, callback /*domid*/);
203 // Executes all async. queries
204 // input queries are specified as a list of {'query_uuid': <query_uuid>, 'id': <possibly null>}
205 asynchroneous_exec : function (query_publish_dom_tuples) {
208 // in case the spin stuff was not loaded, let's make sure we proceed to the exit
210 // if (manifold.asynchroneous_debug)
211 // messages.debug("Turning on spin with " + jQuery(".need-spin").length + " matches for .need-spin");
212 // jQuery('.need-spin').spin(manifold.spin_presets);
213 //} catch (err) { messages.debug("Cannot turn on spins " + err); }
215 // Loop through input array, and use publish_uuid to publish back results
216 jQuery.each(query_publish_dom_tuples, function(index, tuple) {
217 var query=manifold.find_query(tuple.query_uuid);
218 var query_json=JSON.stringify (query);
219 var publish_uuid=tuple.publish_uuid;
220 // by default we publish using the same uuid of course
221 if (publish_uuid==undefined) publish_uuid=query.query_uuid;
222 if (manifold.asynchroneous_debug) {
223 messages.debug("sending POST on " + manifold.proxy_url + " to be published on " + publish_uuid);
224 messages.debug("... ctd... with actual query= " + query.__repr());
227 query.iter_subqueries(function (sq) {
228 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
231 // not quite sure what happens if we send a string directly, as POST data is named..
232 // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
233 jQuery.post(manifold.proxy_url, {'json':query_json} , manifold.success_closure(query, publish_uuid, tuple.callback /*domid*/));
238 * \brief Forward a query to the manifold backend
239 * \param query (dict) the query to be executed asynchronously
240 * \param callback (function) the function to be called when the query terminates
242 * \param domid (string) the domid to be notified about the results (null for using the pub/sub system
244 forward: function(query, callback /*domid*/) {
245 var query_json = JSON.stringify(query);
246 $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, query.query_uuid, callback/*domid*/));
250 * Returns whether a query expects a unique results.
251 * This is the case when the filters contain a key of the object
252 * \fn query_expects_unique_result(query)
254 * \param ManifoldQuery query Query for which we are testing whether it expects a unique result
256 query_expects_unique_result: function(query) {
257 /* XXX we need functions to query metadata */
258 //var keys = MANIFOLD_METADATA[query.object]['keys']; /* array of array of field names */
259 /* TODO requires keys in metadata */
265 * \fn publish_result(query, results)
267 * \param ManifoldQuery query Query which has received results
268 * \param array results results corresponding to query
270 publish_result: function(query, result) {
271 if (typeof result === 'undefined')
275 manifold.raise_record_event(query.query_uuid, CLEAR_RECORDS);
276 $.each(result, function(i, record) {
277 manifold.raise_record_event(query.query_uuid, NEW_RECORD, record);
279 manifold.raise_record_event(query.query_uuid, DONE);
281 // OLD PLUGIN API BELOW
282 /* Publish an update announce */
283 var channel="/results/" + query.query_uuid + "/changed";
284 if (manifold.asynchroneous_debug)
285 messages.debug("publishing result on " + channel);
286 jQuery.publish(channel, [result, query]);
290 * Recursively publish result
291 * \fn publish_result_rec(query, result)
293 * \param ManifoldQuery query Query which has received result
294 * \param array result result corresponding to query
296 publish_result_rec: function(query, result) {
297 /* If the result is not unique, only publish the top query;
298 * otherwise, publish the main object as well as subqueries
299 * XXX how much recursive are we ?
301 if (manifold.query_expects_unique_result(query)) {
302 /* Also publish subqueries */
303 jQuery.each(query.subqueries, function(object, subquery) {
304 manifold.publish_result_rec(subquery, result[0][object]);
305 /* TODO remove object from result */
308 manifold.publish_result(query, result);
311 // if set domid allows the result to be directed to just one plugin
312 // most of the time publish_uuid will be query.query_uuid
313 // however in some cases we wish to publish the result under a different uuid
314 // e.g. an updater wants to publish its result as if from the original (get) query
315 asynchroneous_success : function (data, query, publish_uuid, callback /*domid*/) {
316 // xxx should have a nicer declaration of that enum in sync with the python code somehow
318 /* If a callback has been specified, we redirect results to it */
319 if (!!callback) { callback(data); return; }
321 if (data.code == 2) { // ERROR
322 // We need to make sense of error codes here
323 alert("Your session has expired, please log in again");
324 window.location="/logout/";
327 if (data.code == 1) { // WARNING
328 messages.error("Some errors have been received from the manifold backend at " + MANIFOLD_URL + " [" + data.description + "]");
329 // publish error code and text message on a separate channel for whoever is interested
330 jQuery.publish("/results/" + publish_uuid + "/failed", [data.code, data.description] );
332 $("#notifications").notify("create", "sticky", {
334 text: data.description
341 // once everything is checked we can use the 'value' part of the manifoldresult
342 var result=data.value;
344 //if (!!callback /* domid */) {
345 // /* Directly inform the requestor */
346 // if (manifold.asynchroneous_debug) messages.debug("directing result to callback");
348 // //if (manifold.asynchroneous_debug) messages.debug("directing result to " + domid);
349 // //jQuery('#' + domid).trigger('results', [result]);
351 /* XXX Jordan XXX I don't need publish_uuid here... What is it used for ? */
352 /* query is the query we sent to the backend; we need to find the
353 * corresponding analyezd_query in manifold.all_queries
355 tmp_query = manifold.find_query(query.query_uuid);
356 manifold.publish_result_rec(tmp_query.analyzed_query, result);
362 /**************************************************************************
364 **************************************************************************/
366 raise_event_handler: function(type, query_uuid, event_type, value)
368 if (type == 'query') {
369 var channels = [ manifold.get_query_channel(query_uuid), manifold.get_query_channel('*') ];
370 } else if (type == 'record') {
371 var channels = [ manifold.get_record_channel(query_uuid), manifold.get_record_channel('*') ];
374 throw 'Incorrect type for manifold.raise_event()';
376 $.each(channels, function(i, channel) {
377 if (value === undefined)
378 $('.plugin').trigger(channel, [event_type]);
380 $('.plugin').trigger(channel, [event_type, value]);
384 raise_query_event: function(query_uuid, event_type, value)
386 manifold.raise_event_handler('query', query_uuid, event_type, value);
389 raise_record_event: function(query_uuid, event_type, value)
391 manifold.raise_event_handler('record', query_uuid, event_type, value);
395 raise_event: function(query_uuid, event_type, value)
399 // Query uuid has been updated with the key of a new element
400 query_ext = manifold.query_store.find_analyzed_query(query_uuid);
402 // update is only possible is the query is not pending, etc
405 // XXX we can only update subqueries of the main query. Check !
406 // assert query_ext.parent_query == query_ext.main_query
407 update_query = query_ext.parent_query.update_query;
409 // NOTE: update might modify the fields in Get
410 // NOTE : we have to modify all child queries
411 // NOTE : parts of a query might not be started (eg slice.measurements, how to handle ?)
413 // if everything is done right, update_query should not be null. It is updated when we received results from the get query
414 // object = the same as get
415 // filter = key : update a single object for now
416 // fields = the same as get
420 // Query uuid has been updated with the key of a removed element
425 /* Publish/subscribe channels for internal use */
426 get_query_channel: function(uuid) { return '/query/' + uuid },
427 get_record_channel: function(uuid) { return '/record/' + uuid },
429 }; // manifold object
430 /* ------------------------------------------------------------ */
436 * NOTE: Since we don't have a plugin class, we are extending all jQuery
441 * \brief Associates a query handler to the current plugin
442 * \param uuid (string) query uuid
443 * \param handler (function) handler callback
445 $.fn.set_query_handler = function(uuid, handler)
447 this.on(manifold.get_query_channel(uuid), handler);
450 $.fn.set_record_handler = function(uuid, handler)
452 this.on(manifold.get_record_channel(uuid), handler);
455 // OLD PLUGIN API: extend jQuery/$ with pubsub capabilities
456 // https://gist.github.com/661855
458 $.subscribe = function( channel, selector, data, fn) {
459 /* borrowed from jQuery */
460 if ( data == null && fn == null ) {
463 data = selector = undefined;
464 } else if ( fn == null ) {
465 if ( typeof selector === "string" ) {
466 // ( channel, selector, fn )
470 // ( channel, data, fn )
473 selector = undefined;
478 /* We use an indirection function that will clone the object passed in
479 * parameter to the subscribe callback
481 * FIXME currently we only clone query objects which are the only ones
482 * supported and editable, we might have the same issue with results but
483 * the page load time will be severely affected...
485 o.on.apply(o, [channel, selector, data, function() {
486 for(i = 1; i < arguments.length; i++) {
487 if ( arguments[i].constructor.name == 'ManifoldQuery' )
488 arguments[i] = arguments[i].clone();
490 fn.apply(o, arguments);
494 $.unsubscribe = function() {
495 o.off.apply(o, arguments);
498 $.publish = function() {
499 o.trigger.apply(o, arguments);
504 /* ------------------------------------------------------------ */
506 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
507 //make sure to expose csrf in our outcoming ajax/post requests
509 beforeSend: function(xhr, settings) {
510 function getCookie(name) {
511 var cookieValue = null;
512 if (document.cookie && document.cookie != '') {
513 var cookies = document.cookie.split(';');
514 for (var i = 0; i < cookies.length; i++) {
515 var cookie = jQuery.trim(cookies[i]);
516 // Does this cookie string begin with the name we want?
517 if (cookie.substring(0, name.length + 1) == (name + '=')) {
518 cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
525 if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
526 // Only send the token to relative URLs i.e. locally.
527 xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));