hwmAdvancedMenu

Расширенное меню

当前为 2023-12-21 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name hwmAdvancedMenu
  3. // @namespace Tamozhnya1
  4. // @author Tamozhnya1
  5. // @description Расширенное меню
  6. // @version 1.5
  7. // @include *heroeswm.ru/*
  8. // @include *lordswm.com/*
  9. // @exclude */rightcol.php*
  10. // @exclude */ch_box.php*
  11. // @exclude */chat*
  12. // @exclude */ticker.html*
  13. // @exclude */frames*
  14. // @exclude */brd.php*
  15. // @license MIT
  16. // ==/UserScript==
  17.  
  18. if(!this.GM_getValue) {
  19. this.GM_getValue = function(key, def) { return localStorage[key] || def; };
  20. this.GM_setValue = function(key, value) { localStorage[key] = value; };
  21. this.GM_deleteValue = function(key) { return delete localStorage[key]; };
  22. }
  23. const StoredForumTreadsAmount = 10;
  24. const playerIdMatch = document.cookie.match(/pl_id=(\d+)/);
  25. if(!playerIdMatch) {
  26. return;
  27. }
  28. const PlayerId = playerIdMatch[1];
  29. const isEn = document.documentElement.lang == "en";
  30. const isNewInterface = document.querySelector("div#hwm_header") ? true : false;
  31.  
  32. main();
  33. function main() {
  34. processHouses();
  35. processQuickLinks();
  36. processForum();
  37. // После рынка вставим ссылки на ресурсы, с задержкой в пол секунды
  38. const auctionRef = isNewInterface ? document.querySelector("div.sh_dd_container a[href='auction.php']") : getParent(document.querySelector("li > a[href='auction.php']"), "li");
  39. if(auctionRef) {
  40. let resourcesShowTimer;
  41. let resourcesShown = false;
  42. const resources = [ { type: "1", name: isEn ? 'Wood' : 'Древесина' }, { type: "2", name: isEn ? 'Ore' : 'Руда' }, { type: "3", name: isEn ? 'Mercury' : 'Ртуть' }, { type: "4", name: isEn ? 'Sulfur' : 'Сера' }, { type: "5", name: isEn ? 'Crystals' : 'Кристаллы' }, { type: "6", name: isEn ? 'Gems' : 'Самоцветы' } ];
  43. auctionRef.addEventListener("mouseover", function() { if(!resourcesShown) resourcesShowTimer = setTimeout(function() {
  44. const html = resources.reduce((t, x) => t + getMenuItemTemplate(`auction.php?cat=res&sort=0&type=${x.type}`, `  ${x.name}`), "");
  45. auctionRef.insertAdjacentHTML('afterend', html);
  46. resourcesShown = true;
  47. }, 500) } );
  48. auctionRef.addEventListener("mouseout", function() { clearTimeout(resourcesShowTimer); });
  49. }
  50. // После передачи ресурсов вставим основные ссылки персонажа
  51. const transferRef = isNewInterface ? document.querySelector("div.sh_dd_container a[href='transfer.php']") : getParent(document.querySelector("li > a[href='transfer.php']"), "li");
  52. if(transferRef) {
  53. const personalReferences = [
  54. { href: `el_transfer.php`, text: isEn ? 'Transfer elements' : 'Передача элементов' },
  55. { href: 'javascript:void(0);', text: "" },
  56. { href: `pl_info.php?id=${PlayerId}`, text: isEn ? 'Character' : 'Персонаж' },
  57. { href: `pl_transfers.php?id=${PlayerId}`, text: isEn ? 'Transfer log' : 'Протокол передач' },
  58. { href: `pl_warlog.php?id=${PlayerId}`, text: isEn ? 'Combat log' : 'Протокол боев' },
  59. { href: `pl_cardlog.php?id=${PlayerId}`, text: isEn ? 'Game log' : 'Протокол игр' },
  60. { href: `friends.php`, text: isEn ? 'Your friends' : 'Ваши друзья' },
  61. { href: `ephoto_albums.php`, text: isEn ? 'Your photos' : 'Ваш фотоальбом' },
  62. { href: 'javascript:void(0);', text: "" },
  63. { href: `logout.php?${Math.round( Math.random()* 100000 )}`, text: isEn ? 'Logout' : 'Выход' }
  64. ];
  65. const html = personalReferences.reduce((t, x) => t + getMenuItemTemplate(x.href, x.text), "");
  66. transferRef.insertAdjacentHTML('afterend', html);
  67. }
  68. // Расширение карты
  69. const mapMenuContainer = isNewInterface ? document.querySelector("div.sh_dd_container a[href='map.php?st=hs']") : getParent(document.querySelector("li > a[href='map.php?st=hs']"), "li");
  70. if(mapMenuContainer) {
  71. const housesInfo = JSON.parse(GM_getValue(`PlayerHouses${PlayerId}`, "{}"));
  72. let mapExtenders = Object.keys(housesInfo).map(x => ({ href: `house_info.php?id=${x}`, text: housesInfo[x].replace(" ", " ") }));
  73. // Арендованные дома. Берутся из скрипта Transporter
  74. for(let locationNumber = 1; locationNumber <= 27; locationNumber++) {
  75. const guestInfo = JSON.parse(GM_getValue(`GuestInfo${locationNumber}`, "{}"));
  76. for(const key in guestInfo) {
  77. mapExtenders = [...mapExtenders, { href: `house_info.php?id=${key}`, text: guestInfo[key].HostInfo, title: `до ${(new Date(guestInfo[key].ExpireDate)).toLocaleString()}` }];
  78. }
  79. }
  80. //
  81. mapExtenders = [...mapExtenders, { href: 'javascript:void(0);', text: "" }, { href: 'ecostat.php', text: isEn ? 'Economic statistics' : 'Эконом. статистика' }];
  82. const html = mapExtenders.reduce((t, x) => t + getMenuItemTemplate(x.href, x.text, x.title), "");
  83. //console.log(mapExtenders)
  84. mapMenuContainer.insertAdjacentHTML('afterend', html);
  85. }
  86. // Добавим форумов и дейли
  87. const forumsContainer = isNewInterface ? document.querySelector("div.sh_dd_container a[href='forum.php#t1']") : getParent(document.querySelector("li > a[href='forum.php#t1']"), "li");
  88. if(forumsContainer) {
  89. const forumExtenders = [
  90. { href: `forum_thread.php?id=${isEn ? '103' : '3'}`, text: isEn ? 'Ideas and suggestions' : 'Идеи и предложения' },
  91. { href: `forum_thread.php?id=${isEn ? '121' : '22'}`, text: isEn ? 'Smiths and Ench. services' : 'Услуги кузнецов и оруж.' },
  92. { href: 'javascript:void(0);', text: "" },
  93. { href: `${isEn ? 'http://daily.heroeswm.ru/newscom.php' : 'http://daily.heroeswm.ru/'}`, text: isEn ? 'HWM Daily ENG' : 'Геройская лента' }
  94. ];
  95. let html = forumExtenders.reduce((t, x) => t + getMenuItemTemplate(x.href, x.text), "");
  96. const lastForumTreads = JSON.parse(GM_getValue("LastForumTreads", "[]"));
  97. if(lastForumTreads.length > 0) {
  98. html += getMenuItemTemplate('javascript:void(0);', "");
  99. }
  100. html += lastForumTreads.reduce((t, x) => t + getMenuItemTemplate(`/forum_messages.php?tid=${x.threadId}${x.pageIndex ? `&page=${x.pageIndex}` : ""}`, x.threadName, "", `forumReference${x.threadId}`), "");
  101. forumsContainer.insertAdjacentHTML('afterend', html);
  102. Array.from(document.querySelectorAll(`span[id^='forumReference']`)).forEach(x => x.addEventListener("click", deleteForumReferenceMenuItem));
  103. }
  104. // После чатов добавим быстрые ссылки
  105. const framesContainer = isNewInterface ? document.querySelector("div.sh_dd_container a[href='frames.php?room=4']") : getParent(document.querySelector("li > a[href='frames.php?room=4']"), "li");
  106. if(framesContainer) {
  107. //GM_deleteValue(`QuickLinks${PlayerId}`);
  108. let quickLinks = JSON.parse(GM_getValue(`QuickLinks${PlayerId}`, "[]")).filter(x => x.Name != "" && x.Refernce != "");
  109. if(quickLinks.length > 0) {
  110. quickLinks = [{ Refernce: "javascript:void(0);", Name: "" }, ...quickLinks];
  111. const html = quickLinks.reduce((t, x) => t + getMenuItemTemplate(x.Refernce, x.Name), "");
  112. framesContainer.insertAdjacentHTML('afterend', html);
  113. }
  114. }
  115. }
  116. function deleteForumReferenceMenuItem(e) {
  117. //e.stopPropagation();
  118. e.preventDefault();
  119. const threadId = e.target.id.replace("forumReference", "");
  120. console.log(`threadId: ${threadId}`)
  121. const lastForumTreads = JSON.parse(GM_getValue("LastForumTreads", "[]")).filter(x => x.threadId != threadId);
  122. GM_setValue("LastForumTreads", JSON.stringify(lastForumTreads));
  123. const menuItem = isNewInterface ? getParent(e.target, "a") : getParent(e.target, "li");
  124. console.log(menuItem)
  125. menuItem.remove();
  126. }
  127. function processForum() {
  128. if(location.pathname == '/forum_messages.php') {
  129. if(GM_getValue("LastForumTreads")) {
  130. const saved = JSON.parse(GM_getValue("LastForumTreads"));
  131. if(!Array.isArray(saved)) {
  132. GM_deleteValue("LastForumTreads");
  133. }
  134. }
  135. //https://www.heroeswm.ru/forum_messages.php?tid=2964583&page=5
  136. const threadId = getUrlParamValue(location.href, "tid");
  137. const pageIndex = getUrlParamValue(location.href, "page");
  138. const threadName = document.querySelector(`a[href='forum_messages.php?tid=${threadId}'`).innerText;
  139. const newThread = { threadId: threadId, pageIndex: pageIndex || 0, threadName: threadName, viewTime: Date.now() };
  140. let lastForumTreads = JSON.parse(GM_getValue("LastForumTreads", "[]"));
  141. const thisThread = lastForumTreads.find(x => x.threadId == newThread.threadId && x.pageIndex == newThread.pageIndex);
  142. if(thisThread) {
  143. window.scrollTo(0, thisThread.scrollPosition);
  144. }
  145. newThread.scrollPosition = window.scrollY;
  146. lastForumTreads = lastForumTreads.filter(x => x.threadId != newThread.threadId);
  147. lastForumTreads.unshift(newThread);
  148. lastForumTreads = lastForumTreads.slice(0, StoredForumTreadsAmount);
  149. GM_setValue("LastForumTreads", JSON.stringify(lastForumTreads));
  150. document.addEventListener("scroll", (event) => {
  151. const lastForumTreads = JSON.parse(GM_getValue("LastForumTreads", "[]"))
  152. const scrolledTread = lastForumTreads.find(x => x.threadId == newThread.threadId);
  153. if(scrolledTread) {
  154. scrolledTread.scrollPosition = window.scrollY;
  155. GM_setValue("LastForumTreads", JSON.stringify(lastForumTreads));
  156. }
  157. });
  158. }
  159. }
  160. function getMenuItemTemplate(href, text, title, deleteId) {
  161. if(!isNewInterface) {
  162. if(text == "") {
  163. return "<hr>";
  164. }
  165. let deleteElementText = "";
  166. if(deleteId) {
  167. deleteElementText = `<span id="${deleteId}" title='${isEn ? "Delete" : "Удалить"}' style="cursor: pointer; display: inline; color: yellow;">[x]</span>`;
  168. }
  169. return `<li><a href='${href}' title='${title || ""}' style="">${text}${deleteElementText}</a></li>`;
  170. } else {
  171. let deleteElementText = "";
  172. if(deleteId) {
  173. deleteElementText = `<span id="${deleteId}" title='${isEn ? "Delete" : "Удалить"}' style="cursor: pointer; display: inline; float: right;">[x]</span>`;
  174. }
  175. return `<a href='${href}' title='${title || ""}' style='text-decoration: none;'><div style='${text == "" ? "padding: 0; height: 2px;" : ""}'>${text}${deleteElementText}</div></a>`;
  176. }
  177. }
  178. function processHouses() {
  179. if(location.pathname == "/pl_info_realty.php" && getUrlParamValue(location.href, "id") == PlayerId) {
  180. const housesInfo = Array.from(document.querySelectorAll("a[href^='house_info.php']")).reduce((t, x) => ({...t, [getUrlParamValue(x.href, "id")]: getParent(x, "tr").cells[4].innerText }), {});
  181. //console.log(housesInfo);
  182. GM_setValue(`PlayerHouses${PlayerId}`, JSON.stringify(housesInfo));
  183. }
  184. }
  185. function processQuickLinks() {
  186. if(location.pathname == "/pers_navlinks.php") {
  187. const tbody = getParent(document.querySelector("form[action='pers_navlinks.php']"), "tbody");
  188. const tr = addElement("tr", tbody);
  189. const td = addElement("td", tr);
  190. const table = addElement("table", td);
  191. const quickLinkAmount = 10;
  192. let quickLinks = JSON.parse(GM_getValue(`QuickLinks${PlayerId}`, `[${Array(quickLinkAmount).fill('{"Name":"","Refernce":""}').join()}]`));
  193. if(quickLinks.length != quickLinkAmount) {
  194. GM_deleteValue(`QuickLinks${PlayerId}`);
  195. quickLinks = JSON.parse(`[${Array(quickLinkAmount).fill('{"Name":"","Refernce":""}').join()}]`);
  196. }
  197. //console.log(quickLinks)
  198. let i = 0;
  199. for(const quickLink of quickLinks) {
  200. const html = `
  201. <tr>
  202. <td>
  203. <input id="linkName${i}" name="linkName" type="text" style="width: 200px;" />
  204. <input id="linkValue${i}" name="linkValue" type="text" style="width: 300px;" />
  205. </td>
  206. </tr>`;
  207. table.insertAdjacentHTML('beforeend', html);
  208. table.querySelector(`#linkName${i}`).value = quickLink.Name;
  209. table.querySelector(`#linkValue${i}`).value = quickLink.Refernce;
  210. table.querySelector(`#linkName${i}`).addEventListener("change", saveQuickLinks);
  211. table.querySelector(`#linkValue${i}`).addEventListener("change", saveQuickLinks);
  212. i++;
  213. }
  214. }
  215. }
  216. function saveQuickLinks() {
  217. const quickLinks = Array.from(document.querySelectorAll("input[name=linkName]")).map(x => ({ Name: x.value, Refernce: document.getElementById(x.id.replace("linkName", "linkValue")).value }));
  218. //console.log(quickLinks)
  219. GM_setValue(`QuickLinks${PlayerId}`, JSON.stringify(quickLinks));
  220. }
  221. function addElement(type, parent, data, insertFirst = false) {
  222. let el = createElement(type, data);
  223. if(parent) {
  224. if(insertFirst) {
  225. parent.insertBefore(el, parent.firstChild);
  226. } else {
  227. parent.appendChild(el);
  228. }
  229. }
  230. return el;
  231. }
  232. function createElement(type, data) {
  233. let el = document.createElement(type);
  234. if(data) {
  235. for(let key in data) {
  236. if(key == "innerText" || key == "innerHTML") {
  237. el[key] = data[key];
  238. } else {
  239. el.setAttribute(key, data[key]);
  240. }
  241. }
  242. }
  243. return el;
  244. }
  245. function getParent(element, parentType, number = 1) {
  246. if(!element) {
  247. return;
  248. }
  249. let result = element;
  250. let foundNumber = 0;
  251. while(result = result.parentNode) {
  252. if(result.nodeName.toLowerCase() == parentType.toLowerCase()) {
  253. foundNumber++;
  254. if(foundNumber == number) {
  255. return result;
  256. }
  257. }
  258. }
  259. }
  260. function getUrlParamValue(url, paramName) { return (new URLSearchParams(url.split("?")[1])).get(paramName); }