-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackend_val.ts
More file actions
1215 lines (1055 loc) · 45.6 KB
/
backend_val.ts
File metadata and controls
1215 lines (1055 loc) · 45.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** @jsxImportSource npm:react */
import { sqlite } from "https://esm.town/v/std/sqlite";
import * as cheerio from "npm:cheerio";
// -----------------------------------------------------------------------------
// 1. TYPES & INTERFACES
// -----------------------------------------------------------------------------
type DataSource = "realtime" | "manual";
interface CityData {
city_slug: string;
city_name: string;
percentage: number;
current_volume?: number;
total_capacity?: number;
recorded_at?: string;
// Data source info
data_source: DataSource;
data_date?: string; // The actual date the data represents (for manual entries)
}
interface ApiResponse {
last_updated: string;
data: CityData[];
history?: any[]; // For now, we return latest. Can be expanded.
}
// -----------------------------------------------------------------------------
// 2. DATABASE SETUP
// -----------------------------------------------------------------------------
async function setupDatabase() {
await sqlite.execute(`
CREATE TABLE IF NOT EXISTS daily_records (
id INTEGER PRIMARY KEY AUTOINCREMENT,
city_slug TEXT NOT NULL,
city_name TEXT NOT NULL,
percentage REAL NOT NULL,
current_volume REAL,
recorded_at DATETIME DEFAULT CURRENT_TIMESTAMP,
data_source TEXT DEFAULT 'realtime',
data_date TEXT
);
`);
// Add new columns if they don't exist (for existing databases)
try {
await sqlite.execute(`ALTER TABLE daily_records ADD COLUMN data_source TEXT DEFAULT 'realtime'`);
} catch (e) {
// Column already exists, ignore
}
try {
await sqlite.execute(`ALTER TABLE daily_records ADD COLUMN data_date TEXT`);
} catch (e) {
// Column already exists, ignore
}
}
async function insertRecord(data: CityData) {
await sqlite.execute({
sql: `
INSERT INTO daily_records (city_slug, city_name, percentage, current_volume, data_source, data_date)
VALUES (:city_slug, :city_name, :percentage, :current_volume, :data_source, :data_date)
`,
args: {
city_slug: data.city_slug,
city_name: data.city_name,
percentage: data.percentage,
current_volume: data.current_volume || null,
data_source: data.data_source || "realtime",
data_date: data.data_date || null,
},
});
}
async function getLatestRecords(): Promise<CityData[]> {
// Get the most recent record for each city
const result = await sqlite.execute(`
SELECT city_slug, city_name, percentage, current_volume, recorded_at, data_source, data_date
FROM daily_records
WHERE id IN (
SELECT MAX(id)
FROM daily_records
GROUP BY city_slug
)
`);
// Map array rows to objects
return result.rows.map((row: any) => ({
city_slug: row[0],
city_name: row[1],
percentage: row[2],
current_volume: row[3],
recorded_at: row[4],
data_source: row[5] || "realtime",
data_date: row[6] || null,
}));
}
async function getHistoryForCity(citySlug: string, days: number = 30): Promise<CityData[]> {
const result = await sqlite.execute({
sql: `
SELECT city_slug, city_name, percentage, current_volume, recorded_at, data_source, data_date
FROM daily_records
WHERE city_slug = :city_slug
ORDER BY recorded_at DESC
LIMIT :limit
`,
args: { city_slug: citySlug, limit: days }
});
return result.rows.map((row: any) => ({
city_slug: row[0],
city_name: row[1],
percentage: row[2],
current_volume: row[3],
recorded_at: row[4],
data_source: row[5] || "realtime",
data_date: row[6] || null,
}));
}
async function getPreviousDayRecords(): Promise<Map<string, number>> {
// Get yesterday's record for each city (for trend comparison)
const result = await sqlite.execute(`
SELECT city_slug, percentage
FROM daily_records
WHERE DATE(recorded_at) = DATE('now', '-1 day')
GROUP BY city_slug
`);
const map = new Map<string, number>();
for (const row of result.rows as any[]) {
map.set(row[0], row[1]);
}
return map;
}
// -----------------------------------------------------------------------------
// 3. SCRAPERS
// -----------------------------------------------------------------------------
// Proxy services for SSL bypass (try multiple)
const PROXY_SERVICES = [
(url: string) => `https://corsproxy.io/?${encodeURIComponent(url)}`,
(url: string) => `https://api.allorigins.win/raw?url=${encodeURIComponent(url)}`,
(url: string) => `https://proxy.cors.sh/${url}`,
];
// Helper to fetch with headers (mimic browser)
async function fetchHtml(url: string, useProxy = false) {
const headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
};
if (!useProxy) {
const res = await fetch(url, { headers });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.text();
}
// Try each proxy service until one works
for (const proxyFn of PROXY_SERVICES) {
try {
const proxyUrl = proxyFn(url);
const res = await fetch(proxyUrl, { headers });
if (res.ok) {
return res.text();
}
} catch (e) {
// Try next proxy
continue;
}
}
throw new Error(`All proxies failed for ${url}`);
}
// Helper to fetch JSON with proxy support
async function fetchJson(url: string, useProxy = false) {
const headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
"Accept": "application/json",
};
if (!useProxy) {
const res = await fetch(url, { headers });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
// Try each proxy service until one works
for (const proxyFn of PROXY_SERVICES) {
try {
const proxyUrl = proxyFn(url);
const res = await fetch(proxyUrl, { headers });
if (res.ok) {
const text = await res.text();
return JSON.parse(text);
}
} catch (e) {
// Try next proxy
continue;
}
}
throw new Error(`All proxies failed for ${url}`);
}
async function scrapeIstanbul(): Promise<CityData | null> {
// Istanbul (ISKI) - Baraj Doluluk Oranları
// The site uses JavaScript to render content, so we need special approaches
// Approach 1: Try Jina AI reader which renders JavaScript
try {
const jinaUrl = "https://r.jina.ai/https://iski.istanbul/baraj-doluluk/";
const jinaResponse = await fetch(jinaUrl, {
headers: {
"Accept": "text/plain",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
}
});
if (jinaResponse.ok) {
const text = await jinaResponse.text();
// Look for the percentage in the rendered content
// Pattern: "23.93%" or similar
const percentMatch = text.match(/(\d{1,2}[.,]\d{2})\s*%/);
if (percentMatch) {
const percentage = parseFloat(percentMatch[1].replace(",", "."));
if (percentage >= 5 && percentage <= 100) {
console.log(`Istanbul: Found percentage ${percentage}% via Jina`);
return {
city_slug: "istanbul",
city_name: "Istanbul",
percentage: percentage,
data_source: "realtime" as DataSource,
};
}
}
// Also try looking for "doluluk" near a number
const dolulukMatch = text.match(/[Dd]oluluk[^0-9]*?(\d{1,2}[.,]\d{1,2})/i);
if (dolulukMatch) {
const percentage = parseFloat(dolulukMatch[1].replace(",", "."));
if (percentage > 0 && percentage <= 100) {
console.log(`Istanbul: Found percentage ${percentage}% via Jina (doluluk pattern)`);
return {
city_slug: "istanbul",
city_name: "Istanbul",
percentage: percentage,
data_source: "realtime" as DataSource,
};
}
}
}
} catch (error) {
console.error("Istanbul Jina scraper error:", error);
}
// Approach 2: Try WebShare proxy that renders JS
try {
const webShareUrl = `https://api.webshare.io/v2/proxy/render?url=${encodeURIComponent("https://iski.istanbul/baraj-doluluk/")}`;
// This is a placeholder - WebShare requires API key
} catch (error) {
// Skip
}
// Approach 3: Try scraping with different proxy services
const PROXY_URLS = [
`https://api.allorigins.win/raw?url=${encodeURIComponent("https://iski.istanbul/baraj-doluluk/")}`,
`https://corsproxy.io/?${encodeURIComponent("https://iski.istanbul/baraj-doluluk/")}`,
];
for (const proxyUrl of PROXY_URLS) {
try {
const response = await fetch(proxyUrl, {
headers: {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
}
});
if (response.ok) {
const html = await response.text();
const $ = cheerio.load(html);
// Look in script tags for embedded data
const scripts = $('script').toArray();
for (const script of scripts) {
const content = $(script).html() || '';
// Look for JSON data with doluluk/percentage
// Many sites embed initial state as JSON
const jsonMatches = content.matchAll(/\{[^}]*"?(?:doluluk|percentage|oran)"?\s*:\s*"?(\d{1,2}[.,]\d{1,2})"?[^}]*\}/gi);
for (const match of jsonMatches) {
const percentage = parseFloat(match[1].replace(",", "."));
if (percentage >= 5 && percentage <= 100) {
console.log(`Istanbul: Found percentage ${percentage}% in script JSON`);
return {
city_slug: "istanbul",
city_name: "Istanbul",
percentage: percentage,
data_source: "realtime" as DataSource,
};
}
}
// Look for array data like [23.93] or value: 23.93
const valueMatch = content.match(/(?:value|data|doluluk|oran)['":\s]*(\d{1,2}\.\d{2})/i);
if (valueMatch) {
const percentage = parseFloat(valueMatch[1]);
if (percentage >= 5 && percentage <= 100) {
console.log(`Istanbul: Found percentage ${percentage}% in script value`);
return {
city_slug: "istanbul",
city_name: "Istanbul",
percentage: percentage,
data_source: "realtime" as DataSource,
};
}
}
}
// Check body text
const bodyText = $('body').text();
const percentMatch = bodyText.match(/(\d{1,2}[.,]\d{2})\s*%/);
if (percentMatch) {
const percentage = parseFloat(percentMatch[1].replace(",", "."));
if (percentage >= 5 && percentage <= 100) {
console.log(`Istanbul: Found percentage ${percentage}% in body text`);
return {
city_slug: "istanbul",
city_name: "Istanbul",
percentage: percentage,
data_source: "realtime" as DataSource,
};
}
}
}
} catch (error) {
console.error(`Istanbul proxy scraper error for ${proxyUrl}:`, error);
}
}
// Approach 4: Try direct fetch with various headers
const directUrls = [
"https://iski.istanbul/baraj-doluluk/",
"https://www.iski.istanbul/baraj-doluluk/",
];
for (const url of directUrls) {
try {
const response = await fetch(url, {
headers: {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
"Accept-Language": "tr-TR,tr;q=0.9,en;q=0.8",
"Cache-Control": "no-cache",
}
});
if (response.ok) {
const html = await response.text();
const $ = cheerio.load(html);
// Look for inline data or API URLs in the page
const allScripts = $('script').toArray();
for (const script of allScripts) {
const src = $(script).attr('src');
const content = $(script).html() || '';
// Log script sources for debugging
if (src) {
console.log(`Istanbul: Found script src: ${src}`);
}
// Look for API endpoint URLs
const apiMatch = content.match(/["'](\/api\/[^"']+|https?:\/\/[^"']*api[^"']*baraj[^"']*)["']/i);
if (apiMatch) {
console.log(`Istanbul: Found potential API: ${apiMatch[1]}`);
// Try to fetch from this API
try {
const apiUrl = apiMatch[1].startsWith('http') ? apiMatch[1] : `https://iski.istanbul${apiMatch[1]}`;
const apiResponse = await fetch(apiUrl);
if (apiResponse.ok) {
const apiData = await apiResponse.json();
console.log(`Istanbul: API response:`, JSON.stringify(apiData).substring(0, 200));
// Try to extract percentage from API response
const apiText = JSON.stringify(apiData);
const apiPercentMatch = apiText.match(/(\d{1,2}\.\d{2})/);
if (apiPercentMatch) {
const percentage = parseFloat(apiPercentMatch[1]);
if (percentage >= 5 && percentage <= 100) {
return {
city_slug: "istanbul",
city_name: "Istanbul",
percentage: percentage,
data_source: "realtime" as DataSource,
};
}
}
}
} catch (apiError) {
console.error(`Istanbul API fetch error:`, apiError);
}
}
}
}
} catch (error) {
console.error(`Istanbul direct fetch error for ${url}:`, error);
}
}
console.error("Istanbul scraper failed: Could not parse percentage from any source.");
return null;
}
async function scrapeAnkara(): Promise<CityData | null> {
// Ankara (ASKI) uses an ASP.NET AJAX endpoint for date updates.
// URL: https://www.aski.gov.tr/TR/Default.aspx/Counter
const API_URL = "https://www.aski.gov.tr/TR/Default.aspx/Counter";
try {
const response = await fetch(API_URL, {
method: "POST",
headers: {
"Content-Type": "application/json; charset=utf-8",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
},
body: JSON.stringify({}) // Empty body for this specific endpoint
});
if (!response.ok) throw new Error(`HTTP helper error ${response.status}`);
const json = await response.json();
// The API returns { d: "{\"success\":true,\"BarajDegeri\":\"13.95\",\"SonucSu\":\"29,26\",\"sonuc\":\"...\"}" }
// We need to parse the inner JSON string in 'd'.
if (json.d) {
const innerData = JSON.parse(json.d);
// SonucSu contains the actual dam fill percentage, not BarajDegeri
if (innerData.SonucSu) {
return {
city_slug: "ankara",
city_name: "Ankara",
percentage: parseFloat(innerData.SonucSu.replace(",", ".")),
data_source: "realtime" as DataSource,
};
}
}
console.error("Ankara scraper failed: API response structure changed.", json);
return null;
} catch (error) {
console.error("Ankara scraper error:", error);
return null;
}
}
async function scrapeIzmir(): Promise<CityData | null> {
// Izmir (IZSU) - Multiple URL attempts
// Note: Main IZSU site requires e-Devlet auth, trying alternative approaches
const URLS = [
"https://www.izsu.gov.tr/",
"https://www.izsu.gov.tr/tr/Kurumsal/1",
];
for (const url of URLS) {
try {
const headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "tr-TR,tr;q=0.9,en;q=0.8",
"Cookie": "AspxAutoDetectCookieSupport=1",
};
const res = await fetch(url, {
headers,
redirect: "manual" // Don't follow redirects automatically
});
// Handle redirect manually if needed
if (res.status >= 300 && res.status < 400) {
const location = res.headers.get("Location");
if (location) {
const redirectRes = await fetch(location.startsWith("http") ? location : `https://www.izsu.gov.tr${location}`, { headers });
if (!redirectRes.ok) continue;
const html = await redirectRes.text();
const $ = cheerio.load(html);
const bodyText = $('body').text();
// Look for percentage patterns
const match = bodyText.match(/(?:Doluluk|Baraj)[^0-9]*?(\d{1,2}[.,]\d{1,2})\s*%/i);
if (match) {
const percentage = parseFloat(match[1].replace(",", "."));
if (percentage > 0 && percentage <= 100) {
return { city_slug: "izmir", city_name: "Izmir", percentage, data_source: "realtime" as DataSource };
}
}
}
continue;
}
if (!res.ok) continue;
const html = await res.text();
const $ = cheerio.load(html);
const bodyText = $('body').text();
// Strategy 1: Look for doluluk/baraj percentage patterns
const patterns = [
/(?:Doluluk|Baraj)[^0-9]*?(\d{1,2}[.,]\d{1,2})\s*%/i,
/(?:Toplam|Genel)[^0-9]*?%?\s*(\d{1,2}[.,]\d{1,2})\s*%?/i,
/%\s*(\d{1,2}[.,]\d{1,2})/,
];
for (const pattern of patterns) {
const match = bodyText.match(pattern);
if (match) {
const percentage = parseFloat(match[1].replace(",", "."));
if (percentage > 0 && percentage <= 100) {
return { city_slug: "izmir", city_name: "Izmir", percentage, data_source: "realtime" as DataSource };
}
}
}
} catch (error) {
console.error(`Izmir scraper error for ${url}:`, error);
// Continue to next URL
}
}
console.error("Izmir scraper failed: Could not access data (may require e-Devlet auth).");
return null;
}
async function scrapeAdana(): Promise<CityData | null> {
// Adana (ASKİ) - Dam fill rate page
// URL: https://www.adana-aski.gov.tr/web/barajdoluluk.aspx
// The percentage is shown in the header: "Barajlarımızdaki Doluluk Oranı: XX,XX"
// NOTE: Uses proxy due to SSL certificate issues
const MAIN_URL = "https://www.adana-aski.gov.tr/web/barajdoluluk.aspx";
try {
// Use proxy to bypass SSL issues
const html = await fetchHtml(MAIN_URL, true);
const $ = cheerio.load(html);
const bodyText = $('body').text();
// Strategy 1: Look for the header text "Doluluk Oranı:XX,XX"
// Pattern from site: "Barajlarımızdaki Doluluk Oranı:65,26"
const headerMatch = bodyText.match(/Doluluk\s*Oran[ıi]\s*:?\s*(\d{1,2}[.,]\d{1,2})/i);
if (headerMatch) {
const percentage = parseFloat(headerMatch[1].replace(",", "."));
if (percentage > 0 && percentage <= 100) {
return {
city_slug: "adana",
city_name: "Adana",
percentage: percentage,
data_source: "realtime" as DataSource,
};
}
}
// Strategy 2: Look for percentage in any format
const percentMatch = bodyText.match(/%\s*(\d{1,2}[.,]\d{1,2})|(\d{1,2}[.,]\d{1,2})\s*%/);
if (percentMatch) {
const value = percentMatch[1] || percentMatch[2];
const percentage = parseFloat(value.replace(",", "."));
if (percentage > 0 && percentage <= 100) {
return {
city_slug: "adana",
city_name: "Adana",
percentage: percentage,
data_source: "realtime" as DataSource,
};
}
}
console.error("Adana scraper failed: Could not find percentage data.");
return null;
} catch (error) {
console.error("Adana scraper error:", error);
return null;
}
}
async function scrapeMugla(): Promise<CityData | null> {
// Muğla (MUSKİ) - Dam fill rate page
// URL: https://www.muski.gov.tr/baraj-doluluk-orani
// Shows individual dams with their percentages
const MAIN_URL = "https://www.muski.gov.tr/baraj-doluluk-orani";
try {
const html = await fetchHtml(MAIN_URL);
const $ = cheerio.load(html);
const bodyText = $('body').text();
// Strategy 1: Look for "Doluluk Oranı: %XX" pattern
const dolulukMatch = bodyText.match(/Doluluk\s*Oran[ıi]\s*:?\s*%?\s*(\d{1,2}(?:[.,]\d{1,2})?)/i);
if (dolulukMatch) {
const percentage = parseFloat(dolulukMatch[1].replace(",", "."));
if (percentage > 0 && percentage <= 100) {
return {
city_slug: "mugla",
city_name: "Mugla",
percentage: percentage,
data_source: "realtime" as DataSource,
};
}
}
// Strategy 2: Look for percentage patterns with %
const percentMatches = bodyText.matchAll(/%\s*(\d{1,2}(?:[.,]\d{1,2})?)|(\d{1,2}(?:[.,]\d{1,2})?)\s*%/g);
const percentages = (Array.from(percentMatches) as RegExpMatchArray[])
.map(m => parseFloat((m[1] || m[2]).replace(",", ".")))
.filter(p => p > 0 && p <= 100);
if (percentages.length > 0) {
// Return the first (most prominent) percentage
return {
city_slug: "mugla",
city_name: "Mugla",
percentage: percentages[0],
data_source: "realtime" as DataSource,
};
}
console.error("Mugla scraper failed: Could not find percentage data.");
return null;
} catch (error) {
console.error("Mugla scraper error:", error);
return null;
}
}
async function scrapeSakarya(): Promise<CityData | null> {
// Sakarya (SASKİ) - Uses JSON API endpoints
// Main dam: Çakmak Barajı
// API returns: [{"Doluluk":XX.XX,"Meter":XXX.XX,"HacimHM3":XX.XX}]
// NOTE: Uses proxy due to SSL certificate issues
const MAIN_API = "https://proxy.saski.gov.tr/cakmak-baraji.php";
try {
// Use proxy to bypass SSL issues
const data = await fetchJson(MAIN_API, true);
if (Array.isArray(data) && data[0] && typeof data[0].Doluluk === 'number') {
const percentage = data[0].Doluluk;
if (percentage > 0 && percentage <= 100) {
return {
city_slug: "sakarya",
city_name: "Sakarya",
percentage: Math.round(percentage * 100) / 100,
data_source: "realtime" as DataSource,
};
}
}
console.error("Sakarya scraper failed: Invalid data format.", data);
return null;
} catch (error) {
console.error("Sakarya scraper error:", error);
// Fallback: Try scraping the HTML page with proxy
try {
const html = await fetchHtml("https://www.saski.gov.tr/barajlar/", true);
const $ = cheerio.load(html);
// Look for percentage in the page
const bodyText = $('body').text();
const match = bodyText.match(/Doluluk[^0-9]*(\d{1,2}[.,]\d{1,2})/i);
if (match) {
const percentage = parseFloat(match[1].replace(",", "."));
if (percentage > 0 && percentage <= 100) {
return {
city_slug: "sakarya",
city_name: "Sakarya",
percentage: percentage,
data_source: "realtime" as DataSource,
};
}
}
} catch (fallbackError) {
console.error("Sakarya fallback scraper error:", fallbackError);
}
return null;
}
}
async function scrapeGaziantep(): Promise<CityData | null> {
// Gaziantep (GASKİ) - Homepage has percentage data
// URL: https://www.gaski.gov.tr/
try {
const html = await fetchHtml("https://www.gaski.gov.tr/");
const $ = cheerio.load(html);
const bodyText = $('body').text();
// Look for percentage patterns
const percentMatches = bodyText.matchAll(/(\d{1,2}[.,]\d{1,3})%/g);
const percentages = (Array.from(percentMatches) as RegExpMatchArray[])
.map(m => parseFloat(m[1].replace(",", ".")))
.filter(p => p > 10 && p <= 100);
if (percentages.length > 0) {
// First percentage is usually the main dam
return {
city_slug: "gaziantep",
city_name: "Gaziantep",
percentage: percentages[0],
data_source: "realtime" as DataSource,
};
}
console.error("Gaziantep scraper failed: Could not find percentage data.");
return null;
} catch (error) {
console.error("Gaziantep scraper error:", error);
return null;
}
}
async function scrapeDenizli(): Promise<CityData | null> {
// Denizli (DESKİ) - Homepage has doluluk data
// URL: https://www.deski.gov.tr/
try {
const html = await fetchHtml("https://www.deski.gov.tr/");
const $ = cheerio.load(html);
const bodyText = $('body').text();
// Look for doluluk percentage
const dolulukMatch = bodyText.match(/[Dd]oluluk[^0-9]*(\d{1,2}[.,]\d+)%?/);
if (dolulukMatch) {
const percentage = parseFloat(dolulukMatch[1].replace(",", "."));
if (percentage > 0 && percentage <= 100) {
return {
city_slug: "denizli",
city_name: "Denizli",
percentage: percentage,
data_source: "realtime" as DataSource,
};
}
}
// Fallback: look for percentage patterns
const percentMatches = bodyText.matchAll(/(\d{1,2}[.,]\d+)%/g);
const percentages = (Array.from(percentMatches) as RegExpMatchArray[])
.map(m => parseFloat(m[1].replace(",", ".")))
.filter(p => p > 5 && p <= 100);
if (percentages.length > 0) {
return {
city_slug: "denizli",
city_name: "Denizli",
percentage: percentages[0],
data_source: "realtime" as DataSource,
};
}
console.error("Denizli scraper failed: Could not find percentage data.");
return null;
} catch (error) {
console.error("Denizli scraper error:", error);
return null;
}
}
async function scrapeEskisehir(): Promise<CityData | null> {
// Eskişehir (ESKİ) - Has baraj doluluk page
// URL: https://www.eski.gov.tr/
const URLS = [
"https://www.eski.gov.tr/",
"https://www.eski.gov.tr/baraj-doluluk-oranlari",
];
for (const url of URLS) {
try {
const html = await fetchHtml(url);
const $ = cheerio.load(html);
const bodyText = $('body').text();
// Look for doluluk percentage
const dolulukMatch = bodyText.match(/[Dd]oluluk[^0-9]*(\d{1,2}[.,]\d+)%?/);
if (dolulukMatch) {
const percentage = parseFloat(dolulukMatch[1].replace(",", "."));
if (percentage > 0 && percentage <= 100) {
return {
city_slug: "eskisehir",
city_name: "Eskisehir",
percentage: percentage,
data_source: "realtime" as DataSource,
};
}
}
// Look for baraj percentage
const barajMatch = bodyText.match(/[Bb]araj[^0-9]*(\d{1,2}[.,]\d+)%?/);
if (barajMatch) {
const percentage = parseFloat(barajMatch[1].replace(",", "."));
if (percentage > 0 && percentage <= 100) {
return {
city_slug: "eskisehir",
city_name: "Eskisehir",
percentage: percentage,
data_source: "realtime" as DataSource,
};
}
}
} catch (error) {
console.error(`Eskisehir scraper error for ${url}:`, error);
}
}
console.error("Eskisehir scraper failed: Could not find percentage data.");
return null;
}
async function scrapeTrabzon(): Promise<CityData | null> {
// Trabzon (TİSKİ) - Has baraj doluluk data
// URL: https://www.tiski.gov.tr/
try {
const html = await fetchHtml("https://www.tiski.gov.tr/");
const $ = cheerio.load(html);
const bodyText = $('body').text();
// Look for doluluk percentage
const dolulukMatch = bodyText.match(/[Dd]oluluk[^0-9]*(\d{1,2}[.,]\d+)%?/);
if (dolulukMatch) {
const percentage = parseFloat(dolulukMatch[1].replace(",", "."));
if (percentage > 0 && percentage <= 100) {
return {
city_slug: "trabzon",
city_name: "Trabzon",
percentage: percentage,
data_source: "realtime" as DataSource,
};
}
}
// Fallback: look for percentage patterns
const percentMatches = bodyText.matchAll(/(\d{1,2}[.,]\d+)%/g);
const percentages = (Array.from(percentMatches) as RegExpMatchArray[])
.map(m => parseFloat(m[1].replace(",", ".")))
.filter(p => p > 10 && p <= 100);
if (percentages.length > 0) {
return {
city_slug: "trabzon",
city_name: "Trabzon",
percentage: percentages[0],
data_source: "realtime" as DataSource,
};
}
console.error("Trabzon scraper failed: Could not find percentage data.");
return null;
} catch (error) {
console.error("Trabzon scraper error:", error);
return null;
}
}
async function scrapeKocaeli(): Promise<CityData | null> {
// Kocaeli (İSU) - Baraj doluluk page
// URL: https://www.isu.gov.tr/
const URLS = [
"https://www.isu.gov.tr/",
"https://www.isu.gov.tr/baraj-doluluk-oranlari",
];
for (const url of URLS) {
try {
const html = await fetchHtml(url);
const $ = cheerio.load(html);
const bodyText = $('body').text();
// Look for doluluk percentage
const dolulukMatch = bodyText.match(/[Dd]oluluk[^0-9]*(\d{1,2}[.,]\d+)%?/);
if (dolulukMatch) {
const percentage = parseFloat(dolulukMatch[1].replace(",", "."));
if (percentage > 0 && percentage <= 100) {
return {
city_slug: "kocaeli",
city_name: "Kocaeli",
percentage: percentage,
data_source: "realtime" as DataSource,
};
}
}
// Look for baraj percentage
const barajMatch = bodyText.match(/[Bb]araj[^0-9]*(\d{1,2}[.,]\d+)%?/);
if (barajMatch) {
const percentage = parseFloat(barajMatch[1].replace(",", "."));
if (percentage > 0 && percentage <= 100) {
return {
city_slug: "kocaeli",
city_name: "Kocaeli",
percentage: percentage,
data_source: "realtime" as DataSource,
};
}
}
} catch (error) {
console.error(`Kocaeli scraper error for ${url}:`, error);
}
}
console.error("Kocaeli scraper failed: Could not find percentage data.");
return null;
}
async function scrapeAntalya(): Promise<CityData | null> {
// Antalya (ASAT) - Water utility
// URL: https://www.asat.gov.tr/
try {
const html = await fetchHtml("https://www.asat.gov.tr/");
const $ = cheerio.load(html);
const bodyText = $('body').text();
// Look for doluluk/baraj percentage
const dolulukMatch = bodyText.match(/[Dd]oluluk[^0-9]*(\d{1,2}[.,]\d+)%?/);
if (dolulukMatch) {
const percentage = parseFloat(dolulukMatch[1].replace(",", "."));
if (percentage > 0 && percentage <= 100) {
return {
city_slug: "antalya",
city_name: "Antalya",
percentage: percentage,
data_source: "realtime" as DataSource,
};
}
}
// Fallback: percentage patterns
const percentMatches = bodyText.matchAll(/(\d{1,2}[.,]\d+)%/g);
const percentages = (Array.from(percentMatches) as RegExpMatchArray[])
.map(m => parseFloat(m[1].replace(",", ".")))
.filter(p => p > 10 && p <= 100);
if (percentages.length > 0) {
return {
city_slug: "antalya",
city_name: "Antalya",
percentage: percentages[0],
data_source: "realtime" as DataSource,
};
}
console.error("Antalya scraper failed: Could not find percentage data.");
return null;
} catch (error) {
console.error("Antalya scraper error:", error);
return null;
}
}
// -----------------------------------------------------------------------------
// 4. MANUAL DATA ENTRIES (e-Devlet)
// -----------------------------------------------------------------------------
// Bu veriler e-Devlet üzerinden manuel olarak eklenmektedir.
// İnternet üzerinde anlık veri kaynağı bulunmayan şehirler için kullanılır.
// Yaklaşık 1 hafta gecikme olabilir.
//
// Format:
// {
// city_slug: "sehir_slug",
// city_name: "Şehir Adı",
// percentage: 45.5,
// data_source: "manual",
// data_date: "2026-01-10", // Verinin ait olduğu tarih
// }
interface ManualDataEntry {