forked from Superschnizel/Obsidian-Moviegrabber
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
525 lines (429 loc) · 16.1 KB
/
main.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
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
import { App, Editor, MarkdownView, Modal, Menu, Notice, Plugin, PluginSettingTab, Setting, requestUrl, normalizePath, WorkspaceLeaf, TFile, TAbstractFile } from 'obsidian';
import { MoviegrabberSettings, DEFAULT_SETTINGS, DEFAULT_TEMPLATE, MoviegrabberSettingTab } from "./src/MoviegrabberSettings"
import { MoviegrabberSearchModal } from "./src/MoviegrabberSearchModal"
import { MOVIE_DATA_LOWER, MovieData, MovieRating, MovieSearch, MovieSearchItem, Rating, TEST_SEARCH } from "./src/MoviegrabberSearchObject"
import { MoviegrabberSelectionModal } from 'src/MoviegrabberSelectionModal';
import { MovieGalleryView, VIEW_TYPE_MOVIE_GALLERY } from 'src/MovieGalleryView';
import { ConfirmOverwriteModal } from 'src/ConfirmOverwriteModal';
import { ConfirmCreateNoteModal } from 'src/ConfirmCreateNoteModal';
import { regexTransform } from 'src/RegexTransform'
const OVERWRITE_DELIMITER = /%%==MOVIEGRABBER_KEEP==%%[\s\S]*/
const IMDBID_REGEX = /^ev\d{1,8}\/\d{4}(-\d)?$|^(ch|co|ev|nm|tt)\d{1,8}$/
const EXLUDE_COMMA_SPLIT = ["imdbVotes", "BoxOffice"];
export default class Moviegrabber extends Plugin {
settings: MoviegrabberSettings;
async onload() {
await this.loadSettings();
// Search-Movie command
this.addCommand({
id: 'search-movie',
name: 'Search movie',
callback: () => {
if (this.settings.OMDb_API_Key == '') {
var n = new Notice("missing OMDb API key!")
n.noticeEl.addClass("notice_error");
return;
}
new MoviegrabberSearchModal(this.app, 'movie', (result) => {
this.searchOmdb(result, 'movie');
}).open();
}
});
// Search-Series command
this.addCommand({
id: 'search-series',
name: 'Search series',
callback: () => {
if (this.settings.OMDb_API_Key == '') {
var n = new Notice("missing OMDb API key!")
n.noticeEl.addClass("notice_error");
return;
}
new MoviegrabberSearchModal(this.app, 'series', (result) => {
this.searchOmdb(result, 'series');
}).open();
}
});
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new MoviegrabberSettingTab(this.app, this));
}
onunload() {
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
// search the OMDb and oben selection Modal if some are found
async searchOmdb(title: string, type: 'movie' | 'series', depth: number = 0) {
// cancel recursive retries if depth is too low
if (depth >= 4) {
this.SendWarningNotice(`Stopping after ${depth + 1} tries.`)
return;
}
// check if search string is valid IMDB-id
let isImdbId = IMDBID_REGEX.test(title);
// build request URL
var url = new URL("http://www.omdbapi.com");
// add year to search
let year = title.match(/\(\d{4}\)/g);
title = title.replace(/\(\d{4}\)/g, '').trim();
url.searchParams.append('apikey', this.settings.OMDb_API_Key);
url.searchParams.append(isImdbId ? 'i' : 's', title);
if (year) {
url.searchParams.append('y', year[0].replace(/[\(\)]/g, ''));
}
url.searchParams.append('type', type);
console.log(`requesting: ${url}`);
// fetch data
var response;
try {
response = await requestUrl(url.toString());
} catch (error) {
this.SendWarningNotice(`Error in request while trying to search ${type}!\nretrying...`);
this.searchOmdb(title, type, depth + 1);
return;
}
if (response.status != 200) {
var n = new Notice(`Http Error! Status: ${response.status}`);
n.noticeEl.addClass("notice_error");
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json;
if (data.Response != "True") {
var n = new Notice(`Found no movies named ${title}!`)
n.noticeEl.addClass("notice_error")
return;
}
if (isImdbId) {
let movie = data as MovieData;
new ConfirmCreateNoteModal(this.app, movie, () => {
this.tryCreateNote(movie, type);
}).open();
return;
}
new MoviegrabberSelectionModal(this.app, data as MovieSearch, (result) => {
this.tryCreateNote(result, type);
}).open();
}
// get the Movie Data from OMDb
async getOmdbData(movie: MovieSearchItem, depth: number = 0): Promise<MovieData | null | undefined> {
// end retries if recursion too deep.
if (depth >= 4) {
var n = new Notice(`Could not fetch Movie data: quit after ${depth + 1} tries!`);
n.noticeEl.addClass("notice_error");
return null;
}
// build request URL
var url = new URL("http://www.omdbapi.com");
url.searchParams.append('apikey', this.settings.OMDb_API_Key);
url.searchParams.append('i', movie.imdbID);
url.searchParams.append('plot', this.settings.PlotLength);
// fetch data
var response;
try {
response = await requestUrl(url.toString());
} catch (error) {
var n = new Notice(`Error in request while trying to fetch Movie Data!\n...retrying`);
return this.getOmdbData(movie, depth + 1); // retry by recursion
}
if (response.status != 200) {
var n = new Notice(`Http Error! Status: ${response.status}`);
n.noticeEl.addClass("notice_error");
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json;
if (data.Response != "True") {
var n = new Notice(`Found no movies named ${movie.Title}!`)
n.noticeEl.addClass("notice_error");
return null;
}
return data as MovieData;
}
// get the trailer embed from youtube.
async getTrailerEmbed(title: string, year: number): Promise<string> {
var url = new URL("https://www.googleapis.com/youtube/v3/search");
url.searchParams.append("part", "snippet");
url.searchParams.append("key", this.settings.YouTube_API_Key);
url.searchParams.append("type", "video")
url.searchParams.append("q", `${title} ${year} trailer`)
var response;
try {
response = await requestUrl(url.toString());
} catch (error) {
var n = new Notice(`Error while trying to fetch Youtube trailer embed!`);
n.noticeEl.addClass("notice_error");
return "Could not find trailer."
}
// something went wrong doing the request.
if (response.status != 200) {
var n = new Notice(`Http Error! Status: ${response.status}`);
n.noticeEl.addClass("notice_error");
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json;
if ('error' in data) {
var n = new Notice('failed to grab Trailer');
n.noticeEl.addClass("notice_error");
return '';
}
var embed = `<iframe src="https://www.youtube.com/embed/${data.items[0].id.videoId}" title="${data.items[0].snippet.title.replace(/[/\\?%*:|#"<>]/g, '')}" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>`
return embed;
}
async tryCreateNote(item: MovieSearchItem | MovieData, type: 'movie' | 'series') {
// create path and check for directory before posting the request
// Transform Search into MovieData if it is not already MovieData
var itemData = ('Response' in item) ? item as MovieData : await this.getOmdbData(item);
if (itemData == null || itemData == undefined) {
var n = new Notice(`something went wrong in fetching ${item.Title} data`)
n.noticeEl.addClass("notice_error")
return;
}
var dir = type == 'movie' ? this.settings.MovieDirectory : this.settings.SeriesDirectory;
dir = this.CleanPath(dir);
dir = dir != '' ? `${dir}/` : ''; // this might be unecessary.
if (!(await this.app.vault.adapter.exists(dir))) {
var n = new Notice(`Folder for ${type}: "${dir}" does not exist!`)
n.noticeEl.addClass("notice_error")
return;
}
let filenameTemplate = type == 'movie'
? this.settings.FilenameTemplateMovie
: this.settings.FilenameTemplateSeries;
let filename = await this.FillTemplate(filenameTemplate, itemData);
filename = filename == '' ? item.Title : filename;
const cleanedTitle = filename.replace(/[/\\?%*:|"<>]/g, '')
let path = `${dir}${cleanedTitle}.md`
let file = this.app.vault.getAbstractFileByPath(path);
// console.log(`${file}, path: ${path}`);
if (file != null && file instanceof TFile) {
new ConfirmOverwriteModal(this.app, item, () => {
this.createNote(itemData!, type, path, cleanedTitle, file as TFile);
}).open();
return;
}
this.createNote(itemData, type, path, cleanedTitle);
}
async createNote(item: MovieData, type: 'movie' | 'series', path: string, filename: string, tFile: TFile | null = null) {
new Notice(`Creating Note for: ${item.Title} (${item.Year})`);
// add and clean up data
// clean Movie Title to avoid frontmatter issues
item.Title = item.Title.replace(/[/\\?%*:|"<>]/g, '');
item.Runtime = item.Runtime ? item.Runtime.split(" ")[0] : '';
// add youtube trailer if API key is given
if (this.settings.YouTube_API_Key != '') {
item.YoutubeEmbed = await this.getTrailerEmbed(item.Title, item.Year);
}
// if poster saving is enabled, save images
if (this.settings.enablePosterImageSave && item.Poster !== null && item.Poster !== "N/A") {
const imageName = `${filename}.jpg`;
const posterDirectory = this.settings.posterImagePath;
await this.downloadAndSavePoster(item.Poster, posterDirectory, imageName)
.then(posterLocalPath => {
item.PosterLocal = imageName; // i think full path is usualy not needed.
new Notice(`Saved poster for: ${item!.Title} (${item!.Year})`);
})
.catch(error => {
console.error("Failed to download and save the poster:", error);
let n = new Notice(`Failed to download and save the movie poster for: ${item!.Title} (${item!.Year})`);
n.noticeEl.addClass("notice_error");
item!.PosterLocal = 'null';
});
}
// get and fill template
var template = await this.GetTemplate(type)
if (template == null) {
return;
}
var content = await this.FillTemplate(template, item);
/* var content =
`---\n`+
`type: ${type}\n`+
`country: ${itemData.Country}\n`+
`title: ${itemData.Title}\n`+
`year: ${itemData.Year}\n`+
`director: ${itemData.Director}\n`+
`actors: [${itemData.Actors}]\n`+
`genre: [${itemData.Genre}]\n`+
`length: ${ itemData.Runtime.split(" ")![0] }\n`+
(type == 'movie' ? '' : `seasons: ${itemData.totalSeasons}\n`) +
`seen:\n`+
`rating: \n`+
`found_at: \n`+
(this.settings.YouTube_API_Key != '' ? `trailer_embed: ${await this.getTrailerEmbed(itemData.Title, itemData.Year)}\n` : '') +
`poster: "${itemData.Poster}"\n`+
`availability:\n`+
`---\n`+
`${itemData.Plot}` */
// create and open file
if (tFile == null) {
tFile = await this.app.vault.create(path, content);
} else {
let oldContent = await this.app.vault.read(tFile);
// find delimiter string if it exists and keep whatever is below.
let toKeep = OVERWRITE_DELIMITER.exec(oldContent);
// make sure there is only one delimiter
let newContent = toKeep != null ? content.replace(OVERWRITE_DELIMITER, '\n') + toKeep : content;
this.app.vault.modify(tFile, newContent);
// trigger "create" Event to assure compatibility with other plugins, like templater
this.app.vault.trigger("create", tFile);
}
if (this.settings.SwitchToCreatedNote) {
this.app.workspace.getLeaf().openFile(tFile);
}
}
async downloadAndSavePoster(imageUrl: string, directory: string, imageName: string): Promise<string> {
if (!directory) {
console.error("Poster image directory is not specified.");
throw new Error("Poster image directory is not specified.");
}
const filePath = normalizePath(`${directory}/${imageName}`);
try {
const response = await requestUrl({ url: imageUrl, method: "GET" });
const imageData = response.arrayBuffer;
await this.app.vault.adapter.writeBinary(filePath, imageData);
return filePath;
} catch (error) {
console.error("Error downloading or saving poster image:", error);
throw error;
}
}
async GetTemplate(type: 'movie' | 'series'): Promise<string | null> {
if (this.settings.MovieTemplatePath == '') {
// no template given, return default
return DEFAULT_TEMPLATE;
}
// handle paths with both .md and not .md at the end
var path = type == 'movie' ? this.settings.MovieTemplatePath : this.settings.SeriesTemplatePath;
path = this.CleanPath(path).replace(".md", '') + '.md';
var tAbstractFile = this.app.vault.getAbstractFileByPath(path);
if (tAbstractFile == null || !(tAbstractFile instanceof TFile)) {
this.SendWarningNotice("Template Path is not a File in Vault.\nstopping")
return null;
}
var tFile = tAbstractFile as TFile;
var text = await this.app.vault.cachedRead(tFile);
return text;
}
async FillTemplate(template: string, data: MovieData): Promise<string> {
return template.replace(/{{(.*?)}}/g, (match) => {
// console.log(match);
let inner = match.split(/{{|}}/).filter(Boolean)[0];
if (!inner) {
return match;
}
let split = inner.split(/(?<!\\)\|/); // split at not escaped "|"
const prefix = split.length >= 2 ? split[1].replace(/\\\|/, '|') : '';
const suffix = split.length >= 3 ? split[2].replace(/\\\|/, '|') : '';
const transformation = split.length >= 4 ? split[3].replace(/\\\|/, '|') : '';
const stringFunction = split.length >= 5 ? split[4].replace(/\\\|/, '|') : '';
let result = '';
// handle the data being a list.
let name = MOVIE_DATA_LOWER[split[0].trim().toLowerCase()];
// console.log(`${name}, --> ${data[name]}`);
let rawData = data[name];
// only Ratings are in an array other lists are comma separated
let items = rawData instanceof Array
? rawData.map((elem): string => {
let r = elem as MovieRating;
return `${r.Source}: ${r.Value}`;
})
: (EXLUDE_COMMA_SPLIT.contains(name) ? [rawData] :
rawData?.split(/\,\s?/));
if (!items) {
console.log(`Tag "{{${inner}}}" could not be resolved.`);
new Notice(`Warning: Tag "{{${inner}}}" could not be resolved.`)
return `{{${inner}}}`;
}
items = items.map((elem: string): string => {
return regexTransform(elem, transformation);
})
if (stringFunction != '') {
items = items.map((elem: string): string => {
try {
// @ts-ignore
let str = elem[stringFunction]();
return str;
} catch (error) {
let n = new Notice(`${stringFunction} is not a valid string Function!`)
}
return elem;
})
}
for (let i = 0; i < items.length; i++) {
if (items[i] == '') {
continue;
}
result += result != '' ? ', ' : '';
result += prefix;
result += items[i]; // data
result += suffix;
}
return result;
});
}
SendWarningNotice(text: string) {
var n = new Notice(text);
n.noticeEl.addClass("notice_error")
}
async CreateDefaultTemplateFile() {
var content = DEFAULT_TEMPLATE +
"\n\n\n%%\n" +
"Available tags:\n" +
"----------------------\n" +
"{{Title}}\n" +
"{{Year}}\n" +
"{{Rated}}\n" +
"{{Runtime}}\n" +
"{{Genre}}\n" +
"{{Director}}\n" +
"{{Writer}}\n" +
"{{Actors}}\n" +
"{{Plot}}\n" +
"{{Language}}\n" +
"{{Country}}\n" +
"{{Awards}}\n" +
"{{Poster}}\n" +
"{{PosterLocal}}" +
"{{Ratings}}\n" +
"{{Released}}\n" +
"{{Metascore}}\n" +
"{{imdbRating}}\n" +
"{{imdbVotes}}\n" +
"{{imdbID}}\n" +
"{{Type}}\n" +
"{{DVD}}\n" +
"{{BoxOffice}}\n" +
"{{Production}}\n" +
"{{Website}}\n" +
"{{totalSeasons}}\n" +
"{{YoutubeEmbed}}\n" +
"%%";
// create and open file
var tFile = await this.app.vault.create('/Moviegrabber-example-template.md', content);
this.app.workspace.getLeaf().openFile(tFile);
}
CleanPath(path: string): string {
path.replace(/(^[/\s]+)|([/\s]+$)/g, ''); // clean up forbidden symbols
path = path != '' ? `${path.replace(/\/$/, "")}` : ''; // trim "/"
return path;
}
async activateView() {
let { workspace } = this.app;
let leaf: WorkspaceLeaf;
let leaves = workspace.getLeavesOfType(VIEW_TYPE_MOVIE_GALLERY);
if (leaves.length > 0) {
// A leaf with our view already exists, use that
leaf = leaves[0];
workspace.revealLeaf(leaf);
return
}
// Our view could not be found in the workspace, create a new leaf
// in the right sidebar for it
leaf = workspace.getLeaf(false);
await leaf.setViewState({ type: VIEW_TYPE_MOVIE_GALLERY, active: true });
workspace.revealLeaf(leaf);
// "Reveal" the leaf in case it is in a collapsed sidebar
}
}