pixiv_sort_by_popularity

non premium menber use "Sort by popularity"

目前为 2020-02-21 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name pixiv_sort_by_popularity(working again)
  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.09
  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 newUrl;
  89. var constantMock = window.fetch;
  90. window.fetch = function() {
  91. arguments[0]=newUrl;
  92. //console.log(arguments);
  93.  
  94. return new Promise((resolve, reject) => {
  95. constantMock.apply(this, arguments)
  96. .then((response) => {
  97. if(interceptEnable&&/https:\\/\\/www\\.pixiv\\.net\\/ajax\\/search\\//.test(response.url)){
  98. var blob = new Blob([newData], {type : 'application/json'});
  99. //console.log(newData);
  100.  
  101. var newResponse=new Response(
  102. blob, {
  103. status: response.status,
  104. statusText: response.statusText,
  105. headers: response.headers
  106. });
  107. //console.log(newResponse);
  108. response=newResponse;
  109. interceptEnable=false;
  110. }
  111. resolve(response);
  112. })
  113. .catch((error) => {
  114. reject(response);
  115. })
  116. });
  117. }
  118. `);
  119. //here is script end,
  120. //in console ,log show fetch response body has been changed <--- not very sure
  121. //and page have react ---> stay blank for ever
  122. //my confuse is: even comment "return data" (line:93), page still return blank,
  123. //that makes me wonder: maybe this override function miss something.
  124. //if my terrible code can be understanding somehow,
  125. //and knoa san have nothing else todo in leisure time,
  126. //knoa san can you take while, look my newbie problem?
  127. //of cource if too painful read my code, I totally understand!
  128. //knoa san can read to here already be my greatest honor, and I'm very happy!
  129. }
  130.  
  131. //userscript entry
  132. var init=function(){
  133. //create button
  134. if(window.self === window.top){
  135. debug("init");
  136. cloudFlareUrl=GM_getValue('cloudFlareUrl')||cloudFlareUrl;
  137. intercept();
  138. var nav=document.querySelector('nav');
  139. btn =document.createElement('button');
  140. btn.innerHTML='Sort by popularity';
  141. btn.addEventListener('click',sortByPopularity);
  142. nav.insertBefore(btn,null);
  143. select=document.createElement('select');
  144. select.id='sortByPopularity';
  145. var optionObj={
  146. 'Popular with all':'popular_d',
  147. 'Popular (male)':'popular_male_d',
  148. 'Popular (female)':'popular_female_d'
  149. }
  150. for(var key of Object.keys(optionObj)){
  151. var option=document.createElement('option');
  152. option.innerHTML=key;
  153. option.value=optionObj[key];
  154. select.insertBefore(option,null);
  155. }
  156. nav.insertBefore(select,null);
  157. }
  158. }
  159.  
  160. window.addEventListener('load', init);
  161.  
  162. //get current search word, then use xmlHttpRequest get response(from my server)
  163. function sortByPopularity(e) {
  164. btn.innerHTML='Searching...'
  165. try{
  166. var page;
  167. //var matching=window.location.href.match(/https:\/\/www\.pixiv\.net\/(\w*\/)?tags\/(.*)\/\w*\?(order=[^\?&]*)?&?(mode=(\w\d*))?&?(p=(\d*))?/);
  168. debug(e.target.tagName);
  169. if(/(\d*)/.test(e.target.textContent)&&(e.target.tagName.toLowerCase()=='span'||e.target.tagName.toLowerCase()=="a")){
  170. page=e.target.textContent.match(/(\d*)/)[1];
  171. }
  172. else if(e.target.tagName.toLowerCase()=='svg'||e.target.tagName.toLowerCase()=='polyline'){
  173. //debug('e.target.parentElement.tagName: '+e.target.parentElement.tagName);
  174. if(e.target.parentElement.tagName.toLowerCase()=='a'){
  175. page=e.target.parentElement.href.match(/p=(\d*)/)[1];
  176.  
  177. }
  178. else {
  179. page=e.target.parentElement.parentElement.href.match(/p=(\d*)/)[1];
  180.  
  181. }
  182. }
  183. //for test
  184. /*else if(matching[7]!=null){
  185. page=matching[7];
  186. }*/
  187. else{
  188. page=1;
  189. }
  190. page=parseInt(page);
  191. debug('page: '+page);
  192. var order=document.querySelector('#sortByPopularity').value;
  193. var obj=new requestObject(window.location.href,page,order);
  194. debug('JSON.stringify(obj): '+JSON.stringify(obj));
  195. request(obj,function (responseDetails) {
  196. debug("responseDetails.response: "+JSON.stringify(responseDetails.response));
  197. unsafeWindow.newData=JSON.stringify(responseDetails.response,null,2);
  198. unsafeWindow.interceptEnable=true;
  199. unsafeWindow.newUrl=obj.url.replace(cloudFlareUrl+'https://www.pixiv.net','');
  200. //trigger fetch by click "Newest" or "Oldest"
  201. var spanList=document.querySelectorAll('span');
  202. for(var span of spanList){
  203. if(/(Newest)|(Oldest)|(按最新排序)|(按旧|舊排序)|(新しい順)|(古い順)|(최신순)|(과거순)/.test(span.textContent)){
  204. if(span.parentElement.tagName.toLowerCase()=='a'){
  205. span.parentElement.click();
  206. break;
  207. }
  208. }
  209. }
  210. var interval=setInterval(function () {
  211. var nav=document.querySelectorAll('nav')[1];
  212. if(nav!=null){
  213. nav.addEventListener('click',sortByPopularity);
  214. if(page<=7&&page>1){
  215. //nav button "1" text -> current page number
  216. nav.childNodes[1].childNodes[0].innerText=page;
  217. //nav button "1" href -> current page href
  218. nav.childNodes[1].href=nav.childNodes[page].href;
  219. //current page button text -> "1"
  220. nav.childNodes[page].innerText=1;
  221. //current page button href -> origin nav button "1" href
  222. nav.childNodes[page].href=nav.childNodes[0].href;
  223. //switch two button positon
  224. nav.insertBefore(nav.childNodes[1],nav.childNodes[page]);
  225. nav.insertBefore(nav.childNodes[page],nav.childNodes[1]);
  226.  
  227. }
  228. else if(page>7){
  229. var currentPositionInNav=page%7;
  230. debug("currentPositionInNav: "+currentPositionInNav);
  231. var buttonStartNumber=page-currentPositionInNav;
  232. debug("buttonStartNumber: "+buttonStartNumber);
  233. var navButtonCount=1;
  234. //switch two button positon
  235. nav.insertBefore(nav.childNodes[1],nav.childNodes[currentPositionInNav+1]);
  236. nav.insertBefore(nav.childNodes[currentPositionInNav+1],nav.childNodes[1]);
  237. for(var i=buttonStartNumber;i<=(buttonStartNumber+6);i++){
  238. debug("navButtonCount: "+navButtonCount);
  239. debug("i: "+i);
  240. nav.childNodes[navButtonCount].childNodes[0].innerText=i;
  241. nav.childNodes[navButtonCount].href=nav.childNodes[8].href.replace(/p=\d*/,'p='+(i));
  242. navButtonCount++;
  243. }
  244. }
  245. if(page!=1){
  246. //display previous button
  247. nav.childNodes[0].style='opacity:1!important;';
  248. //previous button href
  249. nav.childNodes[0].href=nav.childNodes[8].href.replace(/p=\d*/,'p='+(page-1));
  250. //next button href
  251. nav.childNodes[8].href=nav.childNodes[8].href.replace(/p=\d*/,'p='+(page+1));
  252.  
  253. }
  254. btn.innerHTML='Sort by popularity';
  255. clearInterval(interval);
  256.  
  257. }
  258. },2000);
  259. });
  260.  
  261. }
  262. catch (e) {
  263. debug('[Error]: '+e)
  264. }
  265.  
  266. }
  267. function request(object,func) {
  268. GM_xmlhttpRequest({
  269. method: object.method,
  270. url: object.url,
  271. headers: object.headers,
  272. responseType: 'json',
  273. overrideMimeType: object.charset,
  274. timeout: 60000,
  275. //synchronous: true
  276. onload: function (responseDetails) {
  277. debug(responseDetails);
  278. //Dowork
  279. func(responseDetails);
  280. },
  281. ontimeout: function (responseDetails) {
  282. //Dowork
  283. func(responseDetails);
  284.  
  285. },
  286. ononerror: function (responseDetails) {
  287. debug(responseDetails);
  288. //Dowork
  289. func(responseDetails);
  290.  
  291. }
  292. });
  293. }
  294. function setUserPref(varName, defaultVal, menuText, promtText, sep){
  295. GM_registerMenuCommand(menuText, function() {
  296. var val = prompt(promtText, GM_getValue(varName, defaultVal));
  297. if (val === null) { return; } // end execution if clicked CANCEL
  298. // prepare string of variables separated by the separator
  299. if (sep && val){
  300. var pat1 = new RegExp('\\s*' + sep + '+\\s*', 'g'); // trim space/s around separator & trim repeated separator
  301. var pat2 = new RegExp('(?:^' + sep + '+|' + sep + '+$)', 'g'); // trim starting & trailing separator
  302. //val = val.replace(pat1, sep).replace(pat2, '');
  303. }
  304. //val = val.replace(/\s{2,}/g, ' ').trim(); // remove multiple spaces and trim
  305. GM_setValue(varName, val);
  306. // Apply changes (immediately if there are no existing highlights, or upon reload to clear the old ones)
  307. //if(!document.body.querySelector(".THmo")) THmo_doHighlight(document.body);
  308. //else location.reload();
  309. });
  310. }