hwmWidget

Виджет для главной страницы ГВД

目前為 2023-12-14 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name hwmWidget
  3. // @include /^https{0,1}:\/\/((www|qrator)\.heroeswm\.ru|178\.248\.235\.15)\/home\.php/
  4. // @description Виджет для главной страницы ГВД
  5. // @version 4.9
  6. // @author Tamozhnya1
  7. // @namespace Tamozhnya1
  8. // @grant GM.xmlHttpRequest
  9. // @grant unsafeWindow
  10. // @grant GM_log
  11. // @grant GM_setValue
  12. // @grant GM_getValue
  13. // @grant GM_addStyle
  14. // @license MIT
  15. // ==/UserScript==
  16. if(typeof GM_getValue != 'function') {
  17. this.GM_getValue = function (key,def) { return localStorage[key] || def; };
  18. this.GM_setValue = function (key,value) { return localStorage[key] = value; };
  19. this.GM_deleteValue = function (key) { return delete localStorage[key]; };
  20. }
  21. const LotType = { Purchase: 1, Auction: 2 };
  22. var ElementsTypes = { "42": "abrasive", "43": "snake_poison", "46": "tiger_tusk", "44": "ice_crystal", "45": "moon_stone", "40": "fire_crystal", "37": "meteorit", "41": "witch_flower", "39": "wind_flower", "78": "fern_flower", "38": "badgrib" }
  23. var ElementNames = ["abrasive", "snake_poison", "tiger_tusk", "ice_crystal", "moon_stone", "fire_crystal", "meteorit", "witch_flower", "wind_flower", "fern_flower", "badgrib"];
  24. var ResourcesTypes = { "wood": { Type: "1", ImageName: "wood" }, "ore": { Type: "2", ImageName: "ore" }, "mercury": { Type: "3", ImageName: "mercury" }, "sulphur": { Type: "4", ImageName: "sulfur" }, "crystal": { Type: "5", ImageName: "crystals" }, "gem": { Type: "6", ImageName: "gems" } };
  25. var forumNames = { "2": "ОиФ", "10": "ВиП", "24": "Турниры", "3": "ИиП", "12": "БиП", "11": "ФВТ", "27": "Встречи", "14": "Обычные артефакты", "21": "Аренда", "22": "УКиО", "23": "ПЭСиП", "25": "ПЗ(Бои)", "13": "ПЗ(Финансы)", "7": "ТП", "8": "ОиС" };
  26. const locations = {
  27. 1: [50,50,"Empire Capital","EmC","Столица Империи"],
  28. 2: [51,50,"East River","EsR","Восточная Река"],
  29. 3: [50,49,"Tiger Lake","TgL","Тигриное Озеро"],
  30. 4: [51,49,"Rogues' Wood","RgW","Лес Разбойников"],
  31. 5: [50,51,"Wolf Dale","WoD","Долина Волков"],
  32. 6: [50,48,"Peaceful Camp","PcC","Мирный Лагерь"],
  33. 7: [49,51,"Lizard Lowland","LzL","Равнина Ящеров"],
  34. 8: [49,50,"Green Wood","GrW","Зеленый Лес"],
  35. 9: [49,48,"Eagle Nest","EgN","Орлиное Гнездо"],
  36. 10: [50,52,"Portal Ruins","PoR","Руины Портала"],
  37. 11: [51,51,"Dragons' Caves","DrC","Пещеры Драконов"],
  38. 12: [49,49,"Shining Spring","ShS","Сияющий Родник"],
  39. 13: [48,49,"Sunny City","SnC","Солнечный Город"],
  40. 14: [52,50,"Magma Mines","MgM","Магма Шахты"],
  41. 15: [52,49,"Bear Mountain","BrM","Медвежья Гора"],
  42. 16: [52,48,"Fairy Trees","FrT","Магический Лес"],
  43. 17: [53,50,"Harbour City","HrC","Портовый Город"],
  44. 18: [53,49,"Mythril Coast","MfC","Мифриловый Берег"],
  45. 19: [51,52,"Great Wall","GtW","Великая Стена"],
  46. 20: [51,53,"Titans' Valley","TiV","Равнина Титанов"],
  47. 21: [52,53,"Fishing Village","FsV","Рыбачье село"],
  48. 22: [52,54,"Kingdom Castle","KiC","Замок Королевства"],
  49. 23: [48,48,"Ungovernable Steppe","UnS","Непокорная Степь"],
  50. 24: [51,48,"Crystal Garden","CrG","Кристальный Сад"],
  51. 25: [53,52,"East Island","EsI","Восточный Остров"],
  52. 26: [49,52,"The Wilderness","ThW","Дикие земли"],
  53. 27: [48,50,"Sublime Arbor","SbA","Великое Древо"]
  54. };
  55. const isEn = document.documentElement.lang == "en";
  56. const Strings = { "ru": { BuyNow: "Купить сразу!" }, "en": { BuyNow: "Buy now!" } };
  57. const LocalizedString = Strings[document.documentElement.lang];
  58. const horizontalPadding = 25;
  59. GM_addStyle(`
  60. .hover-link:hover{ color: red }
  61. .news-head {
  62. text-decoration:none;
  63. align-self: center;
  64. border-radius: 1.5rem;
  65. padding: 0.25rem .75rem;
  66. }
  67.  
  68. .active {
  69. background: #eae8dd;
  70. }
  71.  
  72. .active:hover {
  73. background: #eae8dd80;
  74. }
  75.  
  76. .news-head__title {
  77. display: inline;
  78. font-size: 12px;
  79. font-weight: normal;
  80. cursor: pointer;
  81. }
  82.  
  83. .news-head__switch {
  84. cursor: pointer;
  85. align-self: center;
  86. color: #5D413A40;
  87. margin-left:10px;
  88. }
  89.  
  90. .news-head__settings {
  91. cursor: pointer;
  92. align-self: center;
  93. color: #5D413A40;
  94. margin-left:10px;
  95. width: 1.5%;
  96. }
  97.  
  98. .mrgn-l{
  99. margin-left: 5px;
  100. }
  101.  
  102. .flex {
  103. display: flex;
  104. }
  105.  
  106. .div-style {
  107. margin: 0 auto 10px;
  108. padding: 15px ${horizontalPadding}px 20px;
  109. overflow: hidden;
  110. min-width: 400px;
  111. border-radius: 5px;
  112. border: 0 #adadad solid;
  113. background: url(../i/inv_im/corner_lt2.png) no-repeat top left, url(../i/inv_im/corner_rt2.png) no-repeat top right, url(../i/inv_im/corner_lb2.png) no-repeat bottom left, url(../i/inv_im/corner_rb2.png) no-repeat bottom right #f5f3ea;
  114. background-size: 14px;
  115. box-shadow: inset 0 0 0 1px #b19673, 0 2px 5px rgb(0 0 0 / 25%);
  116. }
  117.  
  118. .res-style {
  119. display: none;
  120. justify-content: space-around;
  121. height: 40px;
  122. background-color: #eae8dd;
  123. border-radius: 5px;
  124. border: 0 #adadad solid;
  125. margin-top: 10px;
  126. }
  127.  
  128. .modal {
  129. width: 100%;
  130. height: 100%;
  131. z-index: 1000;
  132. position: fixed;
  133. top:0;
  134. left:0;
  135. background: #00000050;
  136. display: none;
  137. align-items: center;
  138. }
  139.  
  140. .modal-block {
  141. display: flex;
  142. width: 800px;
  143. height: 500px;
  144. z-index: 120;
  145. margin: 0 auto;
  146. position: relative;
  147. border-radius: 5px;
  148. border: 0 #adadad solid;
  149. background: url(../i/inv_im/corner_lt2.png) no-repeat top left, url(../i/inv_im/corner_rt2.png) no-repeat top right, url(../i/inv_im/corner_lb2.png) no-repeat bottom left, url(../i/inv_im/corner_rb2.png) no-repeat bottom right #f5f3ea;
  150. background-size: 14px;
  151. box-shadow: inset 0 0 0 1px #b19673, 0 2px 5px rgb(0 0 0 / 25%);
  152. padding: 15px;
  153. align-items: flex-start;
  154. flex-direction: column;
  155. overflow: scroll;
  156. }
  157.  
  158. .modal-block__head {
  159. display: flex;
  160. align-items: center;
  161. }
  162.  
  163. .modal-block__text {
  164. margin-top: 20px;
  165. color: #6e6e6e;
  166. }
  167.  
  168. .modal-block__btn {
  169. padding: 5px 15px;
  170. white-space: nowrap;
  171. position: relative;
  172. text-align: center;
  173. color: #592C08;
  174. background: url(../i/shop_images/art_btn_bg_gold.png) #DAB761;
  175. background-size: 100% 100%;
  176. -webkit-border-radius: 5px;
  177. -moz-border-radius: 5px;
  178. border: 0 solid;
  179. border-radius: 5px;
  180. box-shadow: inset 0 0 0 1px #fce6b0, inset 0 0 0 2px #a78750, 0 0 0 1px rgb(0 0 0 / 13%);
  181. cursor: pointer;
  182. margin-left: 150px;
  183. }
  184.  
  185. .modal-block__setting {
  186. display: flex;
  187. flex-wrap: wrap;
  188. }
  189.  
  190. .modal-block__checkbox {
  191. display: flex;
  192. align-items: center;
  193. margin: 0 8px 8px 5px;
  194. padding: 0;
  195. }
  196.  
  197. .clan-block {
  198. flex-direction: column;
  199. }
  200.  
  201. .clan-style {
  202. display: inline-flex;
  203. background-color: #adadad40;
  204. padding: 3px 7px;
  205. margin-left: 7px;
  206. border: 0;
  207. border-radius: 4px;
  208. color: #592C08;
  209. }
  210.  
  211. .res-style__elem {
  212. align-self: center;
  213. display: flex;
  214. }
  215.  
  216. .text-title {
  217. text-align:left;
  218. padding-top: 6px;
  219. }
  220.  
  221. @media screen and (min-width: 320px) and (max-width: 600px) {
  222. .div-style {
  223. width: auto;
  224. }
  225. .news-head__title {
  226. font-size: 10px;
  227. }
  228. .res-style {
  229. flex-wrap: wrap;
  230. height: auto;
  231. padding: 5px;
  232. }
  233. .res-style__elem {
  234. margin: 0 10px 10px 0;
  235. font-size: 12px;
  236. }
  237. .text-title {
  238. font-size: 12px;
  239. }
  240. .news-head__settings {
  241. width: 10%;
  242. }
  243. .modal-block {
  244. width: 500px;
  245. height: 800px;
  246. }
  247. }`);
  248. const isNewPersonPage = document.querySelector("div#hwm_no_zoom") ? true : false;
  249. const isMobileInterface = document.querySelector("div#btnMenuGlobal") ? true : false;
  250.  
  251. main();
  252. async function main() {
  253. //let widgetContainer = isNewPersonPage ? document.querySelector("body > center") : document.querySelector("body > center > table:nth-child(2) > tbody > tr > td > table > tbody > tr:nth-child(6) > td:nth-child(1)");
  254. let widgetContainer = isNewPersonPage ? document.querySelector("div#hwm_no_zoom") : document.querySelector("body > center > table:nth-child(2) > tbody > tr > td > table > tbody > tr:nth-child(6) > td:nth-child(1)");
  255. if(isMobileInterface) {
  256. widgetContainer = isNewPersonPage ? document.querySelector("div#set_mobile_max_width") : document.querySelector("div#android_container > table > tbody > tr:nth-child(6) > td:nth-child(1)");
  257. if(isNewPersonPage) {
  258. widgetContainer.style.flexWrap = "wrap";
  259. addElement("div", widgetContainer, { style: "flex-basis: 100%; height: 0;"});
  260. }
  261. }
  262. let widthSnippet = "";
  263. if(isNewPersonPage) {
  264. const anchorRect = document.querySelector("div#set_mobile_max_width").getBoundingClientRect();
  265. widthSnippet = ` style="width: ${anchorRect.width - horizontalPadding * 2 - 4}px;"`;
  266. }
  267. if(widgetContainer) {
  268. let divOuterInnerHTML = `
  269. <div class="div-style"${widthSnippet}>
  270. <div class="flex">
  271. <div id="hwmWidget" class="flex">
  272. <div id="hwmWidgetDailyPreviewTab" class="news-head active">
  273. <span>📰</span>
  274. <h2 class="news-head__title" title="Новости HWM Daily">Новости HWM Daily</h2>
  275. </div>
  276. <h2 id="hwmWidgetPorumPreviewTab" class="news-head news-head__title mrgn-l" title="Последние темы форума">Последние темы форума</h2>
  277. <h2 id="hwmWidgetClanLettersPreviewTab" class="news-head news-head__title mrgn-l" title="Клановая рассылка">Клановая рассылка</h2>
  278. </div>
  279. <span id="hwmWidgetSwitcher" class="news-head__switch"></span>
  280. <span id="hwmWidgetSettings" class="news-head__settings" title="Настройки"><svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="cog" class="svg-inline--fa fa-cog fa-w-16" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="currentColor" d="M487.4 315.7l-42.6-24.6c4.3-23.2 4.3-47 0-70.2l42.6-24.6c4.9-2.8 7.1-8.6 5.5-14-11.1-35.6-30-67.8-54.7-94.6-3.8-4.1-10-5.1-14.8-2.3L380.8 110c-17.9-15.4-38.5-27.3-60.8-35.1V25.8c0-5.6-3.9-10.5-9.4-11.7-36.7-8.2-74.3-7.8-109.2 0-5.5 1.2-9.4 6.1-9.4 11.7V75c-22.2 7.9-42.8 19.8-60.8 35.1L88.7 85.5c-4.9-2.8-11-1.9-14.8 2.3-24.7 26.7-43.6 58.9-54.7 94.6-1.7 5.4.6 11.2 5.5 14L67.3 221c-4.3 23.2-4.3 47 0 70.2l-42.6 24.6c-4.9 2.8-7.1 8.6-5.5 14 11.1 35.6 30 67.8 54.7 94.6 3.8 4.1 10 5.1 14.8 2.3l42.6-24.6c17.9 15.4 38.5 27.3 60.8 35.1v49.2c0 5.6 3.9 10.5 9.4 11.7 36.7 8.2 74.3 7.8 109.2 0 5.5-1.2 9.4-6.1 9.4-11.7v-49.2c22.2-7.9 42.8-19.8 60.8-35.1l42.6 24.6c4.9 2.8 11 1.9 14.8-2.3 24.7-26.7 43.6-58.9 54.7-94.6 1.5-5.5-.7-11.3-5.6-14.1zM256 336c-44.1 0-80-35.9-80-80s35.9-80 80-80 80 35.9 80 80-35.9 80-80 80z"></path></svg></span>
  281. </div>
  282. <div class="modal" id="hwmWidgetSettingsPanel">
  283. <div class="modal-block">
  284. <div class="modal-block__head">
  285. <h3 class="modal-block__title">Настройки виджета</h3>
  286. <button id="hwmWidgetSettingsPanelCloseButton" class="modal-block__btn">Закрыть</button>
  287. </div>
  288. <form>
  289. <p class="modal-block__text">Выбор форума</p>
  290. <div class="modal-block__setting">`;
  291. for(const forumId in forumNames) {
  292. divOuterInnerHTML += `<div class="modal-block__checkbox"><input type="radio" id="${forumId}" name="forum" ${GM_getValue("ForumId", "2") == forumId ? "checked" : ""}><label for="${forumId}">${forumNames[forumId]}</label></div>`;
  293. }
  294. divOuterInnerHTML += `</div>
  295. </form>
  296. <form>
  297. <p class="modal-block__text">Выбор клана</p>
  298. <div class="modal-block__setting clans-block">
  299. </div>
  300. </form>
  301. <label for="ShowItemsAmountInput">Количество отображаемых сообщений</label><input type="number" id="ShowItemsAmountInput" value="${GM_getValue("ShowItemsAmount", 5)}" onfocus="this.select(); "/>
  302. <label for="widgetPositionCheckbox">Положение виджета (вверху (если отмечено) / внизу)</label><input type="checkbox" id="widgetPositionCheckbox" />
  303. </div>
  304. </div>
  305. <div id="hwmWidgetNewsPanel"></div>
  306. <div id="hwmWidgetResourcesPanel" class="res-style"></div>
  307. </div>
  308. `;
  309. widgetContainer.insertAdjacentHTML(gmGetBool("WidgetPosition") ? "afterbegin" : "beforeend", divOuterInnerHTML),
  310. fillClansList();
  311. const hwmWidgetSwitcher = document.getElementById('hwmWidgetSwitcher');
  312. hwmWidgetSwitcher.addEventListener("click", function(event) { GM_setValue("Shown", 1 - Number(GM_getValue("Shown", 1))); show(); }, false);
  313. const hwmSettings = document.getElementById('hwmWidgetSettings');
  314. hwmSettings.addEventListener("click", function(event) {
  315. document.querySelector("#hwmWidgetSettingsPanel").style.display = 'flex';
  316. document.querySelector("html").style.overflowY = 'hidden';
  317. }, false);
  318. const hwmWidgetDailyPreviewTab = document.getElementById('hwmWidgetDailyPreviewTab');
  319. hwmWidgetDailyPreviewTab.addEventListener("click", function(event) { GM_setValue("SecondClick", parseInt(GM_getValue("SelectedTab", 0)) == 0); GM_setValue("SelectedTab", 0); show(); }, false);
  320. const hwmWidgetPorumPreviewTab = document.getElementById('hwmWidgetPorumPreviewTab');
  321. hwmWidgetPorumPreviewTab.addEventListener("click", function(event) { GM_setValue("SecondClick", parseInt(GM_getValue("SelectedTab", 0)) == 1); GM_setValue("SelectedTab", 1); show(); }, false);
  322. const hwmWidgetClanLettersPreviewTab = document.getElementById('hwmWidgetClanLettersPreviewTab');
  323. hwmWidgetClanLettersPreviewTab.addEventListener("click", function(event) { GM_setValue("SecondClick", parseInt(GM_getValue("SelectedTab", 0)) == 2); GM_setValue("SelectedTab", 2); show(); }, false);
  324.  
  325. const closeSettings = document.getElementById('hwmWidgetSettingsPanelCloseButton');
  326. document.getElementById("widgetPositionCheckbox").checked = gmGetBool("WidgetPosition");
  327. closeSettings.addEventListener("click", function(event) {
  328. document.querySelector("#hwmWidgetSettingsPanel").style.display = 'none';
  329. document.querySelector("html").style.overflowY = 'overlay';
  330. GM_setValue("ForumId", document.querySelector(`input[name='forum']:checked`).id);
  331. const selectedClan = document.querySelector(".clans-block input[name='clan']:checked");
  332. if(selectedClan) {
  333. GM_setValue("ClanId", selectedClan.id);
  334. } else {
  335. GM_deleteValue("ClanId");
  336. }
  337. GM_setValue("ShowItemsAmount", document.getElementById("ShowItemsAmountInput").value);
  338. GM_setValue("WidgetPosition", document.getElementById("widgetPositionCheckbox").checked);
  339. show();
  340. }, false);
  341. GM_setValue("SecondClick", false);
  342. show();
  343. }
  344. }
  345. async function fillClansList() {
  346. const doc = await getRequest(`https://www.heroeswm.ru/pl_clans.php`);
  347. const clanInfos = Array.from(doc.querySelectorAll("td > li > a[href^='clan_info.php']")).map(x => { return { Id: getUrlParamValue(x.href, "id"), Name: x.firstChild.innerText }; });
  348. if(clanInfos.length > 0) {
  349. if(!GM_getValue("ClanId") || !clanInfos.find(x => x.Id == GM_getValue("ClanId"))) {
  350. GM_setValue("ClanId", clanInfos[0].Id);
  351. }
  352. let clans = '';
  353. for(const clanInfo of clanInfos) {
  354. clans += `
  355. <div class="modal-block__checkbox">
  356. <input type="radio" id="${clanInfo.Id}" name="clan" ${clanInfo.Id == GM_getValue("ClanId") ? "checked" : ""}>
  357. <label for="${clanInfo.Id}">#${clanInfo.Id} ${clanInfo.Name}</label>
  358. </div>`;
  359. }
  360. document.querySelector(".clans-block").innerHTML = clans;
  361. } else {
  362. GM_deleteValue("ClanId");
  363. document.querySelector(".clans-block").innerHTML = "Вы не состоите в кланах";
  364. }
  365. }
  366. async function show() {
  367. //console.log(`Shown: ${GM_getValue("Shown")}, SelectedTab: ${GM_getValue("SelectedTab")}, SecondClick: ${GM_getValue("SecondClick")}`);
  368. if(gmGetBool("SecondClick")) {
  369. switch(parseInt(GM_getValue("SelectedTab", 0))) {
  370. case 0: window.open("https://daily.heroeswm.ru/", "_blank"); break;
  371. case 1: window.open(`https://www.heroeswm.ru/forum_thread.php?id=${GM_getValue("ForumId", "2")}`, "_blank"); break;
  372. case 2: window.open(`https://www.heroeswm.ru/sms_clans.php?clan_id=${GM_getValue("ClanId")}`, "_blank"); break;
  373. }
  374. return;
  375. }
  376. const shown = GM_getValue("Shown", 1);
  377. const hwmWidgetSwitcher = document.getElementById('hwmWidgetSwitcher');
  378. const newsPanel = document.getElementById("hwmWidgetNewsPanel");
  379. const resourcesPanel = document.getElementById("hwmWidgetResourcesPanel");
  380. if(shown == 0) {
  381. hwmWidgetSwitcher.innerHTML = '<img src="https://dcdn3.heroeswm.ru/i/inv_im/btn_expand.svg" style="-webkit-transform: rotate(90deg); transform: rotate(90deg);">';
  382. // <img src="https://dcdn3.heroeswm.ru/i/inv_im/btn_expand.svg" class="home_scroll_content_expand_sign inv_rotate90">
  383. newsPanel.style.display = "none";
  384. resourcesPanel.style.display = "none";
  385. } else {
  386. const hwmWidgetDailyPreviewTab = document.getElementById('hwmWidgetDailyPreviewTab');
  387. const hwmWidgetPorumPreviewTab = document.getElementById('hwmWidgetPorumPreviewTab');
  388. const hwmWidgetClanLettersPreviewTab = document.getElementById('hwmWidgetClanLettersPreviewTab');
  389. hwmWidgetDailyPreviewTab.style.background = "#eae8dd00";
  390. hwmWidgetPorumPreviewTab.style.background = "#eae8dd00";
  391. hwmWidgetClanLettersPreviewTab.style.background = "#eae8dd00";
  392. switch(parseInt(GM_getValue("SelectedTab", 0))) {
  393. case 0: hwmWidgetDailyPreviewTab.style.background = "#eae8dd"; getDailyNews(); break;
  394. case 1: hwmWidgetPorumPreviewTab.style.background = "#eae8dd"; getForumNews(); break;
  395. case 2: hwmWidgetClanLettersPreviewTab.style.background = "#eae8dd"; getClanNews(); break;
  396. }
  397. hwmWidgetSwitcher.innerHTML = '<img src="https://dcdn3.heroeswm.ru/i/inv_im/btn_expand.svg" style="-webkit-transform: rotate(270deg); transform: rotate(270deg);">';
  398. newsPanel.style.display = "block";
  399. await getResources();
  400. resourcesPanel.style.display = 'flex'
  401. }
  402. }
  403. function trimming(string, l) {
  404. //console.log(`string: ${string}, l: ${l}`);
  405. var s = string;
  406. if(string.length > l) {
  407. for(var i = l; i >= 0; i--) {
  408. if(string.charAt(i) == ' ') {
  409. s = string.substr(0, i) + '...';
  410. }
  411. }
  412. s = string.substr(0, l) + '...';
  413. }
  414. return s.replace(/&[^#]/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;");
  415. }
  416. async function getElementLots() {
  417. const doc = await getRequest(`https://www.heroeswm.ru/auction.php?cat=elements&sort=0`);
  418. const firstLotRow = doc.querySelector("center > table:nth-child(2) > tbody > tr > td > table > tbody > tr:nth-child(2) > td:nth-child(2) > table > tbody > tr:nth-child(3)");
  419. let arts = [];
  420. let row = firstLotRow;
  421. while(row = row.nextElementSibling) {
  422. const art = parseLotRow(row);
  423. if(art) {
  424. arts.push(art);
  425. }
  426. }
  427. const grouppedArts = groupBy(arts.filter(x => x.LotType == LotType.Purchase), "ArtId");
  428. return grouppedArts;
  429. }
  430. function parseLotRow(row) {
  431. if(!row || row.nodeName != "TR") {
  432. return;
  433. }
  434. const goldImageElement = row.querySelector("img[src*='gold.png']");
  435. if(!goldImageElement) {
  436. return;
  437. }
  438. const lotPrice = parseFloat(goldImageElement.parentNode.nextElementSibling.innerText.replace(/,/g, ""));
  439. let artId;
  440. let lotAmount = 1;
  441. const lotAmountExec = new RegExp(`(\\d+) ${isEn ? "pcs." : "шт."}`).exec(row.innerHTML);
  442. //console.log(lotAmountExec);
  443. if(lotAmountExec) {
  444. lotAmount = parseInt(lotAmountExec[1]);
  445. }
  446. const lotType = row.innerHTML.includes(LocalizedString.BuyNow) ? LotType.Purchase : LotType.Auction;
  447. const artImageRefElement = row.querySelector("a[href*='art_info.php']");
  448. if(!artImageRefElement) {
  449. const elementsList = Object.values(ElementsTypes).join("|");
  450. const elementParse = (new RegExp(`gn_res/(${elementsList}).png`)).exec(row.innerHTML);
  451. if(elementParse) {
  452. artId = elementParse[1];
  453. }
  454. if(row.innerHTML.includes("house_cert")) {
  455. const locationsList = Object.values(locations).map(x => x[2]).join("|");
  456. const sertParse = (new RegExp(`<br>(${locationsList})&nbsp;<b>`)).exec(row.innerHTML);
  457. if(sertParse) {
  458. artId = getSertIdByLocationName(sertParse[1]);
  459. }
  460. }
  461. const resourcesList = Object.values(ResourcesTypes).map(x => x.ImageName).join("|");
  462. const resourceParse = (new RegExp(`/(${resourcesList}).png`)).exec(row.innerHTML);
  463. if(resourceParse) {
  464. artId = "res_" + resourceParse[1];
  465. }
  466. if(row.innerHTML.includes("auc_dom")) {
  467. const locationsList = Object.values(locations).map(x => x[2]).join("|");
  468. const sertParse = (new RegExp(`<br>(${locationsList})&nbsp;<b>`)).exec(row.innerHTML);
  469. if(sertParse) {
  470. artId = getHouseIdByLocationName(sertParse[1]);
  471. }
  472. }
  473. if(row.innerHTML.includes("obj_share_pic")) {
  474. const locationsList = Object.values(locations).map(x => x[2]).join("|");
  475. const sertParse = (new RegExp(`<br>(${locationsList})&nbsp;<b>`)).exec(row.innerHTML);
  476. if(sertParse) {
  477. artId = getShaIdByLocationName(sertParse[1]);
  478. }
  479. }
  480. } else {
  481. artId = getUrlParamValue(artImageRefElement.href, "id");
  482. var artUid = getUrlParamValue(artImageRefElement.href, "uid");;
  483. const strengthData = row.innerText.match(/\d+\/\d+/);
  484. var restLotStrength = parseInt(strengthData[0].split("/")[0]);
  485. var lotStrength = parseInt(strengthData[0].split("/")[1]);
  486. }
  487. const lotRef = row.querySelector("a[href^='auction_lot_protocol.php']");
  488. const lotId = getUrlParamValue(lotRef.href, "id");
  489. const imgR = row.querySelector("td:nth-child(1) > table > tbody > tr > td:nth-child(1) > img");
  490. return { ArtUid: artUid, ArtId: artId, LotStrength: lotStrength, RestLotStrength: restLotStrength, LotPrice: lotPrice, LotType: lotType, LotAmount: lotAmount, LotId: lotId, ImageUrl: imgR.getAttribute('src'), Title: imgR.getAttribute('title') };
  491. }
  492. async function getResources() {
  493. const resourcesPanel = document.getElementById("hwmWidgetResourcesPanel");
  494. resourcesPanel.innerHTML = getWheelImage();
  495. const grouppedArts = await getElementLots();
  496. const elementsData = [];
  497. for(const elementName of ElementNames)
  498. {
  499. const arts = grouppedArts[elementName]
  500. if(arts.length == 0) {
  501. continue;
  502. }
  503. const art = arts[0];
  504. let price = art.LotPrice;
  505. let secondLotPrice = price;
  506. if(arts.length > 1) {
  507. secondLotPrice = arts[1].LotPrice;
  508. }
  509. elementsData.push({ ElementName: elementName,
  510. Price: price,
  511. ImageUrl: art.ImageUrl,
  512. Title: art.Title,
  513. Diffrence: secondLotPrice - price,
  514. AuctionUrl: `https://www.heroeswm.ru/auction.php?cat=elements&sort=0&art_type=${elementName}`,
  515. NewAuctionUrl: `https://www.heroeswm.ru/auction_new_lot.php?${elementName}=${(price - 1)}`
  516. });
  517. }
  518. //console.log(elementsData);
  519. let res = "";
  520. for(const elementData of elementsData)
  521. {
  522. res += `
  523. <div class='res-style__elem'>
  524. <div style='align-self: center;'>
  525. <a class='hover-link' href='${elementData.NewAuctionUrl}' target='_blank'>
  526. <img src='${elementData.ImageUrl}' width='20' heigth='20' border='0'>
  527. </a>
  528. </div>
  529. <a class='hover-link' target='_. blank' style='text-decoration: none; align-self: center; margin-left: 5px; font-size: 9px;' href='${elementData.AuctionUrl}' title='Разница первого и второго лотов: ${elementData.Diffrence}'>${elementData.Price}</a>
  530. <div style='${(elementData.Diffrence >= 150 ? 'display: inline-flex; background-color: #f33800; padding: 5px;margin-left: 5px; border: 0; border-radius: 4px; color: #fff;' : 'display: none;')}'>
  531. <span title='' style='font-size: 8px; font-weight: bold;'>${elementData.Diffrence}</span>
  532. </div>
  533. </div>`;
  534. }
  535. resourcesPanel.innerHTML = res;
  536. }
  537. async function getClanNews() {
  538. if(!GM_getValue("ClanId")) {
  539. document.getElementById("hwmWidgetNewsPanel").innerHTML = "Вы не состоите в кланах";
  540. return;
  541. }
  542. const doc = await getRequest(`https://www.heroeswm.ru/sms_clans.php?clan_id=${GM_getValue("ClanId")}`);
  543. const letters = Array.from(doc.querySelectorAll("table.wbwhite a[href^='/sms_clans.php'][href*='read']")).map(x => { return {
  544. Title: x.innerHTML,
  545. Ref: x.href,
  546. DateText: x.parentNode.previousElementSibling.innerHTML,
  547. IsHot: (Date.now() - parseDate(x.parentNode.previousElementSibling.innerHTML, false, true).getTime()) / (1000 * 60 * 60) <= 12,
  548. }; }).slice(0, parseInt(GM_getValue("ShowItemsAmount", 5)));
  549. //console.log(letters);
  550. //console.log(`letters: ${letters.length}`);
  551. let clanLetters = "";
  552. for(const letter of letters) {
  553. clanLetters += `
  554. <div class='text-title'>
  555. <a class='hover-link' style='text-decoration:none; ${letter.IsHot ? "font-weight: bold; color: red;" : ""}' target='_blank' href='${letter.Ref}' title='${letter.Title}'>${letter.IsHot ? "📣 " : "• "}${letter.Title}</a>
  556. <div class='clan-style'>
  557. <span title='Дата' style='font-size:9px'>${letter.DateText}</span>
  558. </div>
  559. </div>
  560. `;
  561. }
  562. document.getElementById("hwmWidgetNewsPanel").innerHTML = clanLetters;
  563. }
  564. async function getForumNews() {
  565. const forumId = GM_getValue("ForumId", "2");
  566. const doc = await getRequest(`https://www.heroeswm.ru/forum_thread.php?id=${forumId}`);
  567. const messages = Array.from(doc.querySelectorAll("tr > td:nth-child(1) > a[href^='forum_messages.php']")).map(x => { return {
  568. Fixed: getParent(x, "tr").querySelector("img[src*='skrepka.gif']") ? true : false,
  569. Title: x.innerHTML,
  570. Reference: x.href,
  571. LastCommentReference: getParent(x, "tr").querySelector("a[href^='forum_messages.php'][href*='page=last']"),
  572. CommentsAmount: parseInt(getParent(x, "tr").cells[2].innerHTML),
  573. IsHot: parseInt(getParent(x, "tr").cells[2].innerHTML) <= 20
  574. };}).filter(x => !x.Fixed).slice(0, parseInt(GM_getValue("ShowItemsAmount", 5)));
  575. let forumNews = "";
  576. for(const message of messages) {
  577. forumNews += `
  578. <div class='text-title'>
  579. <a class='hover-link' style='text-decoration: none;${(message.IsHot ? ' font-weight: bold; color: #ff4d00' : '')}' target='_blank' href='${message.Reference}' title='${message.Title}'>${(message.IsHot ? "🔥" : "•")} ${message.Title}
  580. </a>
  581. <div style='display: inline-flex; background-color: #adadad40;padding: 3px 7px; margin-left: 7px; border: 0; border-radius: 4px; color: #592C08;'>
  582. <a href="${message.LastCommentReference}" title='Количество комментариев. Перейти к последнему.' target='_blank' style='font-size: 9px'>${message.CommentsAmount}</a>
  583. </div>
  584. </div>`;
  585. }
  586. document.getElementById("hwmWidgetNewsPanel").innerHTML = forumNews;
  587. }
  588. function getDailyNews() {
  589. const newsPanel = document.getElementById("hwmWidgetNewsPanel");
  590. newsPanel.innerHTML = `${getWheelImage()}&nbsp;&nbsp;Загрузка списка новостей...`;
  591. GM.xmlHttpRequest({method: "GET", url: "https://daily.heroeswm.ru/news4script.txt?" + Date.now(), headers: {
  592. 'User-agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.8.1)',
  593. 'Accept': 'text/xml,text/html',
  594. 'Content-Type': 'text/plain; charset=windows-1251'
  595. },
  596. synchronous: false,
  597. overrideMimeType: 'text/plain; charset=windows-1251',
  598. onload: function(response) {
  599. try {
  600. const dailyUrlRegExp = /\/\/daily\.heroeswm\.ru\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*$/i;
  601. const previousMessageIds = GM_getValue("PreviousDailyMessageIds", "").split("|");
  602. const messages = JSON.parse('[["' + response.responseText.replace(/"/g, "\\\"").replace(/\n/g, '"],["').replace(/;;/g, '","').replace(/'/g, "&#39;") + '"]]').filter(x => x.length == 6).map(x => { return {
  603. Code: x[0],
  604. ImageUrl: x[1],
  605. Title: trimming(x[2], 255),
  606. Url: x[3],
  607. Id: x[4],
  608. CommentsAmount: x[5],
  609. IsHot: !previousMessageIds.includes(x[4])
  610. };}).filter(x => dailyUrlRegExp.test(x.ImageUrl) && dailyUrlRegExp.test(x.Url) && /^[1-3]$/.test(x.Code));
  611. GM_setValue("PreviousDailyMessageIds", messages.map(x => x.Id).join("|"));
  612. //console.log(messages);
  613. let newsText = "";
  614. for(const message of messages) {
  615. newsText += `
  616. <div class='text-title'>
  617. <a class='hover-link' style='text-decoration: none;${message.IsHot ? 'font-weight: bold; color:red' : ''}' target='_blank' href='${message.Url}'>${message.IsHot ? "⚡" : "•"} ${message.Title}</a>
  618. <div style='display: inline-flex; background-color: #adadad40; padding: 3px 7px; margin-left: 7px; border: 0; border-radius: 4px; color: #592C08;'>
  619. <span title='комментариев' style='font-size:9px'>${message.CommentsAmount}</span>
  620. </div>
  621. </div>`;
  622. }
  623. newsPanel.innerHTML = newsText;
  624. } catch(e) {
  625. newsPanel.innerHTML = `Ошибка при обработке данных: ${e}`;
  626. }
  627. },
  628. onerror: function(response) { newsPanel.innerHTML = "Ошибка при получении данных с Daily"; }
  629. });
  630. }
  631. function GM_addStyle(css) { addElement("style", document.head, { type: "text/css", innerHTML: css }); }
  632. function addElement(type, parent, data, insertFirst = false) {
  633. let el = createElement(type, data);
  634. if(parent) {
  635. if(insertFirst) {
  636. parent.insertBefore(el, parent.firstChild);
  637. } else {
  638. parent.appendChild(el);
  639. }
  640. }
  641. return el;
  642. }
  643. function createElement(type, data) {
  644. let el = document.createElement(type);
  645. if(data) {
  646. for(let key in data) {
  647. if(key == "innerText" || key == "innerHTML") {
  648. el[key] = data[key];
  649. } else {
  650. el.setAttribute(key, data[key]);
  651. }
  652. }
  653. }
  654. return el;
  655. }
  656. function getWheelImage() { return '<img border="0" align="absmiddle" height="11" src="https://dcdn.heroeswm.ru/css/loading.gif">'; }
  657. function getUrlParamValue(url, paramName) { return (new URLSearchParams(url.split("?")[1])).get(paramName); }
  658. function groupBy(list, key) { return list.reduce(function(rv, item) { (rv[item[key]] = rv[item[key]] || []).push(item); return rv; }, {}); };
  659. function getSertIdByLocationNumber(locationNumber) { return "sec_" + (locationNumber.toString()).padStart(2, "0"); }
  660. function getSertIdByLocationName(locationName) {
  661. const locationNumber = Object.keys(locations).find(x => locations[x][2] == locationName);
  662. return getSertIdByLocationNumber(locationNumber);
  663. }
  664. function getHouseIdByLocationNumber(locationNumber) { return "dom_" + (locationNumber.toString()).padStart(2, "0"); }
  665. function getHouseIdByLocationName(locationName) {
  666. const locationNumber = Object.keys(locations).find(x => locations[x][2] == locationName);
  667. return getHouseIdByLocationNumber(locationNumber);
  668. }
  669. function getRequest(url) {
  670. return new Promise((resolve, reject) => {
  671. GM.xmlHttpRequest({ method: "GET", url: url, overrideMimeType: "text/html; charset=windows-1251",
  672. onload: function(response) { resolve((new DOMParser).parseFromString(response.responseText, "text/html")); },
  673. onerror: function(error) { reject(error); }
  674. });
  675. });
  676. }
  677. function gmGetBool(valueName, defaultValue = false) {
  678. const value = GM_getValue(valueName);
  679. if(value) {
  680. if(typeof(value) == "string") {
  681. return value == "true";
  682. }
  683. if(typeof(value) == "boolean") {
  684. return value;
  685. }
  686. }
  687. return defaultValue;
  688. }
  689. function parseDate(dateString, isFuture = false, isPast = false) {
  690. //console.log(dateString)
  691. if(!dateString) {
  692. return;
  693. }
  694. const dateStrings = dateString.split(" ");
  695. let hours = 0;
  696. let minutes = 0;
  697. let seconds = 0;
  698. const timePart = dateStrings.find(x => x.includes(":"));
  699. if(timePart) {
  700. var time = timePart.split(":");
  701. hours = parseInt(time[0]);
  702. minutes = parseInt(time[1]);
  703. if(time.length > 2) {
  704. seconds = parseInt(time[2]);
  705. }
  706. }
  707.  
  708. const now = new Date();
  709. let year = now.getFullYear();
  710. let month = now.getMonth();
  711. let day = now.getDate();
  712. const datePart = dateStrings.find(x => x.includes("-"));
  713. if(datePart) {
  714. const date = datePart.split("-");
  715. month = parseInt(date[isEn ? (date.length == 3 ? 1 : 0) : 1]) - 1;
  716. day = parseInt(date[isEn ? (date.length == 3 ? 2 : 1) : 0]);
  717. if(date.length == 3) {
  718. year = isEn ? parseInt(date[0]) : parseInt(date[2]);
  719. if(year < 1000) {
  720. year += Math.floor((new Date()).getFullYear() / 1000) * 1000;
  721. }
  722. } else {
  723. if(isFuture && month == 0 && now.getMonth() == 11) {
  724. year += 1;
  725. }
  726. }
  727. }
  728. if(dateStrings.length > 2) {
  729. const letterDateExec = /(\d{2}):(\d{2}) (\d{2}) (.{3,4})/.exec(dateString);
  730. if(letterDateExec) {
  731. //console.log(letterDateExec)
  732. day = parseInt(letterDateExec[3]);
  733. //const monthNames = ['января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря'];
  734. const monthShortNames = ['янв', 'фев', 'март', 'апр', 'май', 'июнь', 'июль', 'авг', 'сент', 'окт', 'ноя', 'дек'];
  735. month = monthShortNames.findIndex(x => x.toLowerCase() == letterDateExec[4].toLowerCase());
  736. if(isPast && (new Date(year, month, day, hours, minutes, seconds)).getTime() > Date.now()) {
  737. year -= 1;
  738. }
  739. }
  740. }
  741. //console.log(`year: ${year}, month: ${month}, day: ${day}, time[0]: ${time[0]}, time[1]: ${time[1]}, ${new Date(year, month, day, parseInt(time[0]), parseInt(time[1]))}`);
  742. return new Date(year, month, day, hours, minutes, seconds);
  743. }
  744. function getParent(element, parentType, number = 1) {
  745. if(!element) {
  746. return;
  747. }
  748. let result = element;
  749. let foundNumber = 0;
  750. while(result = result.parentNode) {
  751. if(result.nodeName.toLowerCase() == parentType.toLowerCase()) {
  752. foundNumber++;
  753. if(foundNumber == number) {
  754. return result;
  755. }
  756. }
  757. }
  758. }

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址