generated from siyuan-note/widget-sample
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
312 lines (273 loc) · 9.94 KB
/
index.html
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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>call http</title>
<style>
.button {
display: inline-block;
padding: 10px 20px;
background-color: #4CAF50;
color: white;
text-align: center;
text-decoration: none;
font-size: 16px;
border: none;
border-radius: 4px;
cursor: pointer;
}
.button:hover {
background-color: #45a049;
}
.button:active {
background-color: #3e8e41;
}
.button.large {
padding: 12px 24px;
font-size: 24px;
}
.button.small {
padding: 8px 16px;
font-size: 14px;
}
.input-field {
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: larger;
width: 300px;
}
.input-field::placeholder {
color: #999;
}
.input-field:focus {
border-color: #4CAF50;
box-shadow: 0 0 5px rgba(76, 175, 80, 0.3);
}
</style>
</head>
<body>
<script>
async function _work(work, printWarn, shouldLoop) {
while (true) {
try {
await work()
break
} catch (e) {
if (printWarn) {
console.log(e)
}
if (shouldLoop) {
await sleep(200)
continue
} else {
break
}
}
}
}
function mainLoop(work) {
window.onload = function () {
_work(work, false, true).catch(e => console.error(e))
}
}
function mainLoopWarn(work) {
window.onload = function () {
_work(work, true, true).catch(e => console.error(e))
}
}
function mainWarn(work) {
window.onload = function () {
_work(work, true, false).catch(e => console.error(e))
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function getTimeSinceDateString(dateString) {
const date = new Date(
dateString.substring(0, 4), // year
dateString.substring(4, 6) - 1, // month (zero-based)
dateString.substring(6, 8), // day
dateString.substring(8, 10), // hour
dateString.substring(10, 12), // minute
dateString.substring(12, 14) // second
);
const timeDiffMs = Date.now() - date.getTime();
const timeDiffHours = timeDiffMs / (1000 * 60 * 60); // convert to hours
const days = Math.floor(timeDiffHours / 24);
const hours = Math.floor(timeDiffHours % 24);
return `${days} days ${hours} hours`;
}
function getWidgetBlockInfo() {
const widgetBlockEle = window.frameElement.parentElement.parentElement;
const widgetBlkID = widgetBlockEle.getAttribute('data-node-id');
return widgetBlkID
}
async function call(url, reqData) {
const method = "POST"
const headers = { 'Content-Type': 'application/json' }
let data = await fetch(url, {
method,
headers,
body: JSON.stringify(reqData),
})
data = await data.json()
if (data?.code && data?.code != 0) {
console.warn("code=%s %s", data?.code, data?.msg)
return null
}
if (data?.data === undefined)
return data
return data.data
}
async function sql(stmt) {
return call('/api/query/sql', { stmt })
}
async function sqlOne(stmt) {
const ret = await sql(stmt)
if (ret.length >= 1) {
return ret[0]
}
return null
}
async function getHPathByID(id) {
return call('/api/filetree/getHPathByID', { id })
}
async function getLocalStorage() {
return call('/api/storage/getLocalStorage')
}
async function getBlockKramdown(id) {
return call('/api/block/getBlockKramdown', { id })
}
async function getBlockAttrs(id) {
return call('/api/attr/getBlockAttrs', { id })
}
async function insertBlockAfter(data, previousID, dataType = 'markdown') {
// dataType [markdown, kramdown]
return call('/api/block/insertBlock', { data, dataType, previousID })
}
async function insertBlockBefore(data, nextID, dataType = 'markdown') {
// dataType [markdown, kramdown]
return call('/api/block/insertBlock', { data, dataType, nextID })
}
async function insertBlockAsChildOf(data, parentID, dataType = 'markdown') {
// dataType [markdown, kramdown]
return call('/api/block/insertBlock', { data, dataType, parentID })
}
async function checkBlockExist(id) {
return call("/api/block/checkBlockExist", { id })
}
async function currentTime() {
return call("/api/system/currentTime", {})
}
async function pushMsg(msg, timeout = 7000) {
return call("/api/notification/pushMsg", { msg, timeout })
}
async function loadData(namespace, storageName, dv = undefined) {
const resp = call("/api/file/getFile", { path: `/data/storage/petal/${namespace}/${storageName}` })
if (!resp) return dv;
return resp;
}
async function saveData(namespace, storageName, value) {
const pathString = `/data/storage/petal/${namespace}/${storageName}`;
let file;
if (typeof value === "object") {
file = new File([new Blob([JSON.stringify(value)], {
type: "application/json"
})], pathString.split("/").pop());
} else {
file = new File([new Blob([value])], pathString.split("/").pop());
}
const formData = new FormData();
formData.append("path", pathString);
formData.append("file", file);
formData.append("isDir", "false");
const method = "POST"
let resp = await fetch("/api/file/putFile", {
method,
body: formData,
})
data = await resp.json()
if (data.code && data.code != 0) {
console.error("code=%s %s", data.code, data.msg)
return null
}
return data.data
}
async function removeData(namespace, storageName) {
return call("/api/file/removeFile", { path: `/data/storage/petal/${namespace}/${storageName}` })
}
</script>
<div>
<label>Name</label>
<input type="text" id="nameField" class="input-field" /> <br>
<label>HTTP URL</label>
<input type="text" id="urlField" class="input-field" /> <br>
<button id="callButton" class="button">Msg7s</button>
</div>
<script>
const storageName = "httpcall.json"
const namespace = "widgets"
function shouldUpdate(data, blockID, url, name) {
if (!data) return true;
if (data[blockID]?.url != url || data[blockID]?.name != name) {
return true;
}
return false;
}
async function updateData(data, blockID, url, name) {
if (!data) data = {}
data[blockID] = { url, name }
return saveData(namespace, storageName, data)
}
async function validData(data) {
const currMs = await currentTime()
const lt = data['updated'] ?? 0
if (currMs - lt < 1000 * 60 * 60) {
return data
}
for (const key in data) {
if (!await checkBlockExist(key)) {
delete data[key]
}
}
data['updated'] = currMs
return data
}
async function work() {
const blockID = getWidgetBlockInfo()
const urlField = document.getElementById("urlField");
const nameField = document.getElementById("nameField");
const data = await loadData(namespace, storageName, {}) ?? {};
urlField.value = data[blockID]?.url ?? "";
nameField.value = data[blockID]?.name ?? "";
async function process(needInsert, msgTimeout = 7000) {
const url = urlField.value;
const name = nameField.value;
let data = await loadData(namespace, storageName, {}) ?? {};
if (shouldUpdate(data, blockID, url, name)) {
data = await validData(data)
await updateData(data, blockID, url, name);
}
if (url) {
let resp = await fetch(url)
let text = await resp.text()
if (needInsert) {
text = "```\n" + text + "\n```"
await insertBlockAfter(text, blockID)
} else {
text = `<h1>${name}</h1><br><h2>${text}</h2>`
await pushMsg(text, msgTimeout)
}
}
}
document.getElementById("callButton").addEventListener("click", async () => {
await process(false)
});
}
mainWarn(work)
</script>
</body>
</html>