generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.ts
304 lines (256 loc) · 8.83 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
import { App, Editor, MarkdownView, Notice, Plugin, PluginSettingTab, Setting } from 'obsidian';
let etherpad = require('etherpad-lite-client');
import { stringifyYaml } from 'obsidian';
let TurndownService = require('turndown')
TurndownService.prototype.escape = (text) => text;
function makeid(length) {
let result = '';
let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let charactersLength = characters.length;
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() *
charactersLength));
}
return result;
}
let td = new TurndownService()
.addRule('strikethrough', {
filter: ['s'],
replacement: function (content) {
return '~~' + content + '~~'
}
})
.addRule('underline', {
filter: ['u'],
replacement: function (content) {
return '==' + content + '==';
}
})
.addRule('a', {
filter: ['a'],
replacement: function (content, node, options) {
return node.getAttribute("href")
}
})
interface EtherpadSettings {
host: string;
port: int;
apikey: string;
random_pad_id: bool;
reload: boolean;
}
const DEFAULT_SETTINGS: EtherpadSettings = {
host: 'localhost',
port: 9001,
apikey: "",
random_pad_id: true,
reload: true
}
export default class Etherpad extends Plugin {
settings: EtherpadSettings;
get etherpad() {
return etherpad.connect({
apikey: this.settings.apikey,
host: this.settings.host,
port: this.settings.port
})
}
async onload() {
await this.loadSettings();
// This adds a status bar item to the bottom of the app. Does not work on mobile apps.
//const statusBarItemEl = this.addStatusBarItem();
//statusBarItemEl.setText('Status Bar Text');
this.registerEvent(
this.app.workspace.on('file-open', async (note) => {
if (this.settings.reload) this.replace_note_from_etherpad(note);
})
);
// This adds an editor command that can perform some operation on the current editor instance
this.addCommand({
id: 'etherpad-create-pad',
name: 'Convert current document to Etherpad',
editorCallback: async (editor: Editor, view: MarkdownView) => {
const note = view.file;
if (!note.name)
return;
let note_text = editor.getValue();
let note_text_without_frontmatter = await this.get_text_without_frontmatter(note_text, note);
// check if pad exists and update
let frontmatter = this.get_frontmatter(note);
if (!frontmatter.etherpad_id) {
let pad_id = this.settings.random_pad_id ? makeid(12) : note.basename;
this.etherpad.createPad({
padID: pad_id,
text: note_text_without_frontmatter
}, (error, data) => {
if (error) {
new Notice(`Error creating pad ${pad_id}: ${error.message}`);
}
else {
this.update_frontmatter(note_text, note, { etherpad_id: pad_id });
}
})
} else {
let pad_id = frontmatter.etherpad_id;
this.etherpad.setText({
padID: pad_id,
text: note_text_without_frontmatter
}, (error, data) => {
if (error) {
new Notice(`Error updating pad ${pad_id}: ${error.message}`);
}
})
}
}
});
this.addCommand({
id: 'etherpad-get-pad',
name: 'Replace note content from Etherpad',
editorCallback: async (editor: Editor, view: MarkdownView) => {
const note = view.file;
this.replace_note_from_etherpad(note);
}
});
this.addCommand({
id: 'etherpad-visit-pad',
name: 'Visit note in Etherpad in system browser',
editorCallback: async (editor: Editor, view: MarkdownView) => {
let note = view.file;
if (!note.name)
return;
let frontmatter = this.get_frontmatter(note);
if (frontmatter?.etherpad_id) {
let url = this.get_url_for_pad_id(frontmatter.etherpad_id);
window.open(url);
}
}
});
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new EtherpadSettingTab(this.app, this));
}
onunload() {
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
get_frontmatter(note) {
// return a copy
return { ...this.app.metadataCache.getFileCache(note)?.frontmatter };
}
async get_text_without_frontmatter(note_text, note) {
//let note_text = await this.app.vault.read(note);
let fmc = app.metadataCache.getFileCache(note)?.frontmatter;
if (!fmc) {
return note_text;
}
//let end = fmc.position.end.line + 1 // account for ending ---
let end = Object.keys(fmc).length + 2; // account for starting & ending ---
return note_text.split("\n").slice(end).join("\n");
}
async update_frontmatter(note_text, note, d) {
let frontmatter = this.get_frontmatter(note);
let updated_frontmatter;
if (!frontmatter) {
// create new frontmatter
updated_frontmatter = d;
} else {
updated_frontmatter = {
...frontmatter,
...d
};
}
delete updated_frontmatter.position;
let frontmatter_text = `---\n${stringifyYaml(updated_frontmatter)}---\n`;
//let note_text = await this.get_text_without_frontmatter(note);
this.app.vault.modify(note, frontmatter_text + note_text);
}
get_url_for_pad_id(pad_id) {
pad_id = pad_id.replace(" ", "_");
return `http://${this.settings.host}:${this.settings.port}/p/${pad_id}`
}
async replace_note_from_etherpad(note) {
if (note == null) return;
let frontmatter = this.get_frontmatter(note);
if (!frontmatter) return;
if (!frontmatter.etherpad_id) return;
this.etherpad.getHTML({ padID: frontmatter.etherpad_id }, (err, data) => {
if (err) {
console.log("err", err);
new Notice("error: " + err);
} else {
delete frontmatter.position;
let now = new Date();
frontmatter.etherpad_get_at = now.toLocaleString();
let frontmatter_text = `---\n${stringifyYaml(frontmatter)}---\n`;
let note_html = data.html;
let note_text = td.turndown(note_html)
this.app.vault.modify(note, frontmatter_text + note_text);
let url = this.get_url_for_pad_id(frontmatter.etherpad_id);
new Notice(`Note was reloaded from ${url}.\nLocal edits will be discarded!`);
}
});
}
}
class EtherpadSettingTab extends PluginSettingTab {
plugin: Etherpad;
constructor(app: App, plugin: Etherpad) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const { containerEl } = this;
containerEl.empty();
containerEl.createEl('h2', { text: 'Etherpad Settings' });
new Setting(containerEl)
.setName('Server host')
.setDesc('Server host')
.addText(text => text
.setPlaceholder('localhost')
.setValue(this.plugin.settings.host)
.onChange(async (value) => {
this.plugin.settings.host = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Server port')
.setDesc('Server port')
.addText(text => text
.setPlaceholder('9001')
.setValue(this.plugin.settings.port.toString())
.onChange(async (value) => {
this.plugin.settings.port = parseInt(value);
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('API key')
.setDesc('API key')
.addText(text => text
.setPlaceholder('')
.setValue(this.plugin.settings.apikey)
.onChange(async (value) => {
this.plugin.settings.apikey = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Random pad ID')
.setDesc('Use a random pad id, or current file name')
.addToggle(b => b
.setValue(this.plugin.settings.random_pad_id)
.onChange(async (value) => {
this.plugin.settings.random_pad_id = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Reload from Etherpad on open')
.setDesc('Download Pad content when Markdown is opened')
.addToggle(b => b
.setValue(this.plugin.settings.reload)
.onChange(async (value) => {
this.plugin.settings.reload = value;
await this.plugin.saveSettings();
}));
}
}