front/js/submission.min.js
2024-09-01 07:27:14 +08:00

16 lines
18 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

let client,s=!1;var curemail="",submitted=0;function getCookie(e){var n=e+"=",o=document.cookie.split(";");for(let t=0;t<o.length;t++){let e=o[t];for(;" "==e.charAt(0);)e=e.substring(1,e.length);if(0==e.indexOf(n))return e.substring(n.length,e.length)}return null}function setLoginCookie(e){var t=window.location.hostname.includes("localhost")?"localhost":"."+window.location.hostname.split(".").slice(-2).join("."),n=new Date(Date.now()+12e5).toUTCString();document.cookie=`loggedIn=true; domain=${t}; path=/; expires=${n}; SameSite=Lax`,document.cookie=`userEmail=${e}; domain=${t}; path=/; expires=${n}; SameSite=Lax`}function logout(){var e=window.location.hostname.includes("localhost")?"localhost":"."+window.location.hostname.split(".").slice(-2).join(".");document.cookie=`loggedIn=; domain=${e}; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT;`,document.cookie=`userEmail=; domain=${e}; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT;`,s=!1,curemail="",window.location.href="/submission"}document.addEventListener("DOMContentLoaded",function(){var e=getCookie("loggedIn"),t=getCookie("userEmail");"true"===e&&t&&(s=!0,curemail=t,initializeUserSession())}),document.getElementById("loginForm").addEventListener("submit",async function(e){e.preventDefault();var e=document.getElementById("email").value,t=document.getElementById("password").value,t=CryptoJS.SHA256(t).toString(),n="user/email.json",o=`user/${e}/p.json`;try{var i,a,l,c,r=await client.get(n),d=JSON.parse(r.content).registeredEmails;d.includes(e)?(i=await client.get(o),JSON.parse(i.content).h[0]===t?(s=!0,curemail=e,document.getElementById("message").innerText="登录成功!正在加载中...",setLoginCookie(curemail),setTimeout(initializeUserSession,3e3)):document.getElementById("message").innerText="密码错误。"):confirm("此邮箱没有注册。是否注册?")&&(d.push(e),a=JSON.stringify({registeredEmails:d},null,2),await client.put(n,new Blob([a],{type:"application/json"})),l={h:[t],nickname:"默认昵称",hasAvatar:!1},c=JSON.stringify(l,null,2),await client.put(o,new Blob([c],{type:"application/json"})),s=!0,curemail=e,document.getElementById("message").innerText="注册并登录成功!正在加载中...",setLoginCookie(curemail),setTimeout(initializeUserSession,3e3))}catch(e){console.error("Error:",e),document.getElementById("message").innerText="发生错误,请稍后重试。"}});var simplemde=new SimpleMDE({element:document.getElementById("input"),placeholder:"请在此处编辑并预览您的内容详情。",spellChecker:!1,toolbar:["side-by-side","|","bold","italic","heading-1","heading-2","heading-3","|","quote","unordered-list","ordered-list","|","link","image","table","horizontal-rule","|","preview","fullscreen"]});function initializeUserSession(){document.getElementById("logout").style.display="block",document.getElementById("login").style.display="none",document.getElementById("navContainer").style.display="block",checkAndLoadAvatar(),updateUserInfo(),checkVerifiedStatus(curemail),checkInvitedStatus(curemail),fetchSubmittedCount(curemail),checkqv(document.getElementById("userEmail").innerText=curemail)}async function checkqv(e){try{var t=await fetch(`https://download.xn--xhq44jb2fzpc.com/user/${e}/qv.json`);t.ok&&!0===await t.json()||showCustomModal()}catch(e){console.error("检查NEU校园网认证状态时出错:",e),showCustomModal()}}function showCustomModal(){var e=document.getElementById("customModal"),t=document.getElementById("modalOverlay");e.style.display="block",t.style.display="block",document.getElementById("confirmButton").addEventListener("click",()=>{window.location.href="/qualification_verify"}),document.getElementById("logoutButton").addEventListener("click",()=>{logout()})}async function f1(){try{var e=await(await fetchNoCache("https://download.xn--xhq44jb2fzpc.com/upload/json/s.json")).json(),t=e.masterKey,n=CryptoJS.SHA256(t),o={region:d2(e.encryptedRegion,n),accessKeyId:d2(e.encryptedKeyId,n),accessKeySecret:d2(e.encryptedKeySecret,n),bucket:d2(e.encryptedBucket,n)};client=new OSS(o)}catch(e){console.error("Failed to fetch or decrypt OSS config:",e)}}function d2(e,t){e=e.replace(/\s/g,"");var e=CryptoJS.enc.Base64.parse(e),n=CryptoJS.lib.WordArray.create(e.words.slice(0,4)),e=CryptoJS.lib.WordArray.create(e.words.slice(4));return CryptoJS.AES.decrypt({ciphertext:e},t,{iv:n,mode:CryptoJS.mode.CBC,padding:CryptoJS.pad.Pkcs7}).toString(CryptoJS.enc.Utf8)}document.addEventListener("DOMContentLoaded",function(){f1().then(()=>{client||console.error("Failed to initialize OSS client due to decryption error.")}).catch(e=>{console.log("Error initializing OSS Client:",e)})});let buttons=document.querySelectorAll(".navButton");function showSubmission(){document.getElementById("submission-area").style.display="block",document.getElementById("myinfo").style.display="none",document.getElementById("mysubmission").style.display="none",document.getElementById("mycoin").style.display="none"}function showMyInfo(){document.getElementById("submission-area").style.display="none",document.getElementById("myinfo").style.display="block",document.getElementById("mysubmission").style.display="none",document.getElementById("mycoin").style.display="none"}function showMyContent(){document.getElementById("submission-area").style.display="none",document.getElementById("myinfo").style.display="none",fetchSubmissionData(curemail,submitted),document.getElementById("mysubmission").style.display="block",document.getElementById("mycoin").style.display="block",loadCoinSystem()}async function updateUserInfo(){if(s){var e=`https://download.xn--xhq44jb2fzpc.com/user/${curemail}/p.json`;try{var t=await fetchNoCache(e);if(!t.ok)throw new Error("p.json not found");var n=await t.json();n&&n.nickname?(document.getElementById("nickname").innerText=n.nickname,console.log("Nickname has been successfully updated.")):(document.getElementById("nickname").innerText="Default Nickname",console.log("Default nickname set due to missing 'nickname' field in response."))}catch(e){console.error("Error loading p.json:",e),document.getElementById("nickname").innerText="Default Nickname"}}else console.log("User is not logged in.")}async function checkAndLoadAvatar(){if(s){var e=`https://download.xn--xhq44jb2fzpc.com/user/${curemail}/p.json`,t=`https://download.xn--xhq44jb2fzpc.com/user/${curemail}/avatar`,n="https://download.xn--xhq44jb2fzpc.com/avatar/default.png";try{var o,i=await fetchNoCache(e);if(!i.ok)throw new Error("p.json not found");(await i.json()).hasAvatar?(o=t+"?t="+Date.now(),document.getElementById("myinfoavatar").src=o,console.log("Custom avatar loaded.")):(document.getElementById("myinfoavatar").src=n,console.log("Default avatar loaded due to `hasAvatar` being false."))}catch(e){document.getElementById("myinfoavatar").src=n,console.error("Error loading p.json. Using default avatar:",e)}}else console.log("User is not logged in.")}function showTooltip(e,t,n){var o=document.getElementById("tooltip"),i=document.getElementById("tooltip-title"),a=document.getElementById("tooltip-content");i.textContent=t,a.textContent=n,o.classList.add("show")}function hideTooltip(){document.getElementById("tooltip").classList.remove("show")}async function checkVerifiedStatus(t){if(t){let e=document.getElementById("verified-icon");try{var n=await fetchNoCache("https://download.xn--xhq44jb2fzpc.com/upload/verified-email/verified-email.json");if(!n.ok)throw new Error("Failed to fetch verified-email.json");(await n.json()).includes(t)?(e.style.display="inline-flex",console.log("Email is verified."),e.addEventListener("mouseenter",()=>fetchVerificationDetails(t,e)),e.addEventListener("mouseleave",hideTooltip),e.addEventListener("click",()=>fetchVerificationDetails(t,e))):console.log("Email is not verified.")}catch(e){console.error("Error loading or parsing verified-email.json:",e)}}else console.log("Email not provided, skipping verified status check.")}async function fetchVerificationDetails(e,t){e=`https://download.xn--xhq44jb2fzpc.com/user/${e}/verified.json`;try{var n=await fetchNoCache(e);n.ok?showTooltip(t,"认证作者",(await n.json()).description):404===n.status&&showTooltip(t,"认证作者","本作者为经过网站认证的优质内容分享者。")}catch(e){console.error("Error fetching verification details:",e),showTooltip(t,"认证作者","本作者为经过网站认证的优质内容分享者。")}}async function checkInvitedStatus(t){if(t){let e=document.getElementById("invited-icon");try{var n=await fetchNoCache("https://download.xn--xhq44jb2fzpc.com/upload/invited-email/invited-email.json");if(!n.ok)throw new Error("Failed to fetch invited-email.json");(await n.json()).includes(t)?(e.style.display="inline-flex",console.log("Email is an invited author."),e.addEventListener("mouseenter",()=>fetchInvitedInfo(t,e)),e.addEventListener("mouseleave",hideTooltip),e.addEventListener("click",()=>fetchInvitedInfo(t,e))):console.log("Email is not an invited author.")}catch(e){console.error("Error loading or parsing invited-email.json:",e)}}else console.log("Email not provided, skipping invited author status check.")}async function fetchInvitedInfo(e,t){e=`https://download.xn--xhq44jb2fzpc.com/user/${e}/invited.json`;try{var n=await fetchNoCache(e);n.ok?showTooltip(t,"特邀作者",(await n.json()).description||"无详细信息"):showTooltip(t,"特邀作者","无法获取信息")}catch(e){console.error("Error fetching invited info:",e),showTooltip(t,"特邀作者","无法加载信息")}}async function editNickname(){if(s){let e=prompt("请输入新的昵称:");if(null!==e)if(""===e.trim())alert("昵称不能为空!");else{var t=`https://download.xn--xhq44jb2fzpc.com/user/${curemail}/p.json`;try{var n=await fetchNoCache(t);if(!n.ok)throw new Error("Failed to fetch p.json");var o=await n.json(),i=(o.nickname=e,new Blob([JSON.stringify(o)],{type:"application/json"}));await client.put(`user/${curemail}/p.json`,i),console.log("p.json has been successfully updated with new nickname."),setTimeout(()=>{document.getElementById("nickname").innerText=e,console.log("Nickname has been updated on the page.")},1e3)}catch(e){console.error("Error updating nickname:",e)}}}else alert("您尚未登录,请登录后再尝试修改昵称。")}async function uploadAvatar(t){t=t.target.files[0];if(t&&t.size<=1048576)if(!0===s){var n=`user/${curemail}/p.json`,o=`user/${curemail}/avatar`;try{var i,a=await fetchNoCache("https://download.xn--xhq44jb2fzpc.com/"+n);let e;e=a.ok?await a.json():{h:[hashedPassword],nickname:"默认昵称",hasAvatar:!1},await client.put(o,t),console.log("Avatar has been successfully uploaded."),e.hasAvatar?setTimeout(()=>{document.getElementById("myinfoavatar").src+="?"+(new Date).getTime(),console.log("Forced reload of the existing avatar.")},2e3):(e.hasAvatar=!0,i=new Blob([JSON.stringify(e)],{type:"application/json"}),await client.put(n,i),console.log("p.json has been successfully uploaded."),setTimeout(()=>{document.getElementById("myinfoavatar").src="https://download.xn--xhq44jb2fzpc.com/"+o,console.log("myinfoavatar's src has been updated to the new avatar.")},2e3))}catch(e){console.error("Failed to upload new avatar or update p.json:",e)}}else alert("You are not logged in, please log in before attempting to upload an avatar.");else alert("头像必须小于 1MB")}buttons.forEach(e=>{e.addEventListener("click",function(){buttons.forEach(e=>e.classList.remove("selected")),this.classList.add("selected")})}),document.body.addEventListener("click",e=>{var t=document.getElementById("tooltip"),n=document.getElementById("verified-icon"),o=document.getElementById("invited-icon");n.contains(e.target)||o.contains(e.target)||t.contains(e.target)||hideTooltip()}),document.getElementById("editNicknameBtn").addEventListener("click",editNickname),document.querySelector(".overlay").addEventListener("click",function(){document.getElementById("fileInput").click()});let input=document.getElementById("input");async function fetchSubmittedCount(e){e=`https://download.xn--xhq44jb2fzpc.com/upload/${e}/submitted.json`;try{var t=await fetchNoCache(e);if(!t.ok)throw new Error("File not found or access error");var n=await t.json();submitted=n,console.log("Submitted count updated:",submitted)}catch(e){submitted=0,console.log("Error fetching submitted count:",e)}}async function fetchSubmissionData(t,n){let o=`
## 投稿记录
| 标题 | 板块 | 审核状态 | 审核备注 |
|------|------|------|------|`;for(let e=1;e<=n;e++){var i=`https://download.xn--xhq44jb2fzpc.com/upload/${t}/${e}/status.json`;try{var a=await fetchNoCache(i);if(a.ok){var{title:l,section:s,status:c,note:r,link:d}=await a.json();let e=l||"无标题";"已通过"===c&&d&&(e=`<a href="${d}" target="_blank">${e}</a>`),o+=`
| ${e} | ${s||"无板块"} | ${c||"无状态"} | ${r||""} |`}else console.error(`无法获取 ${i}: ${a.status} `+a.statusText)}catch(e){console.error(`请求 ${i} 时发生错误:`,e)}}0===n&&(o+=`
| 没有投稿记录 | | | |`),document.getElementById("mysubmission").innerHTML=marked.parse(o)}function validateFiles(n){var o=n.target.files;if(10<o.length)alert("您只能选择最多 10 个文件。"),n.target.value="";else{let t=!1;for(let e=0;e<o.length;e++){var i=o[e],a=i.name,i=i.size,l=a.split(".").pop().toLowerCase();if("zip"===l||"rar"===l){if(t)return alert("您只能上传一个压缩文件。"),void(n.target.value="");if(t=!0,20971520<i)return alert(`压缩文件 "${a}" 超过了大小限制20MB`),void(n.target.value="")}else if(2097152<i)return alert(`文件 "${a}" 超过了大小限制2MB`),void(n.target.value="")}t&&1<o.length&&(alert("上传压缩文件时,只能上传一个文件。"),n.target.value="")}}function getBeijingTime(){var e=new Date,t=6e4*e.getTimezoneOffset();return new Date(e.getTime()+t+288e5).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"})}function displayBeijingTime(){document.getElementById("beijing-time").textContent=getBeijingTime()}async function uploadImage(t){var e=t.target.files[0],n=document.querySelector("input[name='email']").value.trim();if(s)if(e)if(2097152<e.size)alert("图片文件大小不能超过2MB"),t.target.value="";else{n=`upload/${n}/${submitted+1}/postimg/`+e.name;try{await client.put(n,e);var o="https://download.xn--xhq44jb2fzpc.com/"+n,i=`<img src="${o}" alt="自定义图片文字" width="150">`;document.getElementById("imageUrl").innerText=i,document.getElementById("imagePreview").src=o,document.getElementById("imagePreview").style.display="block",document.getElementById("copyButton").style.display="inline-block"}catch(e){console.error("图片上传失败:",e),alert("图片上传失败!"),t.target.value=""}}else alert("请先选择图片文件!");else alert("您还没有登录,请登录后再上传图片!")}function copyImageUrl(){var e=document.getElementById("imageUrl").innerText,t=document.createElement("textarea");t.value=e,document.body.appendChild(t),t.select();try{var n=document.execCommand("copy");alert(n?"标签已复制到剪贴板!请直接粘贴到 markdown 编辑区中,并根据预览效果调整大小。":"复制失败!")}catch(e){alert("复制失败!",e)}document.body.removeChild(t)}window.onload=function(){displayBeijingTime()},document.getElementById("SubmitButton").onclick=function(){let m=document.getElementById("section").value,u=document.querySelector("input[name='wp']").value.trim(),p=document.querySelector("input[name='wppassword']").value.trim();document.querySelector("input[name='note']").value.trim();let y=simplemde.value().trim();confirm("请仔细检查后提交,多次提交无关内容将被禁止访问网站!")&&!async function(){if(s){var t=curemail,e=document.querySelector("input[name='title']").value.trim();if(e){var n=submitted+1;try{var o=await fetch(`https://download.xn--xhq44jb2fzpc.com/user/${t}/p.json`);if(!o.ok)throw new Error("无法加载用户数据");var i=(await o.json()).nickname||"未知昵称",a=`时间:${getBeijingTime()}
内容标题:${e}
邮箱:${t}
板块:${m}
昵称:${i}
备注:${""}
网盘外链:${u}
网盘提取密码:${p}
资源展示页:
`+y,l=`upload/${t}/${n}/userinfo.txt`,c=`upload/${t}/${n}/status.json`,r={title:e,status:"审核中",section:m,note:"",link:""},d=(await client.put(l,new Blob([a],{type:"text/plain"})),await client.put(c,new Blob([JSON.stringify(r)],{type:"application/json"})),document.getElementById("filePicker").files);for(let e=0;e<d.length;e++)await client.put(`upload/${t}/${n}/files/`+d[e].name,d[e]);submitted+=1,await client.put(`upload/${t}/submitted.json`,new Blob([JSON.stringify(submitted)],{type:"application/json"})),window.location.href="/submissionsuccess/"}catch(e){console.error("上传失败:",e),alert("投稿失败,请重试!")}}else alert("请填写内容的标题。")}else alert("您还未登录,请登录后再进行投稿。")}()},document.getElementById("SaveDraft").addEventListener("click",async()=>{if(s){if(confirm("确认保存草稿吗?如您之前有草稿内容,此操作会覆盖前一次的草稿内容。")){var e=simplemde.value(),t=`upload/${curemail}/${submitted+1}/draft.json`,e=new Blob([JSON.stringify({content:e},null,2)],{type:"application/json"});try{await client.put(t,e),alert("草稿已保存!")}catch(e){console.error("保存草稿时出错:",e),alert("保存草稿失败,请稍后再试。")}}}else alert("非法操作!请先登录。")}),document.getElementById("LoadDraft").addEventListener("click",async()=>{if(s){var e=`https://download.xn--xhq44jb2fzpc.com/upload/${curemail}/${submitted+1}/draft.json`;try{var t=await fetchNoCache(e);if(t.ok){var n=await t.json();confirm("此操作会覆盖您当前的输入内容,确认加载草稿吗?")&&(simplemde.value(n.content),alert("草稿已加载!"))}else{if(404!==t.status)throw new Error("无法加载草稿内容");alert("没有草稿记录!")}}catch(e){console.error("加载草稿时出错:",e),alert("加载草稿失败,请稍后再试。")}}else alert("非法操作!请先登录。")});