cosmetic
[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 // this namespace holds functions for globally managing query objects
22 var manifold = {
23
24     all_queries: {},
25
26     insert_query : function (query) { 
27         manifold.all_queries[query.query_uuid]=query; 
28     },
29     find_query : function (query_uuid) { 
30         return manifold.all_queries[query_uuid];
31     },
32
33     // trigger a query asynchroneously
34     proxy_url : '/manifold/proxy/json/',
35
36     asynchroneous_debug : true,
37
38     // Executes all async. queries
39     // input queries are specified as a list of {'query_uuid': <query_uuid>, 'id': <possibly null>}
40     asynchroneous_exec : function (query_publish_dom_tuples) {
41         // start spinners
42
43         // in case the spin stuff was not loaded, let's make sure we proceed to the exit 
44         try {
45             if (manifold.asynchroneous_debug) 
46                 messages.debug("Turning on spin with " + jQuery(".need-spin").length + " matches for .need-spin");
47             jQuery('.need-spin').spin(spin_presets);
48         } catch (err) { messages.debug("Cannot turn on spins " + err); }
49         
50         // We use js function closure to be able to pass the query (array) to the
51         // callback function used when data is received
52         var success_closure = function(query, publish_uuid, domid) {
53             return function(data, textStatus) {manifold.asynchroneous_success(data, query, publish_uuid, domid);}};
54         
55         // Loop through input array, and use publish_uuid to publish back results
56         jQuery.each(query_publish_dom_tuples, function(index, tuple) {
57             var query=manifold.find_query(tuple.query_uuid);
58             var query_json=JSON.stringify (query);
59             var publish_uuid=tuple.publish_uuid;
60             // by default we publish using the same uuid of course
61             if (publish_uuid==undefined) publish_uuid=query.query_uuid;
62             if (manifold.asynchroneous_debug) {
63                 messages.debug("sending POST on " + manifold.proxy_url + " to be published on " + publish_uuid);
64                 messages.debug("... ctd... with actual query= " + query.__repr());
65             }
66             // not quite sure what happens if we send a string directly, as POST data is named..
67             // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
68             jQuery.post(manifold.proxy_url, {'json':query_json} , success_closure(query, publish_uuid, tuple.domid));
69         })
70             },
71
72     // if set domid allows the result to be directed to just one plugin
73     // most of the time publish_uuid will be query.query_uuid
74     // however in some cases we wish to publish the results under a different uuid
75     // e.g. an updater wants to publish its results as if from the original (get) query
76     asynchroneous_success : function (data, query, publish_uuid, domid) {
77         // xxx should have a nicer declaration of that enum in sync with the python code somehow
78         if (data.code == 1) {
79             alert("Your session has expired, please log in again");
80             window.location="/logout/";
81             return;
82         } else if (data.code != 0) {
83             messages.error("Error received from manifold backend at " + MANIFOLD_URL + " [" + data.output + "]");
84             // publish error code and text message on a separate channel for whoever is interested
85             jQuery.publish("/results/" + publish_uuid + "/failed", [data.code, data.output] );
86             return;
87         }
88         // once everything is checked we can use the 'value' part of the manifoldresult
89         var value=data.value;
90         if (value) {
91             if (!!domid) {
92                 /* Directly inform the requestor */
93                 if (manifold.asynchroneous_debug) messages.debug("directing results to " + domid);
94                 jQuery('#' + domid).trigger('results', [value]);
95             } else {
96                 /* Publish an update announce */
97                 var channel="/results/" + publish_uuid + "/changed";
98                 if (manifold.asynchroneous_debug) messages.debug("publishing results on " + channel);
99                 jQuery.publish(channel, [value, query]);
100             }
101
102         }
103     },
104
105 }; // manifold object
106 /* ------------------------------------------------------------ */
107
108 // extend jQuery/$ with pubsub capabilities
109 /* https://gist.github.com/661855 */
110 (function($) {
111
112   var o = $({});
113
114   $.subscribe = function( channel, selector, data, fn) {
115     /* borrowed from jQuery */
116     if ( data == null && fn == null ) {
117         // ( channel, fn )
118         fn = selector;
119         data = selector = undefined;
120     } else if ( fn == null ) {
121         if ( typeof selector === "string" ) {
122             // ( channel, selector, fn )
123             fn = data;
124             data = undefined;
125         } else {
126             // ( channel, data, fn )
127             fn = data;
128             data = selector;
129             selector = undefined;
130         }
131     }
132     /* </ugly> */
133
134     /* We use an indirection function that will clone the object passed in
135      * parameter to the subscribe callback 
136      * 
137      * FIXME currently we only clone query objects which are the only ones
138      * supported and editable, we might have the same issue with results but
139      * the page load time will be severely affected...
140      */
141     o.on.apply(o, [channel, selector, data, function() { 
142         for(i = 1; i < arguments.length; i++) {
143             if ( arguments[i].constructor.name == 'ManifoldQuery' )
144                 arguments[i] = arguments[i].clone();
145         }
146         fn.apply(o, arguments);
147     }]);
148   };
149
150   $.unsubscribe = function() {
151     o.off.apply(o, arguments);
152   };
153
154   $.publish = function() {
155     o.trigger.apply(o, arguments);
156   };
157
158 }(jQuery));
159
160 /* ------------------------------------------------------------ */
161
162 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
163 //make sure to expose csrf in our outcoming ajax/post requests
164 $.ajaxSetup({ 
165      beforeSend: function(xhr, settings) {
166          function getCookie(name) {
167              var cookieValue = null;
168              if (document.cookie && document.cookie != '') {
169                  var cookies = document.cookie.split(';');
170                  for (var i = 0; i < cookies.length; i++) {
171                      var cookie = jQuery.trim(cookies[i]);
172                      // Does this cookie string begin with the name we want?
173                  if (cookie.substring(0, name.length + 1) == (name + '=')) {
174                      cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
175                      break;
176                  }
177              }
178          }
179          return cookieValue;
180          }
181          if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
182              // Only send the token to relative URLs i.e. locally.
183              xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
184          }
185      } 
186 });
187