a48ff37b8f6bdb5942fb8871ecc9f1a5284226f4
[unfold.git] / plugins / static / js / querycode.js
1 /**
2  * MySlice QueryCode plugin
3  * URL: http://trac.myslice.info
4  * Description: display code for a target query in python or ruby
5  * Author: The MySlice Team
6  * Copyright (c) 2012 UPMC Sorbonne Universite - INRIA
7  * License: GPLv3
8  */
9
10 querycode_debug=false;
11 querycode_debug=true;
12
13 function debug_object (msg, o) {
14     var keys=[];
15     for (var k in o) keys.push(k);
16     console.log (msg + " Keys : " + keys);
17 }
18
19 (function($) {
20   
21     var methods = {
22         init : function (options) {
23             return this.each(function() {
24                 var $this=$(this);
25                 var data=$this.data('QueryCode');
26                 if ( ! data ) {
27                     // Subscribe to query updates
28                     var channel='/results/' + options.query_uuid + '/updated';
29                     /* passing $this as 2nd arg: callbacks will retrieve $this as e.data */
30                     $.subscribe(channel, $this, update_plugin);
31                     if (querycode_debug) window.console.log('subscribing to ' + channel);
32                     $this.data('QueryCode', {options: options});
33                     // react to changes to the language selector
34                     $this.find(".querycode-lang").change(change_language);
35                 }
36             });
37
38         console.log("temporarily turned off SyntaxHighlighter ...");
39 //      SyntaxHighlighter.all();
40
41         }, 
42
43 //      destroy : function( ) {
44 //          if (querycode_debug) console.log("QueryCode.destroy...");
45 //      },
46 //      update : function( content ) { 
47 //          if (querycode_debug) console.log("QueryCode.update...");
48 //      },
49         trigger : function () {
50             var channel='/results/' + $(this).data.QueryCode.options.query_uuid + '/updated';
51             publish(channel,"trigger");
52         }
53             
54         
55     } // methods
56                           
57     $.fn.QueryCode = function( method ) {
58         /* Method calling logic */
59         if ( methods[method] ) {
60             return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
61         } else if ( typeof method === 'object' || ! method ) {
62             return methods.init.apply( this, arguments );
63         } else {
64             $.error( 'Method ' +  method + ' does not exist on jQuery.QueryCode' );
65         }    
66     };
67
68     // we retrieve the plugindiv as e.data - cf the 2nd arg to subscribe
69     function update_plugin (e) {
70         var $plugindiv=e.data;
71         do_update ($plugindiv);
72     }
73
74     // linked to 'change' on the selector; this=the selector dom
75     function change_language (e) {
76         var $plugindiv = $(this).closest(".plugin");
77         do_update($plugindiv);
78     }
79  
80     function do_update ($plugindiv) {
81         // just in case
82         $plugindiv.closest('.need-spin').spin(false);
83
84         var lang=$plugindiv.find(".querycode-lang").val();
85         var dom=$plugindiv.find(".querycode-viz");
86         var query = $plugindiv.data().QueryCode.options.query;
87         funname="translate_query_as_" + lang;
88         fun=eval(funname);
89         if ( ! fun) {
90             console.log("Cannot find translator function for lang " + lang);
91             return;
92         }
93         html_code=fun(query);
94         dom.html(html_code);
95         console.log("turned off SyntaxHighlighter.highlight");
96 //      SyntaxHighlighter.highlight()
97
98     }
99
100
101     // private stuff
102     function translate_query_as_ruby (query) {
103         debug_object("query_ruby entering -- query=" + query, query);
104         var output = '# Connection to XMLRPC server\n';
105         output += 'require "xmlrpc/client"\n';
106         output += 'require "pp"\n';
107         output += '\n';
108         output += 'XMLRPC::Config.module_eval do\n';
109         output += '  remove_const :ENABLE_NIL_PARSER\n';
110         output += '  const_set :ENABLE_NIL_PARSER, true\n';
111         output += 'end\n';
112         output += 'srv = XMLRPC::Client.new2("https://www.top-hat.info/API/")\n';
113         //output += 'tophat = xmlrpclib.ServerProxy("' . (TOPHAT_API_PORT == 443 ? 'http' : 'https') . '://' . TOPHAT_API_HOST . ':' . TOPHAT_API_PORT . TOPHAT_API_PATH . '", allow_none=True)\n\n';
114         output += '\n';
115         output += '# Authentication token\n';
116         output += 'auth = {"AuthMethod" => "password", "Username" => "guest", "AuthString" => "guest"}\n';
117         output += '\n';
118
119         ifs = '';
120         $.each(query.filters, function(i, value) {
121             if (ifs != '') ifs += ', ';
122             ifs += '"';
123             if (value[1] != "=")
124                 ifs += value[1];
125             ifs += value[0] + '" => "' + value[2] + '"';
126         });
127         ifs = '{' + ifs + '}';
128         
129         ofs = '';
130         $.each(query.fields, function(index, value) {
131             if (ofs != '')
132                 ofs += ', ';
133             ofs += '"' + value + '"';
134         });
135         ofs = '[' + ofs + ']';
136
137         output += 'pp srv.call("' + query.action +'", auth, "' + query.method + '", "' + query.timestamp + '", ' + ifs + ', ' + ofs + ')';
138
139         var output = '<pre class="brush: ruby; toolbar: false;">' + output + "</pre>";
140         return output;
141
142     }
143
144     function translate_query_as_python (query) {
145         // xxx tmp
146         var TOPHAT_API_HOST="hostname", TOPHAT_API_PORT=443, TOPHAT_API_PATH="/path";
147         var proto = (TOPHAT_API_PORT == 443 ? 'https' : 'http');
148         var output = '# Connection to XMLRPC server\n';
149         output += 'import xmlrpclib\n';
150         output += 'srv = xmlrpclib.ServerProxy("' + proto + '://' + TOPHAT_API_HOST + ':' + TOPHAT_API_PORT + TOPHAT_API_PATH + '", allow_none=True)\n\n';
151         output += '# Authentication token\n';
152         output += 'auth = {"AuthMethod": "password", "Username": "name.surname@domain.name", "AuthString": "mypassword"}\n\n';
153
154         ifs = '';
155         $.each(query.filters, function(i, value) {
156             if (ifs != '')
157                 ifs += ', ';
158             //ifs += '"'
159             //if (value[1] != "=")
160             //    ifs += value[1];
161             ifs += '["' + value[0] + '", "' + value[1] + '", "' + value[2] + '"]';
162         });
163         ifs = '[' + ifs + ']';
164         
165         ofs = '';
166         $.each(query.fields, function(index, value) {
167             if (ofs != '')
168                 ofs += ', ';
169             ofs += '"' + value + '"';
170         });
171         ofs = '[' + ofs + ']';
172
173         output += 'srv.' + query.action + '(auth, "' + query.method + '", ' + ifs + ', {}, ' + ofs + ')';
174         var output = '<pre class="brush: python; toolbar: false;">' + output + "</pre>";
175         return output;
176     }
177     
178
179
180     // get these plugins to update their contents upon loading
181     // manually publishing on the right channel
182 //    $(function () { $(".QueryCode").each(function () { this.trigger(); })})
183
184 })(jQuery); // end closure wrapper
185