pixiv_sort_by_popularity

non premium menber use "Sort by popularity"

当前为 2020-02-21 提交的版本,查看 最新版本

  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. // @namespace pixiv_sort_by_popularity
  7. // @supportURL https://github.com/zhuzemin
  8. // @description non premium menber use "Sort by popularity"
  9. // @description:zh-CN non premium menber use "Sort by popularity"
  10. // @description:zh-TW non premium menber use "Sort by popularity"
  11. // @description:ja non premium menber use "Sort by popularity"
  12. // @include https://www.pixiv.net/*/tags/*
  13. // @include https://www.pixiv.net/tags/*
  14. // @version 1.08
  15. // @run-at document-start
  16. // @author zhuzemin
  17. // @license Mozilla Public License 2.0; http://www.mozilla.org/MPL/2.0/
  18. // @license CC Attribution-ShareAlike 4.0 International; http://creativecommons.org/licenses/by-sa/4.0/
  19. // @grant GM_xmlhttpRequest
  20. // @grant GM_registerMenuCommand
  21. // @grant GM_setValue
  22. // @grant GM_getValue
  23. // @connect-src workers.dev
  24. // ==/UserScript==
  25. var config = {
  26. 'debug': false
  27. }
  28. var debug = config.debug ? console.log.bind(console) : function () {
  29. };
  30.  
  31. //this userscript desire for free member use "Sort by popularity"
  32.  
  33. //default
  34. //pixiv search request through this url will use my cookie.
  35. var cloudFlareUrl='https://proud-surf-e590.zhuzemin.workers.dev/ajax/';
  36.  
  37. //Obejct use for xmlHttpRequest
  38. class requestObject{
  39. constructor(originUrl,page,order) {
  40. this.method = 'GET';
  41. this.url = cloudFlareUrl+originUrl
  42. .replace(/(https:\/\/www\.pixiv\.net\/)(\w*)?\/tags\/([^\/]*)\/(\w*)\?([^\/\?]*)/,
  43. function(match, $1, $2,$3,$4,$5, offset, original){ return $1+'ajax/search/'+$4+'/'+$3+'?'+$5;})
  44. .replace(/p=\d*/,'').replace(/order=[_\w]*/,'')+'&p='+page+'&order='+order;
  45. this.data=null,
  46. this.headers = {
  47. 'User-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0',
  48. 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'
  49. //'Accept': 'application/atom+xml,application/xml,text/xml',
  50. //'Referer': window.location.href,
  51. };
  52. this.charset = 'text/plain;charset=utf8';
  53. this.package=null;
  54. }
  55. }
  56.  
  57. var btn;
  58.  
  59. // prepare UserPrefs
  60. setUserPref(
  61. 'cloudFlareUrl',
  62. cloudFlareUrl,
  63. 'Set cloudFlareUrl',
  64. `cloudFlareUrl only working on "Sort by popularity"`,
  65. ','
  66. );
  67.  
  68.  
  69. //for override fetch, I think override function sure insert to page, otherwise userscript don't have permission modified fetch in page?
  70. function addJS_Node (text)
  71. {
  72. var scriptNode = document.createElement ('script');
  73. scriptNode.type = "text/javascript";
  74. if (text) scriptNode.textContent = text;
  75.  
  76. var targ = document.getElementsByTagName('head')[0] || d.body || d.documentElement;
  77. targ.appendChild (scriptNode);
  78. }
  79.  
  80.  
  81.  
  82. //override fetch
  83. function intercept(){
  84. //insert override function to page
  85. addJS_Node(`
  86. var newData;
  87. var interceptEnable;
  88. var constantMock = window.fetch;
  89. window.fetch = function() {
  90. //console.log(arguments);
  91.  
  92. return new Promise((resolve, reject) => {
  93. constantMock.apply(this, arguments)
  94. .then((response) => {
  95. if(interceptEnable&&/https:\\/\\/www\\.pixiv\\.net\\/ajax\\/search\\//.test(response.url)){
  96. var blob = new Blob([newData], {type : 'application/json'});
  97. //console.log(newData);
  98.  
  99. var newResponse=new Response(
  100. blob, {
  101. status: response.status,
  102. statusText: response.statusText,
  103. headers: response.headers
  104. });
  105. //console.log(newResponse);
  106. response=newResponse;
  107. interceptEnable=false;
  108. }
  109. resolve(response);
  110. })
  111. .catch((error) => {
  112. reject(response);
  113. })
  114. });
  115. }
  116. `);
  117. //here is script end,
  118. //in console ,log show fetch response body has been changed <--- not very sure
  119. //and page have react ---> stay blank for ever
  120. //my confuse is: even comment "return data" (line:93), page still return blank,
  121. //that makes me wonder: maybe this override function miss something.
  122. //if my terrible code can be understanding somehow,
  123. //and knoa san have nothing else todo in leisure time,
  124. //knoa san can you take while, look my newbie problem?
  125. //of cource if too painful read my code, I totally understand!
  126. //knoa san can read to here already be my greatest honor, and I'm very happy!
  127. }
  128.  
  129. //userscript entry
  130. var init=function(){
  131. //create button
  132. if(window.self === window.top){
  133. debug("init");
  134. cloudFlareUrl=GM_getValue('cloudFlareUrl')||cloudFlareUrl;
  135. intercept();
  136. var div=document.querySelector('div.sc-LzNRw.qhAyw');
  137. btn =document.createElement('button');
  138. btn.innerHTML='Sort by popularity';
  139. btn.addEventListener('click',sortByPopularity);
  140. div.insertBefore(btn,null);
  141. select=document.createElement('select');
  142. select.id='sortByPopularity';
  143. var optionObj={
  144. 'Popular with all':'popular_d',
  145. 'Popular (male)':'popular_male_d',
  146. 'Popular (female)':'popular_female_d'
  147. }
  148. for(var key of Object.keys(optionObj)){
  149. var option=document.createElement('option');
  150. option.innerHTML=key;
  151. option.value=optionObj[key];
  152. select.insertBefore(option,null);
  153. }
  154. div.insertBefore(select,null);
  155. }
  156. }
  157.  
  158. window.addEventListener('load', init);
  159.  
  160. //get current search word, then use xmlHttpRequest get response(from my server)
  161. function sortByPopularity(e) {
  162. btn.innerHTML='Searching...'
  163. try{
  164. var page;
  165. //var matching=window.location.href.match(/https:\/\/www\.pixiv\.net\/(\w*\/)?tags\/(.*)\/\w*\?(order=[^\?&]*)?&?(mode=(\w\d*))?&?(p=(\d*))?/);
  166. debug(e.target.tagName);
  167. if(/(\d*)/.test(e.target.textContent)&&(e.target.tagName.toLowerCase()=='span'||e.target.tagName.toLowerCase()=="a")){
  168. page=e.target.textContent.match(/(\d*)/)[1];
  169. }
  170. else if(e.target.tagName.toLowerCase()=='svg'||e.target.tagName.toLowerCase()=='polyline'){
  171. //debug('e.target.parentElement.tagName: '+e.target.parentElement.tagName);
  172. if(e.target.parentElement.tagName.toLowerCase()=='a'){
  173. page=e.target.parentElement.href.match(/p=(\d*)/)[1];
  174.  
  175. }
  176. else {
  177. page=e.target.parentElement.parentElement.href.match(/p=(\d*)/)[1];
  178.  
  179. }
  180. }
  181. //for test
  182. /*else if(matching[7]!=null){
  183. page=matching[7];
  184. }*/
  185. else{
  186. page=1;
  187. }
  188. page=parseInt(page);
  189. debug('page: '+page);
  190. var order=document.querySelector('#sortByPopularity').value;
  191. var obj=new requestObject(window.location.href,page,order);
  192. debug('JSON.stringify(obj): '+JSON.stringify(obj));
  193. request(obj,function (responseDetails) {
  194. debug("responseDetails.response: "+JSON.stringify(responseDetails.response));
  195. unsafeWindow.newData=JSON.stringify(responseDetails.response,null,2);
  196. unsafeWindow.interceptEnable=true;
  197. //trigger fetch by click "Newest" or "Oldest"
  198. var divList=document.querySelectorAll('div.sc-LzMhM.krTqXn');
  199. var div=divList[divList.length-1];
  200. div.querySelector('a').click();
  201. var interval=setInterval(function () {
  202. var nav=document.querySelector('nav.sc-LzNRx.qpXcF');
  203. if(nav!=null){
  204. nav.addEventListener('click',sortByPopularity);
  205. if(page<=7&&page>1){
  206. //nav button "1" text -> current page number
  207. nav.childNodes[1].childNodes[0].innerText=page;
  208. //nav button "1" href -> current page href
  209. nav.childNodes[1].href=nav.childNodes[page].href;
  210. //current page button text -> "1"
  211. nav.childNodes[page].innerText=1;
  212. //current page button href -> origin nav button "1" href
  213. nav.childNodes[page].href=nav.childNodes[0].href;
  214. //switch two button positon
  215. nav.insertBefore(nav.childNodes[1],nav.childNodes[page]);
  216. nav.insertBefore(nav.childNodes[page],nav.childNodes[1]);
  217.  
  218. }
  219. else if(page>7){
  220. var currentPositionInNav=page%7;
  221. debug("currentPositionInNav: "+currentPositionInNav);
  222. var buttonStartNumber=page-currentPositionInNav;
  223. debug("buttonStartNumber: "+buttonStartNumber);
  224. var navButtonCount=1;
  225. //switch two button positon
  226. nav.insertBefore(nav.childNodes[1],nav.childNodes[currentPositionInNav+1]);
  227. nav.insertBefore(nav.childNodes[currentPositionInNav+1],nav.childNodes[1]);
  228. for(var i=buttonStartNumber;i<=(buttonStartNumber+6);i++){
  229. debug("navButtonCount: "+navButtonCount);
  230. debug("i: "+i);
  231. nav.childNodes[navButtonCount].childNodes[0].innerText=i;
  232. nav.childNodes[navButtonCount].href=nav.childNodes[8].href.replace(/p=\d*/,'p='+(i));
  233. navButtonCount++;
  234. }
  235. }
  236. if(page!=1){
  237. //display previous button
  238. nav.childNodes[0].style='opacity:1!important;';
  239. //previous button href
  240. nav.childNodes[0].href=nav.childNodes[8].href.replace(/p=\d*/,'p='+(page-1));
  241. //next button href
  242. nav.childNodes[8].href=nav.childNodes[8].href.replace(/p=\d*/,'p='+(page+1));
  243.  
  244. }
  245. btn.innerHTML='Sort by popularity';
  246. clearInterval(interval);
  247.  
  248. }
  249. },2000);
  250. });
  251.  
  252. }
  253. catch (e) {
  254. debug('[Error]: '+e)
  255. }
  256.  
  257. }
  258. function request(object,func) {
  259. GM_xmlhttpRequest({
  260. method: object.method,
  261. url: object.url,
  262. headers: object.headers,
  263. responseType: 'json',
  264. overrideMimeType: object.charset,
  265. timeout: 60000,
  266. //synchronous: true
  267. onload: function (responseDetails) {
  268. debug(responseDetails);
  269. //Dowork
  270. func(responseDetails);
  271. },
  272. ontimeout: function (responseDetails) {
  273. //Dowork
  274. func(responseDetails);
  275.  
  276. },
  277. ononerror: function (responseDetails) {
  278. debug(responseDetails);
  279. //Dowork
  280. func(responseDetails);
  281.  
  282. }
  283. });
  284. }
  285. function setUserPref(varName, defaultVal, menuText, promtText, sep){
  286. GM_registerMenuCommand(menuText, function() {
  287. var val = prompt(promtText, GM_getValue(varName, defaultVal));
  288. if (val === null) { return; } // end execution if clicked CANCEL
  289. // prepare string of variables separated by the separator
  290. if (sep && val){
  291. var pat1 = new RegExp('\\s*' + sep + '+\\s*', 'g'); // trim space/s around separator & trim repeated separator
  292. var pat2 = new RegExp('(?:^' + sep + '+|' + sep + '+$)', 'g'); // trim starting & trailing separator
  293. //val = val.replace(pat1, sep).replace(pat2, '');
  294. }
  295. //val = val.replace(/\s{2,}/g, ' ').trim(); // remove multiple spaces and trim
  296. GM_setValue(varName, val);
  297. // Apply changes (immediately if there are no existing highlights, or upon reload to clear the old ones)
  298. //if(!document.body.querySelector(".THmo")) THmo_doHighlight(document.body);
  299. //else location.reload();
  300. });
  301. }