pixiv_sort_by_popularity

non premium menber use "Sort by popularity"

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

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