pixiv_sort_by_popularity

non premium menber use "Sort by popularity"

当前为 2020-12-30 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name pixiv_sort_by_popularity
  3. // @name:zh-CN pixiv_sort_by_popularity
  4. // @name:zh-TW pixiv_sort_by_popularity
  5. // @name:ja pixiv_sort_by_popularity
  6. // @name:ru pixiv_sort_by_popularity
  7. // @name:kr pixiv_sort_by_popularity
  8. // @namespace pixiv_sort_by_popularity
  9. // @supportURL https://github.com/zhuzemin
  10. // @description non premium menber use "Sort by popularity"
  11. // @description:zh-CN non premium menber use "Sort by popularity"
  12. // @description:zh-TW non premium menber use "Sort by popularity"
  13. // @description:ja non premium menber use "Sort by popularity"
  14. // @description:ru non premium menber use "Sort by popularity"
  15. // @description:kr non premium menber use "Sort by popularity"
  16. // @include https://www.pixiv.net/*/tags/*
  17. // @include https://www.pixiv.net/tags/*
  18. // @version 1.23
  19. // @run-at document-end
  20. // @author zhuzemin
  21. // @license Mozilla Public License 2.0; http://www.mozilla.org/MPL/2.0/
  22. // @license CC Attribution-ShareAlike 4.0 International; http://creativecommons.org/licenses/by-sa/4.0/
  23. // @grant GM_xmlhttpRequest
  24. // @grant GM_registerMenuCommand
  25. // @grant GM_setValue
  26. // @grant GM_getValue
  27. // @connect-src workers.dev
  28. // @contributionAmount 0.5
  29. // @contributionURL https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=rzzm@hotmail.com&item_name=Greasy+Fork+donation
  30. // ==/UserScript==
  31.  
  32.  
  33. //this userscript desire for free member use "Sort by popularity"
  34.  
  35.  
  36. //config
  37. let config = {
  38. 'debug': false,
  39. api: {
  40. 'base': 'https://proud-surf-e590.zhuzemin.workers.dev',
  41. //pixiv search request through this url will use premium user.
  42. 'ajax': null,
  43. //get premium users number
  44. 'userNum': null,
  45. //share cookie
  46. 'share': null,
  47. 'guides': 'https://zhuzemin4.github.io/pixiv_sort_by_popularity',
  48. 'bookmark': 'https://www.pixiv.net/bookmark.php?rest=show&p=',
  49. },
  50. 'nav': null,
  51. 'btn': null,
  52. 'bookmarkSupport': GM_getValue('bookmarkSupport'), //support bookmark in search result page, but loading will slower.
  53. 'illustId_list': [],
  54. }
  55. config.api.ajax = config.api.base + '/ajax';
  56. config.api.userNum = config.api.base + '/userNum';
  57. config.api.share = config.api.base + '/share';
  58. var debug = config.debug ? console.log.bind(console) : function () {
  59. };
  60.  
  61.  
  62. // prepare UserPrefs
  63. setUserPref(
  64. 'bookmarkSupport',
  65. false,
  66. 'bookmark support',
  67. `support bookmark in search result page, but loading will slower.`,
  68. );
  69.  
  70.  
  71. // prepare UserPrefs
  72. setUserPref(
  73. 'shareCookie',
  74. 'PHPSESSID=***_******, 30',
  75. 'Share my cookie',
  76. `This script depend pixiv premium user share his cookie, for keep script work need at least one user register pixiv premium and share his cookie.\n
  77. but because security strategy of browser, userscript can't get cookie automaticatlly,\n
  78. here is a guides to teach you get cookie, than you can come back fill those parameters below.
  79. *Guides----> `+ config.api.guides + `
  80. *Second parameter is how many days you want cookie be share.`,
  81. shareCookie,
  82. );
  83.  
  84.  
  85. /**
  86. * Obejct use for xmlHttpRequest
  87. * @param {string} originUrl
  88. * @param {int} page
  89. * @param {string} order
  90. */
  91. class requestObject {
  92. constructor(originUrl, page = null, order = null) {
  93. this.method = 'GET';
  94. this.respType = 'json';
  95. this.url = originUrl;
  96. if (order != null) {
  97. this.url = config.api.ajax + '/' + originUrl
  98. .replace(/(https:\/\/www\.pixiv\.net\/)(\w*\/)?tags\/([^\/]*)\/(\w*)\?([^\/\?]*)/,
  99. function (match, $1, $2, $3, $4, $5, offset, original) { return $1 + 'ajax/search/' + $4 + '/' + $3 + '?' + $5; })
  100. .replace(/p=\d*/, '').replace(/order=[_\w]*/, '') + '&p=' + page + '&order=' + order;
  101. }
  102. else if (page != null) {
  103. this.url = originUrl + page;
  104. }
  105. this.body = null;
  106. this.headers = {
  107. "Content-Type": "application/x-www-form-urlencoded",
  108. 'User-agent': window.navigator.userAgent,
  109. 'Referer': window.location.href,
  110. };
  111. this.package = null;
  112. }
  113. }
  114.  
  115.  
  116. //for override fetch, I think override function sure insert to page, otherwise userscript don't have permission modified fetch in page?
  117. function addJS_Node(text) {
  118. var scriptNode = document.createElement('script');
  119. scriptNode.type = "text/javascript";
  120. if (text) scriptNode.textContent = text;
  121.  
  122. var targ = document.getElementsByTagName('head')[0] || d.body || d.documentElement;
  123. targ.appendChild(scriptNode);
  124. }
  125.  
  126.  
  127. //override fetch
  128. function intercept() {
  129. //insert override function to page
  130. addJS_Node(`
  131. var newData;
  132. var interceptEnable;
  133. var newUrl;
  134. var constantMock = window.fetch;
  135. window.fetch = function() {
  136. if(interceptEnable&&/https:\\/\\/www\\.pixiv\\.net\\/ajax\\/search\\//.test(arguments[0])){
  137. arguments[0]=newUrl;
  138. //console.log(arguments);
  139. }
  140. return new Promise((resolve, reject) => {
  141. constantMock.apply(this, arguments)
  142. .then((response) => {
  143. if(interceptEnable&&/https:\\/\\/www\\.pixiv\\.net\\/ajax\\/search\\//.test(response.url)){
  144. var blob = new Blob([newData], {type : 'application/json'});
  145. //console.log(newData);
  146. var newResponse=new Response(
  147. blob, {
  148. status: response.status,
  149. statusText: response.statusText,
  150. headers: response.headers
  151. });
  152. //console.log(newResponse);
  153. response=newResponse;
  154. interceptEnable=false;
  155. }
  156. resolve(response);
  157. })
  158. .catch((error) => {
  159. reject(response);
  160. })
  161. });
  162. }
  163. `);
  164. //here is script end,
  165. //in console ,log show fetch response body has been changed <--- not very sure
  166. //and page have react ---> stay blank for ever
  167. //my confuse is: even comment "return data" (line:93), page still return blank,
  168. //that makes me wonder: maybe this override function miss something.
  169. //if my terrible code can be understanding somehow,
  170. //and knoa san have nothing else todo in leisure time,
  171. //knoa san can you take while, look my newbie problem?
  172. //of cource if too painful read my code, I totally understand!
  173. //knoa san can read to here already be my greatest honor, and I'm very happy!
  174. }
  175.  
  176.  
  177. //userscript entry
  178. var init = function () {
  179. //create button
  180. if (window.self === window.top) {
  181. debug("init");
  182. var interval = setInterval(function () {
  183. var navList = document.querySelectorAll('nav');
  184. debug('navList.length: ' + navList.length)
  185. if (navList.length == 2) {
  186. clearInterval(interval);
  187. config.nav = navList[0];
  188. config.btn = document.createElement('button');
  189. config.btn.innerHTML = 'Sort by popularity';
  190. config.btn.addEventListener('click', sortByPopularity);
  191. config.btn.disabled = true;
  192. config.nav.insertBefore(config.btn, null);
  193. let select = document.createElement('select');
  194. select.id = 'sortByPopularity';
  195. var optionObj = {
  196. 'Popular with all': 'popular_d',
  197. 'Popular (male)': 'popular_male_d',
  198. 'Popular (female)': 'popular_female_d'
  199. }
  200. for (var key of Object.keys(optionObj)) {
  201. var option = document.createElement('option');
  202. option.innerHTML = key;
  203. option.value = optionObj[key];
  204. select.insertBefore(option, null);
  205. }
  206. config.nav.insertBefore(select, null);
  207. if (config.bookmarkSupport) {
  208. if (unsafeWindow.dataLayer[0].login != 'yes') {
  209. let lebal = document.createElement('lebal');
  210. lebal.innerHTML = 'bookmark support need login';
  211. lebal.style.color = 'red';
  212. config.nav.insertBefore(lebal, config.btn);
  213. return;
  214. }
  215. }
  216. getPreUserNum();
  217. }
  218. }, 4000);
  219. }
  220.  
  221. }
  222. window.addEventListener('load', init);
  223.  
  224.  
  225. //get current search word, then use xmlHttpRequest get response(from my server)
  226. function sortByPopularity(e) {
  227. config.btn.innerHTML = 'Searching...'
  228. try {
  229. var page;
  230. //var matching=window.location.href.match(/https:\/\/www\.pixiv\.net\/(\w*\/)?tags\/(.*)\/\w*\?(order=[^\?&]*)?&?(mode=(\w\d*))?&?(p=(\d*))?/);
  231. debug(e.target.tagName);
  232. if (/(\d*)/.test(e.target.textContent) && (e.target.tagName.toLowerCase() == 'span' || e.target.tagName.toLowerCase() == "a")) {
  233. page = e.target.textContent.match(/(\d*)/)[1];
  234. }
  235. else if (e.target.tagName.toLowerCase() == 'svg' || e.target.tagName.toLowerCase() == 'polyline') {
  236. //debug('e.target.parentElement.tagName: '+e.target.parentElement.tagName);
  237. if (e.target.parentElement.tagName.toLowerCase() == 'a') {
  238. page = e.target.parentElement.href.match(/p=(\d*)/)[1];
  239.  
  240. }
  241. else {
  242. page = e.target.parentElement.parentElement.href.match(/p=(\d*)/)[1];
  243.  
  244. }
  245. }
  246. //for test
  247. /*else if(matching[7]!=null){
  248. page=matching[7];
  249. }*/
  250. else {
  251. page = 1;
  252. }
  253. page = parseInt(page);
  254. debug('page: ' + page);
  255. var order = document.querySelector('#sortByPopularity').value;
  256. var obj = new requestObject(window.location.href, page, order);
  257. obj.package = page;
  258. debug('JSON.stringify(obj): ' + JSON.stringify(obj));
  259. getBookmark(obj);
  260.  
  261. }
  262. catch (e) {
  263. debug('[Error]: ' + e)
  264. }
  265.  
  266. }
  267.  
  268.  
  269. function getBookmark(obj, totalPage = 1, page = 1) {
  270. if (config.bookmarkSupport) {
  271. let reqObj = new requestObject(config.api.bookmark, page);
  272. reqObj.respType = 'text';
  273. request(reqObj, function (responseDetails, package) {
  274. if (responseDetails.responseText != null) {
  275. let dom = new DOMParser().parseFromString(responseDetails.responseText, "text/html");
  276. let count_badge = parseInt(dom.querySelector('span.count-badge').textContent.match(/(\d{1,9})/)[1]);
  277. if (count_badge > 0) {
  278. for (let elem of dom.querySelectorAll('li.image-item')) {
  279. let illustId = elem.querySelector('a').href.match(/(\d{1,20})/)[1];
  280. debug('illustId: ' + illustId);
  281. config.illustId_list.push(illustId);
  282. }
  283. let elm_page_list = dom.querySelector('ul.page-list');
  284. if (elm_page_list != null) {
  285. totalPage = elm_page_list.childElementCount;
  286. debug('totalPage: ' + totalPage);
  287. }
  288. }
  289. if (page != totalPage) {
  290. page++;
  291. getBookmark(obj, totalPage, page);
  292. debug('page: ' + page);
  293. }
  294. else {
  295. debug('config.illustId_list: ' + config.illustId_list);
  296. request(obj, replaceContent);
  297.  
  298. }
  299.  
  300. }
  301. else {
  302. request(obj, replaceContent);
  303. }
  304. });
  305.  
  306. }
  307. else {
  308. debug('config.illustId_list: ' + config.illustId_list);
  309. request(obj, replaceContent);
  310.  
  311. }
  312. }
  313.  
  314.  
  315. function replaceContent(responseDetails, obj) {
  316. let page = obj.package;
  317. debug("responseDetails.response: " + JSON.stringify(responseDetails.response));
  318. let remoteResponse = responseDetails.response;
  319. if (config.illustId_list.length > 0) {
  320. for (let data of remoteResponse.body.illustManga.data) {
  321. debug('data.illustId: ' + data.id);
  322. if (config.illustId_list.includes(data.id)) {
  323. debug('data.illustId: ' + data.id);
  324. data.bookmarkData = { "id": "123", "private": false };
  325. }
  326. }
  327. }
  328. debug("remoteResponse: " + JSON.stringify(remoteResponse));
  329. //debug("remoteResponse.body.illustManga.data[0]: "+JSON.stringify(remoteResponse.body.illustManga.data[0]));
  330. unsafeWindow.newData = JSON.stringify(remoteResponse, null, 2);
  331. unsafeWindow.interceptEnable = true;
  332. unsafeWindow.newUrl = obj.url.replace(config.api.ajax + 'https://www.pixiv.net', '');
  333. //trigger fetch by click "Newest" or "Oldest"
  334. var spanList = document.querySelectorAll('span');
  335. for (var span of spanList) {
  336. if (/(Newest)|(Oldest)|(按最新排序)|(按旧|舊排序)|(新しい順)|(古い順)|(최신순)|(과거순)/.test(span.textContent)) {
  337. if (span.parentElement.tagName.toLowerCase() == 'a') {
  338. span.parentElement.click();
  339. break;
  340. }
  341. }
  342. }
  343. var interval = setInterval(function () {
  344. var navList = document.querySelectorAll('nav');
  345. debug('navList.length: ' + navList.length)
  346. if (navList.length == 2) {
  347. let nav = navList[1];
  348. debug('nav: ' + nav.innerHTML)
  349. nav.addEventListener('click', sortByPopularity);
  350. if (page <= 7 && page > 1) {
  351. //nav button "1" text -> current page number
  352. nav.childNodes[1].childNodes[0].innerText = page;
  353. //nav button "1" href -> current page href
  354. nav.childNodes[1].href = nav.childNodes[page].href;
  355. //current page button text -> "1"
  356. nav.childNodes[page].innerText = 1;
  357. //current page button href -> origin nav button "1" href
  358. nav.childNodes[page].href = nav.childNodes[0].href;
  359. //switch two button positon
  360. nav.insertBefore(nav.childNodes[1], nav.childNodes[page]);
  361. nav.insertBefore(nav.childNodes[page], nav.childNodes[1]);
  362.  
  363. }
  364. else if (page > 7) {
  365. var currentPositionInNav = page % 7;
  366. debug("currentPositionInNav: " + currentPositionInNav);
  367. var buttonStartNumber = page - currentPositionInNav;
  368. debug("buttonStartNumber: " + buttonStartNumber);
  369. var navButtonCount = 1;
  370. //switch two button positon
  371. nav.insertBefore(nav.childNodes[1], nav.childNodes[currentPositionInNav + 1]);
  372. nav.insertBefore(nav.childNodes[currentPositionInNav + 1], nav.childNodes[1]);
  373. for (var i = buttonStartNumber; i <= (buttonStartNumber + 6); i++) {
  374. debug("navButtonCount: " + navButtonCount);
  375. debug("i: " + i);
  376. nav.childNodes[navButtonCount].childNodes[0].innerText = i;
  377. nav.childNodes[navButtonCount].href = nav.childNodes[8].href.replace(/p=\d*/, 'p=' + (i));
  378. navButtonCount++;
  379. }
  380. }
  381. if (page != 1) {
  382. //display previous button
  383. nav.childNodes[0].style = 'opacity:1!important;';
  384. //previous button href
  385. nav.childNodes[0].href = nav.childNodes[8].href.replace(/p=\d*/, 'p=' + (page - 1));
  386. //next button href
  387. nav.childNodes[8].href = nav.childNodes[8].href.replace(/p=\d*/, 'p=' + (page + 1));
  388.  
  389. }
  390. config.btn.innerHTML = 'Sort by popularity';
  391. clearInterval(interval);
  392.  
  393. }
  394. }, 4000);
  395. }
  396.  
  397.  
  398. function request(object, func, timeout = 60000) {
  399. GM_xmlhttpRequest({
  400. method: object.method,
  401. url: object.url,
  402. headers: object.headers,
  403. responseType: object.respType,
  404. data: object.body,
  405. timeout: timeout,
  406. onload: function (responseDetails) {
  407. debug(responseDetails);
  408. //Dowork
  409. func(responseDetails, object);
  410. },
  411. ontimeout: function (responseDetails) {
  412. debug(responseDetails);
  413. //Dowork
  414. func(responseDetails);
  415.  
  416. },
  417. ononerror: function (responseDetails) {
  418. debug(responseDetails);
  419. //Dowork
  420. func(responseDetails);
  421.  
  422. }
  423. });
  424. }
  425.  
  426.  
  427. //get premium users number
  428. function getPreUserNum() {
  429. debug('getPreUserNum');
  430. let obj = new requestObject(config.api.userNum);
  431. obj.respType = 'json';
  432. request(obj, function (responseDetails) {
  433. debug('responseDetails.status: ' + responseDetails.status);
  434. if (responseDetails.status == 200) {
  435. let json = responseDetails.response;
  436. let num = json.data.userNum;
  437. debug('num: ' + num);
  438. if (num > 0) {
  439. config.btn.disabled = false;
  440. intercept();
  441. }
  442. let style = document.createElement('style');
  443. style.type = 'text/css';
  444. style.innerHTML = `
  445. [data-tooltip]:before {
  446. /* needed - do not touch */
  447. content: attr(data-tooltip);
  448. position: absolute;
  449. opacity: 0;
  450. /* customizable */
  451. transition: all 0.15s ease;
  452. padding: 10px;
  453. color: #333;
  454. border-radius: 5px;
  455. box-shadow: 2px 2px 1px silver;
  456. }
  457. [data-tooltip]:hover:before {
  458. /* needed - do not touch */
  459. opacity: 1;
  460. /* customizable */
  461. background: white;
  462. margin-top: -50px;
  463. margin-left: 20px;
  464. }
  465. `;
  466. document.getElementsByTagName('head')[0].appendChild(style);
  467. config.btn.setAttribute('data-tooltip', 'Current shared premium user: ' + num);
  468. }
  469. });
  470. }
  471.  
  472.  
  473. /**
  474. * Create a user setting prompt
  475. * @param {string} varName
  476. * @param {any} defaultVal
  477. * @param {string} menuText
  478. * @param {string} promtText
  479. * @param {function} func
  480. * @param {string} sep
  481. */
  482. function setUserPref(varName, defaultVal, menuText, promtText, func = null) {
  483. GM_registerMenuCommand(menuText, function () {
  484. var val = prompt(promtText, GM_getValue(varName, defaultVal));
  485. if (val === null) { return; } // end execution if clicked CANCEL
  486. GM_setValue(varName, val);
  487. if (func != null) {
  488. func(val);
  489. }
  490. });
  491. }
  492.  
  493.  
  494. //share cookie
  495. function shareCookie(val) {
  496. if (/[^,]+,\s?\d+/.test(val)) {
  497. if (unsafeWindow.dataLayer[0].premium == 'yes') {
  498. let array = val.split(',');
  499. let userId = unsafeWindow.dataLayer[0].user_id;
  500. let cookie = array[0];
  501. let expire = array[1].trim();
  502. let obj = new requestObject(config.api.share);
  503. obj.method = 'POST';
  504. obj.respType = 'json';
  505. obj.body = encodeURIComponent(
  506. JSON.stringify(
  507. {
  508. 'key': 'user:' + userId,
  509. 'value': null,
  510. 'metadata': {
  511. 'userId': userId,
  512. 'cookie': cookie,
  513. 'expire': expire,
  514. },
  515. }
  516. )
  517. );
  518. debug('obj: ' + JSON.stringify(obj));
  519. request(obj, function (responseDetails) {
  520. let json = responseDetails.response;
  521. debug('json: ' + JSON.stringify(json));
  522. if (responseDetails.status == 200) {
  523. if (json.status == 200) {
  524. alert('Share success, thank you!');
  525. }
  526. }
  527. });
  528. }
  529. else {
  530. alert('You are not premium user.');
  531. }
  532. }
  533. else {
  534. alert('Parameter invalid.');
  535. }
  536. }

QingJ © 2025

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