pixiv_sort_by_popularity

non premium menber use "Sort by popularity"

当前为 2021-01-17 提交的版本,查看 最新版本

  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.26
  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('load', 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. let obj = new requestObject(window.location.href, page, order);
  310. obj.package = page;
  311. debug('JSON.stringify(obj): ' + JSON.stringify(obj));
  312. getBookmark(obj);
  313.  
  314. }
  315. catch (e) {
  316. debug('[Error]: ' + e)
  317. }
  318.  
  319. }
  320.  
  321.  
  322. function getBookmark(obj, totalPage = 1, page = 1) {
  323. if (config.bookmarkSupport == 1) {
  324. let reqObj = new requestObject(config.api.bookmark, page);
  325. reqObj.respType = 'text';
  326. request(reqObj, function (responseDetails, package) {
  327. if (responseDetails.responseText != null) {
  328. let dom = new DOMParser().parseFromString(responseDetails.responseText, "text/html");
  329. let count_badge = parseInt(dom.querySelector('span.count-badge').textContent.match(/(\d{1,9})/)[1]);
  330. if (count_badge > 0) {
  331. for (let elem of dom.querySelectorAll('li.image-item')) {
  332. let illustId = elem.querySelector('a').href.match(/(\d{1,20})/)[1];
  333. debug('illustId: ' + illustId);
  334. config.illustId_list.push(illustId);
  335. }
  336. let elm_page_list = dom.querySelector('ul.page-list');
  337. if (elm_page_list != null) {
  338. totalPage = elm_page_list.childElementCount;
  339. debug('totalPage: ' + totalPage);
  340. }
  341. }
  342. if (page != totalPage) {
  343. page++;
  344. getBookmark(obj, totalPage, page);
  345. debug('page: ' + page);
  346. }
  347. else {
  348. debug('config.illustId_list: ' + config.illustId_list);
  349. request(obj, replaceContent);
  350.  
  351. }
  352.  
  353. }
  354. else {
  355. request(obj, replaceContent);
  356. }
  357. });
  358.  
  359. }
  360. else {
  361. debug('config.illustId_list: ' + config.illustId_list);
  362. request(obj, replaceContent);
  363.  
  364. }
  365. }
  366.  
  367.  
  368. function replaceContent(responseDetails, obj) {
  369. let page = obj.package;
  370. debug("responseDetails.response: " + JSON.stringify(responseDetails.response));
  371. let remoteResponse = responseDetails.response;
  372. if (config.illustId_list.length > 0) {
  373. for (let data of remoteResponse.body.illustManga.data) {
  374. debug('data.illustId: ' + data.id);
  375. if (config.illustId_list.includes(data.id)) {
  376. debug('data.illustId: ' + data.id);
  377. data.bookmarkData = { "id": "123", "private": false };
  378. }
  379. }
  380. }
  381. debug("remoteResponse: " + JSON.stringify(remoteResponse));
  382. let newData = JSON.stringify(remoteResponse, null, 2);
  383. let interceptEnable = true;
  384. let newUrl = obj.url.replace(config.api.ajax + '/https://www.pixiv.net', '');
  385. intercept(newData, newUrl, interceptEnable);
  386. //trigger fetch by click "Newest" or "Oldest"
  387. let spanList = document.querySelectorAll('span');
  388. for (let span of spanList) {
  389. if (/(Newest)|(Oldest)|(按最新排序)|(按旧|舊排序)|(新しい順)|(古い順)|(최신순)|(과거순)/.test(span.textContent)) {
  390. if (span.parentElement.tagName.toLowerCase() == 'a') {
  391. span.parentElement.click();
  392. break;
  393. }
  394. }
  395. }
  396. let interval = setInterval(function () {
  397. let navList = document.querySelectorAll('nav');
  398. debug('navList.length: ' + navList.length)
  399. if (navList.length == 2) {
  400. let nav = navList[1];
  401. debug('nav: ' + nav.innerHTML)
  402. nav.addEventListener('click', sortByPopularity);
  403. for (let a of nav.querySelectorAll('a')) {
  404. a.addEventListener('click', function (e) { e.preventDefault(); });
  405. }
  406. if (page <= 7 && page > 1) {
  407. //nav button "1" text -> current page number
  408. nav.childNodes[1].childNodes[0].innerText = page;
  409. //nav button "1" href -> current page href
  410. nav.childNodes[1].href = nav.childNodes[page].href;
  411. //current page button text -> "1"
  412. nav.childNodes[page].innerText = 1;
  413. //current page button href -> origin nav button "1" href
  414. nav.childNodes[page].href = nav.childNodes[0].href;
  415. //switch two button positon
  416. nav.insertBefore(nav.childNodes[1], nav.childNodes[page]);
  417. nav.insertBefore(nav.childNodes[page], nav.childNodes[1]);
  418.  
  419. }
  420. else if (page > 7) {
  421. let currentPositionInNav = page % 7;
  422. debug("currentPositionInNav: " + currentPositionInNav);
  423. let buttonStartNumber = page - currentPositionInNav;
  424. debug("buttonStartNumber: " + buttonStartNumber);
  425. let navButtonCount = 1;
  426. //switch two button positon
  427. nav.insertBefore(nav.childNodes[1], nav.childNodes[currentPositionInNav + 1]);
  428. nav.insertBefore(nav.childNodes[currentPositionInNav + 1], nav.childNodes[1]);
  429. for (let i = buttonStartNumber; i <= (buttonStartNumber + 6); i++) {
  430. debug("navButtonCount: " + navButtonCount);
  431. debug("i: " + i);
  432. nav.childNodes[navButtonCount].childNodes[0].innerText = i;
  433. nav.childNodes[navButtonCount].href = nav.childNodes[8].href.replace(/p=\d*/, 'p=' + (i));
  434. navButtonCount++;
  435. }
  436. }
  437. if (page != 1) {
  438. //display previous button
  439. nav.childNodes[0].style = 'opacity:1!important;';
  440. //previous button href
  441. nav.childNodes[0].href = nav.childNodes[8].href.replace(/p=\d*/, 'p=' + (page - 1));
  442. //next button href
  443. nav.childNodes[8].href = nav.childNodes[8].href.replace(/p=\d*/, 'p=' + (page + 1));
  444.  
  445. }
  446. config.elem.btn.textContent = 'Sort by popularity';
  447. clearInterval(interval);
  448.  
  449. }
  450. }, 1000);
  451. }
  452.  
  453.  
  454. function request(object, func, timeout = 60000) {
  455. GM_xmlhttpRequest({
  456. method: object.method,
  457. url: object.url,
  458. headers: object.headers,
  459. responseType: object.respType,
  460. data: object.body,
  461. timeout: timeout,
  462. onload: function (responseDetails) {
  463. debug(responseDetails);
  464. //Dowork
  465. func(responseDetails, object);
  466. },
  467. ontimeout: function (responseDetails) {
  468. debug(responseDetails);
  469. //Dowork
  470. func(responseDetails);
  471.  
  472. },
  473. ononerror: function (responseDetails) {
  474. debug(responseDetails);
  475. //Dowork
  476. func(responseDetails);
  477.  
  478. }
  479. });
  480. }
  481.  
  482.  
  483. //get premium users number
  484. function getPreUserNum() {
  485. debug('getPreUserNum');
  486. let obj = new requestObject(config.api.userNum);
  487. obj.respType = 'json';
  488. request(obj, function (responseDetails) {
  489. debug('responseDetails.status: ' + responseDetails.status);
  490. if (responseDetails.status == 200) {
  491. let json = responseDetails.response;
  492. let num = json.data.userNum;
  493. debug('num: ' + num);
  494. if (num > 0) {
  495. config.elem.btn.disabled = false;
  496. }
  497. config.elem.span.textContent = 'Current shared premium user: ' + num;
  498. }
  499. });
  500. }
  501.  
  502.  
  503. /**
  504. * Create a user setting prompt
  505. * @param {string} varName
  506. * @param {any} defaultVal
  507. * @param {string} menuText
  508. * @param {string} promtText
  509. * @param {function} func
  510. */
  511. function setUserPref(varName, defaultVal, menuText, promtText, func = null) {
  512. GM_registerMenuCommand(menuText, function () {
  513. let val = prompt(promtText, GM_getValue(varName, defaultVal));
  514. if (val === null) { return; } // end execution if clicked CANCEL
  515. GM_setValue(varName, val);
  516. if (func != null) {
  517. func(val);
  518. }
  519. });
  520. }
  521.  
  522.  
  523. //share cookie
  524. function shareCookie(val) {
  525. if (/PHPSESSID=\d+_\w+,\s?\d+/.test(val)) {
  526. if (unsafeWindow.dataLayer[0].premium == 'yes') {
  527. let array = val.split(',');
  528. let userId = unsafeWindow.dataLayer[0].user_id;
  529. let cookie = array[0];
  530. let expire = array[1].trim();
  531. let obj = new requestObject(config.api.share);
  532. obj.method = 'POST';
  533. obj.respType = 'json';
  534. obj.body = encodeURIComponent(
  535. JSON.stringify(
  536. {
  537. 'key': 'user:' + userId,
  538. 'value': null,
  539. 'metadata': {
  540. 'userId': userId,
  541. 'cookie': cookie,
  542. 'expire': expire,
  543. },
  544. }
  545. )
  546. );
  547. debug('obj: ' + JSON.stringify(obj));
  548. request(obj, function (responseDetails) {
  549. let json = responseDetails.response;
  550. debug('json: ' + JSON.stringify(json));
  551. if (responseDetails.status == 200) {
  552. if (json.status == 200) {
  553. alert('Share success, thank you!');
  554. }
  555. }
  556. });
  557. }
  558. else {
  559. alert('You are not premium user.');
  560. }
  561. }
  562. else {
  563. alert('Parameter invalid.');
  564. }
  565. }