-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathlbryURI.js
More file actions
464 lines (407 loc) · 14.8 KB
/
Copy pathlbryURI.js
File metadata and controls
464 lines (407 loc) · 14.8 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
// Disabled flow in this copy. This copy is for uncompiled web server ES5 require()s.
// Placeholder until i18n can be adapted for node usage
const __ = (msg) => msg;
const isProduction = process.env.NODE_ENV === 'production';
const channelNameMinLength = 1;
const claimIdMaxLength = 40;
// see https://spec.lbry.com/#urls
const regexInvalidURI =
/[ =&#:$@%?;/\\"<>%{}|^~[\]`\u{0000}-\u{0008}\u{000b}-\u{000c}\u{000e}-\u{001F}\u{D800}-\u{DFFF}\u{FFFE}-\u{FFFF}]/u;
// const regexAddress = /^(b|r)(?=[^0OIl]{32,33})[0-9A-Za-z]{32,33}$/;
const regexPartProtocol = '^((?:lbry://)?)';
const regexPartStreamOrChannelName = '([^:$#/]*)';
const regexPartModifierSeparator = '([:$#]?)([^/]*)';
const queryStringBreaker = '^([\\S]+)([?][\\S]*)';
const separateQuerystring = new RegExp(queryStringBreaker);
const MOD_SEQUENCE_SEPARATOR = '*';
const MOD_CLAIM_ID_SEPARATOR_OLD = '#';
const MOD_CLAIM_ID_SEPARATOR = ':';
const MOD_BID_POSITION_SEPARATOR = '$';
/**
* Parses a LBRY name into its component parts. Throws errors with user-friendly
* messages for invalid names.
*
* Returns a dictionary with keys:
* - path (string)
* - isChannel (boolean)
* - streamName (string, if present)
* - streamClaimId (string, if present)
* - channelName (string, if present)
* - channelClaimId (string, if present)
* - primaryClaimSequence (int, if present)
* - secondaryClaimSequence (int, if present)
* - primaryBidPosition (int, if present)
* - secondaryBidPosition (int, if present)
*/
function parseURI(url, requireProto = false) {
// Break into components. Empty sub-matches are converted to null
const componentsRegex = new RegExp(
regexPartProtocol + // protocol
regexPartStreamOrChannelName + // stream or channel name (stops at the first separator or end)
regexPartModifierSeparator + // modifier separator, modifier (stops at the first path separator or end)
'(/?)' + // path separator, there should only be one (optional) slash to separate the stream and channel parts
regexPartStreamOrChannelName +
regexPartModifierSeparator
);
// chop off the querystring first
let QSStrippedURL, qs;
const qsRegexResult = separateQuerystring.exec(url);
if (qsRegexResult) {
[QSStrippedURL, qs] = qsRegexResult.slice(1).map((match) => match || null);
}
const cleanURL = QSStrippedURL || url;
const regexMatch = componentsRegex.exec(cleanURL) || [];
const [proto, ...rest] = regexMatch.slice(1).map((match) => match || null);
const path = rest.join('');
const [
streamNameOrChannelName,
primaryModSeparator,
rawPrimaryModValue,
pathSep, // eslint-disable-line no-unused-vars
possibleStreamName,
secondaryModSeparator,
secondaryModValue,
] = rest;
const primaryModValue = rawPrimaryModValue && rawPrimaryModValue.replace(/[^\x00-\x7F]/g, '');
const searchParams = new URLSearchParams(qs || '');
const startTime = searchParams.get('t');
// Validate protocol
if (requireProto && !proto) {
throw new Error(__('LBRY URLs must include a protocol prefix (lbry://).'));
}
// Validate and process name
if (!streamNameOrChannelName) {
throw new Error(__('URL does not include name.'));
}
rest.forEach((urlPiece) => {
if (urlPiece && urlPiece.includes(' ')) {
throw new Error(__('URL can not include a space'));
}
});
const includesChannel = streamNameOrChannelName.startsWith('@');
const isChannel = streamNameOrChannelName.startsWith('@') && !possibleStreamName;
const channelName = includesChannel && streamNameOrChannelName.slice(1);
if (includesChannel) {
if (!channelName) {
throw new Error(__('No channel name after @.'));
}
if (channelName.length < channelNameMinLength) {
throw new Error(
__(`Channel names must be at least ${channelNameMinLength} characters.`, {
channelNameMinLength,
})
);
}
}
// Validate and process modifier
const [primaryClaimId, primaryClaimSequence, primaryBidPosition, primaryPathHash] = parseURIModifier(
primaryModSeparator,
primaryModValue
);
const [secondaryClaimId, secondaryClaimSequence, secondaryBidPosition, secondaryPathHash] = parseURIModifier(
secondaryModSeparator,
secondaryModValue
);
const streamName = includesChannel ? possibleStreamName : streamNameOrChannelName;
const streamClaimId = includesChannel ? secondaryClaimId : primaryClaimId;
const channelClaimId = includesChannel && primaryClaimId;
const pathHash = primaryPathHash || secondaryPathHash;
return {
isChannel,
path,
...(streamName ? { streamName } : {}),
...(streamClaimId ? { streamClaimId } : {}),
...(channelName ? { channelName } : {}),
...(channelClaimId ? { channelClaimId } : {}),
...(primaryClaimSequence ? { primaryClaimSequence: parseInt(primaryClaimSequence, 10) } : {}),
...(secondaryClaimSequence ? { secondaryClaimSequence: parseInt(secondaryClaimSequence, 10) } : {}),
...(primaryBidPosition ? { primaryBidPosition: parseInt(primaryBidPosition, 10) } : {}),
...(secondaryBidPosition ? { secondaryBidPosition: parseInt(secondaryBidPosition, 10) } : {}),
...(startTime ? { startTime: parseInt(startTime, 10) } : {}),
...(pathHash ? { pathHash } : {}),
// The values below should not be used for new uses of parseURI
// They will not work properly with canonical_urls
claimName: streamNameOrChannelName,
claimId: primaryClaimId,
...(streamName ? { contentName: streamName } : {}),
...(qs ? { queryString: qs } : {}),
};
}
function parseURIModifier(modSeperator, modValue) {
let claimId;
let claimSequence;
let bidPosition;
let pathHash;
if (modSeperator) {
if (!modValue) {
throw new Error(__(`No modifier provided after separator ${modSeperator}.`, { modSeperator }));
}
if (modSeperator === MOD_CLAIM_ID_SEPARATOR || MOD_CLAIM_ID_SEPARATOR_OLD) {
claimId = modValue;
} else if (modSeperator === MOD_SEQUENCE_SEPARATOR) {
claimSequence = modValue;
} else if (modSeperator === MOD_BID_POSITION_SEPARATOR) {
bidPosition = modValue;
}
}
if (claimId && (claimId.length > claimIdMaxLength || !claimId.match(/^[0-9a-f]+$/))) {
const hashIndex = claimId.indexOf('#');
if (hashIndex >= 0) {
pathHash = claimId.substring(hashIndex);
claimId = claimId.substring(0, hashIndex);
// As a pre-caution to catch future odd urls coming in,
// validate the new claimId length and characters again after stripping off the pathHash
[claimId] = parseURIModifier(modSeperator, claimId);
} else {
console.log({ modSeperator, modValue }); // eslint-disable-line no-console
throw new Error(__(`Invalid claim ID %claimId%.`, { claimId }));
}
}
if (claimSequence && !claimSequence.match(/^-?[1-9][0-9]*$/)) {
throw new Error(__('Claim sequence must be a number.'));
}
if (bidPosition && !bidPosition.match(/^-?[1-9][0-9]*$/)) {
throw new Error(__('Bid position must be a number.'));
}
return [claimId, claimSequence, bidPosition, pathHash];
}
/**
* Takes an object in the same format returned by parse() and builds a URI.
*
* The channelName key will accept names with or without the @ prefix.
*/
function buildURI(UrlObj, suppressErrors = false, includeProto = true, protoDefault = 'lbry://') {
const {
streamName,
streamClaimId,
channelName,
channelClaimId,
primaryClaimSequence,
primaryBidPosition,
secondaryClaimSequence,
secondaryBidPosition,
startTime,
...deprecatedParts
} = UrlObj;
const { claimId, claimName, contentName } = deprecatedParts;
if (!suppressErrors) {
if (!isProduction) {
if (claimId) {
console.error(__("'claimId' should no longer be used. Use 'streamClaimId' or 'channelClaimId' instead")); // eslint-disable-line no-console
}
if (claimName) {
console.error(__("'claimName' should no longer be used. Use 'streamClaimName' or 'channelClaimName' instead")); // eslint-disable-line no-console
}
if (contentName) {
console.error(__("'contentName' should no longer be used. Use 'streamName' instead")); // eslint-disable-line no-console
}
}
if (!claimName && !channelName && !streamName) {
// eslint-disable-next-line no-console
console.error(
__("'claimName', 'channelName', and 'streamName' are all empty. One must be present to build a url.")
);
}
}
const formattedChannelName = channelName && (channelName.startsWith('@') ? channelName : `@${channelName}`);
const primaryClaimName = claimName || contentName || formattedChannelName || streamName;
const primaryClaimId = claimId || (formattedChannelName ? channelClaimId : streamClaimId);
const secondaryClaimName = (!claimName && contentName) || (formattedChannelName ? streamName : null);
const secondaryClaimId = secondaryClaimName && streamClaimId;
return (
(includeProto ? protoDefault : '') +
// primaryClaimName will always exist here because we throw above if there is no "name" value passed in
// $FlowFixMe
primaryClaimName +
(primaryClaimId ? `#${primaryClaimId}` : '') +
(primaryClaimSequence ? `:${primaryClaimSequence}` : '') +
(primaryBidPosition ? `${primaryBidPosition}` : '') +
(secondaryClaimName ? `/${secondaryClaimName}` : '') +
(secondaryClaimId ? `#${secondaryClaimId}` : '') +
(secondaryClaimSequence ? `:${secondaryClaimSequence}` : '') +
(secondaryBidPosition ? `${secondaryBidPosition}` : '') +
(startTime ? `?t=${startTime}` : '')
);
}
/* Takes a parseable LBRY URL and converts it to standard, canonical format */
function normalizeURI(URL) {
const {
streamName,
streamClaimId,
channelName,
channelClaimId,
primaryClaimSequence,
primaryBidPosition,
secondaryClaimSequence,
secondaryBidPosition,
startTime,
} = parseURI(URL);
return buildURI({
streamName,
streamClaimId,
channelName,
channelClaimId,
primaryClaimSequence,
primaryBidPosition,
secondaryClaimSequence,
secondaryBidPosition,
startTime,
});
}
function isURIValid(URL) {
try {
parseURI(normalizeURI(URL));
} catch (error) {
return false;
}
return true;
}
function isNameValid(claimName) {
return !regexInvalidURI.test(claimName);
}
function isURIClaimable(URL) {
let parts;
try {
parts = parseURI(normalizeURI(URL));
} catch (error) {
return false;
}
return parts && parts.streamName && !parts.streamClaimId && !parts.isChannel;
}
function convertToShareLink(URL) {
const {
streamName,
streamClaimId,
channelName,
channelClaimId,
primaryBidPosition,
primaryClaimSequence,
secondaryBidPosition,
secondaryClaimSequence,
} = parseURI(URL);
return buildURI(
{
streamName,
streamClaimId,
channelName,
channelClaimId,
primaryBidPosition,
primaryClaimSequence,
secondaryBidPosition,
secondaryClaimSequence,
},
false,
true,
'https://open.lbry.com/'
);
}
// WARNING: do not use this to parse a permanent URI. '*' is a valid character.
// Function retained here just in case.
function splitBySeparator(uri) {
const protocolLength = 7;
return uri.startsWith('lbry://') ? uri.slice(protocolLength).split(/[#:*]/) : uri.split(/#:\*\$/);
}
function isURIEqual(uriA, uriB) {
const parseA = parseURI(normalizeURI(uriA));
const parseB = parseURI(normalizeURI(uriB));
if (parseA.isChannel) {
if (parseB.isChannel && parseA.channelClaimId === parseB.channelClaimId) {
return true;
}
} else if (parseA.streamClaimId === parseB.streamClaimId) {
return true;
} else {
return false;
}
}
function normalizeClaimUrl(url) {
return normalizeURI(url.replace(/:/g, '#'));
}
/**
* Checks if a URI might be missing the @ prefix for the channel name.
* Returns a corrected URI with @ if applicable, or null if not applicable.
* This handles cases like "channel:id/content:id" which should be "@channel:id/content:id"
* (e.g., malformed URLs from Grok/Twitter that omit the @)
*/
function getCorrectedChannelUri(uri) {
try {
// Check if the URI has a path separator (indicating channel/content pattern)
// but doesn't have a channel name (meaning no @ was detected)
const parsed = parseURI(uri);
// If it already has a channelName, the @ is present - no correction needed
if (parsed.channelName) {
return null;
}
// Check if the raw URI contains a "/" followed by more content (channel/content pattern)
// Remove lbry:// protocol for checking
const uriWithoutProtocol = uri.replace(/^lbry:\/\//, '');
const slashIndex = uriWithoutProtocol.indexOf('/');
// Must have a slash with content after it (channel/content pattern)
if (slashIndex === -1 || slashIndex === uriWithoutProtocol.length - 1) {
return null;
}
const firstPart = uriWithoutProtocol.substring(0, slashIndex);
const secondPart = uriWithoutProtocol.substring(slashIndex + 1);
// First part should not already start with @
if (firstPart.startsWith('@')) {
return null;
}
// Both parts should have content (non-empty after any modifiers are stripped)
const firstNameMatch = firstPart.match(/^[^#:$*]+/);
const secondNameMatch = secondPart.match(/^[^#:$*]+/);
if (!firstNameMatch || !firstNameMatch[0] || !secondNameMatch || !secondNameMatch[0]) {
return null;
}
// Build the corrected URI with @ prefix
return `lbry://@${uriWithoutProtocol}`;
} catch (e) {
return null;
}
}
/**
* Checks if a web URL path might be missing the @ prefix for the channel name.
* Returns a corrected path with @ if applicable, or null if not applicable.
* This works on raw web paths BEFORE they are parsed into lbry:// URIs.
*
* Example: "JustMe:05/content:0" -> "@JustMe:05/content:0"
*/
function getCorrectedChannelWebPath(webPath) {
try {
// Must have a slash with content after it (channel/content pattern)
const slashIndex = webPath.indexOf('/');
if (slashIndex === -1 || slashIndex === webPath.length - 1) {
return null;
}
const firstPart = webPath.substring(0, slashIndex);
const secondPart = webPath.substring(slashIndex + 1);
// First part should not already start with @
if (firstPart.startsWith('@')) {
return null;
}
// Both parts should have content (non-empty name before any modifiers)
// Modifiers in web URLs use : instead of #
const firstNameMatch = firstPart.match(/^[^#:$*]+/);
const secondNameMatch = secondPart.match(/^[^#:$*]+/);
if (!firstNameMatch || !firstNameMatch[0] || !secondNameMatch || !secondNameMatch[0]) {
return null;
}
// Return the corrected path with @ prefix
return `@${webPath}`;
} catch (e) {
return null;
}
}
module.exports = {
parseURI,
buildURI,
normalizeURI,
normalizeClaimUrl,
isURIValid,
isURIEqual,
isNameValid,
isURIClaimable,
splitBySeparator,
convertToShareLink,
getCorrectedChannelUri,
getCorrectedChannelWebPath,
};