send_memos.html 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
  6. <title>memos记录</title>
  7. <!-- 引入Quill样式 -->
  8. <link rel="stylesheet" href="./js/quill.snow.css">
  9. <script src="js/util.js"></script>
  10. <style>
  11. #editor {
  12. height: 150px;
  13. }
  14. #mask {
  15. position: fixed;
  16. top: 0;
  17. left: 0;
  18. width: 100%;
  19. height: 100%;
  20. background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色背景 */
  21. display: flex;
  22. justify-content: center;
  23. align-items: center;
  24. }
  25. #model {
  26. position: absolute;
  27. top: 50%;
  28. left: 50%;
  29. transform: translate(-50%, -50%);
  30. background-color: white;
  31. width: 50%;
  32. padding: 20px;
  33. border-radius: 5px;
  34. }
  35. </style>
  36. </head>
  37. <body>
  38. <div id="all">
  39. <div style="position: fixed;top: 10px;">
  40. <a href="https://memos.tianyunperfect.cn/">memos主页</a>
  41. <!-- 页码输入框,默认为1,修改触发查询-->
  42. <span style="margin-left: 20px">页码:</span>
  43. <input style="width: 50px; margin-left: 20px" type="number" id="page" value="1" onkeydown="if(event.keyCode===13) {search()}">
  44. <!--输入框,绑定回车事件,触发查询-->
  45. <input style="margin-left: 30px; width: 70vw;" placeholder="搜索" type="text" id="search" onkeydown="if(event.keyCode===13) {search()}">
  46. </div>
  47. <br><br>
  48. <div></div>
  49. <!-- 创建一个用于编辑的容器 -->
  50. <div id="editor"></div>
  51. <!-- 添加多选按钮 -->
  52. <div id="tags"></div>
  53. <br>
  54. <br>
  55. <!-- 添加发送按钮 -->
  56. <button id="log" style="float: right; height: 100px;width: 200px; font-size: 40px" onclick="sendData()">记录</button>
  57. <div id="memos_list">
  58. </div>
  59. </div>
  60. <div id="mask" style="display: none">
  61. <div id="model">
  62. <!-- 创建时间的input-->
  63. <div style="margin: 10px">
  64. <label for="created_ts">创建时间</label>
  65. <input id="created_ts"></input>
  66. </div>
  67. <div id="editorModel"></div>
  68. <br>
  69. <!-- 取消 和 确认按钮-->
  70. <button onclick="hideModel()" style="margin-right: 50px">取消</button>
  71. <button onclick="updateById()">确认</button>
  72. </div>
  73. </div>
  74. <!-- 引入Quill库 -->
  75. <script src="./js/cdn.quilljs.com_1.3.6_quill.js"></script>
  76. <!--异步请求示例:requestUtil.sync('https://jsonplaceholder.typicode.com/posts/1', 'post', data, headers) .then(data => console.log(data))-->
  77. <script>
  78. let authStr = "bearer eyJhbGciOiJIUzI1NiIsImtpZCI6InYxIiwidHlwIjoiSldUIn0.eyJuYW1lIjoidGlhbnl1bnBlcmZlY3QiLCJpc3MiOiJtZW1vcyIsInN1YiI6IjEiLCJhdWQiOlsidXNlci5hY2Nlc3MtdG9rZW4iXSwiaWF0IjoxNzA5MTc5NTUyfQ.LFxWB4efya1sL7VoJ42xpXxbAip-udT_Kx2OwZ8Y3-E";
  79. let myHeaders = {
  80. 'Content-type': 'application/json',
  81. 'Authorization': authStr
  82. };
  83. // console.log(location.href)
  84. // console.log(location.href.indexOf(tag))
  85. // 设置多选按钮 标签
  86. requestUtil.async('https://memos.tianyunperfect.cn/api/v1/tag', 'get', null, {'Authorization': authStr}).then(res => {
  87. // console.log(res); ['tag1','tag2']
  88. // 在 id tags 里面拼接res数组 ,示例todo标签 <input type="checkbox" id="todo" name="category" value="todo" checked> <label for="todo">todo</label>
  89. let tags = document.getElementById('tags');
  90. res.forEach(tag => {
  91. let input = document.createElement('input');
  92. let tagsFromLocal = getTagsFromLocal();
  93. // 如果是location.href 包含tag,则设置为选中状态, href 要反编译以识别中文
  94. if (decodeURI(location.href).indexOf(tag) !== -1) {
  95. input.checked = true;
  96. }else if (tagsFromLocal.indexOf(tag) !== -1) {
  97. input.checked = true;
  98. }
  99. input.type = 'checkbox';
  100. input.id = tag;
  101. input.name = 'category';
  102. input.value = tag;
  103. let label = document.createElement('label');
  104. // 设置margin-right 20
  105. label.style.marginRight = '10px';
  106. label.htmlFor = tag;
  107. label.innerText = tag;
  108. tags.appendChild(input);
  109. tags.appendChild(label);
  110. });
  111. search();
  112. // id="tags" 里面的多选按钮,点击后触发search
  113. let checkboxes = document.querySelectorAll('input[name="category"]');
  114. checkboxes.forEach(checkbox => {
  115. checkbox.onclick = function () {
  116. search();
  117. setTagsToLocal();
  118. }
  119. });
  120. });
  121. function getAllCheckedTags() {
  122. let elements = document.querySelectorAll('input[name="category"]:checked');
  123. // 获取values
  124. elements = Array.from(elements).map(ele => ele.value);
  125. return elements;
  126. }
  127. function setTagsToLocal() {
  128. // 如果是location.href 包含tag,则return,否则存储到localStorage
  129. if (decodeURI(location.href).indexOf("tag") !== -1) {
  130. return;
  131. }
  132. // 存储到localStorage
  133. let tags = getAllCheckedTags();
  134. localStorage.setItem('tags', JSON.stringify(tags));
  135. }
  136. function getTagsFromLocal() {
  137. if (decodeURI(location.href).indexOf("tag") !== -1) {
  138. return [];
  139. }
  140. let tags = localStorage.getItem('tags');
  141. if (tags) {
  142. tags = JSON.parse(tags);
  143. return tags;
  144. }
  145. return [];
  146. }
  147. function showModel() {
  148. document.getElementById('mask').style.display = 'block';
  149. }
  150. function hideModel() {
  151. document.getElementById('mask').style.display = 'none';
  152. }
  153. let option = {
  154. theme: 'snow', // 指定使用的主题
  155. modules: {
  156. toolbar: [
  157. [{'header': [1, 2, false]}, 'bold', 'italic', 'blockquote', 'code-block', 'link'],
  158. [{'list': 'ordered'}, {'list': 'bullet'}, {'indent': '-1'}, {'indent': '+1'}, 'image', 'video'],
  159. ]
  160. }
  161. };
  162. const quill = new Quill('#editor', option);
  163. const quillModel = new Quill('#editorModel', option);
  164. quill.focus();
  165. let contentStr = 'content';
  166. // 从localStorage中获取内容
  167. let item = localStorage.getItem(contentStr);
  168. if (item != null) {
  169. quill.root.innerHTML = item;
  170. }
  171. // 如果处于编辑状态,则执行esc取消
  172. window.onkeydown = function (event) {
  173. let edit = document.getElementById('mask').style.display === 'block';
  174. if (!edit) {
  175. return;
  176. }
  177. // esc
  178. if (event.keyCode === 27) {
  179. hideModel();
  180. }
  181. // 如果是meta + enter 则保存
  182. if (event.metaKey && event.keyCode === 13) {
  183. updateById();
  184. }
  185. // 如果是ctrl + enter 则保存
  186. if (event.ctrlKey && event.keyCode === 13) {
  187. updateById();
  188. }
  189. };
  190. quill.on('text-change', function (delta, oldDelta, source) {
  191. localStorage.setItem(contentStr, quill.root.innerHTML);
  192. });
  193. async function convertToWebPAsync(base64Image) {
  194. // 检查图像格式是否为WebP
  195. if (base64Image.startsWith('data:image/webp')) {
  196. // 如果是WebP格式,直接返回原始的base64字符串
  197. return base64Image;
  198. } else {
  199. // 将图像转换为WebP格式
  200. const image = new Image();
  201. image.src = base64Image;
  202. await new Promise((resolve, reject) => {
  203. image.onload = resolve;
  204. image.onerror = reject;
  205. });
  206. const canvas = document.createElement('canvas');
  207. canvas.width = image.width;
  208. canvas.height = image.height;
  209. const ctx = canvas.getContext('2d');
  210. ctx.drawImage(image, 0, 0);
  211. const webpData = canvas.toDataURL('image/webp');
  212. return webpData;
  213. }
  214. }
  215. /**
  216. * 获取 markdown 格式的内容
  217. * @param delta
  218. * @returns {string}
  219. */
  220. async function deltaToMarkdown(delta) {
  221. let markdown = '';
  222. for (const op of delta['ops']) {
  223. if (op.insert) {
  224. if (typeof op.insert === 'string') {
  225. markdown += op.insert;
  226. } else if (op.insert.image) {
  227. // 如果是图片,转换为webp
  228. const webpBase64 = await convertToWebPAsync(op.insert.image);
  229. markdown += `![${op.insert.alt}](${webpBase64})`;
  230. }
  231. }
  232. }
  233. return markdown;
  234. }
  235. // 获取编辑器内容
  236. // function getContent() {
  237. // const content = quill.root.innerHTML;
  238. // console.log(content);
  239. // }
  240. // 发送数据
  241. async function sendData() {
  242. // 使id=log 不可用
  243. let logBtn = document.getElementById('log');
  244. logBtn.disabled = true;
  245. logBtn.innerText = '正在发送...';
  246. const content = await deltaToMarkdown(quill.getContents());
  247. const categories = getSelectedCategories();
  248. // 添加多选按钮选择的分类到内容前面
  249. let updatedContent = content;
  250. if (categories.length > 0) {
  251. updatedContent = `#${categories.join(' ')} ${content}`;
  252. }
  253. // updatedContent 去除尾部的\n,可能有多个
  254. updatedContent = updatedContent.replace(/\n+$/, '');
  255. // 调用数据备份接口
  256. const data = {
  257. content: updatedContent
  258. };
  259. // 发送异步请求
  260. requestUtil.async('https://memos.tianyunperfect.cn/api/v1/memo', 'post', data, myHeaders).then(res => {
  261. // alert(JSON.stringify(res));
  262. if (res['name']) {
  263. // window.location.href = `https://memos.tianyunperfect.cn/m/${res['name']}`;
  264. showMsg('记录成功', 1);
  265. }
  266. logBtn.disabled = false;
  267. logBtn.innerText = '记录';
  268. quill.root.innerHTML = '';
  269. localStorage.removeItem(contentStr);
  270. search();
  271. });
  272. }
  273. // 获取选择的分类
  274. function getSelectedCategories() {
  275. const checkboxes = document.querySelectorAll('input[name="category"]:checked');
  276. const categories = [];
  277. checkboxes.forEach(checkbox => {
  278. categories.push(checkbox.value);
  279. });
  280. return categories;
  281. }
  282. let tmpId;
  283. // 更新数据
  284. async function updateById() {
  285. let content = await deltaToMarkdown(quillModel.getContents());
  286. content = content.replace(/\n+$/, '');
  287. let data = {
  288. id: tmpId,
  289. content: content,
  290. created_ts: document.getElementById('created_ts').value
  291. };
  292. requestUtil.async(`https://web_history.tianyunperfect.cn/memos/update`, 'post', data, {}).then(res => {
  293. showMsg('保存成功', 1);
  294. hideModel();
  295. // 根据id ,更新当前页面
  296. document.getElementById(tmpId).innerText = formatTimeStr(document.getElementById('created_ts').value) + "\n" + content;
  297. });
  298. }
  299. function formatTimeStr(timeStr) {
  300. // "2024-04-25T08:25:54" 转为 "2024-04-25 08:25:54"
  301. return timeStr.replace('T', ' ').substring(0, 19);
  302. }
  303. function search() {
  304. // 页面滚动到顶部
  305. document.documentElement.scrollTo(0, 0);
  306. let searchStr = document.getElementById('search').value;
  307. // 如果标签不为空,则 拼接成 tag_str ,逗号分隔
  308. let tag_str = '';
  309. let checkboxes = document.querySelectorAll('input[name="category"]:checked');
  310. checkboxes.forEach(checkbox => {
  311. tag_str += checkbox.value + ',';
  312. });
  313. // https://web_history.tianyunperfect.cn/memos/list
  314. // get
  315. // 入参:search tag_str
  316. //
  317. // {'code': 200, 'res': [{'id': 11, 'resource_name': 'g2cyE6nXNCdqsm4ZH2R3Bs', 'creator_id': 1, 'created_ts': '2023-07-04T13:35:18', 'updated_ts': '2024-04-22T13:55:25', 'row_status': 'NORMAL', 'content': '康宁的女儿 易安 \n小名:气气\n#备份', 'visibility': 'PRIVATE'}]}
  318. let params = {'search': searchStr, tag_str: tag_str, page: document.getElementById('page').value, page_size: 100};
  319. let url = 'https://web_history.tianyunperfect.cn/memos/list';
  320. // 拼接url
  321. let urlWithParams = requestUtil.buildUrl(url, params);
  322. requestUtil.async(urlWithParams, 'get', null, null).then(res => {
  323. // console.log(res);
  324. res = res['res'];
  325. let div = document.querySelector('#memos_list');
  326. // 如果res为空,则直接返回
  327. if (res.length === 0) {
  328. div.innerHTML = '';
  329. return;
  330. }
  331. // 循环获取里面所有的id数组
  332. let idArr = [];
  333. res.forEach(item => {
  334. idArr.push(item['id']);
  335. });
  336. let sourceUrl = "https://web_history.tianyunperfect.cn/memos/resource"
  337. let sourceData = {
  338. ids: idArr.join(',') // 逗号分隔的字符串
  339. }
  340. // 获取资源
  341. let sourceRes = requestUtil.sync(sourceUrl, 'post', sourceData, {});
  342. // {'code': 200, 'res': [{'memo_id': 1, 'resource_name': 'EfdmvRsodBviDQWRmDiTaV'}, {'memo_id': 4, 'resource_name': '2rY5kmn3AHsy23vK4vSskV'}, {'memo_id': 7, 'resource_name': 'FMhzJXjoTa7fdtbbCBjXnt'}]}
  343. // 循环遍历,以memo_id为key,resource_name数组为value
  344. let resourceMap = {};
  345. sourceRes['res'].forEach(item => {
  346. if (resourceMap[item['memo_id']]) {
  347. resourceMap[item['memo_id']].push(item['internal_path']);
  348. } else {
  349. resourceMap[item['memo_id']] = [item['internal_path']];
  350. }
  351. });
  352. // flex 定位
  353. div.innerHTML = '';
  354. res.forEach(item => {
  355. let lineDiv = document.createElement('div');
  356. div.appendChild(lineDiv);
  357. let tmpDiv = document.createElement('div');
  358. tmpDiv.id = item['id'];
  359. tmpDiv.innerText = formatTimeStr(item['created_ts']) + "\n" + item['content'];
  360. // 样式加上border,点击跳转到对应的url https://memos.tianyunperfect.cn/m/ + item['resource_name']
  361. tmpDiv.style.border = '1px solid #000';
  362. // 宽度 70vw
  363. tmpDiv.style.width = '70vw';
  364. tmpDiv.style.margin = '10px';
  365. tmpDiv.style.padding = '10px';
  366. tmpDiv.style.cursor = 'pointer';
  367. // inline
  368. tmpDiv.style.display = 'inline-block';
  369. tmpDiv.ondblclick = function () {
  370. tmpId = item['id'];
  371. let innerText = document.getElementById(item['id']).innerText;
  372. quillModel.root.innerHTML = innerText.split('\n').slice(1).join('\n');
  373. document.getElementById('created_ts').value = formatTimeStr(innerText.split('\n')[0]);
  374. showModel();
  375. // focus
  376. quillModel.focus();
  377. };
  378. // 根据id,查找是否存在资源
  379. if (resourceMap[item['id']]) {
  380. // tmpDiv 新增一个换行
  381. tmpDiv.appendChild(document.createElement('br'));
  382. // 循环遍历,以memo_id为key,resource_name数组为value
  383. resourceMap[item['id']].forEach(internal_path => {
  384. // 创建img
  385. let img = document.createElement('img');
  386. img.src = `https://memos_assert.tianyunperfect.cn/${internal_path}?width=150`;
  387. img.style.maxHeight = '200px';
  388. img.style.maxWidth = '200px';
  389. img.style.margin = '10px';
  390. img.style.cursor = 'pointer';
  391. // 添加到div
  392. tmpDiv.appendChild(img);
  393. });
  394. }
  395. lineDiv.appendChild(tmpDiv);
  396. // 右侧添加一个编辑按钮
  397. let editBtn = document.createElement('button');
  398. editBtn.innerText = '跳转查看';
  399. // margin 10
  400. editBtn.style.margin = '10px';
  401. // inline
  402. editBtn.style.display = 'inline-block';
  403. editBtn.onclick = function () {
  404. window.open(`https://memos.tianyunperfect.cn/m/${item['resource_name']}`);
  405. };
  406. lineDiv.appendChild(editBtn);
  407. // 归档按钮
  408. let archiveBtn = document.createElement('button');
  409. archiveBtn.innerText = '归档';
  410. archiveBtn.style.margin = '10px';
  411. // inline
  412. archiveBtn.style.display = 'inline-block';
  413. archiveBtn.onclick = function () {
  414. let data = {
  415. id: item['id']
  416. };
  417. requestUtil.async(`https://web_history.tianyunperfect.cn/memos/archive`, 'post', data, {}).then(res => {
  418. showMsg('归档成功', 1);
  419. lineDiv.style.display = 'none';
  420. });
  421. };
  422. lineDiv.appendChild(archiveBtn);
  423. // 删除按钮
  424. let delBtn = document.createElement('button');
  425. delBtn.innerText = '删除';
  426. delBtn.style.margin = '10px';
  427. // inline
  428. delBtn.style.display = 'inline-block';
  429. delBtn.onclick = function () {
  430. // 确认是否删除
  431. if (!confirm('确认删除吗?')) {
  432. return;
  433. }
  434. let data = {
  435. id: item['id']
  436. };
  437. requestUtil.async(`https://web_history.tianyunperfect.cn/memos/delete`, 'post', data, {}).then(res => {
  438. showMsg('删除成功', 1);
  439. lineDiv.style.display = 'none';
  440. });
  441. };
  442. lineDiv.appendChild(delBtn);
  443. });
  444. });
  445. }
  446. </script>
  447. </body>
  448. </html>