UNPKG

14.6 kBJavaScriptView Raw
1/*
2HOTELPARTNER
3Autor: HotelPartner
4Author's note: “Clean code always looks like it was written by someone who cares.” ― Robert C. Martin,
5
6Date: 16.08.2017
7Version: 2.0
8Notes: Make sure that the hostname is correct!
9
10 ===============================
11
12 */
13
14//LIBARIES
15const parseString = require('xml2js').parseString;
16
17//HP LIBARIES
18const _HP = require("./classHotels.js");
19const _SERVER = require("./server.js");
20const slave = _SERVER.os.hostname().replace('slave','');
21
22let currentip = '0.0.0.0';
23let errjobcounter = 0;
24let client;
25let mobile;
26let hostip;
27let hostport;
28
29const hp_bot = {
30 "init":function init() {
31 setTimeout(async function(){
32 const newjob = await hp_bot.job.getNewJob();
33
34 if(mobile==-1)
35 hp_bot.bot.standart(newjob);
36 else
37 hp_bot.bot.mobile(newjob);
38 },800)
39 },
40 "constructor":function JOB(_mobile=-1,_client='WDS',_host='192.168.56.1',_port='88') {
41
42 mobile = _mobile;
43 client = _client;
44 hostip = _host;
45 hostport = _port;
46
47 //START SERVER
48 _SERVER.start();
49 },
50 job:{
51 'getNewJob':function getNewJob(rebootOnError=true) {
52 console.log("");
53 console.log("GETTING NEW JOB FROM DB... CLIENT:" +client );
54 let data = "";
55
56 return new Promise(resolve=>{
57 _SERVER.http.get('http://www.yieldagent.ch/relay/cityov/requestJobV8.php?version=2217&client='+client, function(res) {
58 if (res.statusCode >= 200 && res.statusCode < 400)
59 {
60 res.on('data', function(data_) { data += data_.toString(); });
61 res.on('end', function() {
62 parseString(data, function (err, result) {
63
64 if(result){
65 let ids = [];
66 let city =result.Request.CityConfig[0].URLArguments[0];
67 city = city.split(';city=');
68 city.shift();
69 city.forEach(t=>{
70 t=t.substr(0,t.indexOf(';'))
71 ids.push(t)
72 })
73 let job = {
74 "id" :result.Request.CityConfig[0].CityID[0],
75 "cityid" :ids,
76 "name" :result.Request.CityConfig[0].CityName[0],
77 "dates" :result.Request.Dates[0].Date,
78 "job" :result.Request.JobID[0]
79 }
80 resolve(job)
81 }
82
83 if(err){
84 console.log(err)
85 _SERVER.reboot();
86 }
87
88 });
89 });
90 }
91 }).on('error',
92 function(err) {
93
94 //Handle error
95 console.log("Error while fetching new Job");
96 let hosturl = 'http://'+hostip+':'+hostport;
97 _SERVER.fetch(hosturl+'/newip?gateway='+slave+'&client='+client+'&job=-1');
98
99 //Reboot or get new ip
100 setTimeout(()=>{
101 if(errjobcounter >=3 && rebootOnError == true)
102 _SERVER.fetch(hosturl+'/reboot?gateway='+slave+'&client='+client+'&job=error');
103 else
104 _SERVER.fetch(hosturl+'/newip?gateway='+slave+'&client='+client).then(newIP=>{
105 hp_bot.job.getNewJob();
106 })
107
108 errjobcounter++;
109 },30000)
110 }
111 );
112 })
113
114 },
115 'nextJob' : async function nextJob(callback) {
116 const newjob = await hp_bot.job.getNewJob();
117 callback(newjob);
118 }
119 },
120 bot:{
121 "mobile" :async function startMobileJob(arg) {
122 let isfetching = true;
123 console.log("->Fetching Mobile Version");
124
125 //IF NO CITY ID go to NEXT JOB
126 if(arg.cityid[0]=='' || !arg.cityid[0])
127 {
128 nextJob(startMobileJob);
129 return
130 }
131
132 console.log("JOB FOUND:");
133 currentip = await _SERVER.showExternalIP(false)
134 console.log(arg);
135 console.log("=====================");
136 console.log("Current IP: " + currentip);
137
138 let city = arg.name.replace(" ", '+');
139 let icity = 0;
140 let countcity = arg.cityid.length;
141
142 let idate = 0;
143 let countdate = arg.dates.length;
144
145
146 nextCityId();
147 function nextCityId() {
148 //Check if we have made all CityID
149 if(icity==countcity && isfetching){
150 console.log("Job Done");
151 console.log(JSON.stringify(_HP.hotels.Booking));
152 hp_bot.job.nextJob(startMobileJob);
153 }
154 //Start fetching next CityID
155 if(icity<countcity)
156 {
157 idate=0;
158 nextDate(arg.cityid[icity])
159 icity++;
160 }
161
162 }
163 function nextDate(cityid) {
164 //Clear after new date
165 _HP.hotels.Booking = [];
166 const start = arg.dates[idate];
167 fetchIphoneXMLData(1,start,city,cityid);
168 idate++;
169 }
170 function fetchIphoneXMLData(adult,start,city,cityid) {
171 return new Promise(resolve=>{
172
173 const end = _SERVER.time(start).add(1, 'day').format('YYYY-MM-DD');
174 const devid = hp_bot.general.generateDeviceID();
175 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}`;
176 const options = {
177 headers: {
178 'Content-Type' : 'application/x-www-form-urlencoded',
179 'Authorization': 'Basic dGhlc2FpbnRzYnY6ZGdDVnlhcXZCeGdN'
180 },
181 url: _url,
182 timeout: 900000
183 };
184
185 _SERVER.request(options, function (err, resp, body) {
186 const allresult = JSON.parse(body);
187 _HP.methods.Booking.parsemobile(allresult.result,adult,start,end,city,cityid).then(isok=>{
188
189 //go to next adult
190 if(isok==1||isok=='1'){
191 fetchIphoneXMLData(2,start,city,cityid);
192 }
193
194 //got to next date
195 //send result to server
196 if(isok==2||isok=='2')
197 {
198 //next cityid
199 if(idate==countdate){
200 nextCityId()
201 }
202
203 //next cityid
204 if(idate<countdate){
205 //send job
206 _HP.methods.general.generateUrl(_HP.hotels.Booking,arg.job,arg.id,start,slave)
207
208 //Go to Nekt Date
209 console.log("=> going to next date: "+idate);
210 nextDate(cityid)
211 }
212 }
213
214 //Get new IP Address
215 if(isok==0||isok=='0'){
216 //standart IP: 192.168.56.1
217 getNewIP(adult,start,city,cityid);
218 hp_bot.general.getNewIP().then(gotNewIP=>{
219 fetchIphoneXMLData(adult,start,city,cityid);
220 })
221 }
222 })
223 })
224
225 })
226 }
227
228
229 },
230 "standart":function startSeleniumJOB(arg) {
231 console.log("->Selenium Version")
232 getNewJob().then(arg => {
233 console.log("JOB FOUND:");
234 console.log(arg);
235 console.log("=====================")
236 _SERVER.showExternalIP().then(ip=>{
237 currentip=ip;
238 let count = 0;
239 /*TODO: remove timeouts*/
240 arg.cityid.forEach(function (cityid, i) {
241 setTimeout(function () {
242 console.log("SELENIUM IS CURRENTLY DISABLED, USE MOBILE");
243 /*
244 arg.dates.forEach(function (start, index) {
245 setTimeout(function () {
246 let room = 1;
247 let adult = 1;
248 let child = 1;
249
250 const end = _SERVER.time(start).add(1, 'day').format('YYYY-MM-DD');
251 const options = {
252 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}`,
253 timeout: 900000
254 }
255
256 _SERVER.request(options, function (err, resp, body) {
257 console.log("req done "+count)
258 console.log(body);
259 count++;
260 if(count>=7){
261 startJOB();
262 count =0;
263 }
264 })
265 }, 55500 * index + 1);
266 })
267 */
268 }, 85000 * i + 1 * arg.cityid.length)
269 })
270 });
271 });
272 }
273 },
274 general:{
275 "generateDeviceID":function gerateDeviceID() {
276 //
277 let nr1 = Math.floor((Math.random() * 9999) + 1000);
278 let nr2 = Math.floor((Math.random() * 9999) + 1000);
279 let nr3 = Math.floor((Math.random() * 1) + 10);
280
281 return `72331403-${nr1}-${nr2}-${nr3}`
282 },
283 "getNewIP": function getNewIP(){
284 return new Promise(resolve=>{
285 console.log("OPS........... IP got blocked");
286 console.log('old ip: '+currentip)
287 const hosturl='http://'+hostip+':'+hostip+'/newip?gateway='+slave+'&client='+client+'&job='+arg.id;
288 _SERVER.fetch(hosturl).then(ok=>{
289 setTimeout(()=>{
290 _SERVER.showExternalIP().then(ip=>{
291 if(!ip)
292 setTimeout(()=>{
293 hp_bot.general.getNewIP();
294 },60000)
295 else{
296 console.log("new ip:"+ip)
297 resolve()
298 }
299 });
300
301 },3500)
302 })
303
304 })
305 }
306 }
307}
308
309
310//EXPORT
311hp_bot.constructor.prototype.start = hp_bot.init
312hp_bot.constructor.prototype.getNewJob = hp_bot.job.getNewJob;
313
314module.exports = hp_bot.constructor;
\No newline at end of file