UNPKG

39.3 kBJavaScriptView Raw
1/*
2Name: Weslley De Souza
3Date: 16.08.2017
4Version: 1.0
5Notes: STRICT MODE
6
7CHANGELOG:
8
9 */
10'use strict';
11
12//Libraries
13const _driver = require('selenium-webdriver');
14const webdriver = require('selenium-webdriver');
15const By = require('selenium-webdriver').By;
16const until = require('selenium-webdriver').until;
17
18const moment = require('moment');
19var request = require('request');
20
21//Spooky Library
22try {
23 var Spooky = require('spooky');
24}
25catch (e) {
26 //npm i tiny-jsonrpc
27 var Spooky = require('../lib/spooky');
28}
29
30//Database connection
31/*
32const mysql = require('mysql2');
33const connection = mysql.createConnection({
34 host: '192.168.254.75',
35 user: 'wds',
36 password:'SAS7Ukku',
37 database: 'hotelpartner'
38});
39*/
40const connection = null;
41
42//###Variables
43var ISFETCHING = false;
44const joburls = {
45 "Booking":[]
46};
47const skipjobs = {
48 "Booking":[]
49};
50const hotellist = {
51 "Trivago":[],
52 "Booking":[],
53 "Hrs":[],
54 "expedia":[],
55 "compared":{
56 "Booking":[],
57 }
58};
59const bewertung = ["Gut","Fabelhaft","Hervorragend"]
60
61
62//###Classes
63class Hotel{
64
65 constructor(name=null, price1=null,price2=null, place=null, stars=null, rating=null, people=null, cancellation=null, peopleview=null, roomleft=null, inclusive=null, start=null, end=null, site=null) {
66
67 //ref
68 this.name = name;
69 this.place = place;
70 this.rating = rating;
71 this.price1 = price1;
72 this.price2 = price2;
73 this.people = people;
74 this.stars = stars;
75 this.roomleft = roomleft;
76 this.peopleview = peopleview;
77 this.cancellation = cancellation;
78 this.inclusive = inclusive;
79 this.site = site;
80 this.datestart = start;
81 this.dateend = end;
82 this.img = null;
83
84 //as obj
85 const obj = { };
86 Object.setPrototypeOf(obj, Hotel.prototype);
87 obj.name = name;
88 obj.place = place;
89 obj.stars = stars;
90 obj.rating = rating;
91 obj.price1 = price1;
92 obj.price2 = price2;
93 obj.people = people;
94 obj.roomleft = roomleft;
95 obj.peopleview = peopleview;
96 obj.cancellation = cancellation;
97 obj.inclusive = inclusive;
98 obj.site = site;
99 obj.datestart = start;
100 obj.dateend = end;
101 obj.img = null;
102
103 return obj
104
105 }
106
107 toString() {
108 return `${this.name} | ${this.place} | ${this.rate} | ${this.price} | ${this.site}`
109 }
110
111 print () {
112 console.log( this.toString() );
113 }
114
115 printToURL() {
116 let _url = `{"Name":"${this.name}","Street":"","City":"${this.place}","Stars":"${this.stars}","Rating":"${this.rating}","Preferred":"0","LastBooking":"0","Success":"0","Values":{"${this.datestart}":"${this.price1};${this.price2};0;0;0;0"}}`;
117 return _url;
118 }
119 }
120
121
122//###Functions
123
124
125/**
126 * Fetch BookingCOM
127 *
128 * return hotellist.Booking
129 */
130function getBooking(destid,place,start,end,room=1,adlt=1,child=0,nextpage=false,job,dbid) {
131
132 let adult = adlt;
133 const startdate = moment(start);
134 const enddate = moment(end);
135
136 let totadd = 0;
137 var pageoffset = 0;
138 let page = 0;
139
140
141 const dt= startdate.format('YYYY-MM-DD');
142 const city = {
143 name:place,
144 id:destid,
145 values:[]
146 }
147
148 //add new destID
149 let cityindex = hotellist.Booking.findIndex(b=>b.id==destid);
150
151 if(cityindex==-1)
152 hotellist.Booking.push(city);
153
154 //add new date
155 cityindex = hotellist.Booking.findIndex(b=>b.id==destid)
156 const dateindex = hotellist.Booking[cityindex].values.findIndex(b=>b.date==dt)
157
158 if(dateindex>=0)
159 hotellist.Booking[cityindex].values[dateindex].values = [];
160 else
161 hotellist.Booking[cityindex].values.push({
162 'date':dt,
163 values:[]
164 })
165
166
167 console.log(`https://www.booking.com/searchresults.de.html?src=index&dest_type=city&dest_id=${destid}&ssne=${place}&ssne_untouched=${place}&ss=${place}&checkin_monthday=${startdate.format('DD')}&checkin_year_month=${startdate.format('YYYY-M')}&checkout_monthday=${enddate.format('DD')}&checkout_year_month=${enddate.format('YYYY-M')}&ci_date=${startdate.format('YYYY-MM-DD')}&co_date=${enddate.format('YYYY-MM-DD')}&room=${room}&no_rooms=${room}&group_adults=${adult}&group_children=${child};unchecked_filter=out_of_stock%20;nflt=;unchecked_filter=out_of_stock&selected_currency=hotel_currency&changed_currency=1`)
168 return new Promise(function (resolve) {
169 // Prevent multiple Fetch
170 //if(ISFETCHING){resolve(false);return};
171 //ISFETCHING= true;
172
173 //**recursive Function**
174 //function will be called while there is a next button on the page
175 function getData() {
176
177 //let url = `https://www.booking.com/searchresults.de.html?l&checkin_monthday=${startdate.format('DD')}&checkin_year_month=${startdate.format('YYYY-M')}&checkout_monthday=${enddate.format('DD')}&checkout_year_month=${enddate.format('YYYY-M')}&ci_date=${startdate.format('YYYY-MM-DD')}&co_date=${enddate.format('YYYY-MM-DD')}&room1=A%2CA&no_rooms=1&group_adults=${adult}&group_children=${child}&ss_raw=${place}&ac_position=0&dest_id=${destid}&dest_type=city&search_pageview_id=b70c6c0a3fea0249&search_selected=true&search_pageview_id=b70c6c0a3fea0249&ac_suggestion_list_length=5&ac_suggestion_theme_list_length=0&nflt=;unchecked_filter=out_of_stock&selected_currency=hotel_currency&changed_currency=1`
178 let url = `https://www.booking.com/searchresults.de.html?src=index&dest_type=city&dest_id=${destid}&ssne=${place}&ssne_untouched=${place}&ss=${place}&checkin_monthday=${startdate.format('DD')}&checkin_year_month=${startdate.format('YYYY-M')}&checkout_monthday=${enddate.format('DD')}&checkout_year_month=${enddate.format('YYYY-M')}&ci_date=${startdate.format('YYYY-MM-DD')}&co_date=${enddate.format('YYYY-MM-DD')}&room=${room}&no_rooms=${room}&group_adults=${adult}&group_children=${child};unchecked_filter=out_of_stock%20;nflt=;unchecked_filter=out_of_stock&selected_currency=hotel_currency&changed_currency=1`
179 if(nextpage)
180 {
181 pageoffset+=20;
182 url.replace(`&rows=16&offset=${pageoffset}`,'')
183 url += `&rows=16&offset=${pageoffset}`
184 }
185
186 //Create new Instance of Webdrvier and pass CasperJS parameters
187 //Spooky does not support ES6!
188 const spooky = new Spooky({
189
190 pageSettings: {
191 loadImages: false,
192 loadPlugins: false,
193 userAgent: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1588.0 Safari/537.36'
194 },
195 verbose: true,
196 logLevel: "debug",
197 },
198 function (err) {
199 //Mozilla/5.0 (X11; Linux i686; rv:14.0) Gecko/20100101 Firefox/14.0.1 Iceweasel/14.0.1
200 //Chrome/37.0.2062.120
201 spooky.userAgent('Mozilla/5.0 (X11; Linux i686; rv:14.0) Gecko/20100101 Firefox/14.0.1 Iceweasel/14.0.1');
202 spooky.start(url);
203 //Show current page
204 //check for pagination
205 spooky.then(function () {
206 this.emit('currentpage',this.getCurrentUrl())
207 this.scrollTo(1000, 1200);
208 this.emit('pagination', this.evaluate(function () {
209 //get elements
210 var next = document.getElementsByClassName("paging-next");
211 return next[0].innerText
212
213 }));
214
215 });
216 //Get Elements
217 //TODO: If booking changes their classname : change it here
218 spooky.then(function() {
219 //wait for elements to be loaded
220 this.capture('page.png');
221 this.scrollTo(100, 100);
222 this.emit('parse', this.evaluate(function () {
223 var items =null
224 var mystring = "";
225 items = document.getElementsByClassName("sr_item_default");
226 var imgs = document.querySelectorAll('.sr_item_default img');
227 if(items)
228 {
229 for(var i=0; i<items.length;i++)
230 {
231 //add divider to split
232 mystring += items[i].innerText + " \n"+ imgs[i].src+ " "+ "myH0TeL";
233 }
234 }
235 return mystring;
236 }));
237 })
238 //start
239 spooky.run();
240 });
241 spooky.on('pagination', function (text) {
242 if(text=='Nächste Seite')
243 {
244 page++;
245 //console.info("page offset "+ pageoffset)
246 console.info("========================= page: "+ page+" Adult: "+adult+ " Datum:"+ startdate.format('DD.MM.YYYY')+" ========================" )
247 nextpage =true
248 }
249 else {
250 console.info("========================= page: "+ (page+1)+" Adult: "+adult+" ========================" )
251 nextpage = false;
252 }
253
254 });
255 spooky.on('currentpage', function (text) {
256 console.log(" ")
257 // console.info(text)
258
259 });
260 spooky.on('parse', function (text) {
261 let totaddpage = 0;
262
263 if(text)
264 {
265 const hotels = text.split("myH0TeL");
266 console.log("Booking array length: "+hotels.length);
267 hotels.forEach(items=>{
268 const words = items.split("\n");
269 //rabattpreis
270 let lastprice = true;
271
272 const parsedhotel = parseBooking(words/*array*/,lastprice/*aktion price*/,dt,enddate.format('YYYY-MM-DD'),'Booking.com',adult)
273
274 //const
275 const cindex = hotellist.Booking.findIndex(b=>b.id==destid)
276 const dindex = hotellist.Booking[cindex].values.findIndex(b=>b.date==dt)
277 const idx = hotellist.Booking[cindex].values[dindex].values.findIndex(i=>i.name == parsedhotel.name);
278
279
280 if( parsedhotel.name && parsedhotel.price1 && idx == -1)
281 {
282
283 console.log("adding " + parsedhotel.name + " p1:"+parsedhotel.price1)
284 hotellist.Booking[cindex].values[dindex].values.push(parsedhotel);
285
286 totadd++;
287 totaddpage++;
288 }
289 else
290 {
291 if(idx >-1 && parsedhotel.name && adult==2)
292 {
293 hotellist.Booking[cindex].values[dindex].values[idx].price2 = parsedhotel.price2;
294 console.log("update "+parsedhotel.name +" p2:"+parsedhotel.price2)
295 }
296 }
297 });
298 console.log("pagetot: "+totaddpage);
299 console.log("tot: " +totadd);
300 //go to next page or add adult
301 //then exit
302 if(nextpage )
303 {
304 setTimeout(()=>{
305 getData();
306 },200);
307 spooky.destroy();
308 return;
309 }
310 else {
311 if(adult==1)
312 {
313 setTimeout(()=>{
314 nextpage=true;
315 page = 0;
316 adult=2;
317 pageoffset=-20
318 getData();
319 },200);
320
321 spooky.destroy();
322 }
323 else
324 {
325 console.log(">>DONE<<")
326 setTimeout(()=>{
327 ISFETCHING= false;
328 generateUrl(hotellist.Booking,job,dbid,startdate.format('YYYY-MM-DD'));
329 resolve(JSON.stringify(hotellist))
330 },200)
331 spooky.destroy();
332 }
333 }
334 }
335 else
336 {
337 //add adult
338 if(adult==1)
339 {
340 setTimeout(()=>{
341 nextpage=true
342 page = 0;
343 pageoffset=-20;
344 adult=2;
345 getData();
346 },200);
347 spooky.destroy();
348 }
349 //finish
350 else {
351 ISFETCHING= false;
352 console.log("no elements found")
353 console.log(">>DONE<<")
354 generateUrl(hotellist.Booking,job,dbid,startdate.format('YYYY-MM-DD'));
355 resolve(JSON.stringify(hotellist))
356 spooky.destroy();
357 }
358 }
359 });
360 spooky.on('error', function(msg,backtrace) {
361 console.log(msg)
362 });
363 }
364 getData();
365 })
366}
367
368/*bellow getgunctions not testet*/
369function getTrivago(place,room='1',start,end) {
370 let startdate =moment(start)
371 let endtdate =moment(end)
372
373 if(room=='1'){
374 room='RoomType=1'
375 }
376 else {
377 room='RoomType=7'
378 }
379
380 return new Promise(function (resolve) {
381
382 resolve([])
383 return
384 // open selenium
385 var driver = new webdriver.Builder().forBrowser('phantomjs').build();
386 // maximize the window
387 driver.manage().window().maximize();
388 // delete all cookies
389 driver.manage().deleteAllCookies();
390
391 // navigate to Trivago
392 driver.get(`https://www.trivago.ch/`).then(()=> {
393
394 setTimeout(() => {
395 driver.wait(until.titleIs('trivago.ch - Hotelpreisvergleich | Günstige Hotels finden | Hotelsuche')).then(function () {
396 const input = driver.findElement(By.xpath("//*[@id='horus-querytext']"));
397 input.sendKeys(place);
398 input.sendKeys(' ');
399 input.sendKeys(_driver.Key.DOWN);
400 input.sendKeys(_driver.Key.ENTER);
401 }).then(() => {
402 setTimeout(() => {
403 driver.getCurrentUrl().then(function () {
404 return driver.getCurrentUrl();
405 }).then(function (currentUrl) {
406
407 let url = currentUrl.replace('Barr%5D=', 'Barr%5D=' + startdate.format('YYYY-MM-DD')+"&n=").replace('dep%5D=2', 'dep%5D=' + endtdate.format('YYYY-MM-DD')+'nn=').replace('RoomType=',room+'nnn=')
408
409 driver.get(`url`).then(() => {
410
411 driver.wait(until.titleIs('trivago.ch - Hotelpreisvergleich | Günstige Hotels finden | Hotelsuche')).then(function () {
412 setTimeout(()=>{
413 let a;
414 // a = driver.findElements(By.className("item"))
415 // if (a.length == 0)
416 a = driver.findElements(By.className("hotel"))
417
418 a.then(items => {
419 hotellist.Trivago = [];
420 items.forEach(element => {
421 element.getText().then(text => {
422
423 let words = text.split("\n");
424 const myhotel = parseTravago(words,startdate.format('YYYY-MM-DD'),endtdate.format('YYYY-MM-DD'),'Trivago')
425 hotellist.Trivago.push(myhotel)
426
427 });
428
429 })
430 }).then(() => {
431 resolve(JSON.stringify(hotellist))
432 })
433 },1000)
434 })
435
436 });
437 }, 2000)
438 })
439 }, 1000)
440 })
441 })
442
443 })
444}
445function getHrs(place,start,end) {
446 let startdate =moment(start)
447 let endtdate =moment(end)
448 return new Promise(function (resolve) {
449 try {
450 // open selenium
451 var driver = new webdriver.Builder().forBrowser('phantomjs').build();
452 // maximize the window
453 driver.manage().window().maximize();
454 // delete all cookies
455 driver.manage().deleteAllCookies();
456
457 // navigate to hrs
458 driver.get("https://www.hrs.de/");
459
460
461
462 driver.getTitle().then(function(title) {
463 console.log(title)
464 });
465 driver.wait(until.titleIs('HRS - Hotel Reservation Service | Hotel finden und günstige Hotels buchen')).then(function () {
466
467
468 const input = driver.findElement(By.xpath("//*[@id='destiny']"));
469 const von = driver.findElement(By.xpath("//input[@id='start_stayPeriod']"));
470 const bis = driver.findElement(By.xpath("//input[@id='end_stayPeriod']"));
471
472 input.sendKeys(place);
473 input.sendKeys(' ');
474 input.sendKeys(_driver.Key.DOWN);
475 input.sendKeys(_driver.Key.ENTER);
476
477 setTimeout(()=>{
478 von.sendKeys(startdate.format('YYYY.MM.DD'));
479 bis.sendKeys(endtdate.format('YYYY.MM.DD'));
480
481 //Close Calendar
482 input.click();
483 console.log("->")
484
485 const btn = driver.findElement(By.xpath("//*[@id='searchForm']/fieldset[3]/input"));
486 btn.click();
487 },290)
488
489 }).then(()=>{
490
491 setTimeout(()=>{
492 console.log("get hotelTeaserContainer")
493 let a= driver.findElements(By.className("hotelTeaserContainer"));
494 a.then(items=>{
495 console.error(items)
496 hotellist.Hrs=[];
497 let i = 0;
498 items.forEach(element=>{
499 element.getText().then(text=>{
500 driver.executeScript("arguments[0].scrollIntoView()", element);
501 console.log("HRS:")
502 console.log(text)
503
504 //HRS:
505 /*
506 [0]
507 [2] Hotelname
508 [3]
509 [3]
510 [4]
511 [5]
512 [5]
513
514 */
515 try{
516 let words = text.split("\n");
517 let a = new _HP.classes.Hotel(words[2], words[3], words[7], _HP.methods.getPrice(words), "Hrs")
518 hotellist.Hrs.push(a)
519 }catch (UnsupportedOperationError){
520 //super error Handler
521 console.log("ERR <>")
522 }
523
524 });
525 })
526
527 }).then(()=>{
528 resolve(JSON.stringify(hotellist))
529 })
530 },4000)
531 })
532
533 }catch (NoSuchElementError){
534 console.log("HRS Element not Found")
535 resolve(null)
536
537 }
538
539 })
540}
541function getExpedia(place,date=null) {
542 return new Promise(function (resolve) {
543 try {
544 // open selenium
545 var driver = new webdriver.Builder().forBrowser('firefox').build();
546 // maximize the window
547 driver.manage().window().maximize();
548 // delete all cookies
549 driver.manage().deleteAllCookies();
550
551
552 // navigate to Trivago
553 driver.open()
554 driver.get(`https://www.expedia.de/`);
555
556
557 driver.getTitle().then(function(title) {
558 console.log(title)
559 });
560
561 driver.wait(until.titleIs('Billige Flüge, Hotels & Mietwagen buchen | Expedia.de')).then(function () {
562
563 setTimeout(()=>{
564
565 let a= driver.findElements(By.className("listing"))
566 a.then(items=>{
567 hotellist.expedia=[];
568 items.forEach(element=>{
569 element.getText().then(text=>{
570 console.log(text)
571
572 //TRIVAGO:
573 /*
574 [0]
575 [1] Hotelname
576 [2] Ort + Distanz
577 [3] Bewertung 100
578 [4] Kommentartbewertungen
579 [5] Other details
580 [5] Site
581
582 [9] first price
583
584 */
585 let words = text.split("\n");
586 let a = new _HP.classes.Hotel(words[0], words[5], words[4], _HP.methods.getPrice(words), "expedia")
587 hotellist.expedia.push(a)
588 });
589 })
590 }).then(()=>{
591 resolve(JSON.stringify(hotellist))
592 })
593
594 },2900)
595 })
596
597 }catch (NoSuchElementError){
598 console.log(NoSuchElementError)
599 console.log("Element not Found")
600 }
601
602 })
603}
604
605
606
607/**
608 * Parse BookingCOM
609 * @param arrayOfWords required {string array} of all innerHTML Elements
610 * @param firstOrLastPrice *optional {boolean} || true == first price
611 *
612 * return new Hotel Obj
613 */
614function parseBooking(arrayOfWords,firstOrLastPrice=false,start,end,site=null, adult) {
615
616 let counter =0;
617 let i =-2;
618
619 let hotel = new Hotel();
620 hotel.site = site;
621 hotel.datestart = start;
622 hotel.dateend = end;
623 hotel.img = arrayOfWords[arrayOfWords.length-1]
624
625 try{
626 JSON.parse(JSON.stringify(arrayOfWords)).forEach(item=>{
627
628 //Price
629 if( item.toUpperCase().indexOf("CHF")!=-1 ||item.toUpperCase().indexOf("€")!=-1 ){
630 if(! hotel.price1 || firstOrLastPrice || ! hotel.price2){
631 if(adult==2 )
632 {
633 if(item.toUpperCase().indexOf("€")!=-1){
634 hotel.price2 = item.substr(item.indexOf('€')+2,item.length);
635 }
636 else if(item.toUpperCase().indexOf("CHF")!=-1){
637 hotel.price2 = item.substr(item.indexOf('CHF')+4,item.length);
638 }
639 hotel.price2 = hotel.price2.replace(/ /g,'')
640 return;
641 }
642 if(adult==1) {
643 if(item.toUpperCase().indexOf("€")!=-1){
644 hotel.price1 = item.substr(item.indexOf('€')+2,item.length);
645 }
646 else if(item.toUpperCase().indexOf("CHF")!=-1){
647 hotel.price1 = item.substr(item.indexOf('CHF')+4,item.length);
648 }
649 hotel.price1 = hotel.price1.replace(/ /g,'')
650 }
651 }
652 }
653
654
655 //Hotelname
656 let nameindex = item.toUpperCase().indexOf("-STERNE")
657
658 if( nameindex >= 0 && !hotel.name )
659 {
660 hotel.stars = item.substr(nameindex -1, 8).replace('Wird in neuem Fenster geöffnet','').replace('-Sterne','');
661 hotel.name = item.substring(0,nameindex - 2).replace(' Wird in neuem Fenster geöffnet','').replace('"',"").replace('"',"");
662 while(/\s+$/.test(hotel.name))
663 {
664
665 hotel.name = hotel.name.substring(0,hotel.name.length-1)
666 }
667
668 //next item will be place
669 i=counter;
670 }
671
672 /*2 Hotelname*/
673 if(!hotel.name && item.indexOf('Wird in neuem Fenster geöffnet') >=3 )
674 {
675 if(item.length>=20)
676 hotel.name = item.substr(0,item.indexOf(' Wird in neuem Fenster')).replace('"',"").replace('"',"")
677 if(/\s+$/.test(hotel.name))
678 while(/\s+$/.test(hotel.name)){
679 hotel.name = hotel.name.substring(0,hotel.name-1)
680 }
681 }
682
683 //Place
684 if(counter==i+1 || item.indexOf('Auf der Karte anzeigen')>=0 || item.indexOf('In U-Bahn-Nähe')>0 )
685 {
686
687 hotel.place = item.replace(' – Auf der Karte anzeigen','');
688 hotel.place = hotel.place.replace(' – In U-Bahn-Nähe','');
689 hotel.place = hotel.place.replace('– In U-Bahn-Nähe','');
690 if(hotel.place.indexOf('(')>=0)
691 {
692 hotel.place = hotel.place.substr(0, hotel.place.indexOf(' ('))
693 }
694
695 }
696
697 //rating
698 if(!hotel.rating && item.indexOf(',')>=0)
699 {
700 bewertung.forEach(i=>{
701 if(item.toUpperCase().indexOf(i.toUpperCase())>=0)
702 hotel.rating = item.substr(item.length-3,item.length);
703 })
704 }
705
706 //amount left
707 if(!hotel.roomleft && item.indexOf('Nur noch')>=0)
708 {
709 let str = item.indexOf('Zimmer')-2
710 hotel.roomleft = item.substring(str, str+8)
711 }
712
713 //Inclusive
714 if(item.indexOf('inbegriffen')>=0){
715 hotel.inclusive = item;
716 }
717
718 //cancellation
719 if(item.indexOf('Stornierung')>=0){
720 hotel.cancellation = item;
721 }
722
723 //Personenzahl (DOPPELZIMMER)
724 if(item.indexOf('Personenzahl')>=0 || item.indexOf('Personenzahl')>=0){
725 hotel.people = item;
726 }
727
728
729 //remove false elements
730 if(hotel.name)
731 if(hotel.name.indexOf('verfügbaren Zimmer')>=0){
732 hotel.name=null
733 }
734
735
736 counter++;
737
738 })
739 }catch (TypeError){
740 console.error(TypeError)
741 }
742
743 return hotel;
744}
745function parseMobileBooking(arry,adult,start,end,place,destid) {
746 console.log(" ");
747 console.log("start parse ADULT:"+adult)
748
749 const dt= start;
750 const city = {
751 name:place.replace('+'," "),
752 id:destid,
753 values:[]
754 }
755
756
757 //add new destID
758 let cityindex = hotellist.Booking.findIndex(b=>b.id==destid);
759
760 if(cityindex==-1)
761 hotellist.Booking.push(city);
762
763 //add new date
764 cityindex = hotellist.Booking.findIndex(b=>b.id==destid)
765 const dateindex = hotellist.Booking[cityindex].values.findIndex(b=>b.date==dt)
766
767 if(dateindex==-1)
768 hotellist.Booking[cityindex].values.push({
769 'date':dt,
770 values:[]
771 })
772
773
774
775 return new Promise((resolve)=>{
776 let addedtot = 0;
777 let updatettot = 0
778 arry.forEach(hotel=> {
779
780 const parsedhotel = new Hotel();
781 parsedhotel.price = '0.00'
782 parsedhotel.price2 = '0.00'
783
784 parsedhotel.name = hotel.hotel_name;
785 parsedhotel.datestart = start;
786 parsedhotel.dateend = end;
787 parsedhotel.stars = hotel.class;
788 parsedhotel.people = adult;
789 parsedhotel.place = hotel.district;
790 parsedhotel.city = hotel.city;
791 parsedhotel.address = hotel.address;
792 parsedhotel.rating = hotel.facilities_review_score['rating'];
793 parsedhotel.ranking = hotel.ranking;
794 parsedhotel.peopleview = hotel.last_reservation_text;
795 parsedhotel.roomleft = hotel.available_rooms
796 parsedhotel.id = hotel.hotel_id;
797 parsedhotel.district_id = hotel.district_id;
798 parsedhotel.currency_code = hotel.currency_code;
799 parsedhotel.zip = hotel.zip;
800 parsedhotel.hotel_include_breakfast = hotel.hotel_include_breakfast
801 parsedhotel.description = hotel.short_description
802 parsedhotel.preferred = hotel.preferred
803 parsedhotel.latitude = hotel.latitude
804 parsedhotel.longitude = hotel.longitude
805 parsedhotel.geodata = hotel.latitude+','+hotel.longitude
806
807 if(hotel.last_reservation_text){
808 parsedhotel.last_reservation = hotel.last_reservation_text.replace('Letzte Buchung: vor ','').replace(' Stunden','').replace(' Stunde','').replace(' gestern','');;
809 }
810
811 if(parsedhotel.last_reservation){
812
813 if(hotel.last_reservation_text.indexOf('Stunde')>=0)
814 parsedhotel.last_reservation = moment().subtract(parseInt(parsedhotel.last_reservation),'hours').unix();
815
816 if(hotel.last_reservation_text.indexOf('gestern')>=0)
817 parsedhotel.last_reservation = moment().subtract(24,'hours').unix();
818
819 if(hotel.last_reservation_text.indexOf('.')>=0){
820 const startidx = hotel.last_reservation_text.indexOf('.');
821 const monthname = hotel.last_reservation_text.substr(startidx+2,hotel.last_reservation_text.length)
822 const daynr = hotel.last_reservation_text.substr(startidx-2,2)
823 const monthnr = moment().locale("de").month(monthname).format("MM")
824 const year = moment().format('YYYY')
825 const string = `${year}-${monthnr}-${daynr}`
826 parsedhotel.last_reservation = moment(string,'YYYY-MM-DD').unix()
827 }
828
829 }
830
831 parsedhotel.site = 'Booking.com';
832
833
834 //const
835 const cindex = hotellist.Booking.findIndex(b=>b.id==destid)
836 const dindex = hotellist.Booking[cindex].values.findIndex(b=>b.date==dt)
837 const idx = hotellist.Booking[cindex].values[dindex].values.findIndex(i=>i.name == parsedhotel.name);
838
839 if(parsedhotel.name && adult == 1)
840 {
841 parsedhotel.price1 = hotel.min_total_price;
842 // console.log("adding " + parsedhotel.name + " p1:"+parsedhotel.price1)
843 hotellist.Booking[cindex].values[dindex].values.push(parsedhotel);
844 addedtot++;
845
846 }
847 else
848 {
849 if(idx >-1 && parsedhotel.name && adult==2)
850 {
851
852 hotellist.Booking[cindex].values[dindex].values[idx].price2 = hotel.min_total_price;
853 // console.log("update "+parsedhotel.name +" p2:"+hotel.min_total_price)
854 updatettot++;
855 }
856 else
857 {
858
859 parsedhotel.price2 = hotel.min_total_price;
860 // console.log("adding " + parsedhotel.name + " p1:"+parsedhotel.price1)
861 hotellist.Booking[cindex].values[dindex].values.push(parsedhotel);
862 addedtot++;
863 }
864 }
865 });
866
867
868 console.log("========================")
869 console.log("total added "+addedtot)
870 console.log("updatet added "+updatettot)
871 console.log("date " +start)
872 console.log("destid "+destid)
873 console.log("total " +arry.length)
874 console.log(" ")
875 if(arry.length==0){
876 resolve(0);
877 }
878
879 resolve(adult);
880 })
881}
882function parseTravago(arrayOfWords,start,end,site=null){
883
884function getObjectKey(obj, keyToFind) {
885 if(keyToFind.indexOf('CHF')>=0)return null;
886 var i = 0, key;
887
888 for (key in obj) {
889 if (key.toUpperCase().indexOf(keyToFind.toUpperCase())>=0) {
890 return key;
891 }
892
893 i++;
894 }
895 return null;
896 }
897
898 //TRIVAGO:
899 /*
900 [0]
901 [1] name
902 [2] Ort + Distanz
903 [3] Bewertung 100
904 [4] Kommentartbewertungen
905
906 */
907
908const array = JSON.parse(JSON.stringify(arrayOfWords))
909
910 const hotel = new Hotel();
911 hotel.name = array[1];
912 hotel.place = array[2];
913
914
915 hotel.site = site;
916 hotel.datestart = start;
917 hotel.dateend = end;
918
919 let previtem;
920 let counter =0;
921 let i =0;
922 let prices = {
923 "mainprice":null,
924 "Hotelwebseite":"",
925 "Elvoline":"",
926 "Expedia":"",
927 "Booking.com":"",
928 "Hotels.com":"",
929 "HRS.com":"",
930 "Hotel.info":"",
931 "otel.com":"",
932 "Tui.ch":"",
933 "Hotelopia":"",
934 };
935
936 array.forEach(item=>{
937
938 //Price
939 if( item.toUpperCase().indexOf("CHF")!=-1 ){
940
941
942 const index = getObjectKey(prices, previtem.toString().replace(" ","") )
943 if(index!=null)
944 prices[index] = item;
945
946 if(prices.mainprice==null)
947 prices.mainprice = item;
948
949 hotel.price = prices;
950
951 }
952
953 //rating
954 if(item){
955 if(item.length == 2 ){
956 hotel.rating = item;
957 }
958 }
959
960
961 //Inclusive
962 if(item.indexOf('inbegriffen')>=0 ||item.indexOf('Gratis')>=0 ||item.indexOf('Gratis')>=0 ){
963 hotel.inclusive = item;
964 }
965
966
967 counter++;
968 previtem = item;
969
970 })
971
972 return hotel;
973}
974
975
976function generateUrl(array,job,dbid,date,slave=null,send=true){
977
978 let bodyjob={
979 "linkcity":dbid,
980 "destid":array[0].id,
981 "job":{
982 id:job,
983 ez:-1,
984 dz:-1
985 },
986 "cityname":array[0].name,
987 "date":date,
988 "data":array[0].values,
989 "dbid":dbid,
990 "slave":slave
991 };
992
993 sendResult(bodyjob,send)
994 return;
995
996
997 let starturl = '';
998 let endurl = `]&job={"JobID":"${job.toString()}","foundEZ":"-1","foundDZ":"-1""pages":"0"}`;
999
1000 /*
1001 try{
1002 array.forEach(city=>{
1003 const cname =city.name;
1004 const destid =city.id;
1005 city.values.forEach(dates=>{
1006
1007 const cdate =dates.date;
1008 if(skipjobs.Booking.indexOf(cdate)==-1)
1009 {
1010 skipjobs.Booking.push(cdate)
1011 starturl = `city=${dbid}&datumList=["${cdate}"]&los=1&data=[`
1012 dates.values.forEach(h=>{
1013 let hotel = new Hotel();
1014 hotel = h;
1015
1016 values += hotel.printToURL()+`,`
1017 })
1018 }
1019
1020 })
1021
1022 let str = starturl +values.substr(0,values.length-1)+ endurl
1023 sendResult(str,true)
1024
1025
1026 })
1027 }
1028 catch (TypeError)
1029 {
1030 console.error(TypeError)
1031 }
1032*/
1033 return joburls
1034
1035}
1036function sendResult(_body, active=true){
1037 if(!active)return;
1038 //&gateway='+_SERVER.os.hostname().replace('slave','')
1039 console.log("sending data to host")
1040 const reciverurl='http://192.168.56.1:88/sendtestdb';
1041 request.post({
1042 headers: {'content-type' : 'application/x-www-form-urlencoded'},
1043 url: reciverurl,
1044 json: true,
1045 form: {
1046 data: JSON.stringify(_body)
1047 }
1048 },
1049 function(error, response, body){
1050 console.log(body);
1051 });
1052
1053
1054 return;
1055 request.post({
1056 headers: {'content-type' : 'application/x-www-form-urlencoded'},
1057 url: 'http://192.168.56.1:202/api/v1',
1058 body: JSON.stringify(_body)
1059 },
1060 function(error, response, body){
1061 console.log(body);
1062 });
1063
1064
1065}
1066
1067//###Export
1068module.exports ={
1069 "db" :connection,
1070 "hotels" :hotellist,
1071 "jobs" :{
1072 "urls":joburls,
1073 "skip":skipjobs
1074 },
1075 "classes":{
1076 "Hotel":Hotel
1077 },
1078 "methods":{
1079 "general": {
1080 generateUrl:generateUrl
1081 },
1082 "Booking":{
1083 "get":getBooking,
1084 "parse":parseBooking,
1085 "parsemobile":parseMobileBooking
1086
1087 },
1088 "Trivago":{
1089 "get":getTrivago,
1090 "parse":parseTravago
1091 }
1092 },
1093};
1094
1095//###Error Output
1096process.on('uncaughtException', function (error) {
1097 console.log(error.stack);
1098});
1099process.on('TypeError', function (error) {
1100 console.log(error.stack);
1101});
\No newline at end of file