added sticky notifications for warnings and errors + clean up code for v2 only
[myslice.git] / manifold / js / manifold.js
1 // utilities 
2 function debug_dict_keys (msg, o) {
3     var keys=[];
4     for (var k in o) keys.push(k);
5     messages.debug ("debug_dict_keys: " + msg + " keys= " + keys);
6 }
7 function debug_dict (msg, o) {
8     for (var k in o) messages.debug ("debug_dict: " + msg + " [" + k + "]=" + o[k]);
9 }
10 function debug_value (msg, value) {
11     messages.debug ("debug_value: " + msg + " " + value);
12 }
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);
18 }
19
20 /* ------------------------------------------------------------ */
21
22 // Constants that should be somehow moved to a plugin.js file
23 var FILTER_ADDED   = 1;
24 var FILTER_REMOVED = 2;
25 var CLEAR_FILTERS  = 3;
26 var FIELD_ADDED    = 4;
27 var FIELD_REMOVED  = 5;
28 var CLEAR_FIELDS   = 6;
29 var NEW_RECORD     = 7;
30 var CLEAR_RECORDS  = 8;
31
32 var IN_PROGRESS    = 101;
33 var DONE           = 102;
34
35 var SET_ADD        = 201;
36 var SET_REMOVED    = 202;
37
38 /*!
39  * This namespace holds functions for globally managing query objects
40  * \Class Manifold
41  */
42 var manifold = {
43
44     spin_presets: {},
45
46     spin: function(locator, active /*= true */) {
47         active = typeof active !== 'undefined' ? active : true;
48         try {
49             if (active) {
50                 $(locator).spin(manifold.spin_presets);
51             } else {
52                 $(locator).spin(false);
53             }
54         } catch (err) { messages.debug("Cannot turn spins on/off " + err); }
55     },
56
57     /*!
58      * Associative array storing the set of queries active on the page
59      * \memberof Manifold
60      */
61     all_queries: {},
62
63     /*!
64      * Insert a query in the global hash table associating uuids to queries.
65      * If the query has no been analyzed yet, let's do it.
66      * \fn insert_query(query)
67      * \memberof Manifold
68      * \param ManifoldQuery query Query to be added
69      */
70     insert_query : function (query) { 
71         if (query.analyzed_query == null) {
72             query.analyze_subqueries();
73         }
74         manifold.all_queries[query.query_uuid]=query;
75     },
76
77     /*!
78      * Returns the query associated to a UUID
79      * \fn find_query(query_uuid)
80      * \memberof Manifold
81      * \param string query_uuid The UUID of the query to be returned
82      */
83     find_query : function (query_uuid) { 
84         return manifold.all_queries[query_uuid];
85     },
86
87     // trigger a query asynchroneously
88     proxy_url : '/manifold/proxy/json/',
89
90     asynchroneous_debug : true,
91
92     /**
93      * \brief We use js function closure to be able to pass the query (array)
94      * to the callback function used when data is received
95      */
96     success_closure: function(query, publish_uuid, callback /*domid*/)
97     {
98         return function(data, textStatus) {
99             manifold.asynchroneous_success(data, query, publish_uuid, callback /*domid*/);
100         }
101     },
102
103     // Executes all async. queries
104     // input queries are specified as a list of {'query_uuid': <query_uuid>, 'id': <possibly null>}
105     asynchroneous_exec : function (query_publish_dom_tuples) {
106         // start spinners
107
108         // in case the spin stuff was not loaded, let's make sure we proceed to the exit 
109         //try {
110         //    if (manifold.asynchroneous_debug) 
111         //   messages.debug("Turning on spin with " + jQuery(".need-spin").length + " matches for .need-spin");
112         //    jQuery('.need-spin').spin(manifold.spin_presets);
113         //} catch (err) { messages.debug("Cannot turn on spins " + err); }
114         
115         // Loop through input array, and use publish_uuid to publish back results
116         jQuery.each(query_publish_dom_tuples, function(index, tuple) {
117             var query=manifold.find_query(tuple.query_uuid);
118             var query_json=JSON.stringify (query);
119             var publish_uuid=tuple.publish_uuid;
120             // by default we publish using the same uuid of course
121             if (publish_uuid==undefined) publish_uuid=query.query_uuid;
122             if (manifold.asynchroneous_debug) {
123                 messages.debug("sending POST on " + manifold.proxy_url + " to be published on " + publish_uuid);
124                 messages.debug("... ctd... with actual query= " + query.__repr());
125             }
126
127             query.iter_subqueries(function (sq) {
128                 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
129             });
130
131             // not quite sure what happens if we send a string directly, as POST data is named..
132             // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
133                 jQuery.post(manifold.proxy_url, {'json':query_json} , manifold.success_closure(query, publish_uuid, tuple.callback /*domid*/));
134         })
135     },
136
137     /**
138      * \brief Forward a query to the manifold backend
139      * \param query (dict) the query to be executed asynchronously
140      * \param callback (function) the function to be called when the query terminates
141      * Deprecated:
142      * \param domid (string) the domid to be notified about the results (null for using the pub/sub system
143      */
144     forward: function(query, callback /*domid*/) {
145         var query_json = JSON.stringify(query);
146         $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, query.query_uuid, callback/*domid*/));
147     },
148
149     /*!
150      * Returns whether a query expects a unique results.
151      * This is the case when the filters contain a key of the object
152      * \fn query_expects_unique_result(query)
153      * \memberof Manifold
154      * \param ManifoldQuery query Query for which we are testing whether it expects a unique result
155      */
156     query_expects_unique_result: function(query) {
157         /* XXX we need functions to query metadata */
158         //var keys = MANIFOLD_METADATA[query.object]['keys']; /* array of array of field names */
159         /* TODO requires keys in metadata */
160         return true;
161     },
162
163     raise_event_handler: function(type, query_uuid, event_type, value)
164     {
165         if (type == 'query') {
166             var channels = [ manifold.get_query_channel(query_uuid), manifold.get_query_channel('*') ];
167         } else if (type == 'record') {
168             var channels = [ manifold.get_record_channel(query_uuid), manifold.get_record_channel('*') ];
169
170         } else {
171             throw 'Incorrect type for manifold.raise_event()';
172         }
173         $.each(channels, function(i, channel) {
174             if (value === undefined)
175                 $('.plugin').trigger(channel, [event_type]);
176             else
177                 $('.plugin').trigger(channel, [event_type, value]);
178         });
179     },
180
181     raise_query_event: function(query_uuid, event_type, value)
182     {
183         manifold.raise_event_handler('query', query_uuid, event_type, value);
184     },
185
186     raise_record_event: function(query_uuid, event_type, value)
187     {
188         manifold.raise_event_handler('record', query_uuid, event_type, value);
189     },
190
191     /*!
192      * Publish result
193      * \fn publish_result(query, results)
194      * \memberof Manifold
195      * \param ManifoldQuery query Query which has received results
196      * \param array results results corresponding to query
197      */
198     publish_result: function(query, result) {
199         if (typeof result === 'undefined')
200             result = [];
201
202         // NEW PLUGIN API
203         manifold.raise_record_event(query.query_uuid, CLEAR_RECORDS);
204         $.each(result, function(i, record) {
205             manifold.raise_record_event(query.query_uuid, NEW_RECORD, record);
206         });
207         manifold.raise_record_event(query.query_uuid, DONE);
208
209         // OLD PLUGIN API BELOW
210         /* Publish an update announce */
211         var channel="/results/" + query.query_uuid + "/changed";
212         if (manifold.asynchroneous_debug)
213             messages.debug("publishing result on " + channel);
214         jQuery.publish(channel, [result, query]);
215     },
216
217     /*!
218      * Recursively publish result
219      * \fn publish_result_rec(query, result)
220      * \memberof Manifold
221      * \param ManifoldQuery query Query which has received result
222      * \param array result result corresponding to query
223      */
224     publish_result_rec: function(query, result) {
225         /* If the result is not unique, only publish the top query;
226          * otherwise, publish the main object as well as subqueries
227          * XXX how much recursive are we ?
228          */
229         if (manifold.query_expects_unique_result(query)) {
230             /* Also publish subqueries */
231             jQuery.each(query.subqueries, function(object, subquery) {
232                 manifold.publish_result_rec(subquery, result[0][object]);
233                 /* TODO remove object from result */
234             });
235         }
236         manifold.publish_result(query, result);
237     },
238
239     // if set domid allows the result to be directed to just one plugin
240     // most of the time publish_uuid will be query.query_uuid
241     // however in some cases we wish to publish the result under a different uuid
242     // e.g. an updater wants to publish its result as if from the original (get) query
243     asynchroneous_success : function (data, query, publish_uuid, callback /*domid*/) {
244         // xxx should have a nicer declaration of that enum in sync with the python code somehow
245
246         /* If a callback has been specified, we redirect results to it */
247         if (!!callback) { callback(data); return; }
248
249         if (data.code == 2) { // ERROR
250             // We need to make sense of error codes here
251             alert("Your session has expired, please log in again");
252             window.location="/logout/";
253             return;
254         }
255         if (data.code == 1) { // WARNING
256             messages.error("Some errors have been received from the manifold backend at " + MANIFOLD_URL + " [" + data.description + "]");
257             // publish error code and text message on a separate channel for whoever is interested
258             jQuery.publish("/results/" + publish_uuid + "/failed", [data.code, data.description] );
259
260             $("#notifications").notify("create", "sticky", {
261               title: 'Warning',
262               text: data.description
263             },{
264               expires: false,
265               speed: 1000
266             });
267             
268         }
269         // once everything is checked we can use the 'value' part of the manifoldresult
270         var result=data.value;
271         if (result) {
272             //if (!!callback /* domid */) {
273             //    /* Directly inform the requestor */
274             //    if (manifold.asynchroneous_debug) messages.debug("directing result to callback");
275             //    callback(result);
276             //    //if (manifold.asynchroneous_debug) messages.debug("directing result to " + domid);
277             //    //jQuery('#' + domid).trigger('results', [result]);
278             //} else {
279                 /* XXX Jordan XXX I don't need publish_uuid here... What is it used for ? */
280                 /* query is the query we sent to the backend; we need to find the
281                  * corresponding analyezd_query in manifold.all_queries
282                  */
283                 tmp_query = manifold.find_query(query.query_uuid);
284                 manifold.publish_result_rec(tmp_query.analyzed_query, result);
285             //}
286
287         }
288     },
289
290     raise_event: function(uuid, event_type, value)
291     {
292         switch(event_type) {
293             case SET_ADD:
294                 // Query uuid has been updated with the key of a new element
295                 break;
296             case SET_REMOVED:
297                 // Query uuid has been updated with the key of a removed element
298                 break;
299         }
300     },
301
302     /* Publish/subscribe channels for internal use */
303     get_query_channel:  function(uuid) { return '/query/'  + uuid },
304     get_record_channel: function(uuid) { return '/record/' + uuid },
305
306 }; // manifold object
307 /* ------------------------------------------------------------ */
308
309 (function($) {
310
311     /* NEW PLUGIN API
312      * 
313      * NOTE: Since we don't have a plugin class, we are extending all jQuery
314      * plugins...
315      */
316
317     /*!
318      * \brief Associates a query handler to the current plugin
319      * \param uuid (string) query uuid
320      * \param handler (function) handler callback
321      */
322     $.fn.set_query_handler = function(uuid, handler)
323     {
324         this.on(manifold.get_query_channel(uuid), handler);
325     }
326
327     $.fn.set_record_handler = function(uuid, handler)
328     {
329         this.on(manifold.get_record_channel(uuid), handler);
330     }
331
332     // OLD PLUGIN API: extend jQuery/$ with pubsub capabilities
333     // https://gist.github.com/661855
334     var o = $({});
335     $.subscribe = function( channel, selector, data, fn) {
336       /* borrowed from jQuery */
337       if ( data == null && fn == null ) {
338           // ( channel, fn )
339           fn = selector;
340           data = selector = undefined;
341       } else if ( fn == null ) {
342           if ( typeof selector === "string" ) {
343               // ( channel, selector, fn )
344               fn = data;
345               data = undefined;
346           } else {
347               // ( channel, data, fn )
348               fn = data;
349               data = selector;
350               selector = undefined;
351           }
352       }
353       /* </ugly> */
354   
355       /* We use an indirection function that will clone the object passed in
356        * parameter to the subscribe callback 
357        * 
358        * FIXME currently we only clone query objects which are the only ones
359        * supported and editable, we might have the same issue with results but
360        * the page load time will be severely affected...
361        */
362       o.on.apply(o, [channel, selector, data, function() { 
363           for(i = 1; i < arguments.length; i++) {
364               if ( arguments[i].constructor.name == 'ManifoldQuery' )
365                   arguments[i] = arguments[i].clone();
366           }
367           fn.apply(o, arguments);
368       }]);
369     };
370   
371     $.unsubscribe = function() {
372       o.off.apply(o, arguments);
373     };
374   
375     $.publish = function() {
376       o.trigger.apply(o, arguments);
377     };
378   
379 }(jQuery));
380
381 /* ------------------------------------------------------------ */
382
383 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
384 //make sure to expose csrf in our outcoming ajax/post requests
385 $.ajaxSetup({ 
386      beforeSend: function(xhr, settings) {
387          function getCookie(name) {
388              var cookieValue = null;
389              if (document.cookie && document.cookie != '') {
390                  var cookies = document.cookie.split(';');
391                  for (var i = 0; i < cookies.length; i++) {
392                      var cookie = jQuery.trim(cookies[i]);
393                      // Does this cookie string begin with the name we want?
394                  if (cookie.substring(0, name.length + 1) == (name + '=')) {
395                      cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
396                      break;
397                  }
398              }
399          }
400          return cookieValue;
401          }
402          if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
403              // Only send the token to relative URLs i.e. locally.
404              xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
405          }
406      } 
407 });
408