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