send_memos.html 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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. <!--输入框,绑定回车事件,触发查询-->
  42. <input style="margin-left: 30px; width: 70vw;" placeholder="搜索" type="text" id="search" onkeydown="if(event.keyCode===13) {search()}">
  43. </div>
  44. <br><br>
  45. <div></div>
  46. <!-- 创建一个用于编辑的容器 -->
  47. <div id="editor"></div>
  48. <!-- 添加多选按钮 -->
  49. <div id="tags"></div>
  50. <br>
  51. <br>
  52. <!-- 添加发送按钮 -->
  53. <button id="log" style="float: right; height: 100px;width: 200px; font-size: 40px" onclick="sendData()">记录</button>
  54. <div id="memos_list">
  55. </div>
  56. </div>
  57. <div id="mask" style="display: none">
  58. <div id="model">
  59. <div id="editorModel"></div>
  60. <br>
  61. <!-- 取消 和 确认按钮-->
  62. <button onclick="hideModel()" style="margin-right: 50px">取消</button>
  63. <button onclick="updateById()">确认</button>
  64. </div>
  65. </div>
  66. <!-- 引入Quill库 -->
  67. <script src="./js/cdn.quilljs.com_1.3.6_quill.js"></script>
  68. <!--异步请求示例:requestUtil.sync('https://jsonplaceholder.typicode.com/posts/1', 'post', data, headers) .then(data => console.log(data))-->
  69. <script>
  70. let authStr = "bearer eyJhbGciOiJIUzI1NiIsImtpZCI6InYxIiwidHlwIjoiSldUIn0.eyJuYW1lIjoidGlhbnl1bnBlcmZlY3QiLCJpc3MiOiJtZW1vcyIsInN1YiI6IjEiLCJhdWQiOlsidXNlci5hY2Nlc3MtdG9rZW4iXSwiaWF0IjoxNzA5MTc5NTUyfQ.LFxWB4efya1sL7VoJ42xpXxbAip-udT_Kx2OwZ8Y3-E";
  71. let myHeaders = {
  72. 'Content-type': 'application/json',
  73. 'Authorization': authStr
  74. };
  75. // console.log(location.href)
  76. // console.log(location.href.indexOf(tag))
  77. // 设置多选按钮 标签
  78. requestUtil.async('https://memos.tianyunperfect.cn/api/v1/tag', 'get', null, {'Authorization': authStr}).then(res => {
  79. // console.log(res); ['tag1','tag2']
  80. // 在 id tags 里面拼接res数组 ,示例todo标签 <input type="checkbox" id="todo" name="category" value="todo" checked> <label for="todo">todo</label>
  81. let tags = document.getElementById('tags');
  82. res.forEach(tag => {
  83. let input = document.createElement('input');
  84. // 如果是location.href 包含tag,则设置为选中状态, href 要反编译以识别中文
  85. if (decodeURI(location.href).indexOf(tag) !== -1) {
  86. input.checked = true;
  87. }
  88. input.type = 'checkbox';
  89. input.id = tag;
  90. input.name = 'category';
  91. input.value = tag;
  92. let label = document.createElement('label');
  93. // 设置margin-right 20
  94. label.style.marginRight = '10px';
  95. label.htmlFor = tag;
  96. label.innerText = tag;
  97. tags.appendChild(input);
  98. tags.appendChild(label);
  99. });
  100. search();
  101. // id="tags" 里面的多选按钮,点击后触发search
  102. let checkboxes = document.querySelectorAll('input[name="category"]');
  103. checkboxes.forEach(checkbox => {
  104. checkbox.onclick = function () {
  105. search();
  106. }
  107. });
  108. });
  109. function showModel() {
  110. document.getElementById('mask').style.display = 'block';
  111. }
  112. function hideModel() {
  113. document.getElementById('mask').style.display = 'none';
  114. }
  115. let option = {
  116. theme: 'snow', // 指定使用的主题
  117. modules: {
  118. toolbar: [
  119. [{'header': [1, 2, false]}, 'bold', 'italic', 'blockquote', 'code-block', 'link'],
  120. [{'list': 'ordered'}, {'list': 'bullet'}, {'indent': '-1'}, {'indent': '+1'}, 'image', 'video'],
  121. ]
  122. }
  123. };
  124. const quill = new Quill('#editor', option);
  125. const quillModel = new Quill('#editorModel', option);
  126. quill.focus();
  127. let contentStr = 'content';
  128. // 从localStorage中获取内容
  129. let item = localStorage.getItem(contentStr);
  130. if (item != null) {
  131. quill.root.innerHTML = item;
  132. }
  133. // 如果处于编辑状态,则执行esc取消
  134. window.onkeydown = function (event) {
  135. if (event.keyCode === 27 && document.getElementById('mask').style.display === 'block') {
  136. hideModel();
  137. }
  138. // 如果是meta + enter 则保存
  139. if (event.metaKey && event.keyCode === 13) {
  140. updateById();
  141. }
  142. // 如果是ctrl + enter 则保存
  143. if (event.ctrlKey && event.keyCode === 13) {
  144. updateById();
  145. }
  146. };
  147. quill.on('text-change', function (delta, oldDelta, source) {
  148. localStorage.setItem(contentStr, quill.root.innerHTML);
  149. });
  150. async function convertToWebPAsync(base64Image) {
  151. // 检查图像格式是否为WebP
  152. if (base64Image.startsWith('data:image/webp')) {
  153. // 如果是WebP格式,直接返回原始的base64字符串
  154. return base64Image;
  155. } else {
  156. // 将图像转换为WebP格式
  157. const image = new Image();
  158. image.src = base64Image;
  159. await new Promise((resolve, reject) => {
  160. image.onload = resolve;
  161. image.onerror = reject;
  162. });
  163. const canvas = document.createElement('canvas');
  164. canvas.width = image.width;
  165. canvas.height = image.height;
  166. const ctx = canvas.getContext('2d');
  167. ctx.drawImage(image, 0, 0);
  168. const webpData = canvas.toDataURL('image/webp');
  169. return webpData;
  170. }
  171. }
  172. /**
  173. * 获取 markdown 格式的内容
  174. * @param delta
  175. * @returns {string}
  176. */
  177. async function deltaToMarkdown(delta) {
  178. let markdown = '';
  179. for (const op of delta['ops']) {
  180. if (op.insert) {
  181. if (typeof op.insert === 'string') {
  182. markdown += op.insert;
  183. } else if (op.insert.image) {
  184. // 如果是图片,转换为webp
  185. const webpBase64 = await convertToWebPAsync(op.insert.image);
  186. markdown += `![${op.insert.alt}](${webpBase64})`;
  187. }
  188. }
  189. }
  190. return markdown;
  191. }
  192. // 获取编辑器内容
  193. // function getContent() {
  194. // const content = quill.root.innerHTML;
  195. // console.log(content);
  196. // }
  197. // 发送数据
  198. async function sendData() {
  199. // 使id=log 不可用
  200. let logBtn = document.getElementById('log');
  201. logBtn.disabled = true;
  202. logBtn.innerText = '正在发送...';
  203. const content = await deltaToMarkdown(quill.getContents());
  204. const categories = getSelectedCategories();
  205. // 添加多选按钮选择的分类到内容前面
  206. let updatedContent = content;
  207. if (categories.length > 0) {
  208. updatedContent = `#${categories.join(' ')} ${content}`;
  209. }
  210. // 调用数据备份接口
  211. const data = {
  212. content: updatedContent
  213. };
  214. // 发送异步请求
  215. requestUtil.async('https://memos.tianyunperfect.cn/api/v1/memo', 'post', data, myHeaders).then(res => {
  216. // alert(JSON.stringify(res));
  217. if (res['name']) {
  218. // window.location.href = `https://memos.tianyunperfect.cn/m/${res['name']}`;
  219. showMsg('记录成功', 1);
  220. }
  221. logBtn.disabled = false;
  222. logBtn.innerText = '记录';
  223. quill.root.innerHTML = '';
  224. localStorage.removeItem(contentStr);
  225. search();
  226. });
  227. }
  228. // 获取选择的分类
  229. function getSelectedCategories() {
  230. const checkboxes = document.querySelectorAll('input[name="category"]:checked');
  231. const categories = [];
  232. checkboxes.forEach(checkbox => {
  233. categories.push(checkbox.value);
  234. });
  235. return categories;
  236. }
  237. let tmpId;
  238. // 更新数据
  239. async function updateById() {
  240. let content = await deltaToMarkdown(quillModel.getContents());
  241. let data = {
  242. id: tmpId,
  243. content: content
  244. };
  245. requestUtil.async(`https://web_history.tianyunperfect.cn/memos/update`, 'post', data, {}).then(res => {
  246. showMsg('保存成功', 1);
  247. hideModel();
  248. search();
  249. });
  250. }
  251. function search() {
  252. let searchStr = document.getElementById('search').value;
  253. // 如果标签不为空,则 拼接成 tag_str ,逗号分隔
  254. let tag_str = '';
  255. let checkboxes = document.querySelectorAll('input[name="category"]:checked');
  256. checkboxes.forEach(checkbox => {
  257. tag_str += checkbox.value + ',';
  258. });
  259. // https://web_history.tianyunperfect.cn/memos/list
  260. // get
  261. // 入参:search tag_str
  262. //
  263. // {'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'}]}
  264. let params = {'search': searchStr, tag_str: tag_str}
  265. let url = 'https://web_history.tianyunperfect.cn/memos/list';
  266. // 拼接url
  267. let urlWithParams = requestUtil.buildUrl(url, params);
  268. requestUtil.async(urlWithParams, 'get', null, null).then(res => {
  269. // console.log(res);
  270. res = res['res'];
  271. // 循环获取里面所有的id数组
  272. let idArr = [];
  273. res.forEach(item => {
  274. idArr.push(item['id']);
  275. });
  276. let sourceUrl = "https://web_history.tianyunperfect.cn/memos/resource"
  277. let sourceData={
  278. ids: idArr.join(',') // 逗号分隔的字符串
  279. }
  280. // 获取资源
  281. let sourceRes = requestUtil.sync(sourceUrl, 'post', sourceData, {});
  282. // {'code': 200, 'res': [{'memo_id': 1, 'resource_name': 'EfdmvRsodBviDQWRmDiTaV'}, {'memo_id': 4, 'resource_name': '2rY5kmn3AHsy23vK4vSskV'}, {'memo_id': 7, 'resource_name': 'FMhzJXjoTa7fdtbbCBjXnt'}]}
  283. // 循环遍历,以memo_id为key,resource_name数组为value
  284. let resourceMap = {};
  285. sourceRes['res'].forEach(item => {
  286. if (resourceMap[item['memo_id']]) {
  287. resourceMap[item['memo_id']].push(item['internal_path']);
  288. } else {
  289. resourceMap[item['memo_id']] = [item['internal_path']];
  290. }
  291. });
  292. let div = document.querySelector('#memos_list');
  293. // flex 定位
  294. div.innerHTML = '';
  295. res.forEach(item => {
  296. let lineDiv = document.createElement('div');
  297. div.appendChild(lineDiv);
  298. let tmpDiv = document.createElement('div');
  299. tmpDiv.innerText = item['content'];
  300. // 样式加上border,点击跳转到对应的url https://memos.tianyunperfect.cn/m/ + item['resource_name']
  301. tmpDiv.style.border = '1px solid #000';
  302. // 宽度 70vw
  303. tmpDiv.style.width = '70vw';
  304. tmpDiv.style.margin = '10px';
  305. tmpDiv.style.padding = '10px';
  306. tmpDiv.style.cursor = 'pointer';
  307. // inline
  308. tmpDiv.style.display = 'inline-block';
  309. tmpDiv.ondblclick = function () {
  310. tmpId = item['id'];
  311. quillModel.root.innerHTML = item['content'];
  312. showModel();
  313. // focus
  314. quillModel.focus();
  315. };
  316. // 根据id,查找是否存在资源
  317. if (resourceMap[item['id']]) {
  318. // 循环遍历,以memo_id为key,resource_name数组为value
  319. resourceMap[item['id']].forEach(internal_path => {
  320. // 创建img
  321. let img = document.createElement('img');
  322. img.src = `https://memos_assert.tianyunperfect.cn/${internal_path}`;
  323. img.style.width = '100px';
  324. img.style.height = '100px';
  325. img.style.margin = '10px';
  326. img.style.cursor = 'pointer';
  327. // 添加到div
  328. tmpDiv.appendChild(img);
  329. });
  330. }
  331. lineDiv.appendChild(tmpDiv);
  332. // 右侧添加一个编辑按钮
  333. let editBtn = document.createElement('button');
  334. editBtn.innerText = '跳转查看';
  335. // margin 10
  336. editBtn.style.margin = '10px';
  337. // inline
  338. editBtn.style.display = 'inline-block';
  339. editBtn.onclick = function () {
  340. window.open(`https://memos.tianyunperfect.cn/m/${item['resource_name']}`);
  341. };
  342. lineDiv.appendChild(editBtn);
  343. // 归档按钮
  344. let archiveBtn = document.createElement('button');
  345. archiveBtn.innerText = '归档';
  346. archiveBtn.style.margin = '10px';
  347. // inline
  348. archiveBtn.style.display = 'inline-block';
  349. archiveBtn.onclick = function () {
  350. let data = {
  351. id: item['id']
  352. };
  353. requestUtil.async(`https://web_history.tianyunperfect.cn/memos/archive`, 'post', data, {}).then(res => {
  354. showMsg('归档成功', 1);
  355. lineDiv.style.display = 'none';
  356. });
  357. };
  358. lineDiv.appendChild(archiveBtn);
  359. // 删除按钮
  360. let delBtn = document.createElement('button');
  361. delBtn.innerText = '删除';
  362. delBtn.style.margin = '10px';
  363. // inline
  364. delBtn.style.display = 'inline-block';
  365. delBtn.onclick = function () {
  366. // 确认是否删除
  367. if (!confirm('确认删除吗?')) {
  368. return;
  369. }
  370. let data = {
  371. id: item['id']
  372. };
  373. requestUtil.async(`https://web_history.tianyunperfect.cn/memos/delete`, 'post', data, {}).then(res => {
  374. showMsg('删除成功', 1);
  375. lineDiv.style.display = 'none';
  376. });
  377. };
  378. lineDiv.appendChild(delBtn);
  379. });
  380. });
  381. }
  382. </script>
  383. </body>
  384. </html>