type MediaType = "twitter" | "youtube" | "external" ; export interface MediaLink { type : MediaType ; url : string ; } export function isMediaLink < T extends { } > ( link ) { if ( ( ( link as MediaLink ) . type === "twitter" || ( link as MediaLink ) . type === "external" || ( link as MediaLink ) . type === "youtube" ) && ( link as MediaLink ) . url ) { return true ; } return false ; } function formatLink ( type , url ) { return { url : url . startsWith ( "http" ) ? url : `https://${ url }` , type , } ; } const patterns = [ { type : "youtube" , pattern : /(https?:\/\/)?(www\.)?(youtube\.com\/watch\?v=[-_a-zA-z0-9]{1,12}|youtu\.be\/[-_a-zA-z0-9]{1,12})/g , } , { type : "twitter" , pattern : /(https?:\/\/)?(www\.|mobile\.)?(twitter\.com\/[a-zA-z0-9]+\/status\/[0-9]+)/g , } , ] ; export function findMediaLinks ( body ) { const media = [ ] ; for ( const { type , pattern } of patterns ) { const urls = new Set ( body . match ( pattern ) || [ ] ) ; Array . from ( urls ) . forEach ( ( url ) => { media . push ( formatLink ( type , url ) ) ; } ) ; } return media ; }