-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.ts
332 lines (295 loc) · 9.2 KB
/
cli.ts
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
/* eslint-disable @typescript-eslint/no-var-requires */
/* eslint-disable no-void */
import fs from "fs";
import path from "path";
import os from "os";
import { fetchMscz, setMscz, MSCZ_URL_SYM } from "./mscz";
import { loadMscore, INDV_DOWNLOADS, WebMscore } from "./mscore";
import {
ScoreInfo,
ScoreInfoHtml,
ScoreInfoObj,
getActualId,
} from "./scoreinfo";
import { getLibreScoreLink } from "./librescore-link";
import { escapeFilename, DISCORD_URL, fetchBuffer } from "./utils";
import { isNpx, getVerInfo, getSelfVer } from "./npm-data";
import { getFileUrl } from "./file";
// import { exportPDF } from "./pdf";
import i18n from "./i18n";
const inquirer: typeof import("inquirer") = require("inquirer");
const ora: typeof import("ora") = require("ora");
const chalk: typeof import("chalk") = require("chalk");
const SCORE_URL_PREFIX = "https://(s.)musescore.com/";
const SCORE_URL_REG = /https:\/\/(s\.)?musescore\.com\//;
const EXT = ".mscz";
type ExpDlType = "midi";
interface Params {
fileInit: string;
confirmed: boolean;
useExpDL: boolean;
expDlTypes: ExpDlType[];
part: number;
types: number[];
dest: string;
}
/**
* Prompt for destination directory
*/
const dest =
"C:\\Users\\Andrew\\OneDrive - 國立中正大學\\ccu cs\\程式設計(二)\\Final Project\\pianotranscription\\midi";
// const promptDest = async () => {
// const { dest } = await inquirer.prompt<Params>({
// type: "input",
// name: "dest",
// message: "Destination Directory:",
// validate(input: string) {
// return input && fs.statSync(input).isDirectory();
// },
// default: process.cwd(),
// });
// return dest;
// };
const createSpinner = () => {
return ora({
text: i18n("PROCESSING")(),
color: "blue",
spinner: "bounce",
indent: 0,
}).start();
};
const checkboxValidate = (input: number[]) => {
return input.length >= 1;
};
/**
* MIDI/MP3/PDF express download using the file API (./file.ts)
*/
const expDL = async (scoreinfo: ScoreInfoHtml) => {
// print a blank line
console.log();
// filetype selection
// const { expDlTypes } = await inquirer.prompt<Params>({
// type: "checkbox",
// name: "expDlTypes",
// message: "Filetype Selection",
// choices: [
// "midi",
// "mp3",
// "pdf", // ExpDlType
// new inquirer.Separator(),
// new inquirer.Separator(
// "Unavailable in express download\n" +
// " - MSCZ\n" +
// " - MusicXML\n" +
// " - FLAC/OGG Audio\n" +
// " - Individual Parts"
// ),
// ],
// validate: checkboxValidate,
// pageSize: Infinity,
// });
const expDlTypes = "midi";
// destination directory selection
const dest =
"C:\\Users\\Andrew\\OneDrive - 國立中正大學\\ccu cs\\程式設計(二)\\Final Project\\pianotranscription\\midi";
const spinner = createSpinner();
// await Promise.all(
// expDlTypes.map(async (type) => {
// download/generate file data
let fileData: Buffer;
// switch (type) {
// case "midi":
// case "mp3": {
// const fileUrl = await getFileUrl(scoreinfo.id, type);
// fileData = await fetchBuffer(fileUrl);
// break;
// }
// // case "pdf": {
// // // fileData = Buffer.from(await exportPDF(scoreinfo, scoreinfo.sheet));
// // break;
// // }
// }
const type = "midi";
const fileUrl = await getFileUrl(scoreinfo.id, type);
fileData = await fetchBuffer(fileUrl);
// save to filesystem
const f = path.join(dest, `${scoreinfo.fileName}.${type}`);
await fs.promises.writeFile(f, fileData);
spinner.info(`Saved ${chalk.underline(f)}`);
// })
// );
spinner.succeed("OK");
};
void (async () => {
const arg = process.argv[2];
if (["-v", "--version"].includes(arg)) {
// ran with flag -v or --version, `msdl -v`
console.log(getSelfVer()); // print musescore-downloader version
return; // exit process
}
// Determine platform and paste message
const platform = os.platform();
let pasteMessage = "";
if (platform === "win32") {
pasteMessage = "right-click to paste";
} else if (platform === "linux") {
pasteMessage = "usually Ctrl+Shift+V to paste";
} // For MacOS, no hint is needed because the paste shortcut is universal.
let scoreinfo: ScoreInfo;
let librescoreLink: Promise<string> | undefined;
// ask for the page url or path to local file
const { fileInit } = await inquirer.prompt<Params>({
type: "input",
name: "fileInit",
message: "Score URL or path to local MSCZ file:",
suffix:
"\n " +
`(starts with "${SCORE_URL_PREFIX}" or local filepath ends with "${EXT}") ` +
`${chalk.bgGray(pasteMessage)}\n `,
validate(input: string) {
return (
input &&
(!!input.match(SCORE_URL_REG) ||
(input.endsWith(EXT) && fs.statSync(input).isFile()))
);
},
default: arg,
});
const isLocalFile = fileInit.endsWith(EXT);
if (!isLocalFile) {
// request scoreinfo
scoreinfo = await ScoreInfoHtml.request(fileInit);
try {
await getActualId(scoreinfo as any);
} catch (err) {
console.error(err);
}
// confirmation
// const { confirmed } = await inquirer.prompt<Params>({
// type: "confirm",
// name: "confirmed",
// message: "Continue?",
// prefix:
// `${chalk.yellow("!")} ` +
// `ID: ${scoreinfo.id}\n ` +
// `Title: ${scoreinfo.title}\n `,
// default: true,
// });
// if (!confirmed) return;
// print a blank line
console.log();
// ask for express download
// const { useExpDL } = await inquirer.prompt<Params>({
// type: "confirm",
// name: "useExpDL",
// prefix:
// `${chalk.blueBright("ℹ")} ` +
// "MIDI/MP3/PDF express download is now available.\n ",
// message: "🚀 Give it a try?",
// default: true,
// });
const useExpDL = true;
if (useExpDL) return expDL(scoreinfo as ScoreInfoHtml);
// initiate LibreScore link request
librescoreLink = getLibreScoreLink(scoreinfo);
librescoreLink.catch(() => ""); // silence this unhandled Promise rejection
// print a blank line to the terminal
console.log();
} else {
scoreinfo = new ScoreInfoObj(0, path.basename(fileInit, EXT));
}
const spinner = createSpinner();
let score: WebMscore;
let metadata: import("webmscore/schemas").ScoreMetadata;
try {
if (!isLocalFile) {
// fetch mscz file from the dataset, and cache it for side effect
await fetchMscz(scoreinfo);
} else {
// load local file
const data = await fs.promises.readFile(fileInit);
await setMscz(scoreinfo, data.buffer);
}
spinner.info("MSCZ file loaded");
if (!isLocalFile) {
spinner.info(`File URL: ${scoreinfo.store.get(MSCZ_URL_SYM) as string}`);
}
if (librescoreLink) {
try {
spinner.info(
`${i18n("VIEW_IN_LIBRESCORE")()}: ${await librescoreLink}`
);
} catch {} // it doesn't affect the main feature
}
spinner.start();
// load score using webmscore
score = await loadMscore(scoreinfo);
metadata = await score.metadata();
spinner.info("Score loaded by webmscore");
} catch (err) {
spinner.fail(err.message);
spinner.info(
"Send your URL to the #dataset-patcher channel in the LibreScore Community Discord server:\n " +
DISCORD_URL
);
return;
}
spinner.succeed("OK\n");
// build part choices
const partChoices = metadata.excerpts.map((p) => ({
name: p.title,
value: p.id,
}));
// add the "full score" option as a "part"
partChoices.unshift({ value: -1, name: i18n("FULL_SCORE")() });
// build filetype choices
const typeChoices = INDV_DOWNLOADS.map((d, i) => ({
name: d.name,
value: i,
}));
// part selection
const { part } = await inquirer.prompt<Params>({
type: "list",
name: "part",
message: "Part Selection",
choices: partChoices,
});
const partName = partChoices[part + 1].name;
await score.setExcerptId(part);
// filetype selection
const { types } = await inquirer.prompt<Params>({
type: "checkbox",
name: "types",
message: "Filetype Selection",
choices: typeChoices,
validate: checkboxValidate,
});
const filetypes = types.map((i) => INDV_DOWNLOADS[i]);
// destination directory
const dest =
"C:\\Users\\Andrew\\OneDrive - 國立中正大學\\ccu cs\\程式設計(二)\\Final Project\\pianotranscription\\midi";
// export files
const fileName = scoreinfo.fileName || (await score.titleFilenameSafe());
spinner.start();
await Promise.all(
filetypes.map(async (d) => {
const data = await d.action(score);
const n = `${fileName} - ${escapeFilename(partName)}.${d.fileExt}`;
const f = path.join(dest, n);
await fs.promises.writeFile(f, data);
spinner.info(`Saved ${chalk.underline(f)}`);
spinner.start();
})
);
spinner.succeed("OK");
if (!isNpx()) {
const { installed, latest, isLatest } = await getVerInfo();
if (!isLatest) {
console.log(
chalk.yellowBright(
`\nYour installed version (${installed}) of the musescore-downloader CLI is not the latest one (${latest})!\nRun npm i -g musescore-downloader@${latest} to update.`
)
);
}
}
})();