-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLianjia Rent Assistant.user.js
More file actions
2855 lines (2526 loc) · 103 KB
/
Copy pathLianjia Rent Assistant.user.js
File metadata and controls
2855 lines (2526 loc) · 103 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
// ==UserScript==
// @name Lianjia Rent Assistant
// @name:zh-CN 链家租房助手
// @namespace http://tampermonkey.net/
// @version 0.5.39
// @description Enhance Lianjia rent pages with helper controls and listing tools.
// @description:zh-CN 增强链家租房列表页,提供筛选辅助和房源工具。
// @author codex
// @license MIT
// @match https://*.lianjia.com/ditiezufang/
// @match https://*.lianjia.com/ditiezufang/*
// @match https://*.lianjia.com/zufang/
// @match https://*.lianjia.com/zufang/*
// @match https://*.lianjia.com/apartment/*
// @noframes
// @grant GM_addStyle
// @grant GM_getValue
// @grant GM_openInTab
// @grant GM_setValue
// @grant unsafeWindow
// ==/UserScript==
(function () {
'use strict';
const SCRIPT_VERSION = '0.5.39';
const STORAGE_KEY = 'LIANJIA_RENT_CONTENT_FILTER_STATE';
const MAP_CACHE_STORAGE_KEY = 'LIANJIA_RENT_MAP_LISTING_CACHE';
const AUTO_FETCH_STORAGE_KEY = 'LIANJIA_RENT_MAP_AUTO_FETCH_STATE';
const TIMING_SETTINGS_STORAGE_KEY = 'LIANJIA_RENT_TIMING_SETTINGS';
const COORDINATE_SOURCE_STORAGE_KEY = 'LIANJIA_RENT_COORDINATE_SOURCE';
const MAP_HEIGHT_STORAGE_KEY = 'LIANJIA_RENT_MAP_HEIGHT';
const NEXT_PAGE_FETCH_MODE_STORAGE_KEY = 'LIANJIA_RENT_NEXT_PAGE_FETCH_MODE';
const SHOW_ALL_FETCHED_ON_MAP_STORAGE_KEY = 'LIANJIA_RENT_SHOW_ALL_FETCHED_ON_MAP';
const MAP_CACHE_VERSION = 1;
const CONTENT_FILTER_HOST_LABEL = '品牌';
const STREAM_LOAD_THRESHOLD_PX = 900;
const BAIDU_MAP_AK = 'djAasQ167kYWRGbjL2az8aGmHBUmXp4V';
const MAP_DETAIL_FETCH_LIMIT = 1;
const MAP_DETAIL_FETCH_DELAY_MS = 4000;
const MAP_DETAIL_FETCH_TIMEOUT_MS = 10000;
const MAP_OVERLAY_BATCH_SIZE = 40;
const MAP_CLUSTER_MIN_RECORDS = 40;
const DEFAULT_MAP_HEIGHT = 360;
const MIN_MAP_HEIGHT = 240;
const MAX_MAP_HEIGHT = 1200;
const AUTO_FETCH_PAGE_DELAY_MS = 4000;
const CAPTCHA_RETRY_DELAY_MS = 20000;
const MAX_AUTO_FETCH_RETRY_COUNT = 99;
const COORDINATE_SOURCE_GEOCODE = 'geocode';
const COORDINATE_SOURCE_FETCH = 'fetch';
const COORDINATE_SOURCE_TAB = 'tab';
const COORDINATE_SOURCE_IFRAME = 'iframe';
const COORDINATE_SOURCE_CASCADE = 'cascade';
const DEFAULT_COORDINATE_SOURCE = COORDINATE_SOURCE_GEOCODE;
const NEXT_PAGE_FETCH_MODE_FETCH = 'fetch';
const DEFAULT_NEXT_PAGE_FETCH_MODE = NEXT_PAGE_FETCH_MODE_FETCH;
const NEXT_PAGE_FETCH_MODE_IFRAME = 'iframe';
const DEFAULT_SHOW_ALL_FETCHED_ON_MAP = false;
const COORDINATE_SOURCE_OPTIONS = Object.freeze([
{ value: COORDINATE_SOURCE_GEOCODE, label: '地理编码' },
{ value: COORDINATE_SOURCE_FETCH, label: 'fetch' },
{ value: COORDINATE_SOURCE_TAB, label: '后台标签' },
{ value: COORDINATE_SOURCE_IFRAME, label: 'iframe' },
{ value: COORDINATE_SOURCE_CASCADE, label: '级联模式' }
]);
const CASCADE_COORDINATE_SOURCES = Object.freeze([
COORDINATE_SOURCE_GEOCODE,
COORDINATE_SOURCE_IFRAME,
COORDINATE_SOURCE_TAB,
COORDINATE_SOURCE_FETCH
]);
const NEXT_PAGE_FETCH_MODE_OPTIONS = Object.freeze([
{ value: NEXT_PAGE_FETCH_MODE_FETCH, label: '后台请求' },
{ value: NEXT_PAGE_FETCH_MODE_IFRAME, label: 'iframe' }
]);
const DEFAULT_FILTER_STATE = Object.freeze({
beikePreferred: true,
apartment: true,
guessYouLike: true
});
const DEFAULT_TIMING_SETTINGS = Object.freeze({
autoFetchPageDelayMs: AUTO_FETCH_PAGE_DELAY_MS,
mapDetailFetchDelayMs: MAP_DETAIL_FETCH_DELAY_MS,
captchaRetryDelayMs: CAPTCHA_RETRY_DELAY_MS
});
const streamState = {
initialized: false,
loading: false,
list: null,
pager: null,
status: null,
observer: null,
nextPage: 0,
totalPage: 0,
pageUrlTemplate: '',
seenKeys: new Set()
};
const mapState = {
initialized: false,
panel: null,
canvas: null,
resizeHandle: null,
status: null,
map: null,
mapScriptPromise: null,
mapReadyPromise: null,
autoFetchControl: null,
autoFetchStatus: null,
autoFetchState: null,
autoFetchLoading: false,
autoFetchTimer: 0,
autoFetchCountdownTimer: 0,
timingSettings: null,
timingSettingsPanel: null,
coordinateSource: null,
nextPageFetchMode: null,
showAllFetchedOnMap: null,
queuedKeys: new Set(),
fetchedListings: new Map(),
failedKeys: new Set(),
previewImageLoadingKeys: new Set(),
previewImageFailedKeys: new Set(),
activeFetches: 0,
mapQueueTimer: 0,
lastMapFetchFinishedAt: 0,
pendingRecords: [],
blocked: false,
cache: null,
mapHeight: 0,
mapRenderToken: 0,
mapViewportTimer: 0,
markerGroupClickHandlers: new Map()
};
function normalizeFilterState(value) {
const source = value && typeof value === 'object' ? value : {};
return {
beikePreferred: source.beikePreferred !== false,
apartment: source.apartment !== false,
guessYouLike: source.guessYouLike !== false
};
}
function serializeFilterState(state) {
return JSON.stringify(normalizeFilterState(state));
}
function classifyListingContent(listing) {
const text = String(listing?.text || '');
const hrefs = Array.isArray(listing?.hrefs) ? listing.hrefs : [];
return {
beikePreferred: /贝壳优选/.test(text),
apartment: /公寓/.test(text) || hrefs.some((href) => /\/apartment\//.test(String(href || ''))),
guessYouLike: listing?.guessYouLike === true
};
}
function shouldShowListing(kinds, state) {
const filters = normalizeFilterState(state);
return (filters.beikePreferred || !kinds.beikePreferred)
&& (filters.apartment || !kinds.apartment)
&& (filters.guessYouLike || !kinds.guessYouLike);
}
function normalizeListingKinds(value) {
if (!value || typeof value !== 'object') return null;
return {
beikePreferred: value.beikePreferred === true,
apartment: value.apartment === true,
guessYouLike: value.guessYouLike === true
};
}
function normalizeAutoFetchState(value) {
let source = value;
if (typeof source === 'string') {
try {
source = JSON.parse(source);
} catch {
source = {};
}
}
const progress = {};
const rawProgress = source?.progress && typeof source.progress === 'object' ? source.progress : {};
Object.entries(rawProgress).forEach(([key, page]) => {
const pageNumber = Number.parseInt(page, 10);
if (key && Number.isFinite(pageNumber) && pageNumber > 0) {
progress[key] = pageNumber;
}
});
const retryCount = Number.parseInt(source?.retryCount, 10);
const state = {
enabled: source?.enabled === true,
progress
};
if (Number.isFinite(retryCount) && retryCount > 0) {
state.retryCount = retryCount;
}
return state;
}
function normalizeDelayMs(value, fallback) {
const number = Number(value);
return Number.isFinite(number) && number > 0 ? Math.round(number) : fallback;
}
function normalizeTimingSettings(value) {
let source = value;
if (typeof source === 'string') {
try {
source = JSON.parse(source);
} catch {
source = {};
}
}
return {
autoFetchPageDelayMs: normalizeDelayMs(source?.autoFetchPageDelayMs, DEFAULT_TIMING_SETTINGS.autoFetchPageDelayMs),
mapDetailFetchDelayMs: normalizeDelayMs(source?.mapDetailFetchDelayMs, DEFAULT_TIMING_SETTINGS.mapDetailFetchDelayMs),
captchaRetryDelayMs: normalizeDelayMs(source?.captchaRetryDelayMs, DEFAULT_TIMING_SETTINGS.captchaRetryDelayMs)
};
}
function serializeTimingSettings(settings) {
return JSON.stringify(normalizeTimingSettings(settings));
}
function getAutoFetchPageDelay(settings = DEFAULT_TIMING_SETTINGS, multiplier = 1) {
const factor = normalizeDelayMs(multiplier, 1);
return normalizeTimingSettings(settings).autoFetchPageDelayMs * factor;
}
function getMapDetailFetchDelay(settings = DEFAULT_TIMING_SETTINGS) {
return normalizeTimingSettings(settings).mapDetailFetchDelayMs;
}
function getCaptchaRetryDelay(settings = DEFAULT_TIMING_SETTINGS) {
return normalizeTimingSettings(settings).captchaRetryDelayMs;
}
function normalizeMapHeight(value) {
const number = Number(value);
const height = Number.isFinite(number) && number > 0 ? Math.round(number) : DEFAULT_MAP_HEIGHT;
return Math.min(MAX_MAP_HEIGHT, Math.max(MIN_MAP_HEIGHT, height));
}
function applyMapCanvasHeight(canvas, height) {
const normalized = normalizeMapHeight(height);
if (canvas?.style) {
canvas.style.height = `${normalized}px`;
}
return normalized;
}
function normalizeCoordinateSource(value) {
const source = String(value || '').trim();
return COORDINATE_SOURCE_OPTIONS.some((option) => option.value === source) ? source : DEFAULT_COORDINATE_SOURCE;
}
function getCoordinateSourceSequence(source) {
const normalized = normalizeCoordinateSource(source);
return normalized === COORDINATE_SOURCE_CASCADE ? Array.from(CASCADE_COORDINATE_SOURCES) : [normalized];
}
function normalizeNextPageFetchMode(value) {
const mode = String(value || '').trim();
return NEXT_PAGE_FETCH_MODE_OPTIONS.some((option) => option.value === mode) ? mode : DEFAULT_NEXT_PAGE_FETCH_MODE;
}
function normalizeShowAllFetchedOnMap(value) {
return value === true || value === 1 || String(value || '').trim() === 'true' || String(value || '').trim() === '1';
}
function normalizePriceRange(value) {
const min = Number(value?.min);
const max = Number(value?.max);
const range = {};
if (Number.isFinite(min) && min >= 0) range.min = min;
if (Number.isFinite(max) && max >= 0) range.max = max;
return range.min !== undefined || range.max !== undefined ? range : null;
}
function normalizeNativeMapFilterState(value) {
const priceRanges = Array.isArray(value?.priceRanges)
? value.priceRanges.map(normalizePriceRange).filter(Boolean)
: [];
return { priceRanges };
}
function parseListingPriceAmount(value) {
const match = /(\d+(?:\.\d+)?)/.exec(String(value || '').replace(/,/g, ''));
return match ? Number(match[1]) : 0;
}
function parsePriceRangeText(value) {
const text = String(value || '').replace(/\s+/g, '');
const between = /(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)/.exec(text);
if (between) return normalizePriceRange({ min: between[1], max: between[2] });
const max = /(?:≤|<=|<)(\d+(?:\.\d+)?)/.exec(text);
if (max) return normalizePriceRange({ max: max[1] });
const min = /(?:≥|>=|>)(\d+(?:\.\d+)?)/.exec(text);
return min ? normalizePriceRange({ min: min[1] }) : null;
}
function matchesPriceRanges(record, priceRanges) {
if (!priceRanges.length) return true;
const price = parseListingPriceAmount(record?.price);
if (!price) return false;
return priceRanges.some((range) => {
return (range.min === undefined || price >= range.min)
&& (range.max === undefined || price <= range.max);
});
}
function filterMapRecordsByNativeState(records, nativeFilterState) {
const filters = normalizeNativeMapFilterState(nativeFilterState);
return records.filter((record) => matchesPriceRanges(record, filters.priceRanges));
}
function getAutoFetchNextPage(state, searchKey, currentPage, totalPage) {
const normalized = normalizeAutoFetchState(state);
const current = parsePositiveInteger(currentPage);
const total = parsePositiveInteger(totalPage);
const fetched = parsePositiveInteger(normalized.progress[searchKey]);
const baseline = Math.max(current, fetched);
return total && baseline < total ? baseline + 1 : 0;
}
function markAutoFetchPageFetched(state, searchKey, page) {
const normalized = normalizeAutoFetchState(state);
const pageNumber = parsePositiveInteger(page);
if (!searchKey || !pageNumber) return normalized;
normalized.progress[searchKey] = Math.max(parsePositiveInteger(normalized.progress[searchKey]), pageNumber);
return normalized;
}
function getAutoFetchRetryDelay(state, settings = DEFAULT_TIMING_SETTINGS) {
return getCaptchaRetryDelay(settings);
}
function getAutoFetchRetryStatusText(remainingMs) {
const seconds = Math.ceil(Math.max(0, Number(remainingMs) || 0) / 1000);
return seconds > 0 ? `遇到验证,${seconds} 秒后重试` : '正在重试';
}
function markAutoFetchCaptchaRetry(state) {
const normalized = normalizeAutoFetchState(state);
normalized.retryCount = Math.min((normalized.retryCount || 0) + 1, MAX_AUTO_FETCH_RETRY_COUNT);
return normalized;
}
function resetAutoFetchRetry(state) {
const normalized = normalizeAutoFetchState(state);
delete normalized.retryCount;
return normalized;
}
function buildPageUrl(template, page, baseUrl) {
const pageNumber = Number(page);
if (!template || !Number.isFinite(pageNumber) || pageNumber < 1) return '';
return new URL(String(template).replace('{page}', String(pageNumber)).replace(/#.*$/, ''), baseUrl).href;
}
function normalizeSubwayStationLinkHref(href) {
const source = String(href || '').trim();
if (!source) return '';
return source
.replace(/^(https?:\/\/[^/]+\.lianjia\.com)\/zufang(?=\/|$|\?)/i, '$1/ditiezufang')
.replace(/^(\/\/[^/]+\.lianjia\.com)\/zufang(?=\/|$|\?)/i, '$1/ditiezufang')
.replace(/^\/zufang(?=\/|$|\?)/, '/ditiezufang');
}
function isSubwaySwitchLinkText(text) {
return /^按地铁(?:线|站)$/.test(String(text || '').replace(/\s+/g, ''));
}
function getListingKey(listing) {
const houseCode = String(listing?.houseCode || '').trim();
if (houseCode) return `house:${houseCode}`;
const hrefs = Array.isArray(listing?.hrefs) ? listing.hrefs : [];
const href = hrefs.map((value) => String(value || '').trim()).find(Boolean);
return href ? `href:${href}` : '';
}
function getListingKeyFromDetailUrl(url) {
const match = /\/(?:zufang|apartment)\/([^/?#]+)\.html(?:[?#].*)?$/.exec(String(url || ''));
return match ? `house:${match[1]}` : '';
}
function filterNewListingKeys(listings, seenKeys) {
const result = [];
listings.forEach((listing) => {
const key = getListingKey(listing);
if (!key || seenKeys.has(key)) return;
seenKeys.add(key);
result.push(key);
});
return result;
}
function getListingDetailUrl(listing, baseUrl) {
const hrefs = Array.isArray(listing?.hrefs) ? listing.hrefs : [];
const href = hrefs.map((value) => String(value || '').trim()).find((value) => {
return /\/(?:zufang|apartment)\/[^/?#]+\.html(?:[?#].*)?$/.test(value);
});
return href ? new URL(href, baseUrl).href : '';
}
function normalizeMapPoint(point) {
const longitude = Number(point?.longitude ?? point?.lng ?? point?.lon);
const latitude = Number(point?.latitude ?? point?.lat);
if (!Number.isFinite(longitude) || !Number.isFinite(latitude)) return null;
if (longitude < 73 || longitude > 136 || latitude < 3 || latitude > 54) return null;
return { longitude, latitude };
}
function readCoordinateField(text, key) {
const match = new RegExp(`${key}["']?\\s*[:=]\\s*["']?(-?\\d+(?:\\.\\d+)?)`, 'i').exec(text);
return match ? match[1] : '';
}
function extractMapPointFromDetailHtml(html) {
const source = String(html || '');
const coordBlock = /g_conf\.coord\s*=\s*\{([\s\S]*?)\}/.exec(source);
if (coordBlock) {
const point = normalizeMapPoint({
longitude: readCoordinateField(coordBlock[1], 'longitude'),
latitude: readCoordinateField(coordBlock[1], 'latitude')
});
if (point) return point;
}
const latFirst = /["']latitude["']\s*:\s*["']?(-?\d+(?:\.\d+)?)["']?\s*,\s*["']longitude["']\s*:\s*["']?(-?\d+(?:\.\d+)?)["']?/i.exec(source);
if (latFirst) {
const point = normalizeMapPoint({ latitude: latFirst[1], longitude: latFirst[2] });
if (point) return point;
}
const lonFirst = /["']longitude["']\s*:\s*["']?(-?\d+(?:\.\d+)?)["']?\s*,\s*["']latitude["']\s*:\s*["']?(-?\d+(?:\.\d+)?)["']?/i.exec(source);
return lonFirst ? normalizeMapPoint({ longitude: lonFirst[1], latitude: lonFirst[2] }) : null;
}
function normalizePreviewImageUrl(value, baseUrl = typeof window === 'object' ? window.location.href : 'https://lianjia.com/') {
const source = String(value || '').trim();
if (!source || /^data:|^javascript:/i.test(source)) return '';
try {
const url = new URL(source.replace(/^\/\//, 'https://'), baseUrl);
return /^https?:$/.test(url.protocol) ? url.href : '';
} catch {
return '';
}
}
function readHtmlAttribute(text, name) {
const match = new RegExp(`${name}\\s*=\\s*["']([^"']+)["']`, 'i').exec(String(text || ''));
return match ? match[1] : '';
}
function extractPreviewImageFromDetailHtml(html, baseUrl) {
const source = String(html || '');
const metaMatch = /<meta\b[^>]*(?:property|name)\s*=\s*["'](?:og:image|twitter:image|image)["'][^>]*>/i.exec(source);
const metaUrl = normalizePreviewImageUrl(readHtmlAttribute(metaMatch?.[0], 'content'), baseUrl);
if (metaUrl) return metaUrl;
const imgMatches = source.match(/<img\b[^>]*>/gi) || [];
for (const img of imgMatches) {
const imageUrl = normalizePreviewImageUrl(
readHtmlAttribute(img, 'data-src') || readHtmlAttribute(img, 'data-original') || readHtmlAttribute(img, 'src'),
baseUrl
);
if (imageUrl) return imageUrl;
}
return '';
}
function normalizeCachedMapRecord(record, fallbackUpdatedAt) {
const key = String(record?.key || '').trim();
const detailUrl = String(record?.detailUrl || '').trim();
if (!key || !detailUrl) return null;
const updatedAt = Number(record?.updatedAt);
const normalized = {
key,
detailUrl,
title: String(record?.title || ''),
price: String(record?.price || ''),
updatedAt: Number.isFinite(updatedAt) && updatedAt > 0 ? updatedAt : fallbackUpdatedAt
};
if (record?.address) normalized.address = String(record.address);
if (record?.city) normalized.city = String(record.city);
const point = normalizeMapPoint(record?.point);
if (point) normalized.point = point;
const previewImageUrl = normalizePreviewImageUrl(record?.previewImageUrl, detailUrl);
if (previewImageUrl) normalized.previewImageUrl = previewImageUrl;
if (record?.coordinateSource) normalized.coordinateSource = normalizeCoordinateSource(record.coordinateSource);
const kinds = normalizeListingKinds(record?.kinds);
if (kinds) normalized.kinds = kinds;
const searchKeys = Array.isArray(record?.searchKeys)
? record.searchKeys.map((value) => String(value || '').trim()).filter(Boolean)
: [];
if (searchKeys.length) normalized.searchKeys = Array.from(new Set(searchKeys));
return normalized;
}
function parseStoredMapCache(rawValue) {
let source = rawValue;
if (typeof source === 'string') {
try {
source = JSON.parse(source);
} catch {
source = {};
}
}
const result = { version: MAP_CACHE_VERSION, listings: {} };
const listings = source?.listings && typeof source.listings === 'object' ? source.listings : {};
Object.values(listings).forEach((record) => {
const normalized = normalizeCachedMapRecord(record, Number(record?.updatedAt) || Date.now());
if (normalized) result.listings[normalized.key] = normalized;
});
return result;
}
function mergeMapCacheRecords(cache, records, updatedAt = Date.now(), sourceKey = '') {
const next = parseStoredMapCache(cache);
records.forEach((record) => {
const key = String(record?.key || '').trim();
const existing = next.listings[key];
const existingPoint = normalizeMapPoint(existing?.point);
const incomingPoint = normalizeMapPoint(record?.point);
const previewImageUrl = normalizePreviewImageUrl(record?.previewImageUrl || existing?.previewImageUrl, record?.detailUrl || existing?.detailUrl);
const searchKeys = [
...(Array.isArray(existing?.searchKeys) ? existing.searchKeys : []),
...(Array.isArray(record?.searchKeys) ? record.searchKeys : []),
sourceKey
].map((value) => String(value || '').trim()).filter(Boolean);
const normalized = normalizeCachedMapRecord({
...existing,
...record,
point: incomingPoint || existingPoint,
previewImageUrl,
searchKeys,
updatedAt
}, updatedAt);
if (normalized) next.listings[normalized.key] = normalized;
});
return next;
}
function getSearchCacheRecords(cache, searchKey, filterState) {
const filters = normalizeFilterState(filterState);
return Object.values(parseStoredMapCache(cache).listings).filter((record) => {
if (!Array.isArray(record.searchKeys) || !record.searchKeys.includes(searchKey)) return false;
const kinds = normalizeListingKinds(record.kinds);
return !kinds || shouldShowListing(kinds, filters);
});
}
function getAllFetchedMapRecords(cache, filterState, nativeFilterState) {
return filterMapRecordsByNativeState(filterMapRecordsByState(
Object.values(parseStoredMapCache(cache).listings).filter((record) => normalizeMapPoint(record.point)),
filterState
), nativeFilterState);
}
function formatShowAllFetchedText(count) {
const number = Number(count);
return `显示所有(${Number.isFinite(number) && number > 0 ? Math.round(number) : 0})`;
}
function getMapOverlayBatchSize(total) {
const count = Math.max(0, Math.round(Number(total) || 0));
return Math.min(count, MAP_OVERLAY_BATCH_SIZE);
}
function getMapRenderProgressText(rendered, total) {
const totalCount = Math.max(0, Math.round(Number(total) || 0));
const renderedCount = Math.min(totalCount, Math.max(0, Math.round(Number(rendered) || 0)));
return `正在标记 ${renderedCount}/${totalCount} 套`;
}
function getMapPointGroupPrecision(total) {
const count = Math.max(0, Math.round(Number(total) || 0));
if (count > 500) return 2;
return count > 200 ? 3 : 5;
}
function getMapRenderGroupPrecision(total, zoom, showAllFetched) {
const currentZoom = Math.max(0, Math.round(Number(zoom) || 0));
if (showAllFetched) {
if (currentZoom >= 17) return 5;
if (currentZoom >= 16) return 4;
if (currentZoom >= 14) return 3;
if (currentZoom >= 13) return 2;
return 1;
}
return Math.max(getMapPointGroupPrecision(total), currentZoom >= 16 ? 5 : (currentZoom >= 14 ? 4 : 0));
}
function getMapClusterSplitZoom(currentZoom) {
const zoom = Math.max(0, Math.round(Number(currentZoom) || 12));
return Math.min(18, zoom + 2);
}
function getMapPointGroupKey(point, precision = getMapPointGroupPrecision(0)) {
const normalized = normalizeMapPoint(point);
if (!normalized) return '';
return `${normalized.longitude.toFixed(precision)},${normalized.latitude.toFixed(precision)}`;
}
function groupMapRecordsByPoint(records, precision = getMapPointGroupPrecision(records?.length)) {
const groups = [];
const groupMap = new Map();
records.forEach((record) => {
const point = normalizeMapPoint(record?.point);
const groupKey = getMapPointGroupKey(point, precision);
if (!groupKey) return;
if (!groupMap.has(groupKey)) {
const group = {
key: groupKey,
point: {
longitude: Number(point.longitude.toFixed(precision)),
latitude: Number(point.latitude.toFixed(precision))
},
records: []
};
groupMap.set(groupKey, group);
groups.push(group);
}
groupMap.get(groupKey).records.push({ ...record, point });
});
return groups;
}
function getSingleMapRecordGroups(records) {
return records.map((record, index) => {
const point = normalizeMapPoint(record?.point);
if (!point) return null;
const key = String(record?.key || '').trim() || `index:${index}`;
return {
key: `single:${key}`,
point,
records: [{ ...record, point }]
};
}).filter(Boolean);
}
function shouldClusterMapRecords(total) {
return Math.max(0, Math.round(Number(total) || 0)) > MAP_CLUSTER_MIN_RECORDS;
}
function getMapRenderGroups(records, zoom, showAllFetched) {
if (!shouldClusterMapRecords(records?.length)) {
return getSingleMapRecordGroups(records || []);
}
return groupMapRecordsByPoint(records || [], getMapRenderGroupPrecision(records.length, zoom, showAllFetched));
}
function filterMapRecordsByState(records, filterState) {
const filters = normalizeFilterState(filterState);
return records.filter((record) => {
const kinds = normalizeListingKinds(record?.kinds);
return !kinds || shouldShowListing(kinds, filters);
});
}
function hydrateMapRecordsFromCache(records, cache) {
const parsed = parseStoredMapCache(cache);
return records.map((record) => {
const cached = parsed.listings[String(record?.key || '').trim()];
const point = normalizeMapPoint(cached?.point);
if (!point) return record;
const previewImageUrl = normalizePreviewImageUrl(record.previewImageUrl || cached.previewImageUrl, record.detailUrl || cached.detailUrl);
return {
...record,
point,
...(previewImageUrl ? { previewImageUrl } : {}),
updatedAt: cached.updatedAt
};
});
}
function parseStoredFilterState(rawValue) {
if (!rawValue) return DEFAULT_FILTER_STATE;
if (typeof rawValue === 'string') {
try {
return normalizeFilterState(JSON.parse(rawValue));
} catch {
return DEFAULT_FILTER_STATE;
}
}
return normalizeFilterState(rawValue);
}
function readStoredFilterState() {
if (typeof GM_getValue === 'function') {
return parseStoredFilterState(GM_getValue(STORAGE_KEY, null));
}
try {
return parseStoredFilterState(window.localStorage?.getItem(STORAGE_KEY));
} catch {
return DEFAULT_FILTER_STATE;
}
}
function writeStoredFilterState(state) {
const serialized = serializeFilterState(state);
if (typeof GM_setValue === 'function') {
GM_setValue(STORAGE_KEY, serialized);
return;
}
try {
window.localStorage?.setItem(STORAGE_KEY, serialized);
} catch {
// Degraded environments can still filter for the current page session.
}
}
function readStoredMapCache() {
if (typeof GM_getValue === 'function') {
return parseStoredMapCache(GM_getValue(MAP_CACHE_STORAGE_KEY, null));
}
try {
return parseStoredMapCache(window.localStorage?.getItem(MAP_CACHE_STORAGE_KEY));
} catch {
return parseStoredMapCache(null);
}
}
function writeStoredMapCache(cache) {
const serialized = JSON.stringify(parseStoredMapCache(cache));
if (typeof GM_setValue === 'function') {
GM_setValue(MAP_CACHE_STORAGE_KEY, serialized);
return;
}
try {
window.localStorage?.setItem(MAP_CACHE_STORAGE_KEY, serialized);
} catch {
// Map points still work for the current page session when storage is unavailable.
}
}
function readStoredAutoFetchState() {
if (typeof GM_getValue === 'function') {
return normalizeAutoFetchState(GM_getValue(AUTO_FETCH_STORAGE_KEY, null));
}
try {
return normalizeAutoFetchState(window.localStorage?.getItem(AUTO_FETCH_STORAGE_KEY));
} catch {
return normalizeAutoFetchState(null);
}
}
function writeStoredAutoFetchState(state) {
const serialized = JSON.stringify(normalizeAutoFetchState(state));
if (typeof GM_setValue === 'function') {
GM_setValue(AUTO_FETCH_STORAGE_KEY, serialized);
return;
}
try {
window.localStorage?.setItem(AUTO_FETCH_STORAGE_KEY, serialized);
} catch {
// The toggle still works for the current page session when storage is unavailable.
}
}
function readStoredTimingSettings() {
if (typeof GM_getValue === 'function') {
return normalizeTimingSettings(GM_getValue(TIMING_SETTINGS_STORAGE_KEY, null));
}
try {
return normalizeTimingSettings(window.localStorage?.getItem(TIMING_SETTINGS_STORAGE_KEY));
} catch {
return DEFAULT_TIMING_SETTINGS;
}
}
function writeStoredTimingSettings(settings) {
const serialized = serializeTimingSettings(settings);
if (typeof GM_setValue === 'function') {
GM_setValue(TIMING_SETTINGS_STORAGE_KEY, serialized);
return;
}
try {
window.localStorage?.setItem(TIMING_SETTINGS_STORAGE_KEY, serialized);
} catch {
// Timing changes still apply for the current page session when storage is unavailable.
}
}
function readStoredCoordinateSource() {
if (typeof GM_getValue === 'function') {
return normalizeCoordinateSource(GM_getValue(COORDINATE_SOURCE_STORAGE_KEY, null));
}
try {
return normalizeCoordinateSource(window.localStorage?.getItem(COORDINATE_SOURCE_STORAGE_KEY));
} catch {
return DEFAULT_COORDINATE_SOURCE;
}
}
function writeStoredCoordinateSource(source) {
const normalized = normalizeCoordinateSource(source);
if (typeof GM_setValue === 'function') {
GM_setValue(COORDINATE_SOURCE_STORAGE_KEY, normalized);
return;
}
try {
window.localStorage?.setItem(COORDINATE_SOURCE_STORAGE_KEY, normalized);
} catch {
// Coordinate source changes still apply for the current page session when storage is unavailable.
}
}
function readStoredNextPageFetchMode() {
if (typeof GM_getValue === 'function') {
return normalizeNextPageFetchMode(GM_getValue(NEXT_PAGE_FETCH_MODE_STORAGE_KEY, null));
}
try {
return normalizeNextPageFetchMode(window.localStorage?.getItem(NEXT_PAGE_FETCH_MODE_STORAGE_KEY));
} catch {
return DEFAULT_NEXT_PAGE_FETCH_MODE;
}
}
function writeStoredNextPageFetchMode(mode) {
const normalized = normalizeNextPageFetchMode(mode);
if (typeof GM_setValue === 'function') {
GM_setValue(NEXT_PAGE_FETCH_MODE_STORAGE_KEY, normalized);
return normalized;
}
try {
window.localStorage?.setItem(NEXT_PAGE_FETCH_MODE_STORAGE_KEY, normalized);
} catch {
// Next-page mode changes still apply for the current page session when storage is unavailable.
}
return normalized;
}
function readStoredShowAllFetchedOnMap() {
if (typeof GM_getValue === 'function') {
return normalizeShowAllFetchedOnMap(GM_getValue(SHOW_ALL_FETCHED_ON_MAP_STORAGE_KEY, null));
}
try {
return normalizeShowAllFetchedOnMap(window.localStorage?.getItem(SHOW_ALL_FETCHED_ON_MAP_STORAGE_KEY));
} catch {
return DEFAULT_SHOW_ALL_FETCHED_ON_MAP;
}
}
function writeStoredShowAllFetchedOnMap(value) {
const normalized = normalizeShowAllFetchedOnMap(value);
if (typeof GM_setValue === 'function') {
GM_setValue(SHOW_ALL_FETCHED_ON_MAP_STORAGE_KEY, normalized);
return normalized;
}
try {
window.localStorage?.setItem(SHOW_ALL_FETCHED_ON_MAP_STORAGE_KEY, String(normalized));
} catch {
// Map display mode changes still apply for the current page session when storage is unavailable.
}
return normalized;
}
function readStoredMapHeight() {
if (typeof GM_getValue === 'function') {
return normalizeMapHeight(GM_getValue(MAP_HEIGHT_STORAGE_KEY, null));
}
try {
return normalizeMapHeight(window.localStorage?.getItem(MAP_HEIGHT_STORAGE_KEY));
} catch {
return DEFAULT_MAP_HEIGHT;
}
}
function writeStoredMapHeight(height) {
const normalized = normalizeMapHeight(height);
if (typeof GM_setValue === 'function') {
GM_setValue(MAP_HEIGHT_STORAGE_KEY, normalized);
return normalized;
}
try {
window.localStorage?.setItem(MAP_HEIGHT_STORAGE_KEY, String(normalized));
} catch {
// Height changes still apply for the current page session when storage is unavailable.
}
return normalized;
}
function getAsideText(row) {
const aside = row?.querySelector?.('.filter__item--aside');
return (aside?.textContent || '').replace(/\s+/g, '');
}
function findFilterHostRow() {
return Array.from(document.querySelectorAll('#filter .filter__ul')).find((row) => getAsideText(row) === CONTENT_FILTER_HOST_LABEL) || null;
}
function buildFilterOption(key, text, checked) {
const item = document.createElement('li');
item.className = 'filter__item--level5 check lj-content-filter__item';
const label = document.createElement('label');
label.className = 'lj-content-filter__option';
const input = document.createElement('input');
input.type = 'checkbox';
input.checked = checked;
input.dataset.ljContentFilterOption = key;
const labelText = document.createElement('span');
labelText.textContent = text;
label.append(input, labelText);
item.append(label);
return item;
}
function getCurrentFilterState(row) {
return normalizeFilterState({
beikePreferred: row.querySelector('[data-lj-content-filter-option="beikePreferred"]')?.checked,
apartment: row.querySelector('[data-lj-content-filter-option="apartment"]')?.checked,
guessYouLike: row.querySelector('[data-lj-content-filter-option="guessYouLike"]')?.checked
});
}
function getSelectedCheckboxTexts(row) {
const labels = Array.from(row?.querySelectorAll?.('label') || []);
const items = labels.length ? labels : Array.from(row?.querySelectorAll?.('li') || []);
return items.map((item) => {
const input = item.querySelector?.('input[type="checkbox"]');
if (!input?.checked) return '';
const clone = item.cloneNode?.(true);
clone?.querySelectorAll?.('input')?.forEach((node) => node.remove());
return (clone.textContent || '').replace(/\s+/g, '').trim();
}).filter(Boolean);
}
function getCurrentNativeMapFilterState() {
const priceRow = Array.from(document.querySelectorAll('#filter .filter__ul'))
.find((row) => getAsideText(row) === '租金');
return normalizeNativeMapFilterState({
priceRanges: getSelectedCheckboxTexts(priceRow).map(parsePriceRangeText).filter(Boolean)
});
}
function isGuessYouLikeCard(card) {
return (card?.parentElement?.previousElementSibling?.textContent || '').replace(/\s+/g, '') === '猜你喜欢';
}
function getListingData(card) {
const hrefs = Array.from(card.querySelectorAll('a[href]')).map((link) => link.getAttribute('href') || '');
return {
houseCode: card.getAttribute('data-house_code') || '',
text: (card.innerText || card.textContent || '').replace(/\s+/g, ' ').trim(),
hrefs,
guessYouLike: isGuessYouLikeCard(card)
};
}
function applyFilters(state) {
document.querySelectorAll('.content__list--item').forEach((card) => {
const kinds = classifyListingContent(getListingData(card));
const show = shouldShowListing(kinds, state);
if (show) {
if (card.dataset.ljContentFilterHidden === 'true') {
card.style.display = '';
delete card.dataset.ljContentFilterHidden;
}
return;
}
card.dataset.ljContentFilterHidden = 'true';
card.style.display = 'none';
});
}
function installStyles() {
const css = [
'.lj-content-filter__item{height:27px;line-height:27px;}',
'.lj-content-filter__option{display:inline-flex;align-items:center;gap:5px;cursor:pointer;color:#394043;font-size:12px;}',
'.lj-content-filter__option input{width:13px;height:13px;margin:0;accent-color:#00ae66;}',
'.lj-content-filter__option span{line-height:27px;}',
'.lj-stream-hidden-pager{display:none!important;}',
'.lj-stream-status{margin:24px 0 8px;text-align:center;color:#888;font-size:13px;line-height:32px;}',
'.lj-stream-status[data-clickable="true"]{cursor:pointer;color:#00ae66;}',
'.lj-rent-map-panel{clear:both;box-sizing:border-box;margin:18px 0 18px;border:1px solid #e5e5e5;background:#fff;}',
'.lj-rent-map-panel__header{display:flex;align-items:center;justify-content:space-between;height:38px;padding:0 14px;border-bottom:1px solid #f0f0f0;color:#394043;font-size:14px;}',
'.lj-rent-map-panel__header strong{font-weight:600;}',
'.lj-rent-map-panel__actions{display:flex;align-items:center;gap:12px;}',
'.lj-rent-map-auto{display:inline-flex;align-items:center;gap:5px;color:#666;font-size:12px;cursor:pointer;white-space:nowrap;}',
'.lj-rent-map-auto input{width:13px;height:13px;margin:0;accent-color:#00ae66;}',
'.lj-rent-map-settings{position:relative;display:inline-flex;align-items:center;}',
'.lj-rent-map-settings__button{height:22px;padding:0 8px;border:1px solid #ddd;background:#fff;color:#666;font-size:12px;line-height:20px;cursor:pointer;}',
'.lj-rent-map-settings__panel{position:absolute;top:28px;right:0;z-index:10;width:210px;padding:10px;border:1px solid #ddd;background:#fff;box-shadow:0 2px 8px rgba(0,0,0,.12);color:#394043;font-size:12px;}',
'.lj-rent-map-settings__row{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px;gap:8px;}',
'.lj-rent-map-settings__row input{width:64px;height:24px;padding:0 5px;border:1px solid #ddd;color:#394043;font-size:12px;}',
'.lj-rent-map-settings__row input[type="checkbox"]{width:13px;height:13px;margin:0;padding:0;border:0;accent-color:#00ae66;}',
'.lj-rent-map-settings__row select{width:94px;height:24px;border:1px solid #ddd;background:#fff;color:#394043;font-size:12px;}',