forked from crazypeace/Url-Shorten-Worker
-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.js
399 lines (334 loc) · 11.9 KB
/
main.js
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
let res
let apiSrv = window.location.pathname
let password_value = document.querySelector("#passwordText").value
// let apiSrv = "https://journal.crazypeace.workers.dev"
// let password_value = "journaljournal"
// 这是默认行为, 在不同的index.html中可以设置为不同的行为
// This is default, you can define it to different funciton in different theme index.html
let buildValueItemFunc = buildValueTxt
function shorturl() {
if (document.querySelector("#longURL").value == "") {
alert("Url cannot be empty!")
return
}
// 短链中不能有空格
// key can't have space in it
document.getElementById('keyPhrase').value = document.getElementById('keyPhrase').value.replace(/\s/g, "-");
document.getElementById("addBtn").disabled = true;
document.getElementById("addBtn").innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>Please wait...';
fetch(apiSrv, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ cmd: "add", url: document.querySelector("#longURL").value, key: document.querySelector("#keyPhrase").value, password: password_value })
}).then(function (response) {
return response.json();
}).then(function (myJson) {
res = myJson;
document.getElementById("addBtn").disabled = false;
document.getElementById("addBtn").innerHTML = 'Shorten it';
// 成功生成短链 Succeed
if (res.status == "200") {
let keyPhrase = res.key;
let valueLongURL = document.querySelector("#longURL").value;
// save to localStorage
localStorage.setItem(keyPhrase, valueLongURL);
// add to urlList on the page
addUrlToList(keyPhrase, valueLongURL)
document.getElementById("result").innerHTML = window.location.protocol + "//" + window.location.host + "/" + res.key;
} else {
document.getElementById("result").innerHTML = res.error;
}
// 弹出消息窗口 Popup the result
var modal = new bootstrap.Modal(document.getElementById('resultModal'));
modal.show();
}).catch(function (err) {
alert("Unknow error. Please retry!");
console.log(err);
document.getElementById("addBtn").disabled = false;
document.getElementById("addBtn").innerHTML = 'Shorten it';
})
}
function copyurl(id, attr) {
let target = null;
if (attr) {
target = document.createElement('div');
target.id = 'tempTarget';
target.style.opacity = '0';
if (id) {
let curNode = document.querySelector('#' + id);
target.innerText = curNode[attr];
} else {
target.innerText = attr;
}
document.body.appendChild(target);
} else {
target = document.querySelector('#' + id);
}
try {
let range = document.createRange();
range.selectNode(target);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
document.execCommand('copy');
window.getSelection().removeAllRanges();
// console.log('Copy success')
} catch (e) {
console.log('Copy error')
}
if (attr) {
// remove temp target
target.parentElement.removeChild(target);
}
}
function loadUrlList() {
// 清空列表
let urlList = document.querySelector("#urlList")
while (urlList.firstChild) {
urlList.removeChild(urlList.firstChild)
}
// 文本框中的长链接
let longUrl = document.querySelector("#longURL").value
// console.log(longUrl)
// 遍历localStorage
let len = localStorage.length
// console.log(+len)
for (; len > 0; len--) {
let keyShortURL = localStorage.key(len - 1)
let valueLongURL = localStorage.getItem(keyShortURL)
// 如果长链接为空,加载所有的localStorage
// If the long url textbox is empty, load all in localStorage
// 如果长链接不为空,加载匹配的localStorage
// If the long url textbox is not empty, only load matched item in localStorage
if (longUrl == "" || (longUrl == valueLongURL)) {
addUrlToList(keyShortURL, valueLongURL)
}
}
}
function addUrlToList(shortUrl, longUrl) {
let urlList = document.querySelector("#urlList")
let child = document.createElement('div')
child.classList.add("mb-3", "list-group-item")
let keyItem = document.createElement('div')
keyItem.classList.add("input-group")
// 删除按钮 Remove item button
let delBtn = document.createElement('button')
delBtn.setAttribute('type', 'button')
delBtn.classList.add("btn", "btn-danger", "rounded-bottom-0")
delBtn.setAttribute('onclick', 'deleteShortUrl(\"' + shortUrl + '\")')
delBtn.setAttribute('id', 'delBtn-' + shortUrl)
delBtn.innerText = "X"
keyItem.appendChild(delBtn)
// 查询访问次数按钮 Query visit times button
let qryCntBtn = document.createElement('button')
qryCntBtn.setAttribute('type', 'button')
qryCntBtn.classList.add("btn", "btn-info")
qryCntBtn.setAttribute('onclick', 'queryVisitCount(\"' + shortUrl + '\")')
qryCntBtn.setAttribute('id', 'qryCntBtn-' + shortUrl)
qryCntBtn.innerText = "?"
keyItem.appendChild(qryCntBtn)
// 短链接信息 Short url
let keyTxt = document.createElement('span')
keyTxt.classList.add("form-control", "rounded-bottom-0")
keyTxt.innerText = window.location.protocol + "//" + window.location.host + "/" + shortUrl
keyItem.appendChild(keyTxt)
// 显示二维码按钮
let qrcodeBtn = document.createElement('button')
qrcodeBtn.setAttribute('type', 'button')
qrcodeBtn.classList.add("btn", "btn-info")
qrcodeBtn.setAttribute('onclick', 'buildQrcode(\"' + shortUrl + '\")')
qrcodeBtn.setAttribute('id', 'qrcodeBtn-' + shortUrl)
qrcodeBtn.innerText = "QR"
keyItem.appendChild(qrcodeBtn)
child.appendChild(keyItem)
// 插入一个二级码占位
let qrcodeItem = document.createElement('div');
qrcodeItem.setAttribute('id', 'qrcode-' + shortUrl)
child.appendChild(qrcodeItem)
// 长链接信息 Long url
child.appendChild(buildValueItemFunc(longUrl))
urlList.append(child)
}
function clearLocalStorage() {
localStorage.clear()
}
function deleteShortUrl(delKeyPhrase) {
// 按钮状态 Button Status
document.getElementById("delBtn-" + delKeyPhrase).disabled = true;
document.getElementById("delBtn-" + delKeyPhrase).innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span>';
// 从KV中删除 Remove item from KV
fetch(apiSrv, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ cmd: "del", key: delKeyPhrase, password: password_value })
}).then(function (response) {
return response.json();
}).then(function (myJson) {
res = myJson;
// 成功删除 Succeed
if (res.status == "200") {
// 从localStorage中删除
localStorage.removeItem(delKeyPhrase)
// 加载localStorage
loadUrlList()
document.getElementById("result").innerHTML = "Delete Successful"
} else {
document.getElementById("result").innerHTML = res.error;
}
// 弹出消息窗口 Popup the result
var modal = new bootstrap.Modal(document.getElementById('resultModal'));
modal.show();
}).catch(function (err) {
alert("Unknow error. Please retry!");
console.log(err);
})
}
function queryVisitCount(qryKeyPhrase) {
// 按钮状态 Button Status
document.getElementById("qryCntBtn-" + qryKeyPhrase).disabled = true;
document.getElementById("qryCntBtn-" + qryKeyPhrase).innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span>';
// 从KV中查询 Query from KV
fetch(apiSrv, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ cmd: "qry", key: qryKeyPhrase + "-count", password: password_value })
}).then(function (response) {
return response.json();
}).then(function (myJson) {
res = myJson;
// 成功查询 Succeed
if (res.status == "200") {
document.getElementById("qryCntBtn-" + qryKeyPhrase).innerHTML = res.url;
} else {
document.getElementById("result").innerHTML = res.error;
// 弹出消息窗口 Popup the result
var modal = new bootstrap.Modal(document.getElementById('resultModal'));
modal.show();
}
}).catch(function (err) {
alert("Unknow error. Please retry!");
console.log(err);
})
}
function query1KV() {
let qryKeyPhrase = document.getElementById("keyForQuery").value;
if (qryKeyPhrase == "") {
return
}
// 从KV中查询 Query from KV
fetch(apiSrv, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ cmd: "qry", key: qryKeyPhrase, password: password_value })
}).then(function (response) {
return response.json();
}).then(function (myJson) {
res = myJson;
// 成功查询 Succeed
if (res.status == "200") {
document.getElementById("longURL").value = res.url;
document.getElementById("keyPhrase").value = qryKeyPhrase;
// 触发input事件
document.getElementById("longURL").dispatchEvent(new Event('input', {
bubbles: true,
cancelable: true,
}))
} else {
document.getElementById("result").innerHTML = res.error;
// 弹出消息窗口 Popup the result
var modal = new bootstrap.Modal(document.getElementById('resultModal'));
modal.show();
}
}).catch(function (err) {
alert("Unknow error. Please retry!");
console.log(err);
})
}
function loadKV() {
//清空本地存储
clearLocalStorage();
// 从KV中查询, cmd为 "qryall", 查询全部
fetch(apiSrv, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ cmd: "qryall", password: password_value })
}).then(function (response) {
return response.json();
}).then(function (myJson) {
res = myJson;
// 成功查询 Succeed
if (res.status == "200") {
// 遍历kvlist
res.kvlist.forEach(item => {
keyPhrase = item.key;
valueLongURL = item.value;
// save to localStorage
localStorage.setItem(keyPhrase, valueLongURL);
});
} else {
document.getElementById("result").innerHTML = res.error;
// 弹出消息窗口 Popup the result
var modal = new bootstrap.Modal(document.getElementById('resultModal'));
modal.show();
}
}).catch(function (err) {
alert("Unknow error. Please retry!");
console.log(err);
})
}
// 生成二维码
function buildQrcode(shortUrl) {
// 感谢项目 https://github.com/lrsjng/jquery-qrcode
var options = {
// render method: 'canvas', 'image' or 'div'
render: 'canvas',
// version range somewhere in 1 .. 40
minVersion: 1,
maxVersion: 40,
// error correction level: 'L', 'M', 'Q' or 'H'
ecLevel: 'Q',
// offset in pixel if drawn onto existing canvas
left: 0,
top: 0,
// size in pixel
size: 256,
// code color or image element
fill: '#000',
// background color or image element, null for transparent background
background: null,
// content
// 要转换的文本
text: window.location.protocol + "//" + window.location.host + "/" + shortUrl,
// corner radius relative to module width: 0.0 .. 0.5
radius: 0,
// quiet zone in modules
quiet: 0,
// modes
// 0: normal
// 1: label strip
// 2: label box
// 3: image strip
// 4: image box
mode: 0,
mSize: 0.1,
mPosX: 0.5,
mPosY: 0.5,
label: 'no label',
fontname: 'sans',
fontcolor: '#000',
image: null
};
$("#qrcode-" + shortUrl.replace(/(:|\.|\[|\]|,|=|@)/g, "\\$1") ).empty().qrcode(options);
}
function buildValueTxt(longUrl) {
let valueTxt = document.createElement('div')
valueTxt.classList.add("form-control", "rounded-top-0")
valueTxt.innerText = longUrl
return valueTxt
}
document.addEventListener('DOMContentLoaded', function() {
var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
return new bootstrap.Popover(popoverTriggerEl)
});
loadUrlList();
});