Bitcoin Forum

Local => Русский (Russian) => Topic started by: madnessteat on January 25, 2019, 03:45:20 PM



Title: Отчет модератору из истории сообщений
Post by: madnessteat on January 25, 2019, 03:45:20 PM
Оригинальная англоязычная тема (https://bitcointalk.org/index.php?topic=5101823.0)

Пользователь Cyrus (https://bitcointalk.org/index.php?action=profile;u=78147/) (администратор) создал очень полезный скрипт, с помощью которого можно отправить отчет модератору прямо из истории сообщений любого пользователя.


Code:
// ==UserScript==
// @name     Post history report button
// @version  1
// @grant    none
// @include  https://bitcointalk.org/index.php?action=profile;u=*;sa=showPosts*
// @require  https://code.jquery.com/jquery-2.2.4.min.js
// ==/UserScript==

var postLinks = $('td.middletext a:last-of-type');
var buttonLink = $("span.middletext").slice(1);

for (var i = 0; i < postLinks.length; i++) {
  var postLink = $(postLinks[i]);
  var reportLink = "<a href=" + postLink.prop("href").replace("index.php?", "index.php?action=reporttm;").replace(".msg", ";msg=") + ">Report to moderator</a>";
  $(buttonLink[i]).prepend (reportLink);
}

Чтобы использовать скрипт вам потребуется установить менеджер пользовательских скриптов, например расширение GreaseMonkey для браузера Mozilla Firefox или Tampermonkey для браузера Chrome.

Для тех кто не умеет пользоваться скриптами решил сделать небольшую инструкцию на примере установки расширения Tampermonkey для браузера Chrome:

1. Перейдите в интернет магазин Chrome (https://chrome.google.com/webstore/detail/tampermonkey/dhdgffkkebhmkfjojejmpbldmpobfkfo?hl=ru) и нажмите установить.

https://a.radikal.ru/a12/1901/e9/2c25eae17425.png (https://radikal.ru)

2. Теперь у вас появилась иконка расширения. Нажимаем на нее, далее Создать новый скрипт...

https://c.radikal.ru/c04/1901/10/597fb1a3dce1.png (https://radikal.ru)

3. Скопируйте весь скрипт из поля Code выше. Затем нажмите Файл и Сохранить.

https://a.radikal.ru/a41/1901/fa/4251280f8a7b.png (https://radikal.ru)

4. Вы увидите что скрипт включен.

https://a.radikal.ru/a00/1901/1a/441e9b2c2df0.png (https://radikal.ru)

5. Далее переходим в историю сообщений любого пользователя и видим, что теперь под каждым постом появилась кнопка отчет модератору.

https://d.radikal.ru/d28/1901/05/33d4d6ee689f.png (https://radikal.ru)

6. Пользуемся!

Огромное спасибо Cyrus (https://bitcointalk.org/index.php?action=profile;u=78147/) за такой удобный и полезный скрипт. Сделаем форум чище, все вместе!



Обновление: по просьбе Xal0lex (https://bitcointalk.org/index.php?action=profile;u=1068464)
Перевод:
Скрипт не работает, если вы просматриваете последние темы пользователя. Было бы неплохо, чтобы скрипт работал и там.
пользователь TryNinja (https://bitcointalk.org/index.php?action=profile;u=557798) доработал скрипт:

Code:
// ==UserScript==
// @name     Post history report button
// @version  1
// @grant    none
// @include  https://bitcointalk.org/index.php?action=profile;u=*;sa=showPosts*
// @include  https://bitcointalk.org/index.php?action=profile;threads;u=*;sa=showPosts*
// @require  https://code.jquery.com/jquery-2.2.4.min.js
// ==/UserScript==

var postLinks = $('td.middletext a:last-of-type');
var buttonLink = $("span.middletext").slice(1);

for (var i = 0; i < postLinks.length; i++) {
  var postLink = $(postLinks[i]);
  var reportLink = "<a href=" + postLink.prop("href").replace("index.php?", "index.php?action=reporttm;").replace(".msg", ";msg=") + ">Report to moderator</a>";
  $(buttonLink[i]).prepend (reportLink);
}





Title: Re: Отчет модератору из истории сообщений
Post by: madnessteat on January 25, 2019, 04:42:56 PM
резерв


Title: Re: Отчет модератору из истории сообщений
Post by: Xal0lex on January 25, 2019, 05:17:36 PM
В своё время написал о скрипте (https://bitcointalk.org/index.php?topic=2833350.0) для удобной раздачи меритов от grue (https://bitcointalk.org/index.php?action=profile;u=5797). И в теме тоже упомянул greasemonkey и tampermonkey. Так меня практически обвинили в том, что я распространяю чуть ли не вирусы :)

Кстати, tampermonkey можно и в firefox установить..


Title: Re: Отчет модератору из истории сообщений
Post by: madnessteat on January 25, 2019, 06:13:25 PM
В своё время написал о скрипте (https://bitcointalk.org/index.php?topic=2833350.0) для удобной раздачи меритов от grue (https://bitcointalk.org/index.php?action=profile;u=5797). И в теме тоже упомянул greasemonkey и tampermonkey. Так меня практически обвинили в том, что я распространяю чуть ли не вирусы :)

 :o Мне не понятны такие нападки на вас. Спасибо за скрипт и информацию. Поставил и его. Зачем тратить время на лишние переходы между окнами, если можно пользоваться скриптами и использовать все те же функции форума, только намного удобнее.

Самое главное понимать какой скрипт использовать безопасно, а какой нет .  


Title: Re: Отчет модератору из истории сообщений
Post by: kzv on January 26, 2019, 10:19:55 AM
Надо обычное расширение сделать. Нафига эти бубны с грисманкеем?


Title: Re: Отчет модератору из истории сообщений
Post by: xandry on January 26, 2019, 10:43:40 AM
Надо обычное расширение сделать. Нафига эти бубны с грисманкеем?
В чём преимущество обычного расширения?


Title: Re: Отчет модератору из истории сообщений
Post by: kzv on January 26, 2019, 10:55:42 AM
Надо обычное расширение сделать. Нафига эти бубны с грисманкеем?
В чём преимущество обычного расширения?

В том, что оно устанавливается в один клик


Title: Re: Отчет модератору из истории сообщений
Post by: xandry on January 26, 2019, 11:39:21 AM
В том, что оно устанавливается в один клик
Вы бы могли такое расширение сделать?


Title: Re: Отчет модератору из истории сообщений
Post by: kzv on January 26, 2019, 12:03:34 PM
Через пару дней время будет. Сделаю. Если надо конечно.
Почему бы теймосу в движок форума это не встроить? Всяко не сложней, чем пляски с трастами и меритами )


Title: Re: Отчет модератору из истории сообщений
Post by: madnessteat on January 26, 2019, 12:31:54 PM
В своё время написал о скрипте (https://bitcointalk.org/index.php?topic=2833350.0) для удобной раздачи меритов от grue (https://bitcointalk.org/index.php?action=profile;u=5797).

Единственное, что не очень удобно в этом скрипте, то что не видно сколько у меня осталось смерита для отправки. Может кто-то сможет добавить эту функцию в скрипт?

Через пару дней время будет. Сделаю. Если надо конечно.
Почему бы теймосу в движок форума это не встроить? Всяко не сложней, чем пляски с трастами и меритами )

Интересно посмотреть как это будет работать. Не понятно почему theymos не хочет добавить полезные плюшки в движок форума, если вы говорите что это не сложно.


Title: Re: Отчет модератору из истории сообщений
Post by: Xal0lex on January 26, 2019, 04:11:57 PM
Надо обычное расширение сделать. Нафига эти бубны с грисманкеем?
В чём преимущество обычного расширения?

В том, что оно устанавливается в один клик

Дело в том, что каждое установленное и запущенное расширение добавляет общий вес браузера в памяти компьютера. Для тех, у кого, например, ноутбук с 2-4 гигами памяти это важно. А скрипт ничего, практически, не добавляет к уже запущенному расширению и, соответственно, к общему весу браузера в памяти. Поэтому, я лично предпочитаю использовать скрипты.




В своё время написал о скрипте (https://bitcointalk.org/index.php?topic=2833350.0) для удобной раздачи меритов от grue (https://bitcointalk.org/index.php?action=profile;u=5797).

Единственное, что не очень удобно в этом скрипте, то что не видно сколько у меня осталось смерита для отправки. Может кто-то сможет добавить эту функцию в скрипт?

Есть такая реализация скрипта от EcuaMobi (https://bitcointalk.org/index.php?action=profile;u=169515):

I have combined my own suggestion (https://bitcointalk.org/index.php?topic=2833350.msg29410086#msg29410086) as well as sncc's (https://bitcointalk.org/index.php?topic=2833350.msg29798554#msg29798554) and modified grue's script to implement them.

This is the result:
https://i.imgur.com/L5xiXfT.png

The available sMerit points are shown. 'Available' is a link which opens the default https://bitcointalk.org/index.php?action=merit;msg=30923337 (with the corresponding msg) in a new window to keep the original functionality.

Here's the modified source. grue, feel free to update your original code if you like the change:
Code:
// ==UserScript==
// @name        bitcointalk merit
// @namespace   grue
// @include     https://bitcointalk.org/index.php?topic=*
// @require     https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js
// @version     1.1-em0.1
// @downloadURL https://grue.blob.core.windows.net/scripts/Merit.user.js?sv=2014-02-14&si=1&sr=c&sig=k%2BqstGBI3oQ8TrHfPWjS5HgjrazuDPmKJ6rYNs7rvRk%3D&.user.js
// @grant none
// ==/UserScript==

(() => {
  var sMerit;
  
  //get csrf token from the logout link
  let sc = $('td.maintab_back a[href*="index.php?action=logout;sesc="').attr("href");
  sc = /;sesc=(.*)/.exec(sc)[1];
  
  //Added by EcuaMobi: Get remaining sMerit
  $.post(
"https://bitcointalk.org/index.php?action=merit;msg=29048068"
  ).then((data) => {
    sMerit = /You have <b>([0-9]+)<\/b> sendable/.exec(data)[1];
  }).catch(() => sMerit = null);

  //selector for the "+Merit" link
  $('td.td_headerandpost div[id^=ignmsgbttns] a[href*="index.php?action=merit;msg="]')
  .each((i, e) => {
    const msgId = /msg=([0-9]+)/.exec(e.href)[1];
    
    const $popup = $(['<div id="grue-merit-popup' + msgId +'" class="grue-merit-popup" style="position: absolute; right: 40px; background-color: #ddd; font-size: 13px; padding: 8px;border-width: 1px;border-color: black;border-style: solid;">',
      '  <form>',
      '    <div>',
      '      Merit points: <input size="6" name="merits" value="0" type="text"/>',
      '    </div>',
 // Modified by EcuaMobi
      '    <div style="margin-top: 6px; "><span id="em-smerit-count' + msgId +'" style="font-size:11px;" /> <input value="Send" type="submit"></div>',
      '  </form>',
      '</div>'
    ].join("\n"));
    $popup.find("form").submit( (e) => {
      e.preventDefault();
      $popup.find('input[type="submit"]')
        .prop("disabled", true)
        .val("Sending...");
      const merits = e.target.elements["merits"].value;
      
      $.post(
        "https://bitcointalk.org/index.php?action=merit",
        {merits, msgID: msgId, sc}
      ).then((data) => {
        //Error pages usually have this (rough heuristic)
        if(data.includes("<title>An Error Has Occurred!</title")) {
          throw "error";
        }
        //double check and see whether the post we merited was added to the list. Its msgId should be visible in the page source.
        if(data.includes("#msg" + msgId)) {
          alert("Merit added.");
          $("#grue-merit-popup" + msgId).toggle(false);
 // Added by EcuaMobi
 if(sMerit!=null) { sMerit -= merits }
          return;
        }
        alert("Server response indeterminate.");
      })
      .catch(() => alert("Failed to add merit."))
      .always(() => {
        $popup.find('input[type="submit"]')
        .prop("disabled", false)
        .val("Send");
      });
    });
    $popup.insertAfter(e);
    
    $(e).click((e) => {
      e.preventDefault();
      $("#grue-merit-popup" + msgId).toggle();
 // Added by EcuaMobi
 if(sMerit!=null) { $("#em-smerit-count" + msgId).html('<a href="https://bitcointalk.org/index.php?action=merit;msg='+msgId+'" target="_blank">Available:</a> <b>'+sMerit+'</b> &nbsp;&nbsp;&nbsp;') };
    });
  });
   $(".grue-merit-popup").toggle(false);
  
})();
I've clearly marked the modified code with either "Added by EcuaMobi" or "Modified by EcuaMobi". I also changed the version

A small limitation is that it queries the available sMerit points once (when the thread is loaded). It does subtract them when points are sent. However, if sMerit points are received the change won't be reflected unless the page is reloaded. That would require re-querying every time which I considered an overkill.

To install this version, you can just modify grue's script or install this from scratch:
https://openuserjs.org/scripts/EcuaMobi/bitcointalk_merit

(grue, I assumed this code is open-source. If that's not the case, let me know to unpublish this)


Title: Re: Отчет модератору из истории сообщений
Post by: madnessteat on January 26, 2019, 06:21:30 PM
~snip~
Есть такая реализация скрипта от EcuaMobi (https://bitcointalk.org/index.php?action=profile;u=169515)

Спасибо. Как я не заметил ее, непонятно. :o Хотел в той теме даже попросить чтобы добавили эту возможность, но посмотрев последнюю активность пользователя grue (https://bitcointalk.org/index.php?action=profile;u=5797) решил не делать этого.