### JavaScript: Internationalization (i18n) Setup Source: https://github.com/tangsengdaodao/tangsengdaodaoserver/blob/main/assets/web/report.html Initializes the i18n plugin to handle multi-language support for elements with the 'i18n' attribute. It sets the default language and specifies the path for language files. Dependencies: jQuery, i18n plugin, `getLang` function. ```javascript $(document).ready(function () { var defaultLang = window.getLang() if (defaultLang.indexOf("en") != -1) { document.title = "Report"; } $("[i18n]").i18n({ defaultLang: defaultLang, filePath: "./i18n/", filePrefix: "i18n_", fileSuffix: "", forever: true, callback: function () { console.log("i18n is ready."); } }); }); ``` -------------------------------- ### JavaScript Image Upload Handling Source: https://github.com/tangsengdaodao/tangsengdaodaoserver/blob/main/assets/web/report.html Manages the process of selecting and uploading an image file. It gets the file object, generates a URL, and triggers the upload process. ```javascript let imageDatas = \[\]; function uploadChange() { var objUrl = getObjectURL(this.files[0]);//获取文件信息 if (objUrl) { imageDatas.push(objUrl); renderImageItes(); uploadImage(this.files[0]); } } let imgPaths = \[\]; function uploadImage(fileObj) { let uid = getQueryString('uid'); let token = getQueryString('token'); $.ajax({ headers: { Accept: "application/json; charset=utf-8", token: token }, url: apiURL + `file/upload?type=report&path=/${uid}/${uuid()}`, type: "get", success: function (result) { var form = new FormData(); form.append("file", fileObj); var xhr = new XMLHttpRequest(); xhr.open("post", result.url, true); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if (xhr.status == 200) { var obj = JSON.parse(xhr.responseText); console.log(obj); imgPaths.push(obj.path); } } } xhr.send(form); } }) } ``` -------------------------------- ### JavaScript: Get Query String Parameter Source: https://github.com/tangsengdaodao/tangsengdaodaoserver/blob/main/assets/web/report.html This function retrieves the value of a specified parameter from the current URL's query string. It's essential for accessing URL-based configurations or states. Dependencies: None. ```javascript function getQueryString("mode") { let mode = getQueryString("mode") if (mode == 'dark') { linkScript("css/report.dark.css"); } } ``` -------------------------------- ### JavaScript: Get Category by Category Number Source: https://github.com/tangsengdaodao/tangsengdaodaoserver/blob/main/assets/web/report.html Searches a list of categories (potentially nested) to find a category that matches the provided category number. It recursively searches through children if the category is not found at the current level. Dependencies: None. ```javascript function getCatgoryWithCategoryNo(categoryNo, categoryList) { for (const category of categoryList) { if (category.category_no == categoryNo) { return category; } if (category.children && category.children.length > 0) { let ct = getCatgoryWithCategoryNo(categoryNo, category.children); if (ct) { return ct } } } } ``` -------------------------------- ### JavaScript: Get User Language Setting Source: https://github.com/tangsengdaodao/tangsengdaodaoserver/blob/main/assets/web/report.html Determines the user's preferred language based on browser settings or a 'lang' query parameter in the URL. It defaults to 'cn' (Chinese) if no specific language is detected or set. Dependencies: `getQueryString` function. ```javascript window.getLang = function () { var defaultLang = "cn"; let lang = window.navigator.userLanguage || window.navigator.language; let userLang = getQueryString("lang") if (userLang && userLang !== "") { lang = userLang } if (lang.indexOf("en") != -1) { defaultLang = "en"; } return defaultLang } ``` -------------------------------- ### Go 死锁错误重试机制 Source: https://github.com/tangsengdaodao/tangsengdaodaoserver/blob/main/docs/deadlock-analysis-and-solution.md 实现一个重试机制,当捕获到死锁错误时,采用指数退避策略等待一段时间后重新尝试操作。这是一种常见的应用层面的错误处理和容错手段。 ```go func retryOnDeadlock(fn func() error, maxRetries int) error { for i := 0; i < maxRetries; i++ { err := fn() if err == nil { return nil } if isDeadlockError(err) && i < maxRetries-1 { time.Sleep(time.Duration(1< 0) { window.history.forward() } }); $(".back").on('touchend', function () { window.history.back() }); $.getJSON(apiURL + `report/categories?lang=${window.getLang()}`).then(function (categories) { window.categories = categories; if (categories && categories.length > 0) { renderCategories(categories); } }) if ("onhashchange" in window) { window.onhashchange = function (ev) { if (window.location.hash && window.location.hash != '') { let categoryNos = window.location.hash.substring(1).split("-") let category = getCatgoryWithCategoryNo(categoryNos[categoryNos.length - 1], window.categories); if (category && category.children && category.children.length > 0) { renderCategories(category.children); } else { $(".reportFormBox").css('display', 'block'); $(".categoryBox").css('display', 'none'); return // renderCategories(window.categories); } } else { renderCategories(window.categories); } }; } }); ``` -------------------------------- ### JavaScript: Fetch and Display Invitation Details Source: https://github.com/tangsengdaodao/tangsengdaodaoserver/blob/main/assets/web/invite_detail.html Fetches invitation details using the inviteNo and auth_code from query parameters. It then populates the UI with inviter information, invited members, and handles the confirmation button's click event. ```javascript let inviteNo = getQueryString('invite_no'); let code = getQueryString('auth_code'); $(function () { im.onReady(); $.getJSON(`${apiURL}group/invites/${inviteNo}`).then(function (resp) { let data = resp; $(".avatar").attr('src', `${apiURL}users/${data.inviter}/avatar`); $(".inviter").text(data.inviter_name); $(".tip").text(`邀请${data.items.length}位朋友加入群聊`); if (data.remark && data.remark != '') { $(".remark").text(`"${data.remark}"`); } for (let i = 0; i < data.items.length; i++) { let item = data.items[i]; let memberElem = $(`
${item.name}
`) $('.members').append(memberElem); } if (data.status == 1) { $("#ok").text('已确认'); } else { $("#ok").click(function () { $.postJSON(`${apiURL}group/invite/sure?auth_code=${code}`).then(function (resp) { im.quit(); }).fail(function (e) { }) }); } }) }) ``` -------------------------------- ### Initialize IM and Handle Close Button Click (JavaScript) Source: https://github.com/tangsengdaodao/tangsengdaodaoserver/blob/main/assets/web/report_success.html This snippet initializes the IM (Instant Messaging) module and sets up an event listener for a close button. When the close button is clicked, it calls the `im.quit()` function to close the IM interface. It relies on an external `im` object, likely provided by a third-party library or a globally defined script. ```javascript $(function () { im.onReady(); // Initialize im $(".closeBtn").on('click', async function () { im.quit(); }) }) ``` -------------------------------- ### Conditional CSS Loading Based on URL Parameter (JavaScript) Source: https://github.com/tangsengdaodao/tangsengdaodaoserver/blob/main/assets/web/report_success.html This snippet demonstrates how to conditionally load a CSS file based on a URL query parameter. It retrieves the value of the 'mode' parameter using `getQueryString`. If the mode is 'dark', it calls the `linkScript` function to load the 'css/report.dark.css' file. This enables dynamic theming of the page. ```javascript let mode = getQueryString("mode") if (mode == 'dark') { linkScript("css/report.dark.css"); } ``` -------------------------------- ### SQL 批量插入 Source: https://github.com/tangsengdaodao/tangsengdaodaoserver/blob/main/docs/deadlock-analysis-and-solution.md 将多个单行插入合并为一次批量插入操作,可以显著减少与数据库的交互次数,缩短事务持有锁的时间,从而降低死锁的风险。 ```sql INSERT IGNORE INTO reminder_done(reminder_id,uid) VALUES (?,?),(?,?),(?,?)... ``` -------------------------------- ### Dynamically Load CSS/JS Files (JavaScript) Source: https://github.com/tangsengdaodao/tangsengdaodaoserver/blob/main/assets/web/report_success.html This function, `linkScript`, dynamically loads CSS or JavaScript files into the HTML document's head. It creates either a `` element for CSS or a `