-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
303 lines (259 loc) · 7.21 KB
/
Copy pathcontent.js
File metadata and controls
303 lines (259 loc) · 7.21 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
(function () {
'use strict';
const CONFIG = {
TELEGRAM_HOSTS: new Set([
't.me',
'telegram.me',
'telegram.dog',
'www.t.me',
'www.telegram.me',
'www.telegram.dog',
]),
RESERVED_PATHS: new Set([
'joinchat',
'proxy',
'login',
's', // /s/username redirects to /username
'iv',
'share',
'addstickers',
'addtheme',
'addemoji',
'bg',
'contact',
'c',
'a',
'k',
]),
USERNAME_PATTERN: /^[a-zA-Z0-9_]{3,}$/,
MUTATION_DEBOUNCE_MS: 16, // ~60fps
};
/**
* Check if hostname belongs to Telegram
* @param {string} hostname - The hostname to check
* @returns {boolean}
*/
function isTelegramHost(hostname) {
return CONFIG.TELEGRAM_HOSTS.has(hostname?.toLowerCase() || '');
}
/**
* Safely encode URI component with fallback
* @param {string} str - String to encode
* @returns {string}
*/
function safeEncodeURIComponent(str) {
try {
return encodeURIComponent(str);
} catch (error) {
console.warn('Failed to encode URI component:', str, error);
return str;
}
}
/**
* Build deep link URL from Telegram web URL
* @param {URL} urlObj - Parsed URL object
* @returns {string|null} - Deep link or null if not convertible
*/
function buildDeepLink(urlObj) {
try {
const pathParts = urlObj.pathname
.split('/')
.filter((part) => part.length > 0);
if (pathParts.length === 0) return null;
let [firstPart, secondPart] = pathParts;
const params = new URLSearchParams(urlObj.search);
if (firstPart.toLowerCase() === 's' && secondPart) {
firstPart = secondPart;
}
if (firstPart.toLowerCase() === 'contact' && secondPart) {
return `tg://contact?token=${safeEncodeURIComponent(secondPart)}`;
}
if (firstPart.toLowerCase() === 'bg' && secondPart) {
let deepLink = `tg://bg?slug=${safeEncodeURIComponent(secondPart)}`;
const mode = params.get('mode');
if (mode) {
deepLink += `&mode=${safeEncodeURIComponent(mode)}`;
}
return deepLink;
}
if (firstPart.startsWith('+')) {
const phoneNumber = firstPart.slice(1); // Remove '+' prefix
if (!phoneNumber) return null;
let deepLink = `tg://resolve?phone=${safeEncodeURIComponent(
phoneNumber
)}`;
if (params.has('text')) {
deepLink += `&text=${safeEncodeURIComponent(params.get('text'))}`;
}
if (params.has('profile')) {
deepLink += '&profile=1';
}
return deepLink;
}
const normalizedFirst = firstPart.toLowerCase();
if (
!CONFIG.RESERVED_PATHS.has(normalizedFirst) &&
CONFIG.USERNAME_PATTERN.test(firstPart)
) {
let deepLink = `tg://resolve?domain=${safeEncodeURIComponent(
firstPart
)}`;
if (params.has('text')) {
deepLink += `&text=${safeEncodeURIComponent(params.get('text'))}`;
}
if (params.has('profile')) {
deepLink += '&profile=1';
}
if (params.has('start')) {
deepLink += `&start=${safeEncodeURIComponent(params.get('start'))}`;
}
return deepLink;
}
return null;
} catch (error) {
console.warn('Error building deep link for URL:', urlObj.href, error);
return null;
}
}
/**
* Convert single anchor element to deep link if applicable
* @param {HTMLAnchorElement} anchor - The anchor element to process
* @returns {boolean} - True if link was modified
*/
function convertAnchorToDeepLink(anchor) {
if (!anchor?.href || anchor.tagName !== 'A') {
return false;
}
if (anchor.href.startsWith('tg://')) {
return false;
}
let urlObj;
try {
urlObj = new URL(anchor.href);
} catch (error) {
return false;
}
if (!isTelegramHost(urlObj.hostname)) {
return false;
}
const deepLink = buildDeepLink(urlObj);
if (!deepLink) {
return false;
}
if (anchor.href !== deepLink) {
anchor.href = deepLink;
return true;
}
return false;
}
/**
* Process all anchor elements within a root element
* @param {Element|Document} root - Root element to search within
* @returns {number} - Number of links converted
*/
function processAllAnchors(root = document) {
let convertedCount = 0;
try {
const anchors = root.querySelectorAll('a[href]');
for (const anchor of anchors) {
if (convertAnchorToDeepLink(anchor)) {
convertedCount++;
}
}
} catch (error) {
console.error('Error processing anchors:', error);
}
return convertedCount;
}
/**
* Debounced mutation processor
*/
let mutationTimeout;
const pendingNodes = new Set();
function processPendingMutations() {
if (pendingNodes.size === 0) return;
let processedCount = 0;
for (const node of pendingNodes) {
if (!document.contains(node)) continue;
if (node.tagName === 'A') {
if (convertAnchorToDeepLink(node)) {
processedCount++;
}
} else {
processedCount += processAllAnchors(node);
}
}
pendingNodes.clear();
if (processedCount > 0) {
console.debug(`Telegram Deep Link: Converted ${processedCount} links`);
}
}
function scheduleMutationProcessing() {
if (mutationTimeout) return;
mutationTimeout = setTimeout(() => {
mutationTimeout = null;
processPendingMutations();
}, CONFIG.MUTATION_DEBOUNCE_MS);
}
/**
* Handle DOM mutations
* @param {MutationRecord[]} mutations - Array of mutation records
*/
function handleMutations(mutations) {
for (const mutation of mutations) {
if (mutation.type === 'childList') {
for (const node of mutation.addedNodes) {
if (node.nodeType === Node.ELEMENT_NODE) {
pendingNodes.add(node);
}
}
} else if (
mutation.type === 'attributes' &&
mutation.target.tagName === 'A' &&
mutation.attributeName === 'href'
) {
pendingNodes.add(mutation.target);
}
}
if (pendingNodes.size > 0) {
scheduleMutationProcessing();
}
}
/**
* Initialize the extension
*/
function initialize() {
try {
const initialCount = processAllAnchors();
if (initialCount > 0) {
console.debug(
`Telegram Deep Link: Initial conversion of ${initialCount} links`
);
}
const observer = new MutationObserver(handleMutations);
observer.observe(document.documentElement, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ['href'],
});
window.addEventListener('beforeunload', () => {
observer.disconnect();
if (mutationTimeout) {
clearTimeout(mutationTimeout);
}
pendingNodes.clear();
});
} catch (error) {
console.error(
'Failed to initialize Telegram Deep Link extension:',
error
);
}
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initialize);
} else {
initialize();
}
})();