1import { Actor, log } from 'apify';
2import { BasicCrawler } from 'crawlee';
3import { htmlToText, parseOffersFromPage } from './offers.js';
4
5await Actor.init();
6
7const input = (await Actor.getInput()) ?? {};
8const {
9 hotels = ['Hotel Lisboa, Lisbon'],
10 startDate,
11 numberOfDates = 14,
12 nights = 1,
13 currency = 'USD',
14 language = 'en',
15 country = 'us',
16 includeAllOffers = true,
17 proxyConfiguration: proxyInput,
18} = input;
19
20const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
21const today = new Date(Date.now() + 864e5).toISOString().slice(0, 10);
22const start = startDate || today;
23if (!DATE_RE.test(start)) throw new Error('startDate must be YYYY-MM-DD.');
24const nDates = Math.min(Math.max(Number(numberOfDates) || 14, 1), 365);
25const nNights = Math.min(Math.max(Number(nights) || 1, 1), 30);
26const cur = String(currency || 'USD').toUpperCase().slice(0, 3);
27
28const addDays = (s, d) => new Date(Date.parse(`${s}T00:00:00Z`) + d * 864e5).toISOString().slice(0, 10);
29
30
31const varint = (n) => { const o = []; while (n > 127) { o.push((n & 127) | 128); n >>>= 7; } o.push(n); return o; };
32const ld = (tag, bytes) => [tag, ...varint(bytes.length), ...bytes];
33const dateBytes = (s) => { const [y, m, d] = s.split('-').map(Number); return [0x08, ...varint(y), 0x10, ...varint(m), 0x18, ...varint(d)]; };
34function makeTs(checkIn, checkOut) {
35 const n = Math.round((Date.parse(checkOut) - Date.parse(checkIn)) / 864e5);
36 const dates = [...ld(0x12, [...ld(0x0a, dateBytes(checkIn)), ...ld(0x12, dateBytes(checkOut))]), 0x18, ...varint(n)];
37 const bytes = [0x08, 0x01, ...ld(0x1a, ld(0x12, dates)), ...ld(0x2a, ld(0x0a, ld(0x3a, [...Buffer.from(cur)])))];
38 return Buffer.from(bytes).toString('base64url');
39}
40
41const ENTITY_RE = /\/travel\/hotels\/entity\/(Ch[A-Za-z0-9_-]{15,})/;
42const qp = `hl=${encodeURIComponent(language)}&gl=${encodeURIComponent(country)}`;
43const isBlocked = (body, url) => /\/sorry\//.test(url || '') || /unusual traffic from your computer/i.test(String(body).slice(0, 20000));
44
45const proxyConfiguration = await Actor.createProxyConfiguration(proxyInput ?? { useApifyProxy: true });
46
47const hotelList = (Array.isArray(hotels) ? hotels : [hotels]).map((h) => String(h || '').trim()).filter(Boolean);
48if (!hotelList.length) throw new Error('Add at least one hotel name or Google Hotels URL to "hotels".');
49
50let budgetReached = false;
51
52const crawler = new BasicCrawler({
53 maxConcurrency: 8,
54 maxRequestRetries: 2,
55 requestHandlerTimeoutSecs: 60,
56 useSessionPool: true,
57 async requestHandler({ request, sendRequest, crawler: c }) {
58 if (budgetReached) return;
59 const { kind } = request.userData;
60 const proxyUrl = await proxyConfiguration?.newUrl(request.userData.session ?? undefined);
61 const res = await sendRequest({ url: request.url, proxyUrl, headers: { 'accept-language': `${language},en;q=0.8` } });
62 const body = res.body;
63 if (isBlocked(body, res.url)) {
64 throw new Error('Google temporarily blocked this request (CAPTCHA page). Retrying with a different connection; CAPTCHAs are never solved.');
65 }
66
67 if (kind === 'resolve') {
68 const { query } = request.userData;
69 const id = (query.match(ENTITY_RE) || body.match(ENTITY_RE) || [])[1];
70 if (!id) {
71 log.warning(`Hotel not found on Google Hotels: "${query}"`);
72 await Actor.pushData({ query, error: 'Hotel not found on Google Hotels. Try adding the city, e.g. "Hotel Lisboa, Lisbon".' });
73 return;
74 }
75 const reqs = [];
76 for (let i = 0; i < nDates; i += 1) {
77 const checkIn = addDays(start, i);
78 const checkOut = addDays(checkIn, nNights);
79 reqs.push({
80 url: `https://www.google.com/travel/hotels/entity/${id}/prices?ts=${makeTs(checkIn, checkOut)}&${qp}`,
81 uniqueKey: `${id}|${checkIn}|${checkOut}|${cur}`,
82 userData: { kind: 'prices', query, entityId: id, checkIn, checkOut },
83 });
84 }
85 await c.addRequests(reqs);
86 return;
87 }
88
89
90 const { query, entityId, checkIn, checkOut } = request.userData;
91 const text = htmlToText(body);
92 const { offers, typicalPriceRange } = parseOffersFromPage(text);
93 const hotelName = (body.match(/<title>([^<]+?)\s*-\s*Google hotels<\/title>/i) || [])[1] ?? null;
94 const address = (body.match(/hotel address is ([^"<]+)/) || [])[1] ?? null;
95 const priced = offers.filter((o) => o.price != null).map((o) => ({ ...o, currency: cur }));
96 const lowest = priced.reduce((m, o) => (!m || o.price < m.price ? o : m), null);
97 const official = priced.find((o) => o.isOfficialSite) ?? null;
98 const item = {
99 query,
100 hotelName,
101 address,
102 checkIn,
103 checkOut,
104 nights: nNights,
105 currency: cur,
106 available: priced.length > 0,
107 lowestPrice: lowest?.price ?? null,
108 lowestPriceProvider: lowest?.provider ?? null,
109 officialSitePrice: official?.price ?? null,
110 offersCount: priced.length,
111 typicalPriceRange,
112 offers: includeAllOffers ? priced : undefined,
113 googleHotelUrl: `https://www.google.com/travel/hotels/entity/${entityId}`,
114 scrapedAt: new Date().toISOString(),
115 };
116 const charge = await Actor.pushData(item, 'price-date');
117 if (charge?.eventChargeLimitReached) {
118 budgetReached = true;
119 log.info('Maximum charge for this run reached. Stopping.');
120 await c.autoscaledPool?.abort();
121 }
122 },
123 failedRequestHandler({ request, error }) {
124 log.error(`Failed ${request.userData.kind} for "${request.userData.query}" ${request.userData.checkIn ?? ''}: ${error?.message}`);
125 },
126});
127
128await crawler.run(hotelList.map((h) => ({
129 url: ENTITY_RE.test(h) ? `https://www.google.com/travel/hotels/entity/${h.match(ENTITY_RE)[1]}?${qp}` : `https://www.google.com/travel/search?q=${encodeURIComponent(h)}&${qp}`,
130 uniqueKey: `resolve|${h}`,
131 userData: { kind: 'resolve', query: h },
132})));
133
134await Actor.exit();