-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
214 lines (189 loc) · 6.6 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
import jetpack from "fs-jetpack";
import { Notice, Plugin, TFile, parseYaml } from "obsidian";
import * as path from "path";
import bangumiApi from "./lib/bangumiApi";
import { BangumiMatrix } from "./lib/bangumiMatrix";
import { parseEpisode } from "./lib/parser";
import { AnimeParserModal } from "./modal";
import { AnimeParserSettings, DEFAULT_SETTINGS } from "./settings/settings";
import { AnimeParserSettingTab } from "./settings/settingsTab";
import { open } from "./utils/mediaExtendedUtils";
import { createNote, pos2EditorRange, tFrontmatter, templateBuild } from "./utils/obsidianUtils";
import { generatePaddedSequence } from "./utils/utils";
export default class AnimeParserPlugin extends Plugin {
settings: AnimeParserSettings;
async onload() {
await this.loadSettings();
this.addSettingTab(new AnimeParserSettingTab(this.app, this));
this.addCommand({
id: "import a anime",
name: "Import a anime to obsidian",
callback: async () => {
new AnimeParserModal(this.app, this.settings.libraryPath, async (result) => {
await this.parseAnime(result);
}).open();
},
});
this.addCommand({
id: "sync the animes library",
name: "Sync the animes library to obsidian",
callback: async () => {
await this.syncLibrary();
},
});
this.addCommand({
id: "play the anime",
name: "Play the anime from current episode",
checkCallback: (checking) => {
const activeFile = this.app.workspace.getActiveFile();
if (!activeFile) return false;
if (!this.app.metadataCache.getFileCache(activeFile).frontmatter?.bangumiID)
return false;
if (checking) return true;
this.playAnime(activeFile);
return true;
},
});
this.addCommand({
id: "sync the bangumi",
name: "Sync the progress of current anime to bangumi",
checkCallback: (checking) => {
const activeFile = this.app.workspace.getActiveFile();
if (!activeFile) return false;
if (!this.app.metadataCache.getFileCache(activeFile).frontmatter?.bangumiID)
return false;
if (checking) return true;
this.syncBangumi(activeFile);
return true;
},
});
this.registerMarkdownPostProcessor((element, context) => {
const bangumiMatrix = new BangumiMatrix(this.app, this.settings);
return bangumiMatrix.process(element, context);
});
}
async loadSettings(): Promise<void> {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings(): Promise<void> {
await this.saveData(this.settings);
}
async syncLibrary() {
const animes = jetpack.list(this.settings.libraryPath);
for (const anime of animes) {
await this.parseAnime(anime);
await new Promise((resolve) => setTimeout(resolve, 500));
}
}
async parseAnime(name: string) {
const animePath = path.join(this.settings.libraryPath, name);
const { id } = await bangumiApi.search(name);
const {
images: { large: cover },
summary,
tags: tagNames,
total_episodes: totalEps,
} = await bangumiApi.getMetadata(id);
const tags = tagNames.map((tag) => tag.name);
const episodes = await bangumiApi.getEpisodes(id);
const episodeNames = episodes.map((ep) => ep.name_cn);
const videoExtensions = ["*.mp4", "*.mkv"];
const videos = jetpack.find(animePath, { matching: videoExtensions });
const suffix = path.extname(videos[0]);
const epIndexs = generatePaddedSequence(totalEps);
const unprocessedVideos = videos.filter(
(video) => !epIndexs.includes(path.basename(video, suffix))
);
if (unprocessedVideos.length) {
let parsedVideos;
const allUnprocessed = unprocessedVideos.length === videos.length;
if (allUnprocessed) {
parsedVideos = parseEpisode(videos);
parsedVideos.forEach((video, i) => jetpack.rename(video, epIndexs[i] + suffix));
} else {
const of = jetpack.find(animePath, { matching: ["*.of"] });
const processedVideos = videos.filter((video) =>
epIndexs.includes(path.basename(video, suffix))
);
const maxProcessedEpisode = Math.max(
...processedVideos.map((video) => parseInt(path.basename(video, suffix)))
);
const parsedEpisodes = parseEpisode(
of.concat(unprocessedVideos)
);
parsedVideos = [...parsedEpisodes.slice(1)];
unprocessedVideos.forEach((_, i) =>
jetpack.rename(parsedVideos[i], epIndexs[maxProcessedEpisode + i] + suffix)
);
}
if (videos.length < totalEps) {
jetpack
.find(animePath, { matching: ["*.of"], recursive: false })
.forEach(jetpack.remove);
const ofPath = path.join(
animePath,
path.basename(parsedVideos.slice(-1)[0], suffix) + ".of"
);
jetpack.write(ofPath, "");
}
}
const content = generatePaddedSequence(totalEps)
.slice(0, videos.length)
.map(
(video, index) =>
`- [ep${index + 1}. ${episodeNames[index]}](${
"mx://animes/" + name.replaceAll(" ", "%20") + "/" + video + suffix
})`
)
.join("\n");
const variables = {
cover: cover,
id: id,
summary: summary.replaceAll(/\n/g, ""),
tags: tags,
epNum: episodes.length,
};
const notePath = this.settings.savePath
? path.posix.join(this.settings.savePath, name + ".md")
: name + ".md";
const existingFile = this.app.vault.getFileByPath(notePath);
if (!existingFile) {
await createNote(
this.app,
notePath,
tFrontmatter(parseYaml(templateBuild(this.settings.yamlTemplate, variables))) +
"\n" +
content
);
} else {
const frontmatter = this.app.metadataCache.getFileCache(existingFile).frontmatter;
await this.app.vault.modify(existingFile, tFrontmatter(frontmatter) + "\n" + content);
}
new Notice(`${name} has been ${existingFile ? "updated" : "imported"}`);
}
async playAnime(currentFile: TFile) {
const frontmatter = this.app.metadataCache.getFileCache(currentFile)?.frontmatter;
const progress = frontmatter["progress"];
const items = this.app.metadataCache.getFileCache(currentFile).listItems;
const itemContexts = items.map((item) =>
this.app.workspace.activeEditor.editor.getRange(
pos2EditorRange(item.position).from,
pos2EditorRange(item.position).to
)
);
const paths = itemContexts.map((item) => item.match(new RegExp("\\((.*?)\\)"))[1]);
const videoUrl = paths[progress];
open(this.app, videoUrl);
}
async syncBangumi(currentFile: TFile) {
const frontmatter = this.app.metadataCache.getFileCache(currentFile)?.frontmatter;
const progress = frontmatter["progress"];
if (progress <= 0) {
new Notice("Your watching data is abnormal, please fix it manually");
return;
}
const id = frontmatter["bangumiID"];
await bangumiApi.updateProgress(this.settings.accessToken, id, progress);
new Notice("The progress has been uploaded to bangumi");
}
}