Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ==UserScript==
- // @name 0chan custom search
- // @name:ru Поиск по тредам
- // @namespace 0ch usability
- // @author AHOHNMYC
- // @description Скрипт схороняет ОП-посты в дазу банных и великодушно позволяет вам проводить по ней поиск
- // @homepage https://pastebin.com/u/AHOHNMYC
- // @include https://0chan.hk/*
- // @grant GM_getValue
- // @grant GM_setValue
- // @grant GM_listValues
- // @grant GM_deleteValue
- // @grant unsafeWindow
- // @grant GM_registerMenuCommand
- // @supportURL https://0chan.hk/0x59f3c84d
- // @version v0.0.1
- // ==/UserScript==
- const debug = false;
- // refreshContentDone -> addOPpostToBase -> ls.add -> GM_setValue
- ///////////////////////////////////////////////////////////////
- // АПИ для работы с хранилищем
- const ls = {
- _lastSearch: '',
- _contextLength: 200,
- add: function(obj) {
- if ( !obj ) return;
- if ( obj.content == ' ' ) {
- if (debug) console.log('0chan custom search: OP-post is empty. Thread will not be added in DB');
- return;
- }
- let id = obj.board+' '+obj.postId;
- if ( GM_getValue(id) ) {
- if (debug) console.log('0chan custom search: ID:"%s %s" was already added', obj.board, obj. postId);
- return;
- }
- GM_setValue(id, obj.content);
- if (debug) console.log('0chan custom search: thread added to database. ID:"%s %s" DB contains %d elements', obj.board, obj. postId, GM_listValues().length);
- },
- search: function(text, board) {
- text = text.toLowerCase().replace(/[^ A-яё]/g,'');
- ls._lastSearch = text.split(' ')[0];
- if ( !board ) board = '[^ ]+';
- let keywords = text.split(' '),
- regex = new RegExp('^'+board+' ', 'i'),
- threads = [];
- GM_listValues().forEach(e=>{
- if ( !regex.test(e) ) return;
- for (let i=0; i<keywords.length; i++) {
- if ( GM_getValue(e).search(new RegExp(keywords[i], 'i') ) == -1 ) return;
- }
- threads.push(e);
- });
- return threads;
- },
- searchWithContext: function (text, board) {
- return ls.search(text, board).map(e=>{return{
- postId: e,
- context: ls._getContext(e)
- };}, ls);
- },
- _getContext: function(id) {
- let pos = GM_getValue(id).search(ls._lastSearch),
- start = (pos < ls._contextLength/2) ? 0 : pos-ls._contextLength/2;
- // console.log(ls._lastSearch+' '+id+' '+pos+' '+start);
- // console.log( start +' '+ start+retLen );
- return '...'+ GM_getValue(id).slice(start, start+ls._contextLength).replace(/\n/g, ' ') +'...';
- },
- _clear: function() {
- GM_listValues().forEach( GM_deleteValue );
- }
- };
- // Конец АПИ для работы с хранилищем
- ///////////////////////////////////////////////////////////////
- // Вспомогательные функции
- function addOPpostToBase(oppost) {
- // Пост может быть свёрнут
- if ( !oppost.querySelector('.post-body-message') ) return false;
- let meta = oppost.querySelector('.post-header > span > span+a').href.split('/'),
- message = oppost.querySelector('.post-body-message'),
- entry = {
- board: meta[3],
- postId: +meta[4],
- content: message.textContent
- };
- ls.add( entry );
- }
- // Конец вспомогательных функций
- ///////////////////////////////////////////////////////////////
- // Cобытиеёбля
- // !!!!!!!!!!!!
- // ls._clear();
- // !!!!!!!!!!!!
- // Some modified parts form Kagami's Шебм script
- unsafeWindow._searchIndexer = (typeof exportFunction === 'undefined') ? handleThreads : exportFunction(handleThreads, unsafeWindow);
- (function(){
- let observer = new MutationObserver(function() {
- let app = unsafeWindow.app;
- if (!app.$bus) return;
- observer.disconnect();
- app.$bus.on('refreshContentDone', unsafeWindow._searchIndexer);
- });
- observer.observe(document.body, {childList: true});
- })();
- function handleThreads() {
- let thread = document.querySelector('.threads');
- if (!thread) return;
- addOPpostToBase( thread.querySelector('.post-op') );
- }
- // Конец событиеебли
- ///////////////////////////////////////////////////////////////
- // Взаимодействие с пользователем
- ////////////////////////
- // Регистрируем элемент в менюшке. Не хочу я влезать в нутро этой one-page хуйни
- function searchTextFromMenu(){
- // console.log( 'Database contains %d elements', GM_listValues().length );
- let txt = prompt('Что искать?'),
- // board = prompt('Где искать? (название борды. Напр "b")');
- board = false;
- let result = ls.searchWithContext(txt, board);
- result.forEach( e=>{console.log(e);} );
- // alert( result );
- }
- GM_registerMenuCommand('Искать', searchTextFromMenu, 'И');
- ////////////////////////
- // Конец взаимодействия с пользователем
- ///////////////////////////////////////////////////////////////
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement