-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
444 lines (370 loc) · 10.8 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
import {
App,
Modal,
Notice,
Plugin,
PluginSettingTab,
Setting,
TFile,
requestUrl
} from "obsidian";
interface TranscriptItem {
text: string;
duration: number;
offset: number;
}
interface PluginSettings {
noteFolder: string;
}
const DEFAULT_SETTINGS: PluginSettings = {
noteFolder: "",
};
interface VideoMetadata {
title: string;
channel: string;
duration: string;
publishDate: string;
}
const RE_YOUTUBE = /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/i;
const USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36';
const RE_XML_TRANSCRIPT = /<text start="([^"]*)" dur="([^"]*)">([^<]*)<\/text>/g;
interface YouTubeResponse {
status: string;
data: {
title: string;
description: string;
date: string;
url: string;
duration: string;
channel: string;
thumbnail_url: string;
transcript: string;
video_id: string;
};
}
export default class YouTubeTranscriptPlugin extends Plugin {
settings: PluginSettings = DEFAULT_SETTINGS;
private readonly DEBUG = true;
async onload() {
console.log("Loading YouTubeTranscriptPlugin");
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
this.addCommand({
id: "open-yt-transcript-modal",
name: "Fetch YouTube Transcript",
callback: () => {
new YouTubeTranscriptModal(this.app, this).open();
},
});
this.addSettingTab(new YouTubeTranscriptPluginSettingTab(this.app, this));
}
async fetchTranscript(url: string): Promise<string> {
this.debug("Fetching transcript for URL:", url);
try {
const cleanUrl = this.cleanYouTubeUrl(url);
this.debug("Cleaned URL:", cleanUrl);
const requestBody = {
url: cleanUrl
};
this.debug("Request body:", requestBody);
const response = await requestUrl({
url: 'https://yt-transcripts.replit.app/api/convert/json',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(requestBody)
});
this.debug("API Response status:", response.status);
this.debug("API Response text:", response.text);
if (response.status !== 200) {
let errorMessage = "Failed to fetch transcript";
try {
const errorData = response.json;
this.debug("Error response data:", errorData);
errorMessage = errorData?.detail || errorMessage;
} catch (e) {
errorMessage = response.text || errorMessage;
}
throw new Error(errorMessage);
}
let data: YouTubeResponse;
try {
data = typeof response.json === 'string' ?
JSON.parse(response.json) :
response.json as YouTubeResponse;
} catch (e) {
this.debug("Error parsing JSON response:", e);
throw new Error("Invalid JSON response from service");
}
if (data.status !== "success" || !data.data) {
this.debug("Invalid API response:", data);
throw new Error("Invalid response from transcript service");
}
return this.formatTranscriptNote(data.data);
} catch (error) {
this.debug("Error fetching transcript:", error);
const errorMessage = error instanceof Error ? error.message : "Unknown error";
throw new Error(`Failed to fetch transcript: ${errorMessage}`);
}
}
private retrieveVideoId(videoId: string): string {
if (videoId.length === 11) {
return videoId;
}
const matchId = videoId.match(RE_YOUTUBE);
if (matchId && matchId.length) {
return matchId[1];
}
throw new Error('Invalid YouTube URL or video ID');
}
public getFormattedDateTime(): string {
const now = new Date();
const date = now.toISOString().split('T')[0];
const time = now.toTimeString()
.split(' ')[0]
.replace(/:/g, '-');
return `${date}-${time}`;
}
private sanitizeTitle(title: string): string {
return title
.replace(/[/\\?%*:|"<>]/g, '-')
.replace(/\s+/g, '-')
.replace(/-+/g, '-')
.toLowerCase();
}
private formatDate(date: Date): string {
return date.toISOString().split('T')[0];
}
private decodeHtmlEntities(text: string): string {
const entities: Record<string, string> = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
''': "'",
''': "'",
};
return text.replace(/&#39;|&|<|>|"|'|'/g,
(entity: string): string => entities[entity] || entity
);
}
private async formatTranscriptNote(data: YouTubeResponse['data']): Promise<string> {
try {
const transcriptText = this.decodeHtmlEntities(data.transcript);
const duration = parseInt(data.duration);
const formattedDuration = duration ?
`${Math.floor(duration / 60)}:${(duration % 60).toString().padStart(2, '0')}` :
"Unknown Duration";
const templateContent = `---
title: ${data.title}
description: ${data.description.split('\n')[0]}
created: ${this.getFormattedDateTime()}
video-id: ${data.video_id}
url: ${data.url}
duration: ${formattedDuration}
channel: ${data.channel}
date: ${data.date}
thumbnail: ${data.thumbnail_url}
tags:
- youtube-transcript
- video
---
# ${data.title}
## Video Information
- **Channel**: ${data.channel}
- **Published**: ${data.date}
- **Duration**: ${formattedDuration}
- **URL**: [Watch Video](${data.url})
- **Thumbnail**: ![Thumbnail](${data.thumbnail_url})
## Description
${data.description}
## Transcript
${transcriptText}
## Key Points
-
## Notes
-
## Related
-
`;
return templateContent;
} catch (error) {
console.error("Error creating note from template:", error);
return this.createFallbackNote(data);
}
}
private createFallbackNote(data: YouTubeResponse['data']): string {
return `---
title: ${data.title || "YouTube Transcript"}
description: ${data.description?.split('\n')[0] || "Transcript of YouTube video"}
date: ${data.date || this.formatDate(new Date())}
url: ${data.url}
tags:
- youtube-transcript
- video
---
# ${data.title || "YouTube Video Transcript"}
## Video Information
- **URL**: [Watch Video](${data.url})
## Transcript
${this.decodeHtmlEntities(data.transcript)}
## Notes
`;
}
onunload() {
console.log("Unloading YouTubeTranscriptPlugin");
}
async saveSettings() {
await this.saveData(this.settings);
}
private debug(...args: any[]): void {
if (this.DEBUG) {
console.log("[YT Transcript]", ...args);
}
}
public sanitizeFileTitle(title: string): string {
return title
.replace(/[\\/:*?"<>|]/g, '')
.replace(/\s+/g, ' ')
.trim()
.slice(0, 100);
}
private cleanYouTubeUrl(url: string): string {
try {
let videoId = '';
// Handle youtu.be format
if (url.includes('youtu.be/')) {
videoId = url.split('youtu.be/')[1]?.split(/[?&]/)[0];
}
// Handle youtube.com format
else if (url.includes('youtube.com/watch')) {
const urlParams = new URL(url).searchParams;
videoId = urlParams.get('v') || '';
}
// Handle youtube.com/v/ format
else if (url.includes('youtube.com/v/')) {
videoId = url.split('youtube.com/v/')[1]?.split(/[?&]/)[0];
}
if (!videoId || videoId.length !== 11) {
throw new Error("Could not extract valid YouTube video ID");
}
// Return clean YouTube URL in the format the API expects
return `https://youtu.be/${videoId}`; // Changed to youtu.be format
} catch (error: unknown) {
if (error instanceof Error) {
throw new Error(`Invalid YouTube URL: ${error.message}`);
}
throw new Error('Invalid YouTube URL: Unknown error');
}
}
}
class YouTubeTranscriptModal extends Modal {
plugin: YouTubeTranscriptPlugin;
constructor(app: App, plugin: YouTubeTranscriptPlugin) {
super(app);
this.plugin = plugin;
}
private getFormattedDateTime(): string {
const now = new Date();
const date = now.toISOString().split('T')[0];
const time = now.toTimeString()
.split(' ')[0]
.replace(/:/g, '-');
return `${date}-${time}`;
}
private sanitizeFileName(name: string): string {
return name.replace(/[\\/:*?"<>|]/g, '-');
}
private sanitizeFileTitle(title: string): string {
return title
.replace(/[\\/:*?"<>|]/g, '')
.replace(/[^\w\s-]/g, '')
.replace(/\s+/g, ' ')
.trim()
.slice(0, 100);
}
onOpen() {
const { contentEl } = this;
contentEl.createEl("h2", { text: "Enter YouTube URL" });
const urlInput = new Setting(contentEl)
.setName("URL")
.addText((text) =>
text.setPlaceholder("Paste URL").onChange((value) => {})
);
new Setting(contentEl).addButton((btn) =>
btn
.setButtonText("Fetch Transcript")
.setCta()
.onClick(async () => {
const url = urlInput.controlEl.querySelector("input")?.value ?? "";
if (!url.trim()) {
new Notice("Please enter a YouTube URL");
return;
}
if (!url.includes('youtube.com') && !url.includes('youtu.be')) {
new Notice("Please enter a valid YouTube URL");
return;
}
new Notice("Fetching transcript...");
this.close();
try {
const transcript = await this.plugin.fetchTranscript(url);
if (!transcript) {
throw new Error("No transcript content received");
}
const titleMatch = transcript.match(/^title: (.+)$/m);
const videoTitle = titleMatch ?
titleMatch[1] :
'Untitled Video';
const safeTitle = this.sanitizeFileTitle(videoTitle)
.replace(/\s+/g, '-');
const noteName = `YT - ${safeTitle}.md`;
const folderPath = this.sanitizeFileName(this.plugin.settings.noteFolder || "YouTube Transcripts");
if (folderPath && !(await this.app.vault.adapter.exists(folderPath))) {
await this.app.vault.createFolder(folderPath);
}
const filePath = `${folderPath}/${noteName}`;
try {
const newFile: TFile = await this.app.vault.create(filePath, transcript);
new Notice(`Transcript saved to: ${newFile.path}`);
} catch (fileError) {
console.error("File creation error:", fileError);
new Notice("Error saving transcript. The file name might be invalid.");
}
} catch (err) {
console.error(err);
new Notice(`Error: ${err instanceof Error ? err.message : "Failed to fetch transcript"}`);
}
})
);
}
onClose() {
const { contentEl } = this;
contentEl.empty();
}
}
class YouTubeTranscriptPluginSettingTab extends PluginSettingTab {
plugin: YouTubeTranscriptPlugin;
constructor(app: App, plugin: YouTubeTranscriptPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const { containerEl } = this;
containerEl.empty();
containerEl.createEl("h2", { text: "YouTube Transcript Plugin Settings" });
new Setting(containerEl)
.setName("Transcript Note Folder")
.setDesc("Folder to store transcript notes (leave blank for vault root).")
.addText((text) =>
text
.setPlaceholder("e.g. Transcripts")
.setValue(this.plugin.settings.noteFolder)
.onChange(async (value) => {
this.plugin.settings.noteFolder = value.trim();
await this.plugin.saveSettings();
})
);
}
}