Advertisement
Guest User

Untitled

a guest
Dec 12th, 2021
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const profileRx = /\/u\/([0-9]*)-([A-Za-z]|[0-9]|-)*(\/entries|\/comments|\/favourites|\/votes|\/drafts|\/updates|\/donates|\/details|)+/;
  2. const userIdRx  = /\/u\/([0-9]*)/;
  3.  
  4. let dataSet = false;
  5.  
  6. function setCounter(urlPart, label, value) {
  7.     const tabBlock = document.querySelector(`a[href*="${urlPart}"][class*="v-tab"]`);
  8.     if (!tabBlock)
  9.         return;
  10.  
  11.     tabBlock.firstChild.innerHTML = `<span class="v-tab__label" id="counterInsert">${label}<span class="v-tab__counter">${value}</span></span>`;
  12. }
  13.  
  14. async function loadProfileViaAPI(id, host) {
  15.     // я не смог вытащить этих данных из текущей страницы
  16.     // поэтому пока единственным решением вижу её скачать вручную и спарсить
  17.     const profile = await fetch(`https://api.${host}/v1.9/user/${id}`);
  18.     if (profile.status !== 200)
  19.         return;
  20.  
  21.     const rawData = await profile.json();
  22.  
  23.     // может быть 403 ошибка, если, к примеру, администрация скрыла профиль
  24.     // профиль того же Олегоси не получить через api
  25.     if (rawData.error) {
  26.         console.error('cant load profile info: ', rawData.message);
  27.  
  28.         return;
  29.     }
  30.  
  31.     const json = rawData.result;
  32.  
  33.     if (!json || !json.counters)
  34.         return;
  35.  
  36.     const postsCount    = json.counters.entries;
  37.     const commentsCount = json.counters.comments;
  38.  
  39.     setCounter('entries', 'Статьи', postsCount);
  40.     setCounter('comments', 'Комментарии', commentsCount);
  41.  
  42.     dataSet = true;
  43. }
  44.  
  45.  
  46. async function loadProfileAsIs(id, host) {
  47.     // я не смог вытащить этих данных из текущей страницы
  48.     // поэтому пока единственным решением вижу её скачать вручную и спарсить
  49.     const profile = await fetch(`https://${host}/u/${id}`);
  50.     if (profile.status !== 200)
  51.         return;
  52.  
  53.     const rawData = await profile.text();
  54.  
  55.     const data  = rawData.match(/<textarea(.*?){(.*?)<\/textarea>/gms);
  56.     const raw   = data[0];
  57.     let jsonStr = raw.substr(raw.indexOf('{'));
  58.     jsonStr     = jsonStr.substr(0, jsonStr.lastIndexOf('}') + 1);
  59.     const json  = JSON.parse(jsonStr.replace(/&quot;/g, '"'));
  60.  
  61.     if (!json.header || !json.header.tabs || !json.header.tabs.length)
  62.         return;
  63.  
  64.     for (const tab of json.header.tabs) {
  65.         if (tab.label === `Черновики`)
  66.             continue;
  67.  
  68.         const tabBlock = document.querySelector(`a[href*="${tab.url}"][class*="v-tab"]`);
  69.         if (!tabBlock)
  70.             continue;
  71.  
  72.         tabBlock.firstChild.innerHTML = `<span class="v-tab__label">${tab.label}<span class="v-tab__counter">${tab.counter}</span></span>`;
  73.     }
  74. }
  75.  
  76. async function loadProfile(id, host) {
  77.     console.log('loadProfile', id);
  78.     try {
  79.         await loadProfileViaAPI(id, host);
  80.     } catch (e) {
  81.         console.error(e);
  82.         await loadProfileAsIs(id, host);
  83.     }
  84.  
  85.     dataSet = true;
  86. }
  87.  
  88. function clear() {
  89.     dataSet = false;
  90. }
  91.  
  92. async function checkIfProfile() {
  93.     // получаем текущий адрес и проверяем на то, что это профиль
  94.     const location = document.location;
  95.     const href     = location.href;
  96.  
  97.         if (document.getElementById("counterInsert")) {
  98.             return;
  99.         }
  100.  
  101.     // не какая-либо страница юзера
  102.     const uIndex = href.indexOf('/u/');
  103.     // явно не профиль
  104.     if (uIndex === -1) {
  105.         clear();
  106.         return;
  107.     }
  108.  
  109.     const lastSlash = href.lastIndexOf('/');
  110.     // какая-то юзерская страница, но не корневая
  111.     if (lastSlash !== uIndex + 2) {
  112.         const rx = profileRx.exec(href);
  113.  
  114.         // скорей всего конкретный пост
  115.         if (!(rx && rx.length && rx.length >= 4 && rx[3])) {
  116.             clear();
  117.             return;
  118.         }
  119.     }
  120.  
  121.     // сюда попали, если это корневая страница профиля или одна из дополнительных (комменты, закладки и т. п).
  122.  
  123.     // проверяем, если уже устанавливали счётчики, чтоб лишний раз не нагружать страницу
  124.     // if (dataSet)
  125.     //     return;
  126.  
  127.     // вытаскиваем id юзера
  128.     const id = userIdRx.exec(href);
  129.  
  130.     await loadProfile(id[1], location.host);
  131. }
  132.  
  133. // async function checkProfile() {
  134. //     checkIfProfile();
  135. //     // хрен знает, как сделать, чтоб проверялка работала только при открытии профиля
  136. //     setInterval(() => {
  137. //         new Promise(checkIfProfile)
  138. //             .catch(er => {
  139. //                 console.error(er);
  140. //             });
  141. //     }, 3000);
  142. // }
  143.  
  144. setInterval(() => {
  145.     checkIfProfile()
  146.         .catch(er => {
  147.                 console.error(er);
  148.         });
  149. }, 3000);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement