This repository has been archived by the owner on Mar 13, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
youtube.js
42 lines (31 loc) · 1.17 KB
/
youtube.js
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
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
export const ytRegex = /(?:http|https):\/\/(?:www\.|m\.)?(?:(?:youtube\.com\/(?:(?:v\/)|(?:(?:watch|embed\/watch)(?:\/|.*v=))|(?:embed\/)|(?:user\/[^/]+\/u\/[0-9]\/)))|(?:youtu\.be\/))([^#&?]*)/;
export function handleYoutubeTime(link) {
const timeRegex = /[\\?&](t|time|start|time_continue)=([0-9]+h)?([0-9]+m)?([0-9]+s?)/;
const time = link.match(timeRegex);
if (!time?.[0]) {
return '';
}
const hours = time[2]?.match(/([0-9]+)h/) ?? null;
const minutes = time[3]?.match(/([0-9]+)m/) ?? null;
const seconds = time[4]?.match(/([0-9]+)s?/) ?? null;
let startSeconds = 0;
if (hours?.[1]) {
startSeconds += parseInt(hours[1], 10) * 3600;
}
if (minutes?.[1]) {
startSeconds += parseInt(minutes[1], 10) * 60;
}
if (seconds?.[1]) {
startSeconds += parseInt(seconds[1], 10);
}
return `&start=${startSeconds}`;
}
export function getVideoId(link) {
const match = link.trim().match(ytRegex);
if (!match || match[1].length !== 11) {
return null;
}
return match[1];
}