upload pod file
[hband-tools.git] / óraállás-diktáló / nkmfoldgaz.js
blobf3b3f783632c4f67bbe96a2560d9026eab74dd2f
1 #!/usr/bin/env phantomjs2 --ssl-protocol=any --ignore-ssl-errors=true --web-security=false
3 /*
4         EXIT CODE
5         0       report successful
6         1       a web interaction step failed on user side
7         2       wrong invocation
8         3       page load failed
9         4       a web interaction step failed on navigator side
10         5       report failed
13 var llDebug = 1, llStatus = 2, llError = 3, llMsg = 4;
14 var vlDebug = false;
15 var vlStatus = false;
16 var vlError = true;
17 var vlMsg = true;
18 var system = require('system');
19 var stderr = system.stderr;
20 var stdout = system.stdout;
21 var Glob = {};
23 for(var i=1; i<system.args.length; i++)
25         if(system.args[i] == '--debug') vlDebug = true;
26         else if(system.args[i] == '--verbose') vlStatus = true;
27         else if(system.args[i].match(/^-/))
28         {
29                 stderr.write("Unknown option: "+system.args[i]+"\n");
30                 phantom.exit(2);
31         }
32         else
33         {
34                 Glob.felhazon = system.args[i];
35                 Glob.gyariszam = system.args[i+1];
36                 Glob.meroallas = system.args[i+2];
37                 Glob.email = system.args[i+3];
38                 Glob.datum = system.args[i+4];
39                 i += 4;
40         }
43 if(Glob.datum == undefined)
45         stderr.write("Usage: nkmfoldgaz.js [--debug] [--verbose] <felhasználó-azonosító> <mérőóra-gyári-szám> <mérőállás> <email> <dátum>\n");
46         phantom.exit(2);
51 var url_form = "https://www.nkmfoldgaz.hu/Ugyfelszolgalat/Havi-meroallas-kozlese-pub";
52 var loadInProgress = false;
53 var stepindex = 0;
54 var page = new WebPage();
55 page.settings.userAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.90 Safari/537.36 Vivaldi/1.91.867.38";
57 function log(level, msg)
59         if(level == llDebug && vlDebug || 
60            level == llStatus && vlStatus ||
61            level == llError && vlError ||
62            level == llMsg && vlMsg)
63         {
64                 stderr.write(msg + "\n");
65         }
68 page.onConsoleMessage = function(msg)
70         if(msg.match(/^\[DEBUG\]/))
71                 log(llDebug, msg);
72         else
73                 log(llMsg, ">>> " + msg);
76 page.onLoadStarted = function()
78         loadInProgress = true;
79         log(llStatus, "load started [" + page.url + "]");
82 page.onLoadFinished = function()
84         loadInProgress = false;
85         log(llStatus, "load finished [" + page.evaluate(function(){return document.title;}) + "]");
88 page.onError = function(msg, stack)
90         log(llError, "ERROR: " + msg + "\nSTACK: " + JSON.stringify(stack));
93 page.onResourceRequested = function(requestData, networkRequest)
95         if(!requestData.url.match(/^data:/))
96         {
97                 log(llDebug, requestData.method+' '+requestData.url);
98         }
99         /*
100         for(var i=0; i<requestData.headers.length; i++)
101         {
102                 log(llDebug, requestData.headers[i].name + ': ' + requestData.headers[i].value);
103         }
104         log(llDebug, JSON.stringify(requestData));
105         */
109 page.open(url_form, function(status)
111         if(status !== 'success')
112         {
113                 log(llError, "ERROR " + status);
114                 phantom.exit(3);
115         }
116         else
117         {
118                 var steps = [
119                         function(param)
120                         {
121                                 /* Waiting iframe to load */
122                                 /* Search for the 'Rögzít' button */
123                                 var button_span;
124                                 var spans = document.getElementsByTagName('span');
125                                 for(var x = 0; x < spans.length; x++)
126                                 {
127                                         if(spans[x].innerText.match(/állás mentése/))
128                                         {
129                                                 button_span = spans[x];
130                                         }
131                                 }
132                                 if(typeof button_span == 'undefined')
133                                 {
134                                         // uncomment this to see the current document and debug
135                                         //console.log(document.querySelectorAll('html')[0].outerHTML);
136                                         console.log("Waiting for submit button...");
137                                         return 0;
138                                 }
139                                 return 1;
140                         },
141                         function(param)
142                         {
143                                 /* Filling in form fields by simulating typing on keyboard */
144                                 
145                                 function typein(field_id, str)
146                                 {
147                                         console.log("[DEBUG] Typing in '" + str + "' in field '#" + field_id + "'...");
148                                         var field = document.getElementById(field_id);
149                                         field.focus();
150                                         for(var pos = 0; pos < str.length; pos++)
151                                         {
152                                                 for(var keyevent in {"keydown":1, "keypress":1, "input":1, "change":1, "keyup":1})
153                                                 {
154                                                         var ev = document.createEvent("KeyboardEvent");
155                                                         var keyCode = str.charCodeAt(pos);
156                                                         var charCode = str.charCodeAt(pos);
157                                                         ev.initKeyboardEvent(keyevent, true, true, window, null, false, false, false, false, keyCode, charCode);
158                                                         ev.key = str[pos];
159                                                         ev.code = charCode;
160                                                         field.dispatchEvent(ev);
161                                                 }
162                                         }
163                                         field.value = str;
164                                 }
165                                 
166                                 var starting_field_id;
167                                 /* Find first input field's Id */
168                                 var inputs = document.getElementsByTagName('input');
169                                 for(var x = 0; x < inputs.length; x++)
170                                 {
171                                         if(inputs[x].getAttribute('title') == "Felhasználó azonosító")
172                                         {
173                                                 starting_field_id = inputs[x].getAttribute('id');
174                                         }
175                                 }
176                                 if(typeof starting_field_id == 'undefined')
177                                 {
178                                         console.log("input filed ID is not found");
179                                         return false;
180                                 }
181                                 var starting_field_num = eval("0x" + starting_field_id.substr(2,2));
182                                 function mkWDid(n)
183                                 {
184                                         var x = n.toString(16).toUpperCase();
185                                         if(x.length == 1) x = '' + '0' + x;
186                                         return 'WD' + x;
187                                 }
188                                 
189                                 typein(mkWDid(starting_field_num +  0), param.felhazon);
190                                 typein(mkWDid(starting_field_num +  5), param.gyariszam);
191                                 typein(mkWDid(starting_field_num + 10), param.meroallas);
192                                 typein(mkWDid(starting_field_num + 15), param.email);
193                                 typein(mkWDid(starting_field_num + 20), param.datum);
194                                 
195                                 param['submit_button_id'] = mkWDid(starting_field_num + 23);
196                                 param['result_element_id'] = mkWDid(starting_field_num + 30);
197                                 return JSON.stringify({
198                                         jump: 1,
199                                         result: param,
200                                 });
201                         },
202                         function(param)
203                         {
204                                 /* Submit form by simulating user clicking on button */
205                                 
206                                 var submit_button = document.getElementById(param['submit_button_id']);
207                                 var ev = document.createEvent("MouseEvent");
208                                 ev.initMouseEvent("click", true /* bubble */, true /* cancelable */, window, null, 0, 0, 0, 0, /* coordinates */ false, false, false, false, /* modifier keys */ 0 /*left*/, null);
209                                 submit_button.dispatchEvent(ev);
210                                 return 1;
211                         },
212                         function(param)
213                         {
214                                 /* Wait response page to load */
215                                 if(!document.getElementById(param['result_element_id']))
216                                 {
217                                         console.log("Waiting for results..."+param['result_element_id']);
218                                         return 0;
219                                 }
220                                 return 1;
221                         },
222                         function(param)
223                         {
224                                 /* Echo response from server */
225                                 var result_elem = document.getElementById(param['result_element_id'])
226                                 /* the WD element (usually #WD37 or #WD38) we calculated is not always the element which holds lsdata,
227                                    so we look for the first element actually having lsdata with result_element_id */
228                                 if(!result_elem.getAttribute('lsdata'))
229                                         result_elem = document.querySelector('#'+param['result_element_id']+' [lsdata]');
230                                 param.result_elem_html_outer = result_elem.outerHTML;
231                                 param.result_elem_html_inner = result_elem.innerHTML;
232                                 param.result_elem_text_inner = result_elem.innerText;
233                                 param.result = result_elem.getAttribute('lsdata');
234                                 return JSON.stringify({
235                                         jump: 1,
236                                         result: param,
237                                 });
238                         }
239                 ];
241                 timeout = 500;
242                 worker = function()
243                 {
244                         function display_nkm_result(result)
245                         {
246                                 try {
247                                         var v = result.replace(/\\x(..)/g, function(match, group_1, start_pos, whole_string){
248                                                 return String.fromCharCode(Number("0x" + group_1));
249                                         });
250                                         stdout.write(v + "\n");
251                                 }
252                                 catch(error) {
253                                         true;
254                                 }
255                         }
256                         
257                         if(!loadInProgress)
258                         {
259                                 /* Make sure we are in the correct frame */
260                                 page.switchToFrame('wasframe');
261                                 log(llDebug, "Frame: " + page.frameName + " \"" + page.frameTitle + "\" [" + page.frameUrl + "]");
262                                 
263                                 /* Execute next step in navigator's context */
264                                 log(llDebug, "step " + stepindex);
265                                 var ret = page.evaluate(steps[stepindex], Glob);
266                                 
267                                 if(ret === false)
268                                 {
269                                         phantom.exit(1);
270                                 }
271                                 else if(ret === undefined || ret === null)
272                                 {
273                                         phantom.exit(4);
274                                 }
275                                 
276                                 if(typeof ret != "number")
277                                 {
278                                         ret = JSON.parse(ret);
279                                         for(var key in Glob)
280                                         {
281                                                 if(!ret.result.hasOwnProperty(key)) delete Glob[key];
282                                         }
283                                         for(var key in ret.result)
284                                         {
285                                                 Glob[key] = ret.result[key];
286                                         }
287                                         //stderr.write(JSON.stringify(Glob));
288                                         ret = ret.jump;
289                                 }
290                                 
291                                 log(llDebug, "step " + stepindex + " jump " + ret);
292                                 stepindex += ret;
293                                 
294                                 if(stepindex >= steps.length)
295                                 {
296                                         log(llDebug, "complete");
297                                         if(Glob.result && Glob.result.match(/POSITIVE/))
298                                         {
299                                                 stderr.write("[OK] Transaction passed.\n");
300                                                 stdout.write(Glob.result + "\n");
301                                                 display_nkm_result(Glob.result);
302                                                 phantom.exit(0);
303                                         }
304                                         else
305                                         {
306                                                 stderr.write("[ERROR] Transaction failed.\n");
307                                                 stderr.write(Glob.result_elem_html_outer + "\n");
308                                                 stderr.write(Glob.result_elem_text_inner + "\n");
309                                                 stderr.write(Glob.result + "\n");
310                                                 display_nkm_result(Glob.result);
311                                                 phantom.exit(5);
312                                         }
313                                 }
314                         }
315                         
316                         setTimeout(worker, timeout);
317                 }               
318                 setTimeout(worker, timeout);
319         }