Skip to content

Commit

Permalink
Remove the query string from links to xeets (#303)
Browse files Browse the repository at this point in the history
* Remove query string from xeet links

* Move formatter test suite next to formatter itself

* Write test suite for URL normalization
  • Loading branch information
11k committed Aug 15, 2023
1 parent 3cb1c2d commit b72855b
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { AmazonAssociatesTagInjector } from './formatters';
import AmazonAssociatesTagInjector from './AmazonAssociatesTagInjector';

const chatStub = {
config: {
Expand Down
19 changes: 17 additions & 2 deletions assets/chat/js/formatters/UrlFormatter.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,16 +71,31 @@ export default class UrlFormatter {
const m = decodedUrl.match(self.linkregex);
if (m) {
const encodedUrl = self.encodeUrl(m[0]);
const normalizedUrl = this.normalizeUrl(encodedUrl);
const maxUrlLength = 90;
let urlText = encodedUrl;
let urlText = normalizedUrl;
if (urlText.length > maxUrlLength) {
urlText = `${urlText.slice(0, 40)}...${urlText.slice(-40)}`;
}
const extra = self.encodeUrl(decodedUrl.substring(m[0].length));
const href = `${scheme ? '' : 'http://'}${encodedUrl}`;
const href = `${scheme ? '' : 'http://'}${normalizedUrl}`;
return `<a target="_blank" class="externallink ${extraclass}" href="${href}" rel="nofollow">${urlText}</a>${extra}`;
}
return url;
});
}

/**
* @param {string} url
* @return {string} The normalized URL.
*/
normalizeUrl(url) {
if (/(x|twitter)\.com\/\w{1,15}\/status\/\d{2,19}\?/i.test(url)) {
// Remove the query string from xeet URLs to protect users from clicking
// on a link to a xeet they've already seen.
return url.split('?')[0];
}

return url;
}
}
29 changes: 29 additions & 0 deletions assets/chat/js/formatters/UrlFormatter.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import UrlFormatter from './UrlFormatter';

const urlFormatter = new UrlFormatter();

describe('Normalizing URLs', () => {
test('Remove the query string from a tweet URL', () => {
expect(
urlFormatter.normalizeUrl('https://twitter.com/jack/status/20?lang=en')
).toBe('https://twitter.com/jack/status/20');
});

test('Remove the query string from a xeet URL', () => {
expect(
urlFormatter.normalizeUrl('https://x.com/jack/status/20?lang=en')
).toBe('https://x.com/jack/status/20');
});

test("Don't modify a URL to a tweet that doesn't contain a query string", () => {
expect(urlFormatter.normalizeUrl('https://x.com/jack/status/20')).toBe(
'https://x.com/jack/status/20'
);
});

test("Don't modify a URL that isn't Twitter or X", () => {
expect(
urlFormatter.normalizeUrl('https://www.twitch.tv/search?term=vtuber')
).toBe('https://www.twitch.tv/search?term=vtuber');
});
});

0 comments on commit b72855b

Please sign in to comment.