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;
36 var SET_REMOVED = 202;
38 // A structure for storing queries
40 function QueryExt(query, parent_query, main_query) {
43 if (typeof query == "undefined")
44 throw "Must pass a query in QueryExt constructor";
46 this.parent_query = (typeof parent_query == "undefined") ? false : parent_query
47 this.main_query = (typeof main_query == "undefined") ? false : main_query
49 // How to link to an update query ? they both have the same UUID !!
53 function QueryStore() {
55 var main_queries = {};
56 var analyzed_queries = {};
60 this.insert = function(query)
62 if (query.analyzed_query == null) {
63 query.analyze_subqueries();
66 query_ext = QueryExt(query, null, null)
67 manifold.query_store.main_queries[query.query_uuid] = query_ext;
69 // We also need to insert all queries and subqueries from the analyzed_query
70 query.iter_subqueries(function(sq, data, parent_query) {
71 parent_query_ext = this.find_analyzed_query_ext(parent_query.query_uuid);
72 sq_ext = QueryExt(sq, parent_query_ext, query_ext)
73 this.analyzed_queries[sq.query_uuid] = sq_ext;
79 this.find_query_ext = function(query_uuid)
81 return this.main_queries[query_uuid];
84 this.find_query = function(query_uuid)
86 return this.find_query_ext(query_uuid).query;
89 this.find_analyzed_query_ext = function(query_uuid)
91 return this.analyzed_queries[query_uuid];
94 this.find_analyzed_query = function(query_uuid)
96 return this.find_analyzed_query_ext(query_uuid).query;
101 * This namespace holds functions for globally managing query objects
106 /**************************************************************************
108 **************************************************************************/
112 spin: function(locator, active /*= true */) {
113 active = typeof active !== 'undefined' ? active : true;
116 $(locator).spin(manifold.spin_presets);
118 $(locator).spin(false);
120 } catch (err) { messages.debug("Cannot turn spins on/off " + err); }
123 /**************************************************************************
125 **************************************************************************/
127 query_store: QueryStore(),
129 // XXX Remaining functions are deprecated since they are replaced by the query store
132 * Associative array storing the set of queries active on the page
138 * Insert a query in the global hash table associating uuids to queries.
139 * If the query has no been analyzed yet, let's do it.
140 * \fn insert_query(query)
142 * \param ManifoldQuery query Query to be added
144 insert_query : function (query) {
145 if (query.analyzed_query == null) {
146 query.analyze_subqueries();
148 manifold.all_queries[query.query_uuid]=query;
152 * Returns the query associated to a UUID
153 * \fn find_query(query_uuid)
155 * \param string query_uuid The UUID of the query to be returned
157 find_query : function (query_uuid) {
158 return manifold.all_queries[query_uuid];
161 /**************************************************************************
163 **************************************************************************/
165 // trigger a query asynchroneously
166 proxy_url : '/manifold/proxy/json/',
168 asynchroneous_debug : true,
171 * \brief We use js function closure to be able to pass the query (array)
172 * to the callback function used when data is received
174 success_closure: function(query, publish_uuid, callback /*domid*/)
176 return function(data, textStatus) {
177 manifold.asynchroneous_success(data, query, publish_uuid, callback /*domid*/);
181 // Executes all async. queries
182 // input queries are specified as a list of {'query_uuid': <query_uuid>, 'id': <possibly null>}
183 asynchroneous_exec : function (query_publish_dom_tuples) {
186 // in case the spin stuff was not loaded, let's make sure we proceed to the exit
188 // if (manifold.asynchroneous_debug)
189 // messages.debug("Turning on spin with " + jQuery(".need-spin").length + " matches for .need-spin");
190 // jQuery('.need-spin').spin(manifold.spin_presets);
191 //} catch (err) { messages.debug("Cannot turn on spins " + err); }
193 // Loop through input array, and use publish_uuid to publish back results
194 jQuery.each(query_publish_dom_tuples, function(index, tuple) {
195 var query=manifold.find_query(tuple.query_uuid);
196 var query_json=JSON.stringify (query);
197 var publish_uuid=tuple.publish_uuid;
198 // by default we publish using the same uuid of course
199 if (publish_uuid==undefined) publish_uuid=query.query_uuid;
200 if (manifold.asynchroneous_debug) {
201 messages.debug("sending POST on " + manifold.proxy_url + " to be published on " + publish_uuid);
202 messages.debug("... ctd... with actual query= " + query.__repr());
205 query.iter_subqueries(function (sq) {
206 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
209 // not quite sure what happens if we send a string directly, as POST data is named..
210 // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
211 jQuery.post(manifold.proxy_url, {'json':query_json} , manifold.success_closure(query, publish_uuid, tuple.callback /*domid*/));
216 * \brief Forward a query to the manifold backend
217 * \param query (dict) the query to be executed asynchronously
218 * \param callback (function) the function to be called when the query terminates
220 * \param domid (string) the domid to be notified about the results (null for using the pub/sub system
222 forward: function(query, callback /*domid*/) {
223 var query_json = JSON.stringify(query);
224 $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, query.query_uuid, callback/*domid*/));
228 * Returns whether a query expects a unique results.
229 * This is the case when the filters contain a key of the object
230 * \fn query_expects_unique_result(query)
232 * \param ManifoldQuery query Query for which we are testing whether it expects a unique result
234 query_expects_unique_result: function(query) {
235 /* XXX we need functions to query metadata */
236 //var keys = MANIFOLD_METADATA[query.object]['keys']; /* array of array of field names */
237 /* TODO requires keys in metadata */
243 * \fn publish_result(query, results)
245 * \param ManifoldQuery query Query which has received results
246 * \param array results results corresponding to query
248 publish_result: function(query, result) {
249 if (typeof result === 'undefined')
253 manifold.raise_record_event(query.query_uuid, CLEAR_RECORDS);
254 $.each(result, function(i, record) {
255 manifold.raise_record_event(query.query_uuid, NEW_RECORD, record);
257 manifold.raise_record_event(query.query_uuid, DONE);
259 // OLD PLUGIN API BELOW
260 /* Publish an update announce */
261 var channel="/results/" + query.query_uuid + "/changed";
262 if (manifold.asynchroneous_debug)
263 messages.debug("publishing result on " + channel);
264 jQuery.publish(channel, [result, query]);
268 * Recursively publish result
269 * \fn publish_result_rec(query, result)
271 * \param ManifoldQuery query Query which has received result
272 * \param array result result corresponding to query
274 publish_result_rec: function(query, result) {
275 /* If the result is not unique, only publish the top query;
276 * otherwise, publish the main object as well as subqueries
277 * XXX how much recursive are we ?
279 if (manifold.query_expects_unique_result(query)) {
280 /* Also publish subqueries */
281 jQuery.each(query.subqueries, function(object, subquery) {
282 manifold.publish_result_rec(subquery, result[0][object]);
283 /* TODO remove object from result */
286 manifold.publish_result(query, result);
289 // if set domid allows the result to be directed to just one plugin
290 // most of the time publish_uuid will be query.query_uuid
291 // however in some cases we wish to publish the result under a different uuid
292 // e.g. an updater wants to publish its result as if from the original (get) query
293 asynchroneous_success : function (data, query, publish_uuid, callback /*domid*/) {
294 // xxx should have a nicer declaration of that enum in sync with the python code somehow
296 /* If a callback has been specified, we redirect results to it */
297 if (!!callback) { callback(data); return; }
299 if (data.code == 2) { // ERROR
300 // We need to make sense of error codes here
301 alert("Your session has expired, please log in again");
302 window.location="/logout/";
305 if (data.code == 1) { // WARNING
306 messages.error("Some errors have been received from the manifold backend at " + MANIFOLD_URL + " [" + data.description + "]");
307 // publish error code and text message on a separate channel for whoever is interested
308 jQuery.publish("/results/" + publish_uuid + "/failed", [data.code, data.description] );
310 $("#notifications").notify("create", "sticky", {
312 text: data.description
319 // once everything is checked we can use the 'value' part of the manifoldresult
320 var result=data.value;
322 //if (!!callback /* domid */) {
323 // /* Directly inform the requestor */
324 // if (manifold.asynchroneous_debug) messages.debug("directing result to callback");
326 // //if (manifold.asynchroneous_debug) messages.debug("directing result to " + domid);
327 // //jQuery('#' + domid).trigger('results', [result]);
329 /* XXX Jordan XXX I don't need publish_uuid here... What is it used for ? */
330 /* query is the query we sent to the backend; we need to find the
331 * corresponding analyezd_query in manifold.all_queries
333 tmp_query = manifold.find_query(query.query_uuid);
334 manifold.publish_result_rec(tmp_query.analyzed_query, result);
340 /**************************************************************************
342 **************************************************************************/
344 raise_event_handler: function(type, query_uuid, event_type, value)
346 if (type == 'query') {
347 var channels = [ manifold.get_query_channel(query_uuid), manifold.get_query_channel('*') ];
348 } else if (type == 'record') {
349 var channels = [ manifold.get_record_channel(query_uuid), manifold.get_record_channel('*') ];
352 throw 'Incorrect type for manifold.raise_event()';
354 $.each(channels, function(i, channel) {
355 if (value === undefined)
356 $('.plugin').trigger(channel, [event_type]);
358 $('.plugin').trigger(channel, [event_type, value]);
362 raise_query_event: function(query_uuid, event_type, value)
364 manifold.raise_event_handler('query', query_uuid, event_type, value);
367 raise_record_event: function(query_uuid, event_type, value)
369 manifold.raise_event_handler('record', query_uuid, event_type, value);
373 raise_event: function(query_uuid, event_type, value)
377 // Query uuid has been updated with the key of a new element
378 query = manifold.find_query(query_uuid);
380 // XXX We need to find the parent to update the property
381 // XXX We need to find the non-analyzed query so that it can be updated also
384 // Query uuid has been updated with the key of a removed element
389 /* Publish/subscribe channels for internal use */
390 get_query_channel: function(uuid) { return '/query/' + uuid },
391 get_record_channel: function(uuid) { return '/record/' + uuid },
393 }; // manifold object
394 /* ------------------------------------------------------------ */
400 * NOTE: Since we don't have a plugin class, we are extending all jQuery
405 * \brief Associates a query handler to the current plugin
406 * \param uuid (string) query uuid
407 * \param handler (function) handler callback
409 $.fn.set_query_handler = function(uuid, handler)
411 this.on(manifold.get_query_channel(uuid), handler);
414 $.fn.set_record_handler = function(uuid, handler)
416 this.on(manifold.get_record_channel(uuid), handler);
419 // OLD PLUGIN API: extend jQuery/$ with pubsub capabilities
420 // https://gist.github.com/661855
422 $.subscribe = function( channel, selector, data, fn) {
423 /* borrowed from jQuery */
424 if ( data == null && fn == null ) {
427 data = selector = undefined;
428 } else if ( fn == null ) {
429 if ( typeof selector === "string" ) {
430 // ( channel, selector, fn )
434 // ( channel, data, fn )
437 selector = undefined;
442 /* We use an indirection function that will clone the object passed in
443 * parameter to the subscribe callback
445 * FIXME currently we only clone query objects which are the only ones
446 * supported and editable, we might have the same issue with results but
447 * the page load time will be severely affected...
449 o.on.apply(o, [channel, selector, data, function() {
450 for(i = 1; i < arguments.length; i++) {
451 if ( arguments[i].constructor.name == 'ManifoldQuery' )
452 arguments[i] = arguments[i].clone();
454 fn.apply(o, arguments);
458 $.unsubscribe = function() {
459 o.off.apply(o, arguments);
462 $.publish = function() {
463 o.trigger.apply(o, arguments);
468 /* ------------------------------------------------------------ */
470 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
471 //make sure to expose csrf in our outcoming ajax/post requests
473 beforeSend: function(xhr, settings) {
474 function getCookie(name) {
475 var cookieValue = null;
476 if (document.cookie && document.cookie != '') {
477 var cookies = document.cookie.split(';');
478 for (var i = 0; i < cookies.length; i++) {
479 var cookie = jQuery.trim(cookies[i]);
480 // Does this cookie string begin with the name we want?
481 if (cookie.substring(0, name.length + 1) == (name + '=')) {
482 cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
489 if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
490 // Only send the token to relative URLs i.e. locally.
491 xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));