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_ext = (typeof parent_query == "undefined") ? false : parent_query
61 this.main_query_ext = (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 // XXX We need the root of all subqueries
86 query.iter_subqueries(function(sq, data, parent_query) {
88 parent_query_ext = manifold.query_store.find_analyzed_query_ext(parent_query.query_uuid);
90 parent_query_ext = null;
91 // XXX parent_query_ext == false
92 // XXX main.subqueries = {} # Normal, we need analyzed_query
93 sq_ext = new QueryExt(sq, parent_query_ext, query_ext)
94 manifold.query_store.analyzed_queries[sq.query_uuid] = sq_ext;
100 this.find_query_ext = function(query_uuid)
102 return this.main_queries[query_uuid];
105 this.find_query = function(query_uuid)
107 return this.find_query_ext(query_uuid).query;
110 this.find_analyzed_query_ext = function(query_uuid)
112 return this.analyzed_queries[query_uuid];
115 this.find_analyzed_query = function(query_uuid)
117 return this.find_analyzed_query_ext(query_uuid).query;
122 * This namespace holds functions for globally managing query objects
127 /**************************************************************************
129 **************************************************************************/
135 spin: function(locator, active /*= true */) {
136 active = typeof active !== 'undefined' ? active : true;
139 $(locator).spin(manifold.spin_presets);
141 $(locator).spin(false);
143 } catch (err) { messages.debug("Cannot turn spins on/off " + err); }
146 /**************************************************************************
148 **************************************************************************/
150 query_store: new QueryStore(),
152 // XXX Remaining functions are deprecated since they are replaced by the query store
155 * Associative array storing the set of queries active on the page
161 * Insert a query in the global hash table associating uuids to queries.
162 * If the query has no been analyzed yet, let's do it.
163 * \fn insert_query(query)
165 * \param ManifoldQuery query Query to be added
167 insert_query : function (query) {
169 manifold.query_store.insert(query);
172 if (query.analyzed_query == null) {
173 query.analyze_subqueries();
175 manifold.all_queries[query.query_uuid]=query;
179 * Returns the query associated to a UUID
180 * \fn find_query(query_uuid)
182 * \param string query_uuid The UUID of the query to be returned
184 find_query : function (query_uuid) {
185 return manifold.all_queries[query_uuid];
188 /**************************************************************************
190 **************************************************************************/
192 // trigger a query asynchroneously
193 proxy_url : '/manifold/proxy/json/',
195 asynchroneous_debug : true,
198 * \brief We use js function closure to be able to pass the query (array)
199 * to the callback function used when data is received
201 success_closure: function(query, publish_uuid, callback /*domid*/)
203 return function(data, textStatus) {
204 manifold.asynchroneous_success(data, query, publish_uuid, callback /*domid*/);
208 // Executes all async. queries
209 // input queries are specified as a list of {'query_uuid': <query_uuid>, 'id': <possibly null>}
210 asynchroneous_exec : function (query_publish_dom_tuples) {
213 // in case the spin stuff was not loaded, let's make sure we proceed to the exit
215 // if (manifold.asynchroneous_debug)
216 // messages.debug("Turning on spin with " + jQuery(".need-spin").length + " matches for .need-spin");
217 // jQuery('.need-spin').spin(manifold.spin_presets);
218 //} catch (err) { messages.debug("Cannot turn on spins " + err); }
220 // Loop through input array, and use publish_uuid to publish back results
221 jQuery.each(query_publish_dom_tuples, function(index, tuple) {
222 var query=manifold.find_query(tuple.query_uuid);
223 var query_json=JSON.stringify (query);
224 var publish_uuid=tuple.publish_uuid;
225 // by default we publish using the same uuid of course
226 if (publish_uuid==undefined) publish_uuid=query.query_uuid;
227 if (manifold.asynchroneous_debug) {
228 messages.debug("sending POST on " + manifold.proxy_url + " to be published on " + publish_uuid);
229 messages.debug("... ctd... with actual query= " + query.__repr());
232 query.iter_subqueries(function (sq) {
233 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
236 // not quite sure what happens if we send a string directly, as POST data is named..
237 // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
238 jQuery.post(manifold.proxy_url, {'json':query_json} , manifold.success_closure(query, publish_uuid, tuple.callback /*domid*/));
243 * \brief Forward a query to the manifold backend
244 * \param query (dict) the query to be executed asynchronously
245 * \param callback (function) the function to be called when the query terminates
247 * \param domid (string) the domid to be notified about the results (null for using the pub/sub system
249 forward: function(query, callback /*domid*/) {
250 var query_json = JSON.stringify(query);
251 $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, query.query_uuid, callback/*domid*/));
255 * Returns whether a query expects a unique results.
256 * This is the case when the filters contain a key of the object
257 * \fn query_expects_unique_result(query)
259 * \param ManifoldQuery query Query for which we are testing whether it expects a unique result
261 query_expects_unique_result: function(query) {
262 /* XXX we need functions to query metadata */
263 //var keys = MANIFOLD_METADATA[query.object]['keys']; /* array of array of field names */
264 /* TODO requires keys in metadata */
270 * \fn publish_result(query, results)
272 * \param ManifoldQuery query Query which has received results
273 * \param array results results corresponding to query
275 publish_result: function(query, result) {
276 if (typeof result === 'undefined')
280 manifold.raise_record_event(query.query_uuid, CLEAR_RECORDS);
281 $.each(result, function(i, record) {
282 manifold.raise_record_event(query.query_uuid, NEW_RECORD, record);
284 manifold.raise_record_event(query.query_uuid, DONE);
286 // OLD PLUGIN API BELOW
287 /* Publish an update announce */
288 var channel="/results/" + query.query_uuid + "/changed";
289 if (manifold.asynchroneous_debug)
290 messages.debug("publishing result on " + channel);
291 jQuery.publish(channel, [result, query]);
295 * Recursively publish result
296 * \fn publish_result_rec(query, result)
298 * \param ManifoldQuery query Query which has received result
299 * \param array result result corresponding to query
301 publish_result_rec: function(query, result) {
302 /* If the result is not unique, only publish the top query;
303 * otherwise, publish the main object as well as subqueries
304 * XXX how much recursive are we ?
306 if (manifold.query_expects_unique_result(query)) {
307 /* Also publish subqueries */
308 jQuery.each(query.subqueries, function(object, subquery) {
309 manifold.publish_result_rec(subquery, result[0][object]);
310 /* TODO remove object from result */
313 manifold.publish_result(query, result);
316 // if set domid allows the result to be directed to just one plugin
317 // most of the time publish_uuid will be query.query_uuid
318 // however in some cases we wish to publish the result under a different uuid
319 // e.g. an updater wants to publish its result as if from the original (get) query
320 asynchroneous_success : function (data, query, publish_uuid, callback /*domid*/) {
321 // xxx should have a nicer declaration of that enum in sync with the python code somehow
323 /* If a callback has been specified, we redirect results to it */
324 if (!!callback) { callback(data); return; }
326 if (data.code == 2) { // ERROR
327 // We need to make sense of error codes here
328 alert("Your session has expired, please log in again");
329 window.location="/logout/";
332 if (data.code == 1) { // WARNING
333 messages.error("Some errors have been received from the manifold backend at " + MANIFOLD_URL + " [" + data.description + "]");
334 // publish error code and text message on a separate channel for whoever is interested
335 jQuery.publish("/results/" + publish_uuid + "/failed", [data.code, data.description] );
337 $("#notifications").notify("create", "sticky", {
339 text: data.description
346 // once everything is checked we can use the 'value' part of the manifoldresult
347 var result=data.value;
349 //if (!!callback /* domid */) {
350 // /* Directly inform the requestor */
351 // if (manifold.asynchroneous_debug) messages.debug("directing result to callback");
353 // //if (manifold.asynchroneous_debug) messages.debug("directing result to " + domid);
354 // //jQuery('#' + domid).trigger('results', [result]);
356 /* XXX Jordan XXX I don't need publish_uuid here... What is it used for ? */
357 /* query is the query we sent to the backend; we need to find the
358 * corresponding analyezd_query in manifold.all_queries
360 tmp_query = manifold.find_query(query.query_uuid);
361 manifold.publish_result_rec(tmp_query.analyzed_query, result);
367 /**************************************************************************
369 **************************************************************************/
371 raise_event_handler: function(type, query_uuid, event_type, value)
373 if ((type != 'query') && (type != 'record'))
374 throw 'Incorrect type for manifold.raise_event()';
376 var channels = [ manifold.get_channel(type, query_uuid), manifold.get_channel(type, '*') ];
378 $.each(channels, function(i, channel) {
379 if (value === undefined)
380 $('.plugin').trigger(channel, [event_type]);
382 $('.plugin').trigger(channel, [event_type, value]);
386 raise_query_event: function(query_uuid, event_type, value)
388 manifold.raise_event_handler('query', query_uuid, event_type, value);
391 raise_record_event: function(query_uuid, event_type, value)
393 manifold.raise_event_handler('record', query_uuid, event_type, value);
397 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_ext(query_uuid);
401 query = query_ext.query;
405 // update is only possible is the query is not pending, etc
408 // XXX we can only update subqueries of the main query. Check !
409 // assert query_ext.parent_query == query_ext.main_query
410 update_query = query_ext.parent_query_ext.update_query;
412 // NOTE: update might modify the fields in Get
413 // NOTE : we have to modify all child queries
414 // NOTE : parts of a query might not be started (eg slice.measurements, how to handle ?)
416 // if everything is done right, update_query should not be null. It is updated when we received results from the get query
417 // object = the same as get
418 // filter = key : update a single object for now
419 // fields = the same as get
423 // Query uuid has been updated with the key of a removed element
430 main_query = query_ext.main_query_ext.query;
431 main_update_query = query_ext.main_query_ext.update_query;
434 // Here we need the full path through all subqueries
436 // XXX We might need the query name in the QueryExt structure
437 main_query.select(value);
439 // XXX When is an update query associated ?
440 // XXX main_update_query.select(value);
445 query = query_ext.query;
446 main_query = query_ext.main_query_ext.query;
447 main_update_query = query_ext.main_query_ext.update_query;
448 query.unselect(value);
449 main_query.unselect(value);
451 // We need to inform about changes in these queries to the respective plugins
452 // Note: query & main_query have the same UUID
453 manifold.raise_query_event(query_uuid, event_type, value);
456 // We need to inform about changes in these queries to the respective plugins
457 // Note: query, main_query & update_query have the same UUID
458 manifold.raise_query_event(query_uuid, event_type, value);
459 // We are targeting the same object with get and update
460 // The notion of query is bad, we should have a notion of destination, and issue queries on the destination
461 // NOTE: Editing a subquery == editing a local view on the destination
463 // XXX We might need to run the new query again and manage the plugins in the meantime with spinners...
464 // For the time being, we will collect all columns during the first query
467 /* Publish/subscribe channels for internal use */
468 get_channel: function(type, query_uuid)
470 if ((type !== 'query') && (type != 'record'))
472 return '/' + type + '/' + query_uuid;
475 }; // manifold object
476 /* ------------------------------------------------------------ */
480 // OLD PLUGIN API: extend jQuery/$ with pubsub capabilities
481 // https://gist.github.com/661855
483 $.subscribe = function( channel, selector, data, fn) {
484 /* borrowed from jQuery */
485 if ( data == null && fn == null ) {
488 data = selector = undefined;
489 } else if ( fn == null ) {
490 if ( typeof selector === "string" ) {
491 // ( channel, selector, fn )
495 // ( channel, data, fn )
498 selector = undefined;
503 /* We use an indirection function that will clone the object passed in
504 * parameter to the subscribe callback
506 * FIXME currently we only clone query objects which are the only ones
507 * supported and editable, we might have the same issue with results but
508 * the page load time will be severely affected...
510 o.on.apply(o, [channel, selector, data, function() {
511 for(i = 1; i < arguments.length; i++) {
512 if ( arguments[i].constructor.name == 'ManifoldQuery' )
513 arguments[i] = arguments[i].clone();
515 fn.apply(o, arguments);
519 $.unsubscribe = function() {
520 o.off.apply(o, arguments);
523 $.publish = function() {
524 o.trigger.apply(o, arguments);
529 /* ------------------------------------------------------------ */
531 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
532 //make sure to expose csrf in our outcoming ajax/post requests
534 beforeSend: function(xhr, settings) {
535 function getCookie(name) {
536 var cookieValue = null;
537 if (document.cookie && document.cookie != '') {
538 var cookies = document.cookie.split(';');
539 for (var i = 0; i < cookies.length; i++) {
540 var cookie = jQuery.trim(cookies[i]);
541 // Does this cookie string begin with the name we want?
542 if (cookie.substring(0, name.length + 1) == (name + '=')) {
543 cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
550 if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
551 // Only send the token to relative URLs i.e. locally.
552 xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));