about summary refs log tree commit diff
path: root/src/lib/extractYoutubeMeta.ts
blob: 566e3be46df60bc1fb1b675dde79325143a20363 (plain) (blame)
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
export const extractYoutubeMeta = (html: string): Record<string, string> => {
  const res: Record<string, string> = {}
  const youtubeTitleRegex = /"videoDetails":.*"title":"([^"]*)"/i
  const youtubeDescriptionRegex =
    /"videoDetails":.*"shortDescription":"([^"]*)"/i
  const youtubeThumbnailRegex = /"videoDetails":.*"url":"(.*)(default\.jpg)/i

  const youtubeTitleMatch = youtubeTitleRegex.exec(html)
  const youtubeDescriptionMatch = youtubeDescriptionRegex.exec(html)
  const youtubeThumbnailMatch = youtubeThumbnailRegex.exec(html)

  if (youtubeTitleMatch && youtubeTitleMatch.length >= 1) {
    res.title = decodeURI(youtubeTitleMatch[1])
  }
  if (youtubeDescriptionMatch && youtubeDescriptionMatch.length >= 1) {
    res.description = decodeURI(youtubeDescriptionMatch[1]).replace(
      /\\n/g,
      '\n',
    )
  }
  if (youtubeThumbnailMatch && youtubeThumbnailMatch.length >= 2) {
    res.image = youtubeThumbnailMatch[1] + 'default.jpg'
  }

  return res
}