pixiv_sort_by_popularity

non premium menber use "Sort by popularity"

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