generateImages.js 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. const sleep = (delay) => new Promise((resolve) => setTimeout(resolve, delay))
  2. /**
  3. * @param text 生成图像的描述
  4. * @param requestId 请求id,如果不是对话生成图片可以为undefined
  5. * @param countF 回调函数,获取当前是第几次请求。
  6. * @return [...{img:url,mImg:url}...] img:图片url mIng:缩略图url
  7. * */
  8. async function generateImages(text,requestId,countF){
  9. let theUrls = new URLSearchParams();
  10. theUrls.append('re', '1');
  11. theUrls.append('showselective', '1');
  12. theUrls.append('sude', '1');
  13. theUrls.append('kseed', '7500');
  14. theUrls.append('SFX', '2');
  15. theUrls.append('q', text);
  16. theUrls.append('iframeid', requestId);
  17. let theUrl = magicUrl+`images/create?${theUrls.toString()}`;
  18. let response = await fetch(theUrl,
  19. {"sec-fetch-site": "same-origin",
  20. "referer": "https://www.bing.com/search?q=bingAI"});
  21. let html = (await response.text());
  22. //let cookieID = response.headers.get('cookieID');
  23. //如果返回的是有错误的页面
  24. let urr = new RegExp('class="gil_err_mt">([^<>]*)</div>').exec(html);
  25. if(urr && urr[1]){
  26. let error = `<h3>${urr[1]}</h3>`;
  27. urr = new RegExp('class="gil_err_sbt">(([^<>]*<(a|div)[^<>]*>[^<>]*</(a|div)>[^<>]*)*)</div>').exec(html);
  28. if(urr && urr[1]){
  29. error = error+`<p>${urr[1]}</p>`;
  30. }
  31. throw new Error(error);
  32. }
  33. //如果没错误就匹配链接获取图片
  34. urr = new RegExp('"/(images/create/async/results/(\\S*))"').exec(html);
  35. if(!urr || !urr[1]){
  36. console.log(html);
  37. throw new Error("请求图片返回不正确的页面,无法加载图片。");
  38. }
  39. let ur = urr[1];
  40. ur = ur.replaceAll('&amp;','&');
  41. let imgPageHtmlUrl = magicUrl + `${ur}`;
  42. let options = {"sec-fetch-site":"same-origin", "referer":"https://www.bing.com/images/create?partner=sydney&showselective=1&sude=1&kseed=7000"};
  43. for(let count = 1;count<=20;count++){
  44. if((!!countF)&&(typeof countF =='function')){
  45. countF(count);
  46. }
  47. await sleep(3000);
  48. let imgPageHtml;
  49. try{
  50. imgPageHtml = (await (await fetch(imgPageHtmlUrl,options)).text());
  51. }catch(e){
  52. console.error(e);
  53. }
  54. if(!imgPageHtml){
  55. continue;
  56. }
  57. //用正则找全部图片
  58. let allSrc = imgPageHtml.matchAll(/<img[^<>]*src="([^"]*)"[^<>]*>/g);
  59. let imgs = [];
  60. for(let src;!(src=allSrc.next()).done;){
  61. imgs[imgs.length] = {
  62. img:src.value[1].split('?')[0],
  63. mImg:src.value[1].replaceAll('&amp;','&')
  64. }
  65. }
  66. if(imgs.length>0){
  67. return imgs;
  68. }else{
  69. throw new Error("服务器未正常返回图片!");
  70. }
  71. }
  72. }