aboutsummaryrefslogtreecommitdiff
path: root/src/utils.ts
blob: 2e10fb43f38e12a2a3916e310a2c876fc3fe5e64 (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
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import isNodeJs from "detect-node";
import { isGmAvailable, _GM } from "./gm";

export const escapeFilename = (s: string): string => {
    return s.replace(/[\s<>:{}"/\\|?*~.\0\cA-\cZ]+/g, "_");
};

export const getIndexPath = (id: number): string => {
    const idStr = String(id);
    // 获取最后三位,倒序排列
    // x, y, z are the reversed last digits of the score id. Example: id 123456789, x = 9, y = 8, z = 7
    // https://developers.musescore.com/#/file-urls
    // "5449062" -> ["2", "6", "0"]
    const indexN = idStr.split("").reverse().slice(0, 3);
    return indexN.join("/");
};

const NODE_FETCH_HEADERS = {
    "User-Agent":
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.2535.85",
    "Accept-Language": "en-US;q=0.8",
};

export const getFetch = (): typeof fetch => {
    if (!isNodeJs) {
        return fetch;
    } else {
        // eslint-disable-next-line @typescript-eslint/no-var-requires
        const nodeFetch = require("node-fetch");
        // eslint-disable-next-line @typescript-eslint/no-var-requires
        // Use proxy based on standard proxy environment variables
        const ProxyAgent = require("proxy-agent");
        return (input: RequestInfo, init?: RequestInit) => {
            if (typeof input === "string" && !input.startsWith("http")) {
                // fix: Only absolute URLs are supported
                input = "https://musescore.com" + input;
            }
            init = Object.assign({
                headers: NODE_FETCH_HEADERS,
                // Use the `HTTPS_PROXY` environment variable for no URL given
                // see: https://github.com/TooTallNate/node-proxy-agent#proxy-agent
                agent: new ProxyAgent(),
            }, init);
            // eslint-disable-next-line @typescript-eslint/no-unsafe-return
            return nodeFetch(input, init);
        };
    }
};

export const fetchData = async (
    url: string,
    init?: RequestInit
): Promise<Uint8Array> => {
    const _fetch = getFetch();
    const r = await _fetch(url, init);
    const data = await r.arrayBuffer();
    return new Uint8Array(data);
};

export const fetchBuffer = async (
    url: string,
    init?: RequestInit
): Promise<Buffer> => {
    const d = await fetchData(url, init);
    return Buffer.from(d.buffer);
};

export const assertRes = (r: Response): void => {
    if (!r.ok) throw new Error(`${r.url} ${r.status} ${r.statusText}`);
};

export const useTimeout = async <T>(
    promise: T | Promise<T>,
    ms: number
): Promise<T> => {
    if (!(promise instanceof Promise)) {
        return promise;
    }

    return new Promise((resolve, reject) => {
        const i = setTimeout(() => {
            reject(new Error("timeout"));
        }, ms);
        promise.then(resolve, reject).finally(() => clearTimeout(i));
    });
};

export const getSandboxWindowAsync = async (
    targetEl: Element | undefined = undefined
): Promise<Window> => {
    if (typeof document === "undefined") return {} as any as Window;

    if (isGmAvailable("addElement")) {
        // create iframe using GM_addElement API
        const iframe = await _GM.addElement("iframe", {});
        iframe.style.display = "none";
        return iframe.contentWindow as Window;
    }

    if (!targetEl) {
        return new Promise((resolve) => {
            // You need ads in your pages, right?
            const observer = new MutationObserver(() => {
                for (let i = 0; i < window.frames.length; i++) {
                    // find iframe windows created by ads
                    const frame = frames[i];
                    try {
                        const href = frame.location.href;
                        if (href === location.href || href === "about:blank") {
                            resolve(frame);
                            return;
                        }
                    } catch {}
                }
            });
            observer.observe(document.body, { subtree: true, childList: true });
        });
    }

    return new Promise((resolve) => {
        const eventName = "onmousemove";
        const id = Math.random().toString();

        targetEl[id] = (iframe: HTMLIFrameElement) => {
            delete targetEl[id];
            targetEl.removeAttribute(eventName);

            iframe.style.display = "none";
            targetEl.append(iframe);
            const w = iframe.contentWindow;
            resolve(w as Window);
        };

        targetEl.setAttribute(
            eventName,
            `this['${id}'](document.createElement('iframe'))`
        );
    });
};

export const getUnsafeWindow = (): Window => {
    // eslint-disable-next-line no-eval
    return window.eval("window") as Window;
};

export const console: Console = (
    typeof window !== "undefined" ? window : global
).console; // Object.is(window.console, unsafeWindow.console) == false

export const windowOpenAsync = (
    targetEl: Element | undefined,
    ...args: Parameters<Window["open"]>
): Promise<Window | null> => {
    return getSandboxWindowAsync(targetEl).then((w) => w.open(...args));
};

export const attachShadow = (el: Element): ShadowRoot => {
    return Element.prototype.attachShadow.call(el, {
        mode: "open",
    }) as ShadowRoot;
};

export const waitForDocumentLoaded = (): Promise<void> => {
    if (document.readyState !== "complete") {
        return new Promise((resolve) => {
            const cb = () => {
                if (document.readyState === "complete") {
                    resolve();
                    document.removeEventListener("readystatechange", cb);
                }
            };
            document.addEventListener("readystatechange", cb);
        });
    } else {
        return Promise.resolve();
    }
};

/**
 * Run script before the page is fully loaded
 */
export const waitForSheetLoaded = (): Promise<void> => {
    return new Promise((resolve) => {
        const observer = new MutationObserver(() => {
            const meta = document.querySelector(
                "meta[property='og:type'][content='musescore:score']"
            );
            if (meta) {
                resolve();
                observer.disconnect();
            }
        });
        observer.observe(document, { childList: true, subtree: true });
    });
};