updater now has the logic to turn itself off and back on (although for now only in...
[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         if (manifold.asynchroneous_debug) 
78             messages.debug("received manifold result with code " + data.code + " for publish on " + publish_uuid);
79         // xxx should have a nicer declaration of that enum in sync with the python code somehow
80         if (data.code == 1) {
81             alert("Your session has expired, please log in again");
82             window.location="/logout/";
83             return;
84         } else if (data.code != 0) {
85             messages.error("Error received from manifold backend at " + MANIFOLD_URL + " [" + data.output + "]");
86             // publish error code and text message on a separate channel for whoever is interested
87             jQuery.publish("/results/" + publish_uuid + "/failed", [data.code, data.output] );
88             return;
89         }
90         // once everything is checked we can use the 'value' part of the manifoldresult
91         var value=data.value;
92         if (value) {
93             if (!!domid) {
94                 /* Directly inform the requestor */
95                 if (manifold.asynchroneous_debug) messages.debug("directing results to " + domid);
96                 jQuery('#' + domid).trigger('results', [value]);
97             } else {
98                 /* Publish an update announce */
99                 if (manifold.asynchroneous_debug) messages.debug("publishing results on " + publish_uuid);
100                 jQuery.publish("/results/" + publish_uuid + "/changed", [value, query]);
101             }
102
103         }
104     },
105
106 }; // manifold object
107 /* ------------------------------------------------------------ */
108
109 // extend jQuery/$ with pubsub capabilities
110 /* https://gist.github.com/661855 */
111 (function($) {
112
113   var o = $({});
114
115   $.subscribe = function( types, selector, data, fn) {
116     /* borrowed from jQuery */
117     if ( data == null && fn == null ) {
118         // ( types, fn )
119         fn = selector;
120         data = selector = undefined;
121     } else if ( fn == null ) {
122         if ( typeof selector === "string" ) {
123             // ( types, selector, fn )
124             fn = data;
125             data = undefined;
126         } else {
127             // ( types, data, fn )
128             fn = data;
129             data = selector;
130             selector = undefined;
131         }
132     }
133     /* </ugly> */
134
135     /* We use an indirection function that will clone the object passed in
136      * parameter to the subscribe callback 
137      * 
138      * FIXME currently we only clone query objects which are the only ones
139      * supported and editable, we might have the same issue with results but
140      * the page load time will be severely affected...
141      */
142     o.on.apply(o, [types, selector, data, function() { 
143         for(i = 1; i < arguments.length; i++) {
144             if ( arguments[i].constructor.name == 'Query' )
145                 arguments[i] = arguments[i].clone();
146         }
147         fn.apply(o, arguments);
148     }]);
149   };
150
151   $.unsubscribe = function() {
152     o.off.apply(o, arguments);
153   };
154
155   $.publish = function() {
156     o.trigger.apply(o, arguments);
157   };
158
159 }(jQuery));
160
161 /* ------------------------------------------------------------ */
162
163 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
164 //make sure to expose csrf in our outcoming ajax/post requests
165 $.ajaxSetup({ 
166      beforeSend: function(xhr, settings) {
167          function getCookie(name) {
168              var cookieValue = null;
169              if (document.cookie && document.cookie != '') {
170                  var cookies = document.cookie.split(';');
171                  for (var i = 0; i < cookies.length; i++) {
172                      var cookie = jQuery.trim(cookies[i]);
173                      // Does this cookie string begin with the name we want?
174                  if (cookie.substring(0, name.length + 1) == (name + '=')) {
175                      cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
176                      break;
177                  }
178              }
179          }
180          return cookieValue;
181          }
182          if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
183              // Only send the token to relative URLs i.e. locally.
184              xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
185          }
186      } 
187 });
188