forked from mayankchd/movie
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.js
executable file
·571 lines (556 loc) · 16.6 KB
/
cli.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
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
#!/usr/bin/env node
"use strict";
import { Command } from "commander";
import chalk from "chalk";
import elegantSpinner from "elegant-spinner";
import logUpdate from "log-update";
import cliSelect from "cli-select";
import clipboardy from "node-clipboardy";
import dateFormat, { masks } from "dateformat";
import fs from "fs";
import sanitize from "sanitize-filename";
import prompts from "prompts";
import Conf from "conf";
import isFirstRun, { clearFirstRun } from "first-run";
import normalize from "normalize-path";
const omdbUrl = "http://www.omdbapi.com/?apikey=";
const tmdbUrlfind = "https://api.themoviedb.org/3/find/";
const program = new Command();
const options = program.opts();
const frame = elegantSpinner();
const now = new Date();
const cfg = new Conf({
projectName: 'movie-cli-2'
});
var clipboard = "";
var movietitle = "";
var originalTitle = "";
program
.name("movie")
.usage("[title] or [movie1]::[movie2]")
.version(
`movie-cli-2 1.1.0\nsettings are saved in ${cfg.path}`,
"-v, --version",
"output the current version"
)
.description(
"Get information about a movie or tv series or compare two movies"
)
.option("-k, --key", "set and save your apîkeys")
.option("-r, --reset", "resets options and clear keys")
.option("-s, --settings", "define settings")
.addHelpText(
"after",
`\n\nExamples:\n> movie Brazil\n> movie star wars::star trek // will compare 'star wars' and 'star trek'
settings are saved in ${cfg.path}`
)
.showHelpAfterError()
.parse(process.argv);
if ((isFirstRun({ name: "movie-cli-2" }) === true && !options.reset) || options.settings) {
console.log(`Thank you for using ${program.version()}\n`+
chalk.cyan(`This configuration step should only appear on the first run, or after using the --reset or --settings options.\n`));
await setConfig();
}
if (options.reset && isFirstRun({ name: "movie-cli-2" }) !== true) {
clearFirstRun({name: 'movie-cli-2'});
cfg.clear();
console.log('cleared prefs\n');
process.exit(1);
}
if (options.key) {
await askuser(
"omdbapiKey",`enter your omdb api key :`,
cfg.get("omdbapiKey", `2. enter your new tmdb api key :`, cfg.get("tmdbKey"))
);
await askuser(
"tmdbKey",
`2. enter your new tmdb api key :`,
cfg.get("tmdbKey")
);
}
if (program.args.length < 1) {
console.log(chalk.red("\nPlease input a movie name\n"));
program.help();
process.exit(1);
}
if (program.args.join().toUpperCase().indexOf("::") !== -1) {
compareInfo();
} else {
if (cfg.get("omdbapiKey") === undefined) {
await askuser("omdbapiKey", "please enter your omdb api key", "5e540903");
}
fetchMovie(
`${omdbUrl}${cfg.get('omdbapiKey')}&s=${program.args
.join()
.trim()
.replace(/ /g, "+")}`
)
.then(async (mov) => {
await printInfo(mov);
})
.then(async () => {
if (cfg.get("addCustomInfo") === true) {
await addCustomInfo();
}
})
.catch((error) => {
console.error(chalk.red('fetch error :', error));
});
}
async function fetchMovie(url) {
const interval = setInterval(function () {
logUpdate("Loading..." + chalk.cyan.bold.dim(frame()));
}, 50);
try {
const res = await fetch(url);
const data = await res.json();
clearInterval(interval);
logUpdate.clear();
if (data.Response === "False") {
console.log(chalk.red("ERROR : can't find matching title using ",url,"\n"));
process.exit(1);
}
return data;
} catch (error) {
logUpdate.clear();
console.log(chalk.red("ERROR !", error));
process.exit(1);
}
}
function compareInfo() {
const movies = program.args.join(" ").toUpperCase().split("::");
const urls = movies.map(function (mov) {
return `${omdbUrl}${cfg.get('omdbapiKey')}&t=${mov.trim().replace(/ /g, "+")}`;
});
const m0 = fetchMovie(urls[0]);
const m1 = fetchMovie(urls[1]);
Promise.all([m0, m1]).then((movies) => {
cfg.get("propsToCompare").forEach((prop) => {
if (movies[0][prop] === undefined) {
movies[0][prop] = "N/A";
}
if (movies[1][prop] === undefined) {
movies[1][prop] = "N/A";
}
console.log(
chalk.bold.cyan(prop),
" ".repeat(13 - prop.length),
movies[0][prop],
" ".repeat(50 - movies[0][prop].length),
movies[1][prop],
""
);
});
});
}
async function printInfo(movie) {
const movielist = new Array();
for (const result of movie["Search"]) {
movielist.push(`${result["Title"]} [[${result["Year"]}]]`);
}
await cliSelect({
values: movielist,
cleanup: true,
indentation: 3,
valueRenderer: (value, selected) => {
if (selected) {
return chalk.bold.green.underline(value);
}
return value;
},
})
.then(async (value) => {
//console.log('value:',value);
movietitle = value.value;
console.log(chalk.bold.green.underline("\n" + movietitle));
const movieinfo = await fetchMovie(
`${omdbUrl}${cfg.get('omdbapiKey')}&plot=full&i=${
movie["Search"][value.id]["imdbID"]
}`
);
logUpdate.clear();
// custom tags
var mytag = "";
if (cfg.get("includeTitleProp") === true) {
if (movieinfo.Type === "movie") {
mytag = "#movies";
} else if (movieinfo.Type === "series") {
mytag = "#TV";
}
var clipboard = `title:: ${movietitle}\ntags:: ${cfg.get("DefaultTags")}, ${mytag}\n`;
} else {
var clipboard = `tags:: ${cfg.get("DefaultTags")}, ${movieinfo.Type}\n`;
}
// check original title
if (cfg.get("fetchOriginalTitle") === true) {
const tmdbinfo = await fetchMovie(
`${tmdbUrlfind}${movieinfo.imdbID}?api_key=${cfg.get("tmdbKey")}&language=en-US&external_source=imdb_id`
);
//map only if original_title is different from title
if (tmdbinfo["movie_results"].length > 0) {
if (
tmdbinfo["movie_results"][0]["original_title"] !==
tmdbinfo["movie_results"][0]["title"] &&
tmdbinfo["movie_results"][0]["original_title"].length !== 0
) {
originalTitle = tmdbinfo["movie_results"][0]["original_title"];
}
} else {
originalTitle = "N/A";
}
}
// loop through keys
cfg.get('propsToShow').forEach(function (prop, i, arr) {
const dispValue = Object.create(movieinfo);
// reformat specific properties::values
switch (prop) {
case "original-title":
dispValue[prop] = `${originalTitle}`;
break;
case "imdbID":
dispValue[
prop
] = `[${movieinfo[prop]}](https://www.imdb.com/title/${movieinfo[prop]})`;
break;
case "Year":
dispValue[prop] = "[[" + dispValue[prop] + "]]";
break;
default:
dispValue[prop] = `${movieinfo[prop]}`;
}
if (dispValue[prop] !== "N/A" && dispValue[prop].length>0) {
console.log(
chalk.bold.cyan(prop) +
" ".repeat(15 - prop.length) +
": " +
dispValue[prop] +
""
);
clipboard += `${prop}:: ${dispValue[prop]}\n`;
}
});
console.log(
chalk.bold.cyan("imdbLink") +
" ".repeat(7) +
": https://www.imdb.com/title/",
movieinfo["imdbID"] + "\n\n"
);
if (cfg.get("copyToClipboard") === true) {
clipboardy.write(clipboard);
}
})
.catch((err) => {
console.log(" - cancelled - ", err);
});
}
async function addCustomInfo() {
// keep asking questions on Esc
const onCancel = (resp) => {
return true;
};
const resp = await prompts(
[
{
type: cfg.get("askRating") === true ? "number" : null,
name: "rating",
message: "input rating:: (0-10) > ",
initial: 5,
increment: 1,
round: 1,
min: 0,
max: 10,
},
{
type: cfg.get("askWatchedDate") === true ? "date" : null,
name: "watchdate",
message: "input watched:: (date) > ",
initial: now,
mask: "YYYY-MM-DD",
},
{
type: cfg.get("askAnything") === true ? "text" : null,
name: "customtext",
message: "input custom text > ",
},
{
type: "toggle",
name: "appendToJournal",
message: "Append entry to Journal Page ?",
initial: true,
active: "yes",
inactive: "no",
},
{
type: "toggle",
name: "saveToFile",
message: `Save details as ${movietitle}.md ?`,
initial: false,
active: "yes",
inactive: "no",
},
],
{ onCancel }
);
if (cfg.get("copyToClipboard") === true) {
var clip = await clipboardy.read();
// user rating
if (cfg.get("ratingStars") === true) {
clipboard += clip + convertToStars(resp.rating) + "\n";
} else {
clipboard += clip + `rating:: [[${resp.rating}]]\n`;
}
// watched
clipboard +=
"watched:: [[" +
dateFormat(resp.watchdate, cfg.get("myDateFormat")) +
"]]\n";
if (resp.customtext !== undefined) {
clipboard += resp.customtext;
}
clipboardy.write(clipboard);
}
if (resp.appendToJournal === true) {
fs.appendFile(
`${normalize(cfg.get("pathToJournal"))}/${dateFormat(
resp.watchdate,
"yyyy_mm_dd"
)}.md`,
"\n\n" + cfg.get("dailylogtemplate").replace("%movie%", movietitle),
"utf-8",
(err) => {
if (err) {console.log(err);}
}
);
}
if (resp.saveToFile === true) {
fs.writeFile(
`${normalize(cfg.get("saveFilePath"))}/${sanitize(movietitle)}.md`,
clipboard,
(err) => {
if (err) {
console.error(err);
} else {
console.log(
chalk.green(
`saved '${sanitize(movietitle)}.md' to '${normalize(cfg.get(
"saveFilePath"
))}'\n\n`
));
}
}
);
}
}
function convertToStars(val) {
var result = "rating:: ";
if (val === 0) {result += "[[💣]]";
return result;
}
result += "[[" + "⭐".repeat(Math.trunc(val / 2));
if (val % 2 !== 0) {result += "½]]";
} else {result += "]]";
}
return result;
}
async function askuser(dispKey, msg, initial) {
var prName = await prompts({
type: "text",
name: "prOmdb",
message: msg,
initial: initial !== undefined ? initial : "",
});
cfg.set(dispKey, prName.prOmdb);
}
async function setConfig() {
if (cfg.get("omdbapiKey") !== undefined && cfg.get("omdbapiKey") !== "")
{var init1 = cfg.get("omdbapiKey")} else {var init1 = "5e540903"}
if (cfg.get("tmdbKey") !== undefined && cfg.get("tmdbKey") !== "") {
var init2 = cfg.get("tmdbKey");
} else {
var init2 = "1a8d1689f01251ca6ee058b29622441e";
}
await askuser("omdbapiKey", `1. enter your new omdb api key :`, init1);
await askuser("tmdbKey", `2. enter your new tmdb api key :`, init2);
const ask = await prompts([
{
type: "multiselect",
name: "propsToShow",
message: `3. select metadata to display when SEARCHING :`,
choices: [
{ title: "original-title", value: "original-title" },
{ title: "Year", value: "Year" },
{ title: "Genre", value: "Genre" },
{ title: "Director", value: "Director" },
{ title: "Writer", value: "Writer" },
{ title: "Actors", value: "Actors" },
{ title: "Language", value: "Language" },
{ title: "Country", value: "Country" },
{ title: "Awards", value: "Awards" },
{ title: "Metascore", value: "Metascore" },
{ title: "imdbRating", value: "imdbRating" },
{ title: "imdbVotes", value: "imdbVotes" },
{ title: "Production", value: "Production" },
{ title: "Released", value: "Released" },
{ title: "Runtime", value: "Runtime" },
{ title: "Rated", value: "Rated" },
{ title: "DVD", value: "DVD" },
{ title: "BoxOffice", value: "BoxOffice" },
{ title: "imdbID", value: "imdbID" },
{ title: "Poster", value: "Poster" },
{ title: "Plot", value: "Plot" },
],
optionsPerPage: 28,
min: 1,
},
{
type: "multiselect",
name: "propsToCompare",
message: `4. select metadata to fetch when COMPARING items :`,
choices: [
{ title: "Title", value: "Title" },
{ title: "Year", value: "Year" },
{ title: "Released", value: "Released" },
{ title: "Runtime", value: "Runtime" },
{ title: "Genre", value: "Genre" },
{ title: "Metascore", value: "Metascore" },
{ title: "imdbRating", value: "imdbRating" },
{ title: "BoxOffice", value: "BoxOffice" },
{ title: "Production", value: "Production" },
{ title: "Director", value: "Director" },
{ title: "Writer", value: "Writer" },
{ title: "Actors", value: "Actors" },
],
optionsPerPage: 14,
min: 1,
},
{
type: "toggle",
name: "copyToClipboard",
message: `5. automatically save movie details to the clipboard (only for single search) ?`,
initial: true,
active: "yes",
inactive: "no",
},
{
type: "toggle",
name: "addCustomInfo",
message: `6. enable adding more data (eg: watched date, user rating, ...) once the details have been fetched ?`,
initial: true,
active: "yes",
inactive: "no",
},
{
type: (prev) => prev === true ? "toggle" : null,
name: "saveToFile",
message: ` - display option to "Save to file" after each search ?`,
initial: true,
active: "yes",
inactive: "no",
}
]);
const ask2 = await prompts([
{
type:
ask.copyToClipboard === true || ask.saveToFile === true
? "toggle"
: null,
name: "includeTitleProp",
message: ` - include "Title:: %movie% [[%year%]]" property when saving?`,
initial: true,
active: "yes",
inactive: "no",
},
{
type:
ask.copyToClipboard === true || ask.saveToFile === true
? "toggle"
: null,
name: "addDefaultTags",
message: ` - include "Tags:: %type%" property when saving ?`,
initial: true,
active: "yes",
inactive: "no",
},
{
type: (prev) => (prev === true ? "text" : null),
name: "DefaultTags",
message: ` - enter default tags (string) :`,
initial: "#watched",
},
{
type: ask.addCustomInfo === true ? "toggle" : null,
name: "askRating",
message: `7. prompt for user Rating (0-10) and add "rating::" property ? `,
initial: true,
active: "yes",
inactive: "no",
},
{
type: (prev) => (prev === true ? "toggle" : null),
name: "ratingStars",
message: ` - convert rating to stars [[⭐⭐🌟]] (else keep number) ?`,
initial: true,
active: "yes",
inactive: "no",
},
{
type: "toggle",
name: "askWatchedDate",
message: `8. prompt for watched date and add "watched:: [[%date%]]" property ?`,
initial: true,
active: "yes",
inactive: "no",
},
{
type: "toggle",
name: "askAnything",
message: `9. enable extra input (add a line with a note or review) ? `,
initial: false,
active: "yes",
inactive: "no",
},
{
type: "toggle",
name: "addToJournal",
message: `10.[logseq] append a log line in the daily journal page ?`,
initial: true,
active: "yes",
inactive: "no",
},
{
type: (prev) => (prev === true ? "text" : null),
name: "dailylogtemplate",
message: ` - set the log template (where %movie% will be replaced by the title):`,
initial: "- DONE #watched [[%movie%]]",
},
{
type: "text",
name: "myDateFormat",
message: `11. date format (see https://github.com/felixge/node-dateformat#mask-options) :`,
initial: "yyyy-mm-dd",
},
{
type: "text",
name: "pathToJournal",
message: `12.path to logseq journals (must exist) :`,
initial: "d:/logseq-movies/journals",
},
{
type: "text",
name: "saveFilePath",
message: `13.path to save files (must exist) :`,
initial: "d:/logseq-movies/pages",
},
]);
//map settings to config file
const mapset = (ask) => {
for (const [key, value] of Object.entries(ask)) {
cfg.set(key, value);
}}
mapset(ask);
mapset(ask2);
if (cfg.get("propsToShow"[0] === "original-title")) {
cfg.set("fetchOriginalTitle", true);
}
console.log('\n\nThank you ! settings are saved in :', chalk.yellow(cfg.path));
}