@levellr/crossgram
Version:
Repost Tweets to Telegram automatically
51 lines • 1.86 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.TwitterLinkUnshortener = void 0;
const node_fetch_1 = require("node-fetch");
const TWITTER_MEDIA_TYPES = ['video', 'photo'];
const SHORTLINK_REGEX = /https\:\/\/t\.co\/\w+/g;
class TwitterLinkUnshortener {
static extractShortlinks(tweetText) {
return [...tweetText.matchAll(SHORTLINK_REGEX)].map((match) => match[0]);
}
static async unshortenLinks(tweetText) {
const shortlinks = TwitterLinkUnshortener.extractShortlinks(tweetText);
for (const shortlink of shortlinks) {
let url = await TwitterLinkUnshortener.unshortenLink(shortlink);
if (TwitterLinkUnshortener.isTwitterMediaUrl(url)) {
url = '';
}
tweetText = tweetText.replace(shortlink, url).trim();
}
return tweetText;
}
static async unshortenLink(shortlink) {
if (!shortlink.startsWith('https://t.co/')) {
return shortlink;
}
let url = null;
try {
const response = await (0, node_fetch_1.default)(shortlink, {
method: 'head',
redirect: 'manual',
});
url = response.headers.get('location');
}
catch (err) {
throw new Error(`Error fetching ${shortlink}: ${err}`);
}
if (!url) {
throw new Error(`Request for URL ${shortlink} had no location header`);
}
return url;
}
static isTwitterMediaUrl(url) {
if (!url.startsWith('https://twitter.com/')) {
return false;
}
const parts = url.split('/');
return TWITTER_MEDIA_TYPES.includes(parts[parts.length - 2]);
}
}
exports.TwitterLinkUnshortener = TwitterLinkUnshortener;
//# sourceMappingURL=unshortener.js.map