aboutsummaryrefslogtreecommitdiff
path: root/src/index.ts
blob: f3dcd0fb1f8753f8ef8f51066470a082a262f2d5 (plain)
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
import joplin from 'api';
import { SettingItemType, ModelType, ToastType } from 'api/types';

enum ItemChangeEventType {
    create = 1,
    update = 2,
    delete = 3
}

const settingObjs = {
	'HooksEnabled': {
		value: false,
		type: SettingItemType.Bool,
		section: 'WebAngling',
		public: true,
		label: 'Enable Webhooks. Must also enable Note Changes or Resource Changes.'
	},
	"URL": {
		value: null,
		type: SettingItemType.String,
		section: 'WebAngling',
		public: true,
		label: 'Webhook URL.'
	},
	"Method": {
		value: false,
		type: SettingItemType.String,
		section: 'WebAngling',
		public: true,
		label: 'HTTP Method to use sending webhook (e.g., POST, GET).',
		isEnum: true,
		options: {
			'POST': 'POST',
			'GET': 'GET',
		},
	},
	"NoteChangesEnabled": {
		value: false,
		type: SettingItemType.Bool,
		section: 'WebAngling',
		public: true,
		label: 'Send Webhooks on note changes.'
	},
	"ResourceChangesEnabled": {
		value: false,
		type: SettingItemType.Bool,
		section: 'WebAngling',
		public: true,
		label: 'Send Webhooks on resource changes.'
	},
	"IncludeTitle": {
		value: true,
		type: SettingItemType.Bool,
		section: 'WebAngling',
		public: true,
		label: 'Include Note/Resource title in webhook payload.'
	}
}

async function registerSettings(){
	await joplin.settings.registerSection('WebAngling', {
		label: 'Web Angling',
		iconName: 'fas fa-fish',
	});
	await joplin.settings.registerSettings(settingObjs)
}

async function onEvent(
	event_type: string,
	id: string,
	change_type="Update",
){
	const anglerSettings = await joplin.settings.values(Object.keys(settingObjs));
	
	if(!anglerSettings["HooksEnabled"]){
		return
	}

	const obj_type = ModelType[await joplin.data.itemType(id)]
	let title = undefined;
	if(obj_type == "Note"){
		if(!anglerSettings["NoteChangesEnabled"]){
			return
		}
		if(anglerSettings["IncludeTitle"]){
			const note = await joplin.data.get(['notes', id], { fields: ['title'] });	
			title = note.title
		}
	} else {
		if(!anglerSettings["ResourceChangesEnabled"]){
			return
		}
	}

	const payload = {
		object_type: obj_type,
		object_id: id,
		change_type: change_type,
		title: title
	}
	try {
		await doFetch(
			anglerSettings["URL"],
			payload,
			anglerSettings["Method"] as string,
			{},
			"application/json",
		)
	} catch (error) {
		await joplin.views.dialogs.showToast(
			{
				message: `Webhook error ${error.message}`,
				type: ToastType.Error,
				duration: 5000,
			}
		);
	}
}

async function doFetch(url, payload, method = 'POST', headers = {}, contentType = 'application/json') {
  const finalHeaders = {
    'Content-Type': contentType,
    ...headers,
  };

  try {
    const response = await fetch(url, {
      method: method,
      headers: finalHeaders,
      body: contentType === 'application/json' ? JSON.stringify(payload) : payload,
    });

    if (!response.ok) {
      throw new Error(`Webhook request failed with status ${response.status}`);
    }

    return response;
  } catch (error) {
    console.error("Webhook request error:", error);
    throw error;
  }
}

joplin.plugins.register({
	onStart: async function() {
		await registerSettings()

		await joplin.workspace.onNoteChange(async (e) => {
			await onEvent("note", e.id, ItemChangeEventType[e.event])
		});

		await joplin.workspace.onResourceChange(async (e) => {
			await onEvent("resource", e.id, "update")
		});
	},
});