|
| 1 | +// ported from https://github.com/takker99/ScrapBubble/blob/0.4.0/Page.tsx#L662 |
| 2 | + |
| 3 | +export interface YoutubeProps { |
| 4 | + params: URLSearchParams; |
| 5 | + videoId: string; |
| 6 | +} |
| 7 | + |
| 8 | +const youtubeRegExp = |
| 9 | + /https?:\/\/(?:www\.|)youtube\.com\/watch\?((?:[^\s]+&|)v=([a-zA-Z\d_-]+)(?:&[^\s]+|))/; |
| 10 | +const youtubeShortRegExp = |
| 11 | + /https?:\/\/youtu\.be\/([a-zA-Z\d_-]+)(?:\?([^\s]{0,100})|)/; |
| 12 | +const youtubeListRegExp = |
| 13 | + /https?:\/\/(?:www\.|)youtube\.com\/playlist\?((?:[^\s]+&|)list=([a-zA-Z\d_-]+)(?:&[^\s]+|))/; |
| 14 | + |
| 15 | +/** YoutubeのURLを解析してVideo IDなどを取り出す |
| 16 | + * |
| 17 | + * @param url YoutubeのURL |
| 18 | + * @return 解析結果 YoutubeのURLでなかったときは`undefined`を返す |
| 19 | + */ |
| 20 | +export const parseYoutube = (url: string): YoutubeProps | undefined => { |
| 21 | + { |
| 22 | + const matches = url.match(youtubeRegExp); |
| 23 | + if (matches) { |
| 24 | + const [, params, videoId] = matches; |
| 25 | + const _params = new URLSearchParams(params); |
| 26 | + _params.delete("v"); |
| 27 | + _params.append("autoplay", "0"); |
| 28 | + return { |
| 29 | + videoId, |
| 30 | + params: _params, |
| 31 | + }; |
| 32 | + } |
| 33 | + } |
| 34 | + { |
| 35 | + const matches = url.match(youtubeShortRegExp); |
| 36 | + if (matches) { |
| 37 | + const [, videoId] = matches; |
| 38 | + return { |
| 39 | + videoId, |
| 40 | + params: new URLSearchParams("autoplay=0"), |
| 41 | + }; |
| 42 | + } |
| 43 | + } |
| 44 | + { |
| 45 | + const matches = url.match(youtubeListRegExp); |
| 46 | + if (matches) { |
| 47 | + const [, params, listId] = matches; |
| 48 | + |
| 49 | + const _params = new URLSearchParams(params); |
| 50 | + const videoId = _params.get("v"); |
| 51 | + if (!videoId) return; |
| 52 | + _params.delete("v"); |
| 53 | + _params.append("autoplay", "0"); |
| 54 | + _params.append("list", listId); |
| 55 | + return { |
| 56 | + videoId, |
| 57 | + params: _params, |
| 58 | + }; |
| 59 | + } |
| 60 | + } |
| 61 | + return undefined; |
| 62 | +}; |
0 commit comments