UNPKG

12 kBJavaScriptView Raw
1/*
2HOTELPARTNER
3Name: Weslley De Souza
4Date: 16.08.2017
5Version: 1.0
6Notes: Entry Point
7
8CHANGELOG:
9
10 */
11
12//Library's
13const _HP = require("./classHotels.js");
14const _SERVER = require("./server.js");
15const parseString = require('xml2js').parseString;
16
17//START SERVER
18_SERVER.start();
19
20//GET PARAMETERS
21let currentip = '0.0.0.0';
22const hasclient = process.argv.indexOf('-client');
23const hasmobile = process.argv.indexOf('-mobile');
24const client = hasclient>=0? process.argv[hasclient+1] :'WDS';
25const slave = _SERVER.os.hostname().replace('slave','');
26let errjobcounter =0;
27
28function getNewJob() {
29 console.log("");
30 console.log("GETTING NEW JOB FROM DB... CLIENT:" +client );
31 let data = "";
32
33 return new Promise(resolve=>{
34 _SERVER.http.get('http://www.yieldagent.ch/relay/cityov/requestJobV8.php?version=2217&client='+client, function(res) {
35 if (res.statusCode >= 200 && res.statusCode < 400)
36 {
37 res.on('data', function(data_) { data += data_.toString(); });
38 res.on('end', function() {
39 parseString(data, function (err, result) {
40
41 if(result){
42 let ids = [];
43 let city =result.Request.CityConfig[0].URLArguments[0];
44 city = city.split(';city=');
45 city.shift();
46 city.forEach(t=>{
47 t=t.substr(0,t.indexOf(';'))
48 ids.push(t)
49 })
50 let job = {
51 "id" :result.Request.CityConfig[0].CityID[0],
52 "cityid" :ids,
53 "name" :result.Request.CityConfig[0].CityName[0],
54 "dates" :result.Request.Dates[0].Date,
55 "job" :result.Request.JobID[0]
56 }
57 resolve(job)
58 }
59
60 if(err){
61 console.log(err)
62 _SERVER.reboot();
63 }
64
65 });
66 });
67 }
68 }).on('error', function(err) {
69 // Handle error
70 console.log("Error while fetching new Job");
71 let hosturl = 'http://192.168.56.1:88/newip?gateway='+slave+'&client='+client+'&job=-1';
72 _SERVER.fetch(hosturl)
73 setTimeout(()=>{
74 if(errjobcounter >=3)
75 {
76 let hosturl = 'http://192.168.56.1:88/reboot?gateway='+slave+'&client='+client+'&job=error';
77 _SERVER.fetch(hosturl)
78 }
79 else
80 {
81 const hosturl='http://192.168.56.1:88/newip?gateway='+slave+'&client='+client;
82 _SERVER.fetch(hosturl).then(newIP=>{
83 getNewJob();
84 })
85 }
86 errjobcounter++;
87 },30000)
88 });
89 })
90
91}
92function startSeleniumJOB() {
93 console.log("->Selenium Version")
94 getNewJob().then(arg => {
95 console.log("JOB FOUND:");
96 console.log(arg);
97 console.log("=====================")
98 _SERVER.showExternalIP().then(ip=>{
99 currentip=ip;
100 let count = 0;
101 /*TODO: remove timeouts*/
102 arg.cityid.forEach(function (cityid, i) {
103 setTimeout(function () {
104 console.log("SELENIUM IS CURRENTLY DISABLED, USE MOBILE");
105 /*
106 arg.dates.forEach(function (start, index) {
107 setTimeout(function () {
108 let room = 1;
109 let adult = 1;
110 let child = 1;
111
112 const end = _SERVER.time(start).add(1, 'day').format('YYYY-MM-DD');
113 const options = {
114 url: 'http://' + _SERVER.config.ip + ':' + _SERVER.config.port + `/all?id=${cityid.replace('city=', '').replace('|si=ai%2Cco%2Cci%2Cre%2Cdi', '')}&place=${arg.name.replace(" ", '+')}&startdate=${start}&enddate=${end}&room=${room}&adult=${adult}&child=0&job=${arg.job}&dbid=${arg.id}`,
115 timeout: 900000
116 }
117
118 _SERVER.request(options, function (err, resp, body) {
119 console.log("req done "+count)
120 console.log(body);
121 count++;
122 if(count>=7){
123 startJOB();
124 count =0;
125 }
126 })
127 }, 55500 * index + 1);
128 })
129 */
130 }, 85000 * i + 1 * arg.cityid.length)
131 })
132 });
133 });
134 }
135function startMobileJob() {
136 console.log("->Mobile Version")
137 let isfetching = true;
138 getNewJob().then(arg => {
139 if(arg.cityid[0]=='' || !arg.cityid[0])
140 {
141 getNewJob();
142 return
143 }
144
145 console.log("JOB FOUND:");
146 _SERVER.showExternalIP(false).then(ip=>{
147
148 currentip = ip;
149 console.log(arg);
150 console.log("=====================")
151 console.log("Current IP: " + currentip)
152
153 let city = arg.name.replace(" ", '+');
154
155 let icity = 0;
156 let countcity = arg.cityid.length;
157
158 let idate = 0;
159 let countdate = arg.dates.length;
160
161
162 nextCityId();
163 function nextCityId() {
164 if(icity==countcity && isfetching){
165 console.log("Job Done")
166 console.log(JSON.stringify(_HP.hotels.Booking))
167 startMobileJob();
168 }
169 if(icity<countcity)
170 {
171 idate=0;
172 nextDate(arg.cityid[icity])
173 icity++;
174 }
175
176 }
177 function nextDate(cityid) {
178 //Clear after new date
179 _HP.hotels.Booking = [];
180 const start = arg.dates[idate];
181 fetchIphoneXMLData(1,start,city,cityid);
182 idate++;
183 }
184
185
186 function fetchIphoneXMLData(adult,start,city,cityid) {
187 return new Promise(resolve=>{
188
189 const end = _SERVER.time(start).add(1, 'day').format('YYYY-MM-DD');
190 const devid = gerateDeviceID();
191 const _url = `https://iphone-xml.booking.com/json/bookings.getHotelAvailabilityMobile?detail_level=1&genius_freebies=2&show_distance_cc=1&request_less_fields=2&show_facilities_review_score=1&show_last_minute_saving=1&include_translations=2&add_bh_info=1&languagecode=de&urgency=1&include_taxes=1&include_count=1&location_source=autocomplete&show_price_trend=1&show_deals=flash%2Clastm%2Csmart%2Cgenius&children_qty=0&low_av_alternatives=0&&&order_by=popularity&show_if_class_is_estimated=1&show_categories=v3&show_location_score=1&show_last_reservation_text=1&show_reinforcement_text=v2&show_filtered_facilities=1&show_if_no_cc_allowed=2&show_soldout=1&show_is_personalized_result=0&show_flash_saving=1&max_persons=-2&use_direct_payment=1&add_ctrip_info=1&include_rack_rate_savings=1&&include_url=1&bh_alt_urgency_msg=1&show_refundable=1&check_price_is_final=1&show_extra_charges=1&room_qty=1&show_if_city_center=1&available_rooms=0&price_buckets=100&flash_deals_amount_if_unsigned=2&show_low_availability=2&show_business_badge=1&autoextend=1&affiliate_id=337862&user_os=6.0.1&user_version=11.3.1-android&network_type=wifi&bt=1&arrival_date=${start}&departure_date=${end}&city_ids=${cityid.replace('city=', '').replace('|si=ai%2Cco%2Cci%2Cre%2Cdi', '')}&rows=5000&device_id=${devid}da-ef8edab1ad7f&guest_qty=${adult}`;
192 const options = {
193 headers: {
194 'Content-Type': 'application/x-www-form-urlencoded',
195 'Authorization': 'Basic dGhlc2FpbnRzYnY6ZGdDVnlhcXZCeGdN'
196 },
197 url: _url,
198 timeout: 900000
199 };
200
201 _SERVER.request(options, function (err, resp, body) {
202 const allresult = JSON.parse(body);
203 _HP.methods.Booking.parsemobile(allresult.result,adult,start,end,city,cityid).then(isok=>{
204
205 //go to next adult
206 if(isok==1||isok=='1'){
207 fetchIphoneXMLData(2,start,city,cityid);
208 }
209 //got to next date
210 //send result to server
211 if(isok==2||isok=='2'){
212
213 if(idate==countdate){
214 nextCityId()
215 }
216 if(idate<countdate){
217 //send job
218 _HP.methods.general.generateUrl(_HP.hotels.Booking,arg.job,arg.id,start,slave)
219
220 //Go to Nekt Date
221 console.log("=> going to next date: "+idate);
222 nextDate(cityid)
223 }
224 }
225
226 //Got new IP Address
227 if(isok==0||isok=='0'){
228 //standart IP: 192.168.56.1
229 getNewIP(adult,start,city,cityid);
230
231 }
232 })
233 })
234
235 })
236 }
237 function getNewIP(adult,start,city,cityid) {
238 console.log("OPS........... IP got blocked");
239 console.log('old ip:')
240 console.log(currentip)
241 try{
242 const hosturl='http://192.168.56.1:88/newip?gateway='+slave+'&client='+client+'&job='+arg.id;
243 _SERVER.fetch(hosturl).then(newIP=>{
244 console.log("new ip:")
245 setTimeout(()=>{
246 _SERVER.showExternalIP().then(ip=>{
247 if(!ip)
248 setTimeout(()=>{
249 getNewIP(adult,start,city,cityid);
250 },60000)
251 });
252 fetchIphoneXMLData(adult,start,city,cityid)
253 },3000)
254 })
255 }
256 catch(SyntaxError)
257 {
258 console.error(SyntaxError)
259 console.error("Restarting..")
260 isfetching = false; //prevent loop and wait
261 setTimeout(()=>{
262 startMobileJob();
263 },220000)
264
265 }
266 }
267 });
268 })
269
270}
271function gerateDeviceID() {
272 //
273 let nr1 = Math.floor((Math.random() * 9999) + 1000);
274 let nr2 = Math.floor((Math.random() * 9999) + 1000);
275 let nr3 = Math.floor((Math.random() * 1) + 10);
276
277 return `72331403-${nr1}-${nr2}-${nr3}`
278}
279
280
281setTimeout(()=>{
282
283 if(hasmobile==-1)
284 startSeleniumJOB();
285
286 else
287 startMobileJob()
288
289},800);