aboutsummaryrefslogtreecommitdiff
path: root/src/yewtube-urls/yewtube_urls.js
blob: 9eca21f9f36539c693c8031d73c3f23c5746ffb5 (about) (plain)
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
 * SPDX-License-Identifier: CC0-1.0
 *
 * Library to convert youtube.com URLs to yewtu.be URLs.
 *
 * Copyright (C) 2021 Wojtek Kosior <koszko@koszko.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the CC0 1.0 Universal License as published by
 * the Creative Commons Corporation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * CC0 1.0 Universal License for more details.
 */

function decode_query_options(url)
{
    const query_options = {};
    const match = /^[^?]*\?(.*)/.exec(url);
    if (!match)
	return query_options;

    for (const opt of match[1].split("&")) {
	const [key, val] =
	      /^([^=]*)=?(.*)/.exec(opt).splice(1, 2).map(decodeURIComponent);
	query_options[key] = val;
    }

    return query_options;
}

function encode_query_options(query_options)
{
    return Object.entries(query_options)
	.map(ar => ar.map(encodeURIComponent).join("=")).join("&");
}

function make_yewtube_url(youtube_url)
{
    const query_options = decode_query_options(youtube_url);

    let endpoint = "";

    const match = /^(?:(?:https?:)?\/\/)?[^/]*\/([^?]*)/.exec(youtube_url);
    if (match)
	endpoint = match[1];

    if (/^embed\//.test(query_options.v))
	endpoint = query_options.v;

    if (/^embed\/.+/.test(endpoint))
	delete query_options.v;

    const encoded_options = encode_query_options(query_options);
    return `https://yewtu.be/${endpoint}?${encoded_options}`;
}