Greasy Fork is available in English.

ChatGPT Infinity ∞

Generate endless answers from all-knowing ChatGPT (in any language!)

  1. // ==UserScript==
  2. // @name ChatGPT Infinity ∞
  3. // @name:af ChatGPT Oneindig ∞
  4. // @name:ar دردشةGPT إنفينيتي ∞
  5. // @name:az ChatGPT Sonsuzluq ∞
  6. // @name:be ChatGPT Бясконцасць ∞
  7. // @name:bg ChatGPT Безкрайност ∞
  8. // @name:bn ChatGPT ইনফিনিটি ∞
  9. // @name:bo ChatGPT དག་སྐྱེས་ཡོད་པ་ ∞
  10. // @name:bs ChatGPT Beskrajnost ∞
  11. // @name:ca ChatGPT Infinit ∞
  12. // @name:ckb ChatGPT نەپێندییە ∞
  13. // @name:cs ChatGPT Nekonečno ∞
  14. // @name:cy ChatGPT Anfeidredd ∞
  15. // @name:da ChatGPT Uendelighed ∞
  16. // @name:de ChatGPT Unendlichkeit ∞
  17. // @name:dv ChatGPT ނުވަތަ ބާވައްޖޭގެން ∞
  18. // @name:dz ChatGPT རྩེད་སྒྲིབ་གཉིས་ ∞
  19. // @name:el ChatGPT Άπειρο ∞
  20. // @name:eo ChatGPT Infinito ∞
  21. // @name:es ChatGPT Infinito ∞
  22. // @name:et ChatGPT Lõpmatus ∞
  23. // @name:eu ChatGPT Infinitua ∞
  24. // @name:fa ChatGPT بینهایت ∞
  25. // @name:fi ChatGPT Ääretön ∞
  26. // @name:fo ChatGPT Óendanlighed ∞
  27. // @name:fr ChatGPT Infini ∞
  28. // @name:fr-CA ChatGPT Infini ∞
  29. // @name:gl ChatGPT Infinito ∞
  30. // @name:gu ChatGPT અનંત ∞
  31. // @name:haw ChatGPT Māhina ʻole ∞
  32. // @name:he ChatGPT אינסוף ∞
  33. // @name:hi ChatGPT अनंत ∞
  34. // @name:hr ChatGPT Beskrajnost ∞
  35. // @name:hu ChatGPT Végtelenség ∞
  36. // @name:hy ChatGPT Անվերջ ∞
  37. // @name:id ChatGPT Infinity ∞
  38. // @name:is ChatGPT Óendanleiki ∞
  39. // @name:it ChatGPT Infinito ∞
  40. // @name:ja ChatGPT 無限 ∞
  41. // @name:ka ChatGPT უსასრულობა ∞
  42. // @name:km ChatGPT អនឡាញ ∞
  43. // @name:kn ChatGPT ಅನಂತ ∞
  44. // @name:ko ChatGPT 무한 ∞
  45. // @name:ku ChatGPT Pêşangeh ∞
  46. // @name:ky ChatGPT Ички ∞
  47. // @name:la ChatGPT Infinitas ∞
  48. // @name:lb ChatGPT Unendlechkeet ∞
  49. // @name:lo ChatGPT ບໍ່ໄປສູ່ຈັກຂອງສາມຫວ່າງ ∞
  50. // @name:lt ChatGPT Begalybė ∞
  51. // @name:lv ChatGPT Bezgalība ∞
  52. // @name:mk ChatGPT Бесконечност ∞
  53. // @name:ml ChatGPT അനന്തത ∞
  54. // @name:mn ChatGPT Тэгш бус ∞
  55. // @name:mt ChatGPT Infinità ∞
  56. // @name:my ChatGPT မြင်ကွင်း ∞
  57. // @name:ne ChatGPT अनंत ∞
  58. // @name:nl ChatGPT Oneindigheid ∞
  59. // @name:no ChatGPT Uendelighet ∞
  60. // @name:pa ChatGPT ਇਨਫਿਨਿਟੀ ∞
  61. // @name:pl ChatGPT Nieskończoność ∞
  62. // @name:ps ChatGPT لامکان ∞
  63. // @name:pt ChatGPT Infinito ∞
  64. // @name:pt-BR ChatGPT Infinito ∞
  65. // @name:ro ChatGPT Infinitate ∞
  66. // @name:ru ChatGPT Бесконечность ∞
  67. // @name:si ChatGPT අනන්තය ∞
  68. // @name:sk ChatGPT Nekonečno ∞
  69. // @name:sl ChatGPT Neskončnost ∞
  70. // @name:so ChatGPT Qaybtiisa ∞
  71. // @name:sr ChatGPT Бескрајност ∞
  72. // @name:sv ChatGPT Oändlighet ∞
  73. // @name:ta ChatGPT முடிவிலிருந்து ∞
  74. // @name:te ChatGPT అనంతత ∞
  75. // @name:tg ChatGPT Беоҳӣ ∞
  76. // @name:th ChatGPT อนันต์ ∞
  77. // @name:ti ChatGPT መደመር ∞
  78. // @name:tk ChatGPT Sonsuzluk ∞
  79. // @name:tr ChatGPT Sonsuzluk ∞
  80. // @name:uk ChatGPT Нескінченність ∞
  81. // @name:ur ChatGPT بے انتہا ∞
  82. // @name:vi ChatGPT Vô cùng ∞
  83. // @name:yi ChatGPT אינפיניטי ∞
  84. // @name:zh ChatGPT 无限 ∞
  85. // @name:zh-CN ChatGPT 无限 ∞
  86. // @name:zh-HK ChatGPT 無限 ∞
  87. // @name:zh-SG ChatGPT 无限 ∞
  88. // @name:zh-TW ChatGPT 無限 ∞
  89. // @description Generate endless answers from all-knowing ChatGPT (in any language!)
  90. // @description:af Genereer eindelose antwoorde van die alwetende ChatGPT (in enige taal!)
  91. // @description:am ሓበሬታይ ኣይነበርና መልእኽቲ ኣለኹም ኣሎኻዊ ያልኣይት ChatGPT (በቋንቋ!)
  92. // @description:ar قم بتوليد إجابات لا نهائية من ChatGPT المعرف بكل شيء (بأي لغة!)
  93. // @description:az Hər şeyi bilən ChatGPT-dən sonsuz cavablar yaradın (hər hansı bir dil ilə!)
  94. // @description:be Стварыце бясконцы адказы ад ўсеведучага ChatGPT (на любой мове!)
  95. // @description:bem Pamene mwaposa mafolosho a mʌnoze ChatGPT (mu lupiya lwa ndalama!)
  96. // @description:bg Генерирайте безкрайни отговори от всезнайния ChatGPT (на всяк език!)
  97. // @description:bn সর্বজ্ঞ চ্যাটজিপিটি থেকে অসীম উত্তর তৈরি করুন (যে কোন ভাষায়!)
  98. // @description:bo བཟོས་པ་བརྗོད་པའི་ChatGPTགི་གྲོས་པར་འགྲུབ་འདེམས་བསྐྱེད་མི་འོངས་པ། (ལས་སྐབས་ཀྱི་སྐད་ཡིག་གི་སྐད་!)
  99. // @description:bs Generišite beskonačne odgovore od sveznajućeg ChatGPT (na bilo kom jeziku!)
  100. // @description:ca Genereu respostes infinites des de l'omniscient ChatGPT (en qualsevol idioma!)
  101. // @description:ceb Sukdagon ang walay katapusan nga mga tubag gikan sa tanan-mahibaw-anong ChatGPT (sa bisan unsang pinulongan!)
  102. // @description:ckb پێشبینی چاتگپتەکە دیارییەکانی پێکراوەکان بنووسە (بە هەر زمانێکی دیکە!)
  103. // @description:cs Generujte nekonečné odpovědi od vševědoucího ChatGPT (v jakémkoli jazyce!)
  104. // @description:cy Cynhyrchwch atebion diddiwedd o ChatGPT y gŵr sy'n gwybod popeth (mewn unrhyw iaith!)
  105. // @description:da Generer endeløse svar fra den altvidende ChatGPT (på hvilket som helst sprog!)
  106. // @description:de Generieren Sie endlose Antworten von dem allwissenden ChatGPT (in beliebiger Sprache!)
  107. // @description:dv އެހެނދުކަޗެއްވެސީ ޗެއްސިސްޓޯނަށް ނިޔަލައިފައިވަނީ ސުރުކޮށް ފީހުން (ކަންއެވެސް ހަމަވެސް!)
  108. // @description:dz ཆགས་ཀྱིས་ལ་བརྟེན་གང་རུང་གི་ChatGPTགི་ཚོགས་པའི་སྐད་ཡིག་གྱི་སྐད་ཡིག་བྱེད་པ། (བླ་མའི་སྐད་ཡིག་!)
  109. // @description:el Δημιουργήστε ατελείωτες απαντήσεις από το γνώστη ChatGPT (σε οποιαδήποτε γλώσσα!)
  110. // @description:eo Kreu nesfinaĵajn respondojn el la ĉio-scianta ChatGPT (en ajn lingvo!)
  111. // @description:es Genera respuestas infinitas desde el ChatGPT omnisciente (¡en cualquier idioma!)
  112. // @description:et Loo lõputuid vastuseid kõike-teadvast ChatGPT-st (mis tahes keeles!)
  113. // @description:eu Sortu erantzun infinituak guztiz-arduratsuaren ChatGPT-tik (edozein hizkuntzan!)
  114. // @description:fa پاسخهای بیپایانی را از ChatGPT همهدانا تولید کنید (به هر زبانی!)
  115. // @description:fi Luo loputtomia vastauksia kaikkitietävästä ChatGPT:stä (millä tahansa kielellä!)
  116. // @description:fo Skapa endalaus svør frá altvitandi ChatGPT (á hvørjum málrøð!)
  117. // @description:fr Générez des réponses infinies à partir de ChatGPT qui sait tout (dans n'importe quelle langue!)
  118. // @description:fr-CA Générez des réponses infinies à partir de ChatGPT qui sait tout (dans n'importe quelle langue!)
  119. // @description:gd Cruthaich freagairtean gun crìoch à ChatGPT a tha a' faighneachd gach càil (ann an sam bith cànan!)
  120. // @description:gl Xere as respostas infinitas do ChatGPT que todo o sabe (en calquera lingua!)
  121. // @description:gu જ્ઞાનવાન ChatGPT થી અનંત જવાબો ઉત્પન કરો (કોઈ પણ ભાષામાં!)
  122. // @description:haw Haleleʻa i nā ʻōlelo pālulelo mai ke kupa ʻike loa o ChatGPT (i loko o kēlā ʻōlelo aku aʻe!)
  123. // @description:he יצרו תשובות אינסופיות מה-ChatGPT המבין הכל (בכל שפה!)
  124. // @description:hi सभी-जाननेवाले चैटजीपीटी से अनंत उत्तरों का उत्पादन करें (किसी भी भाषा में!)
  125. // @description:hr Generirajte beskrajne odgovore iz sveznajućeg ChatGPT-a (na bilo kojem jeziku!)
  126. // @description:ht Jenere repons san fen soti nan ChatGPT k-ap konnen tout bagay yo (nan nenpòt lang!)
  127. // @description:hu Végtelen válaszokat generáljon a mindentudó ChatGPT-ből (bármely nyelven!)
  128. // @description:hy Ստեղծեք անսահմանափակ պատասխաններ ամենագիտական ChatGPT-ից (ցանկացած լեզուն մեջ!)
  129. // @description:id Hasilkan jawaban tak terbatas dari ChatGPT yang tahu segalanya (dalam bahasa apa pun!)
  130. // @description:is Búið til endalaus svör frá allvissu ChatGPT (á hvaða tungumáli sem er!)
  131. // @description:it Genera risposte infinite dall'onnisciente ChatGPT (in qualsiasi lingua!)
  132. // @description:ja あらゆる言語で全知のChatGPTから無限の回答を生成します!
  133. // @description:jv Mbukak panggung jawaban saka ChatGPT kang suwénéh kabèh (kénging basa apapun!)
  134. // @description:ka შექმენით უსასრულო პასუხები ყველგანაწილებული ChatGPT-დან (ნელა ენაზე!)
  135. // @description:kab Kkes-as yidir seg yisem-asen n tafriqt ara ddunnit ChatGPT (di tifrat ara ddunit!)
  136. // @description:kk Барлық тілде бар білген ChatGPT-ден шексіз жауаптар жасау (қандай да тілде!)
  137. // @description:km បង្កើតចម្លើយមិនឃើញចប់ពី ChatGPT ដែលចែកសង្ស័យទាំងអស់ (ជាន់គ្រប់ភាសា!)
  138. // @description:kn ಎಲ್ಲರು ತಿಳಿದಿರುವ ಚಾಟ್ಜಿಪಿಟಿಯಿಂದ ಅನಂತ ಉತ್ತರಗಳನ್ನು ರಚಿಸಿ (ಯಾವುದೇ ಭಾಷೆಯಲ್ಲಿ!)
  139. // @description:ko 어떤 언어로든지 무궁무진한 답변을 만들어내는 ChatGPT입니다!
  140. // @description:ku Ji ChatGPT-ê, ku hemî tiştan dizane, bersiva li serbazên li dor qewî yên hilbijartin (bi hertiştî zimanek!)
  141. // @description:ky Түз билимдүү ChatGPT боюнча чыгармаларды жаса
  142. // @description:la Genera infinitas responsiones de ChatGPT omniscio (in qualibet lingua!)
  143. // @description:lb Generéiert endlos Äntwerten vum allwëssende ChatGPT (op jiddere Sprooch!)
  144. // @description:lo ສ້າງຜົນສົດທີ່ສາມາດເລືອກຈາກພາສາທີ່ຮູ້ບຸກກຳລັງ ChatGPT (ໃນພາສາໃດໜຶ່ງ!)
  145. // @description:lt Sugeneruokite begalinį atsakymų kiekį iš visai žinoančio ChatGPT (bet kuria kalba!)
  146. // @description:lv Ģenerē nebeidzamus atbilžu variantus no vissapratīgā ChatGPT (jebkurā valodā!)
  147. // @description:mg Mandoza ny valiny miaraka amin'ny ChatGPT mahalala ny zavatra rehetra (amin'ny fiteny iray kokoa!)
  148. // @description:mi Whakapūmau i ngā whakautu kore mutunga mai i te ChatGPT matau i ngā reo katoa!
  149. // @description:mk Генерирајте безброј одговори од сèзнаената ChatGPT (на било кој јазик!)
  150. // @description:ml എന്നെഴുതാൻ അനന്യനായ ChatGPT (ഏതെങ്കിലും ഭാഷയിൽ) ഇന്നേക്കും വേണ്ടി അവസാനിപ്പിക്കുക!
  151. // @description:mn Сүүлд үлдсэнээсээ хайрцаг болох ChatGPT (ямар ч хэл дээр) дээрхээр ярих
  152. // @description:ms Cipta pelbagai jawapan daripada ChatGPT yang tahu segala-galanya (dalam apa-apa bahasa!)
  153. // @description:mt Iġġenera risposti infiniti mill-ChatGPT li kollha jaf (f'xi lingwa!)
  154. // @description:my အားလုံးကိုသင်ရိုးရိုးဆွဲနိုင်သည့် ChatGPT (တစ်ခုမှာယူသုံးရန်!)
  155. // @description:ne सबै-ज्ञानी ChatGPT बाट अनंत उत्तरहरू उत्पन्न गर्नुहोस् (कुनै पनि भाषामा!)
  156. // @description:nl Genereer eindeloze antwoorden van alwetende ChatGPT (in elke taal!)
  157. // @description:no Generer endeløse svar fra allvitende ChatGPT (på hvilket som helst språk!)
  158. // @description:ny Galimoto mabwino a mtendere zosiyanasiyana kuchokera ku ChatGPT woyankhula zonse! (muyankhulitsa chilichonse!)
  159. // @description:pa ਸਭ ਜਾਣ ਵਾਲੇ ChatGPT ਤੋਂ ਲੰਬੇ ਉੱਤਰਾਂ ਨੂੰ ਬਣਾਓ (ਕਿਸੇ ਵੀ ਭਾਸ਼ਾ ਵਿੱਚ!)
  160. // @description:pap Hasi respuesta sinfin di ChatGPT ku tur sabi (na kua idioma!)
  161. // @description:pl Generuj nieskończone odpowiedzi od wszechwiedzącego ChatGPT (w dowolnym języku!)
  162. // @description:ps د هغوی چټکال ChatGPT لخوا نهایت جوابونه جوړه کړئ (د هر یوه ژبه کی!)
  163. // @description:pt Gere respostas infinitas do ChatGPT onisciente (em qualquer idioma!)
  164. // @description:pt-BR Gere respostas infinitas do ChatGPT onisciente (em qualquer idioma!)
  165. // @description:rn Basha inzira nk'itandukanye z'uko ChatGPT uzi (mu rurimi rwose!)
  166. // @description:ro Generează răspunsuri infinite de la ChatGPT omniscient (în orice limbă!)
  167. // @description:ru Генерируйте бесконечные ответы от всезнающего ChatGPT (на любом языке!)
  168. // @description:rw Banda inama z'imirimo isigaye zose z'umuco wa ChatGPT (mu rurimi rwose!)
  169. // @description:sg Tia ngamana nga mbetela ti ChatGPT tozuwa mitayi mingi (po wundi ndimi yo ngambo!)
  170. // @description:si සියළු දැනටමත් සහතිකපත්කරන තවත් සිතියම් සැකසුම් ලබා දෙන්නාවූ ChatGPT සෑදීම (ඕනෑම භාෂාවෙන්ම!)
  171. // @description:sk Generujte nekonečné odpovede od vševietajúceho ChatGPT (v akomkoľvek jazyku!)
  172. // @description:sl Generirajte neskončne odgovore iz vsevednega ChatGPT (v katerem koli jeziku!)
  173. // @description:sm Faia se faiga tele i le ChatGPT eseese (i nisi gagana!)
  174. // @description:sn Simudza mhinduro dzakawanda kubva kune ChatGPT ichiwanikwa chisarudzo! (mune rimwe nguva!)
  175. // @description:so Kor u qaado jawaabo kala duwan oo ka soo saar ChatGPT (luuqad ka mid ah!)
  176. // @description:sr Генеришите безброј одговора од свемоћног ChatGPT (на било ком језику!)
  177. // @description:sv Generera oändliga svar från allvetande ChatGPT (på valfritt språk!)
  178. // @description:sw Toa majibu yasiyokuwa na mwisho kutoka kwa ChatGPT mwenye maarifa yote (katika lugha yoyote!)
  179. // @description:ta அனைத்து தகவலையும் அறியப்பட்ட சொந்தமான ChatGPT இலிருந்து முடிவுகளை உருவாக்கவும் (எந்த மொழியிலும்!)
  180. // @description:te అన్నింటినీకింట మాటలు రాయండి ChatGPT గురించి అనేక జవాబాలను సృష్టించండి (ఏదైనా భాషలో!)
  181. // @description:tg Ҷавобҳои бесуданни ChatGPTи ҳамаифақат (дар як забони муайяни!)
  182. // @description:th สร้างคำตอบไม่สิ้นสุดจาก ChatGPT ที่รู้ทุกสิ่ง (ในภาษาใดก็ได้!)
  183. // @description:ti ክርስትን ለማውጣት ከገጽታውን ChatGPT የተከሳሽ አስተካክል አስተካክሎት (በእውነት ቋንቋ!)
  184. // @description:tk Şeýle anlaşylýan ChatGPT (her hili üçin) arasyndan bäşmüňhat jawaplar döret
  185. // @description:tn Hlela zitsha zwine zwiṱhiselela kha ChatGPT vhufudziṱe (muvhili wo vha u ite!)
  186. // @description:to Fakatonutonu ʻihe ngāuekesi mei he ChatGPT fakaongoongo toenga (i he lea faka-Tonga ia!)
  187. // @description:tpi Sanapim hamamasples long save olsem ChatGPT i masples (long wanpela tok ples!)
  188. // @description:tr Bilge ChatGPT'den sonsuz cevaplar üret (herhangi bir dilde!)
  189. // @description:uk Генеруйте безкінечні відповіді від усезнаючого ChatGPT (на будь-якій мові!)
  190. // @description:ur سب جاننے والے ChatGPT سے لامتناہی جوابات پیدا کریں (کسی بھی زبان میں!)
  191. // @description:uz Barcha biladigan ChatGPT dan cheklovli javoblar oling (hech qanday tilda ham)!
  192. // @description:vi Tạo ra vô số câu trả lời từ ChatGPT thông minh (bằng bất kỳ ngôn ngữ nào!)
  193. // @description:xh Bhala izinto ezingekwaziyo eziyimfihlo kusuka ku ChatGPT (ngolwimi lwanyanetha!)
  194. // @description:yi דזשענערייט סאָף ענטפֿערס פֿון אַלע-געוויסן ChatGPT (אין קיין שפּראַך!)
  195. // @description:zh 从无所不知的 ChatGPT 生成无穷无尽的答案 (用任何语言!)
  196. // @description:zh-CN 从无所不知的 ChatGPT 生成无穷无尽的答案 (用任何语言!)
  197. // @description:zh-HK 從無所不知的 ChatGPT 生成無窮無盡的答案 (用任何語言!)
  198. // @description:zh-SG 从无所不知的 ChatGPT 生成无穷无尽的答案 (用任何语言!)
  199. // @description:zh-TW 從無所不知的 ChatGPT 生成無窮無盡的答案 (用任何語言!)
  200. // @author Adam Lui
  201. // @namespace https://github.com/adamlui
  202. // @version 2024.10.20.2
  203. // @license MIT
  204. // @match *://chatgpt.com/*
  205. // @match *://chat.openai.com/*
  206. // @icon https://media.chatgptinfinity.com/images/icons/infinity-symbol/circled/with-robot/icon48.png?f196818
  207. // @icon64 https://media.chatgptinfinity.com/images/icons/infinity-symbol/circled/with-robot/icon64.png?f196818
  208. // @compatible chrome
  209. // @compatible firefox
  210. // @compatible edge
  211. // @compatible opera
  212. // @compatible brave
  213. // @compatible vivaldi
  214. // @compatible waterfox
  215. // @compatible librewolf
  216. // @compatible ghost
  217. // @compatible qq
  218. // @compatible whale
  219. // @compatible kiwi
  220. // @require https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js@3.3.5/dist/chatgpt.min.js#sha256-rfC4kk8q0byrafp7X0Qf9vaa3JNvkHRwNnUt6uL2hUE=
  221. // @require https://cdn.jsdelivr.net/gh/adamlui/chatgpt-infinity@a0d6630c225f26ae7cd5ccd1fda39bc45177bebc/chrome/extension/lib/dom.js#sha256-pbJ15rhD5UtxxSCn+L0ybKnlrT3SNm3t8Dc99qtN4KQ=
  222. // @connect cdn.jsdelivr.net
  223. // @connect update.greatest.deepsurf.us
  224. // @grant GM_setValue
  225. // @grant GM_getValue
  226. // @grant GM_registerMenuCommand
  227. // @grant GM_unregisterMenuCommand
  228. // @grant GM_xmlhttpRequest
  229. // @grant GM.xmlHttpRequest
  230. // @noframes
  231. // @homepageURL https://www.chatgptinfinity.com
  232. // @supportURL https://support.chatgptinfinity.com
  233. // @contributionURL https://github.com/sponsors/adamlui
  234. // ==/UserScript==
  235. // Documentation: https://docs.chatgptinfinity.com
  236. // NOTE: This script relies on the powerful chatgpt.js library @ https://chatgpt.js.org © 2023–2024 KudoAI & contributors under the MIT license.
  237. (async () => {
  238. // Init ENV vars
  239. const env = {
  240. browser: { isMobile: chatgpt.browser.isMobile(), isFF: chatgpt.browser.isFirefox() },
  241. scriptManager: (() => { try { return GM_info.scriptHandler } catch (err) { return 'unknown' }})()
  242. }
  243. const xhr = env.scriptManager == 'OrangeMonkey' ? GM_xmlhttpRequest : GM.xmlHttpRequest
  244. // Init APP info
  245. const app = { configKeyPrefix: 'chatGPTinfinity', latestAssetCommitHash: '0d8badd' },
  246. assetHostURL = `https://cdn.jsdelivr.net/gh/adamlui/chatgpt-infinity@${app.latestAssetCommitHash}`
  247. Object.assign(app, await new Promise(resolve => xhr({
  248. method: 'GET', url: `${assetHostURL}/app.json`,
  249. onload: resp => resolve(JSON.parse(resp.responseText))
  250. })))
  251. app.urls.update = app.urls.greasyFork.replace('https://', 'https://update.')
  252. .replace(/(\d+)-?([a-zA-Z-]*)$/, (_, id, name) => `${id}/${ name || 'script' }.meta.js`)
  253. // Init CONFIG
  254. const config = { userLanguage: chatgpt.getUserLanguage() }
  255. const settings = {
  256. load(...keys) {
  257. if (Array.isArray(keys[0])) keys = keys[0] // use 1st array arg, else all comma-separated ones
  258. keys.forEach(key => config[key] = GM_getValue(app.configKeyPrefix + '_' + key, false))
  259. },
  260. save(key, value) { GM_setValue(app.configKeyPrefix + '_' + key, value) ; config[key] = value }
  261. } ; settings.load('autoScrollDisabled', 'autoStart', 'replyInterval', 'replyLanguage', 'replyTopic', 'toggleHidden')
  262. if (!config.replyLanguage) settings.save('replyLanguage', config.userLanguage) // init reply language if unset
  263. if (!config.replyTopic) settings.save('replyTopic', 'ALL') // init reply topic if unset
  264. if (!config.replyInterval) settings.save('replyInterval', 7) // init refresh interval to 7 secs if unset
  265. // Init app MESSAGES
  266. app.msgs = {
  267. appName: app.name,
  268. appAuthor: app.author.name,
  269. appDesc: 'Generate endless answers from all-knowing ChatGPT (in any language!)',
  270. menuLabel_infinityMode: 'Infinity Mode',
  271. menuLabel_autoStart: 'Auto-Start',
  272. menuLabel_toggleVis: 'Toggle Visibility',
  273. menuLabel_autoScroll: 'Auto-Scroll',
  274. menuLabel_replyLang: 'Reply Language',
  275. menuLabel_replyTopic: 'Reply Topic',
  276. menuLabel_all: 'ALL',
  277. menuLabel_replyInt: 'Reply Interval',
  278. menuLabel_about: 'About',
  279. menuLabel_donate: 'Please send a donation',
  280. menuLabel_disabled: 'Disabled (extension installed)',
  281. about_version: 'Version',
  282. about_poweredBy: 'Powered by',
  283. about_sourceCode: 'Source code',
  284. prompt_updateReplyLang: 'Update reply language',
  285. prompt_updateReplyTopic: 'Update reply topic',
  286. prompt_orEnter: 'or enter',
  287. prompt_updateReplyInt: 'Update reply interval (minimum 5 secs)',
  288. alert_replyLangUpdated: 'Language updated',
  289. alert_willReplyIn: 'will reply in',
  290. alert_yourSysLang: 'your system language',
  291. alert_replyTopicUpdated: 'Topic updated',
  292. alert_willAnswer: 'will answer questions',
  293. alert_onTopicOf: 'on the topic of',
  294. alert_onAllTopics: 'on ALL topics',
  295. alert_replyIntUpdated: 'Interval updated',
  296. alert_willReplyEvery: 'will reply every',
  297. alert_choosePlatform: 'Choose a platform',
  298. alert_updateAvail: 'Update available',
  299. alert_newerVer: 'An update to',
  300. alert_isAvail: 'is available',
  301. alert_upToDate: 'Up-to-date',
  302. alert_isUpToDate: 'is up-to-date',
  303. alert_showYourSupport: 'Show your support',
  304. alert_isOSS: 'is open-source software built & maintained for free through 100% volunteer efforts',
  305. alert_despiteAffliction: 'Despite being severely afflicted by',
  306. alert_longCOVID: 'long COVID',
  307. alert_since2020: 'since 2020',
  308. alert_byDonatingResults: 'by donating, you help me to continue improving, fixing bugs, adding new features, and making the software even better',
  309. alert_yourContrib: 'Your contribution',
  310. alert_noMatterSize: 'no matter the size',
  311. alert_directlySupports: 'directly supports my unpaid efforts to ensure this project remains free and open for all to use',
  312. alert_tyForSupport: 'Thank you for your support',
  313. alert_author: 'author',
  314. btnLabel_moreApps: 'More ChatGPT Apps',
  315. btnLabel_rateUs: 'Rate Us',
  316. btnLabel_getSupport: 'Get Support',
  317. btnLabel_updateCheck: 'Check for Updates',
  318. btnLabel_update: 'Update',
  319. btnLabel_dismiss: 'Dismiss',
  320. link_viewChanges: 'View changes',
  321. unit_seconds: 'seconds',
  322. state_enabled: 'enabled',
  323. state_disabled: 'disabled',
  324. state_on: 'on',
  325. state_off: 'off'
  326. }
  327. if (!config.userLanguage.startsWith('en')) { // localize msgs for non-English users
  328. const localizedMsgs = await new Promise(resolve => {
  329. const msgHostDir = assetHostURL + '/chrome/extension/_locales/',
  330. msgLocaleDir = ( config.userLanguage ? config.userLanguage.replace('-', '_') : 'en' ) + '/'
  331. let msgHref = msgHostDir + msgLocaleDir + 'messages.json', msgXHRtries = 0
  332. function fetchMsgs() { xhr({ method: 'GET', url: msgHref, onload: handleMsgs })}
  333. function handleMsgs(resp) {
  334. try { // to return localized messages.json
  335. const msgs = JSON.parse(resp.responseText), flatMsgs = {}
  336. for (const key in msgs) // remove need to ref nested keys
  337. if (typeof msgs[key] == 'object' && 'message' in msgs[key])
  338. flatMsgs[key] = msgs[key].message
  339. resolve(flatMsgs)
  340. } catch (err) { // if bad response
  341. msgXHRtries++ ; if (msgXHRtries == 3) return resolve({}) // try up to 3X (original/region-stripped/EN) only
  342. msgHref = config.userLanguage.includes('-') && msgXHRtries == 1 ? // if regional lang on 1st try...
  343. msgHref.replace(/([^_]+_[^_]+)_[^/]*(\/.*)/, '$1$2') // ...strip region before retrying
  344. : ( msgHostDir + 'en/messages.json' ) // else use default English messages
  345. fetchMsgs()
  346. }
  347. }
  348. fetchMsgs()
  349. })
  350. Object.assign(app.msgs, localizedMsgs)
  351. }
  352. // Init SETTINGS props
  353. Object.assign(app, { settings: {
  354. autoStart: { type: 'toggle', label: app.msgs.menuLabel_autoStart },
  355. toggleHidden: { type: 'toggle', label: app.msgs.menuLabel_toggleVis },
  356. autoScrollDisabled: { type: 'toggle', label: app.msgs.menuLabel_autoScroll },
  357. replyLanguage: { type: 'prompt', symbol: '🌐', label: app.msgs.menuLabel_replyLang },
  358. replyTopic: { type: 'prompt', symbol: '🧠', label: app.msgs.menuLabel_replyTopic },
  359. replyInterval: { type: 'prompt', symbol: '⌚', label: app.msgs.menuLabel_replyInt }
  360. }})
  361. // Define MENU functions
  362. const menu = {
  363. ids: [], state: {
  364. symbols: ['❌', '✔️'], separator: env.scriptManager == 'Tampermonkey' ? ' — ' : ': ',
  365. words: [app.msgs.state_off.toUpperCase(), app.msgs.state_on.toUpperCase()]
  366. },
  367. register() {
  368. // Init prompt setting status labels
  369. const re_all = new RegExp(`^(${app.msgs.menuLabel_all}|all|any|every)$`, 'i')
  370. app.settings.replyLanguage.status = config.replyLanguage
  371. app.settings.replyTopic.status = re_all.test(config.replyTopic) ? app.msgs.menuLabel_all : toTitleCase(config.replyTopic)
  372. app.settings.replyInterval.status = `${config.replyInterval}s`
  373. // Add Infinity Mode toggle
  374. const imLabel = `${menu.state.symbols[+!!config.infinityMode]} `
  375. + `${app.msgs.menuLabel_infinityMode} `
  376. + menu.state.separator + menu.state.words[+!!config.infinityMode]
  377. menu.ids.push(GM_registerMenuCommand(imLabel, () => { document.getElementById('infinity-toggle-label').click() }))
  378. // Add setting entries
  379. Object.keys(app.settings).forEach(key => {
  380. const settingIsEnabled = config[key] ^ /disabled|hidden/i.test(key),
  381. menuLabel = `${ app.settings[key].symbol || menu.state.symbols[+settingIsEnabled] } ${app.settings[key].label}`
  382. + ( app.settings[key].type == 'toggle' ? ( menu.state.separator + menu.state.words[+settingIsEnabled] )
  383. : `— ${app.settings[key].status}` )
  384. menu.ids.push(GM_registerMenuCommand(menuLabel, () => {
  385. if (key == 'replyLanguage') {
  386. while (true) {
  387. let replyLanguage = prompt(
  388. `${app.msgs.prompt_updateReplyLang}:`, config.replyLanguage)
  389. if (replyLanguage === null) break // user cancelled so do nothing
  390. else if (!/\d/.test(replyLanguage)) {
  391. replyLanguage = ( // auto-case for menu/alert aesthetics
  392. [2, 3].includes(replyLanguage.length) || replyLanguage.includes('-') ? replyLanguage.toUpperCase()
  393. : replyLanguage.charAt(0).toUpperCase() + replyLanguage.slice(1).toLowerCase() )
  394. settings.save('replyLanguage', replyLanguage || config.userLanguage)
  395. siteAlert(( app.msgs.alert_replyLangUpdated ) + '!', // title
  396. ( app.msgs.appName ) + ' ' // msg
  397. + ( app.msgs.alert_willReplyIn ) + ' '
  398. + ( replyLanguage || app.msgs.alert_yourSysLang) + '.')
  399. if (config.infinityMode) infinity.restart({ target: 'new' }) // using new reply language
  400. break
  401. }
  402. }
  403. } else if (key == 'replyTopic') {
  404. const replyTopic = prompt(( app.msgs.prompt_updateReplyTopic )
  405. + ' (' + ( app.msgs.prompt_orEnter ) + ' \'ALL\'):', config.replyTopic)
  406. if (replyTopic !== null) { // user didn't cancel
  407. const str_replyTopic = replyTopic.toString()
  408. settings.save('replyTopic', !replyTopic || re_all.test(str_replyTopic) ? 'ALL' : str_replyTopic)
  409. siteAlert(( app.msgs.alert_replyTopicUpdated ) + '!',
  410. ( app.msgs.appName ) + ' '
  411. + ( app.msgs.alert_willAnswer ) + ' '
  412. + ( !replyTopic || re_all.test(str_replyTopic)
  413. ? app.msgs.alert_onAllTopics
  414. : (( app.msgs.alert_onTopicOf ) + ' ' + str_replyTopic ))
  415. + '!'
  416. )
  417. if (config.infinityMode) { // restart session using new reply topic
  418. chatgpt.stop() ; document.getElementById('infinity-toggle-label').click() // toggle off
  419. setTimeout(() => { document.getElementById('infinity-toggle-label').click() }, 500) // toggle on
  420. }
  421. }
  422. } else if (key == 'replyInterval') {
  423. while (true) {
  424. const replyInterval = prompt(
  425. `${app.msgs.prompt_updateReplyInt}:`, config.replyInterval)
  426. if (replyInterval === null) break // user cancelled so do nothing
  427. else if (!isNaN(parseInt(replyInterval, 10)) && parseInt(replyInterval, 10) > 4) { // valid int set
  428. settings.save('replyInterval', parseInt(replyInterval, 10))
  429. siteAlert(( app.msgs.alert_replyIntUpdated ) + '!', // title
  430. ( app.msgs.appName ) + ' ' // msg
  431. + ( app.msgs.alert_willReplyEvery ) + ' '
  432. + replyInterval + ' ' + ( app.msgs.unit_seconds ) + '.')
  433. if (config.infinityMode) infinity.restart({ target: 'self' }) // using new reply interval
  434. break
  435. }
  436. }
  437. } else { // save toggled state + notify
  438. settings.save(key, !config[key])
  439. notify(`${app.settings[key].label}: ${menu.state.words[+(/disabled|hidden/i.test(key) ^ config[key])]}`)
  440. }
  441. syncConfigToUI()
  442. }))
  443. })
  444. // Add About entry
  445. const aboutLabel = `💡 ${app.msgs.menuLabel_about} ${app.msgs.appName}`
  446. menu.ids.push(GM_registerMenuCommand(aboutLabel, modals.about.show))
  447. // Add Donate entry
  448. const donateLabel = `💖 ${app.msgs.menuLabel_donate}`
  449. menu.ids.push(GM_registerMenuCommand(donateLabel, modals.donate.show))
  450. },
  451. refresh() {
  452. if (env.scriptManager == 'OrangeMonkey') return
  453. for (const id of menu.ids) { GM_unregisterMenuCommand(id) } menu.register()
  454. }
  455. }
  456. function updateCheck() {
  457. // Fetch latest meta
  458. const currentVer = GM_info.script.version
  459. xhr({
  460. method: 'GET', url: app.urls.update + '?t=' + Date.now(),
  461. headers: { 'Cache-Control': 'no-cache' },
  462. onload: response => { const updateAlertWidth = 377
  463. // Compare versions
  464. const latestVer = /@version +(.*)/.exec(response.responseText)[1]
  465. for (let i = 0 ; i < 4 ; i++) { // loop thru subver's
  466. const currentSubVer = parseInt(currentVer.split('.')[i], 10) || 0,
  467. latestSubVer = parseInt(latestVer.split('.')[i], 10) || 0
  468. if (currentSubVer > latestSubVer) break // out of comparison since not outdated
  469. else if (latestSubVer > currentSubVer) { // if outdated
  470. // Alert to update
  471. const updateModalID = siteAlert(`🚀 ${app.msgs.alert_updateAvail}!`, // title
  472. `${app.msgs.alert_newerVer} ${app.msgs.appName} `
  473. + `(v${latestVer}) ${app.msgs.alert_isAvail}! `
  474. + '<a target="_blank" rel="noopener" style="font-size: 0.7rem" '
  475. + 'href="' + app.urls.gitHub + '/commits/main/greasemonkey/'
  476. + app.urls.update.replace(/.*\/(.*)meta\.js/, '$1user.js') + '"'
  477. + `> ${app.msgs.link_viewChanges}</a>`,
  478. function update() { // button
  479. modals.safeWinOpen(app.urls.update.replace('meta.js', 'user.js') + '?t=' + Date.now())
  480. }, '', updateAlertWidth
  481. )
  482. // Localize button labels if needed
  483. if (!config.userLanguage.startsWith('en')) {
  484. const updateAlert = document.querySelector(`[id="${updateModalID}"]`),
  485. updateBtns = updateAlert.querySelectorAll('button')
  486. updateBtns[1].textContent = app.msgs.btnLabel_update
  487. updateBtns[0].textContent = app.msgs.btnLabel_dismiss
  488. }
  489. return
  490. }}
  491. // Alert to no update, return to About modal
  492. siteAlert(`${app.msgs.alert_upToDate}!`, // title
  493. `${app.msgs.appName} (v${currentVer}) ${app.msgs.alert_isUpToDate}!`, // msg
  494. '', '', updateAlertWidth
  495. )
  496. modals.about.show()
  497. }})}
  498. function toTitleCase(str) {
  499. const words = str.toLowerCase().split(' ')
  500. for (let i = 0 ; i < words.length ; i++) // for each word
  501. words[i] = words[i][0].toUpperCase() + words[i].slice(1) // title-case it
  502. return words.join(' ') // join'em back together
  503. }
  504. // Define FEEDBACK functions
  505. function notify(msg, pos = '', notifDuration = '', shadow = '') {
  506. // Strip state word to append colored one later
  507. const foundState = menu.state.words.find(word => msg.includes(word))
  508. if (foundState) msg = msg.replace(foundState, '')
  509. // Show notification
  510. chatgpt.notify(`${app.symbol} ${msg}`, pos, notifDuration, shadow || chatgpt.isDarkMode() ? '' : 'shadow')
  511. const notif = document.querySelector('.chatgpt-notif:last-child')
  512. // Append styled state word
  513. if (foundState) {
  514. const styledState = document.createElement('span')
  515. styledState.style.cssText = `color: ${
  516. foundState == menu.state.words[0] ? '#ef4848 ; text-shadow: rgba(255, 169, 225, 0.44) 2px 1px 5px'
  517. : '#5cef48 ; text-shadow: rgba(255, 250, 169, 0.38) 2px 1px 5px' }`
  518. styledState.append(foundState) ; notif.append(styledState)
  519. }
  520. }
  521. function siteAlert(title = '', msg = '', btns = '', checkbox = '', width = '') {
  522. return chatgpt.alert(title, msg, btns, checkbox, width )}
  523. // Define MODAL functions
  524. const modals = {
  525. stack: [],
  526. about: {
  527. show() {
  528. modals.stack.unshift('about') ; modals.stack = [...new Set(modals.stack)] // track for nav
  529. // Show alert
  530. const chatgptJSver = (/chatgpt-([\d.]+)\.min/.exec(GM_info.script.header) || [null, ''])[1],
  531. headingStyle = 'font-size: 1.15rem',
  532. pStyle = 'position: relative ; left: 3px',
  533. pBrStyle = 'position: relative ; left: 4px ',
  534. aStyle = 'color: ' + ( chatgpt.isDarkMode() ? '#c67afb' : '#8325c4' ) // purple
  535. const aboutModalID = siteAlert(
  536. app.msgs.appName, // title
  537. `<span style="${headingStyle}"><b>🏷️ <i>${app.msgs.about_version}</i></b>: </span>`
  538. + `<span style="${pStyle}">${GM_info.script.version}</span>\n`
  539. + `<span style="${headingStyle}"><b>⚡ <i>${app.msgs.about_poweredBy}</i></b>: </span>`
  540. + `<span style="${pStyle}"><a style="${aStyle}" href="${app.urls.chatgptJS}" target="_blank" rel="noopener">`
  541. + 'chatgpt.js</a>' + ( chatgptJSver ? ( ' v' + chatgptJSver ) : '' ) + '</span>\n'
  542. + `<span style="${headingStyle}"><b>📜 <i>${app.msgs.about_sourceCode}</i></b>:</span>\n`
  543. + `<span style="${pBrStyle}"><a href="${app.urls.gitHub}" target="_blank" rel="nopener">`
  544. + app.urls.gitHub + '</a></span>',
  545. [ // buttons
  546. function checkForUpdates() { updateCheck() },
  547. function getSupport() { modals.safeWinOpen(app.urls.support) },
  548. function rateUs() { modals.feedback.show() },
  549. function moreChatGPTapps() { modals.safeWinOpen(app.urls.relatedApps) }
  550. ], '', 478 // set width
  551. )
  552. // Re-format buttons to include emoji + localized label + hide Dismiss button
  553. for (const button of document.getElementById(aboutModalID).querySelectorAll('button')) {
  554. button.style.cssText = 'cursor: pointer !important' // since tweaks won't load on auto-disable
  555. if (/updates/i.test(button.textContent)) button.textContent = (
  556. '🚀 ' + ( app.msgs.btnLabel_updateCheck ))
  557. else if (/support/i.test(button.textContent)) button.textContent = (
  558. '🧠 ' + ( app.msgs.btnLabel_getSupport ))
  559. else if (/rate/i.test(button.textContent)) button.textContent = (
  560. '⭐ ' + ( app.msgs.btnLabel_rateUs ))
  561. else if (/apps/i.test(button.textContent)) button.textContent = (
  562. '🤖 ' + ( app.msgs.btnLabel_moreApps ))
  563. else button.style.display = 'none' // hide Dismiss button
  564. }
  565. }
  566. },
  567. donate: {
  568. longCOVIDwikiLink: 'https://en.wikipedia.org/wiki/Long_COVID',
  569. show() {
  570. modals.stack.unshift('donate') ; modals.stack = [...new Set(modals.stack)] // track for nav
  571. // Show alert
  572. const donateModalID = siteAlert(
  573. `💖 ${app.msgs.alert_showYourSupport}`, // title
  574. `<p>${app.msgs.appName} ${app.msgs.alert_isOSS}.</p>`
  575. + `<p>${app.msgs.alert_despiteAffliction} `
  576. + `<a target="_blank" rel="noopener" href="${modals.donate.longCOVIDwikiLink}">${app.msgs.alert_longCOVID}</a> `
  577. + `${app.msgs.alert_since2020}, ${app.msgs.alert_byDonatingResults}.</p>`
  578. + `<p>${app.msgs.alert_yourContrib}, <b>${app.msgs.alert_noMatterSize}</b>, ${app.msgs.alert_directlySupports}.</p>`
  579. + `<p>${app.msgs.alert_tyForSupport}!</p>`
  580. + `<img src="https://cdn.jsdelivr.net/gh/adamlui/adamlui/images/siggie/${ chatgpt.isDarkMode() ? 'white' : 'black' }.png"`
  581. + ' style="height: 54px ; margin: 5px 0 -2px 5px"></img>'
  582. + `<p>—<b><a target="_blank" rel="noopener" href="${app.author.url}">${app.msgs.appAuthor}</a></b>, ${app.msgs.alert_author}</p>`,
  583. [ // buttons
  584. function paypal() { modals.safeWinOpen(app.urls.donate.payPal) },
  585. function githubSponsors() { modals.safeWinOpen(app.urls.donate.gitHub) },
  586. function cashApp() { modals.safeWinOpen(app.urls.donate.cashApp) },
  587. function rateUs() { modals.feedback.show() }
  588. ], '', 478 // set width
  589. )
  590. // Format text
  591. const donateModal = document.getElementById(donateModalID)
  592. donateModal.querySelectorAll('p').forEach(p => // v-pad text, shrink line height
  593. p.style.cssText = 'padding: 8px 0 ; line-height: 20px')
  594. // Format buttons
  595. const btns = donateModal.querySelectorAll('button')
  596. btns.forEach((btn, idx) => {
  597. if (idx == 0) btn.style.display = 'none' // hide Dismiss button
  598. else {
  599. btn.style.cssText = 'padding: 8px 6px !important ; margin-top: -14px ; width: 107px ; line-height: 14px'
  600. if (idx == btns.length -1) // de-emphasize right-most button
  601. btn.classList.remove('primary-modal-btn')
  602. else if (/rate/i.test(btn.textContent)) // localize 'Rate Us' label
  603. btn.textContent = app.msgs.btnLabel_rateUs
  604. }
  605. })
  606. }
  607. },
  608. feedback: {
  609. show() {
  610. const reviewModalID = chatgpt.alert(
  611. `${app.msgs.alert_choosePlatform}:`, '', // title
  612. [ // buttons
  613. function greasyFork() { modals.safeWinOpen(app.urls.review.greasyFork) },
  614. function productHunt() { modals.safeWinOpen(app.urls.review.productHunt) },
  615. function alternativeTo() { modals.safeWinOpen(app.urls.review.alternativeTo) }
  616. ]
  617. )
  618. const reviewModal = document.getElementById(reviewModalID)
  619. reviewModal.querySelector('button').style.display = 'none' // hide Dismiss button
  620. reviewModal.addEventListener('DOMNodeRemoved', () => modals[modals.stack[0]]?.show() ) // nav back on btn/bg clicks
  621. }
  622. },
  623. safeWinOpen(url) { open(url, '_blank', 'noopener') } // to prevent backdoor vulnerabilities
  624. }
  625. // Define UI functions
  626. const navToggle = {
  627. insert() {
  628. // Insert toggle
  629. const toggleParent = document.querySelector('nav')
  630. if (!toggleParent.contains(navToggleDiv))
  631. toggleParent.insertBefore(navToggleDiv, toggleParent.children[1])
  632. // Tweak styles
  633. const knobSpan = document.getElementById('infinity-toggle-knob-span'),
  634. navicon = document.getElementById('infinity-toggle-navicon')
  635. navToggleDiv.style.flexGrow = 'unset' // overcome OpenAI .grow
  636. navToggleDiv.style.paddingLeft = '8px'
  637. if (knobSpan) knobSpan.style.boxShadow = (
  638. 'rgba(0, 0, 0, .3) 0 1px 2px 0' + ( chatgpt.isDarkMode() ? ', rgba(0, 0, 0, .15) 0 3px 6px 2px' : '' ))
  639. if (navicon) navicon.src = `${ // update navicon color in case scheme changed
  640. app.urls.mediaHost}/images/icons/infinity-symbol/`
  641. + `${ chatgpt.isDarkMode() ? 'white' : 'black' }/icon32.png?${app.latestAssetCommitHash}`
  642. },
  643. update() {
  644. if (config.toggleHidden) navToggleDiv.style.display = 'none'
  645. else {
  646. // Create/size/position navicon
  647. const navicon = document.getElementById('infinity-toggle-navicon')
  648. || dom.create.elem('img', { id: 'infinity-toggle-navicon' })
  649. navicon.style.width = navicon.style.height = '1.25rem'
  650. navicon.style.marginLeft = '2px' ; navicon.style.marginRight = '4px'
  651. // Create/ID/disable/hide/update checkbox
  652. const toggleInput = document.getElementById('infinity-toggle-input')
  653. || dom.create.elem('input', { id: 'infinity-toggle-input', type: 'checkbox', disabled: true })
  654. toggleInput.style.display = 'none' ; toggleInput.checked = config.infinityMode
  655. // Create/ID/stylize switch
  656. const switchSpan = document.getElementById('infinity-switch-span')
  657. || dom.create.elem('span', { id: 'infinity-switch-span' })
  658. const switchStyles = {
  659. position: 'relative', left: `${ env.browser.isMobile ? 211 : !ui.firstLink ? 160 : 154 }px`,
  660. backgroundColor: toggleInput.checked ? '#ccc' : '#AD68FF', // init opposite final color
  661. bottom: `${ !ui.firstLink ? -0.15 : env.browser.isFF ? 0.05 : 0 }em`,
  662. width: '30px', height: '15px', '-webkit-transition': '.4s', transition: '0.4s', borderRadius: '28px'
  663. }
  664. Object.assign(switchSpan.style, switchStyles)
  665. // Create/stylize knob, append to switch
  666. const knobSpan = document.getElementById('infinity-toggle-knob-span')
  667. || dom.create.elem('span', { id: 'infinity-toggle-knob-span' })
  668. const knobStyles = {
  669. position: 'absolute', left: '3px', bottom: '1.25px',
  670. width: '12px', height: '12px', content: '""', borderRadius: '28px',
  671. transform: toggleInput.checked ? // init opposite final pos
  672. 'translateX(0)' : 'translateX(13px) translateY(0)',
  673. backgroundColor: 'white', '-webkit-transition': '0.4s', transition: '0.4s'
  674. }
  675. Object.assign(knobSpan.style, knobStyles) ; switchSpan.append(knobSpan)
  676. // Create/stylize/fill label
  677. const toggleLabel = document.getElementById('infinity-toggle-label')
  678. || dom.create.elem('label', { id: 'infinity-toggle-label' })
  679. if (!ui.firstLink) { // add font size/weight since no ui.firstLink to borrow from
  680. toggleLabel.style.fontSize = '0.875rem' ; toggleLabel.style.fontWeight = 600 }
  681. toggleLabel.style.marginLeft = `-${ !ui.firstLink ? 23 : 41 }px` // left-shift to navicon
  682. toggleLabel.style.cursor = 'pointer' // add finger cursor on hover
  683. toggleLabel.style.width = `${ env.browser.isMobile ? 201 : 148 }px` // to truncate overflown text
  684. toggleLabel.style.overflow = 'hidden' // to truncate overflown text
  685. toggleLabel.style.textOverflow = 'ellipsis' // to truncate overflown text
  686. toggleLabel.innerText = ( app.msgs.menuLabel_infinityMode ) + ' '
  687. + ( toggleInput.checked ? ( app.msgs.state_enabled || 'enabled' )
  688. : ( app.msgs.state_disabled ))
  689. // Append elements
  690. for (const elem of [navicon, toggleInput, switchSpan, toggleLabel]) navToggleDiv.append(elem)
  691. // Update visual state
  692. navToggleDiv.style.display = 'flex'
  693. setTimeout(() => {
  694. switchSpan.style.backgroundColor = toggleInput.checked ? '#ad68ff' : '#ccc'
  695. switchSpan.style.boxShadow = toggleInput.checked ? '2px 1px 9px #d8a9ff' : 'none'
  696. knobSpan.style.transform = toggleInput.checked ? 'translateX(13px) translateY(0)' : 'translateX(0)'
  697. }, 1) // min delay to trigger transition fx
  698. }
  699. }
  700. }
  701. chatgpt.isIdle = function() { // replace waiting for chat to start in case of interrupts
  702. return new Promise(resolve => { // when stop btn missing
  703. new MutationObserver((_, obs) => {
  704. if (!chatgpt.getStopBtn()) { obs.disconnect(); resolve() }
  705. }).observe(document.body, { childList: true, subtree: true })
  706. })
  707. }
  708. // Define INFINITY MODE functions
  709. const infinity = {
  710. async activate() {
  711. settings.save('infinityMode', true) ; syncConfigToUI()
  712. const activatePrompt = 'Generate a single random question'
  713. + ( config.replyLanguage ? ( ' in ' + config.replyLanguage ) : '' )
  714. + ( ' on ' + ( config.replyTopic == 'ALL' ? 'ALL topics' : 'the topic of ' + config.replyTopic ))
  715. + ' then answer it. Don\'t type anything else.'
  716. notify(`${app.msgs.menuLabel_infinityMode}: ${app.msgs.state_on.toUpperCase()}`)
  717. if (env.browser.isMobile && chatgpt.sidebar.isOn()) chatgpt.sidebar.hide()
  718. if (!new URL(location).pathname.startsWith('/g/')) // not on GPT page
  719. try { chatgpt.startNewChat() } catch (err) { return } // start new chat
  720. await new Promise(resolve => setTimeout(resolve, 500)) // sleep 500ms
  721. chatgpt.send(activatePrompt)
  722. await new Promise(resolve => setTimeout(resolve, 3000)) // sleep 3s
  723. if (!document.querySelector('[data-message-author-role]') // new chat reset due to OpenAI bug
  724. && config.infinityMode) // ...and toggle still active
  725. chatgpt.send(activatePrompt) // ...so prompt again
  726. await chatgpt.isIdle()
  727. if (config.infinityMode && !infinity.isActive) // double-check in case de-activated before scheduled
  728. infinity.isActive = setTimeout(infinity.continue, parseInt(config.replyInterval, 10) * 1000)
  729. },
  730. async continue() {
  731. if (!config.autoScrollDisabled) try { chatgpt.scrollToBottom() } catch(err) {}
  732. chatgpt.send('Do it again.')
  733. await chatgpt.isIdle() // before starting delay till next iteration
  734. if (infinity.isActive) // replace timer
  735. infinity.isActive = setTimeout(infinity.continue, parseInt(config.replyInterval, 10) * 1000)
  736. },
  737. deactivate() {
  738. settings.save('infinityMode', false) ; syncConfigToUI()
  739. chatgpt.stop() ; clearTimeout(infinity.isActive) ; infinity.isActive = null
  740. notify(`${app.msgs.menuLabel_infinityMode}: ${app.msgs.state_off.toUpperCase()}`)
  741. },
  742. async restart(options = { target: 'new' }) {
  743. if (options.target == 'new') {
  744. chatgpt.stop() ; infinity.deactivate()
  745. setTimeout(() => infinity.activate(), 750)
  746. } else {
  747. clearTimeout(infinity.isActive) ; infinity.isActive = null ; await chatgpt.isIdle()
  748. if (config.infinityMode && !infinity.isActive) // double-check in case de-activated before scheduled
  749. infinity.isActive = setTimeout(infinity.continue, parseInt(config.replyInterval, 10) * 1000)
  750. }
  751. },
  752. toggle() { infinity[config.infinityMode ? 'activate' : 'deactivate']() }
  753. }
  754. // Define SYNC functions
  755. function syncConfigToUI() {
  756. navToggle.update() // based on config.toggleHidden + config.infinityMode
  757. menu.refresh() // symbols/suffixes
  758. }
  759. // Run MAIN routine
  760. // Create browser TOOLBAR MENU or DISABLE SCRIPT if extension installed
  761. const extensionInstalled = await Promise.race([
  762. new Promise(resolve => {
  763. (function checkExtensionInstalled() {
  764. if (document.querySelector('[cif-extension-installed]')) resolve(true)
  765. else setTimeout(checkExtensionInstalled, 200)
  766. })()
  767. }), new Promise(resolve => setTimeout(() => resolve(false), 1500))])
  768. if (extensionInstalled) { // disable script/menu
  769. GM_registerMenuCommand(`${menu.state.symbols[0]} ${app.msgs.menuLabel_disabled}`, modals.about.show)
  770. return // exit script
  771. } else menu.register() // create functional menu
  772. // Init BROWSER/UI props
  773. await Promise.race([chatgpt.isLoaded(), new Promise(resolve => setTimeout(resolve, 5000))]) // initial UI loaded
  774. await chatgpt.sidebar.isLoaded()
  775. const ui = { firstLink: chatgpt.getNewChatLink() }
  776. // Add LISTENER to auto-disable Infinity Mode
  777. if (document.hidden != undefined) // ...if Page Visibility API supported
  778. document.onvisibilitychange = () => { if (config.infinityMode) infinity.deactivate() }
  779. // Add/update TWEAKS style
  780. const tweaksStyleUpdated = 20241002 // datestamp of last edit for this file's `tweaksStyle`
  781. let tweaksStyle = document.getElementById('tweaks-style') // try to select existing style
  782. if (!tweaksStyle || parseInt(tweaksStyle.getAttribute('last-updated'), 10) < tweaksStyleUpdated) { // if missing or outdated
  783. if (!tweaksStyle) { // outright missing, create/id/attr/append it first
  784. tweaksStyle = document.createElement('style') ; tweaksStyle.id = 'tweaks-style'
  785. tweaksStyle.setAttribute('last-updated', tweaksStyleUpdated.toString())
  786. document.head.append(tweaksStyle)
  787. }
  788. tweaksStyle.innerText = (
  789. ( chatgpt.isDarkMode() ? '.chatgpt-modal > div { border: 1px solid white }' : '' )
  790. + '.chatgpt-modal button {'
  791. + 'font-size: 0.77rem ; text-transform: uppercase ;' // shrink/uppercase labels
  792. + `border: 2px dashed ${ chatgpt.isDarkMode() ? 'white' : 'black' } !important ; border-radius: 0 !important ;` // thiccen/square/dash borders
  793. + 'transition: transform 0.1s ease-in-out, box-shadow 0.1s ease-in-out ;' // smoothen hover fx
  794. + 'cursor: pointer !important ;' // add finger cursor
  795. + 'padding: 5px !important ; min-width: 102px }' // resize
  796. + '.chatgpt-modal button:hover {' // add zoom, re-scheme
  797. + 'transform: scale(1.055) ;'
  798. + ( chatgpt.isDarkMode() ? 'background-color: #2cff00 !important ; box-shadow: 2px 1px 54px #38ff00 !important ; color: black !important'
  799. : 'background-color: #c7ff006b !important ; box-shadow: 2px 1px 30px #97ff006b !important' ) + '}'
  800. + '.modal-buttons { margin-left: -13px !important }'
  801. + '* { scrollbar-width: thin }' // make FF scrollbar skinny to not crop toggle
  802. )
  803. }
  804. // Create NAV TOGGLE div, add styles
  805. const navToggleDiv = document.createElement('div')
  806. navToggleDiv.style.height = '37px'
  807. navToggleDiv.style.margin = '2px 0' // add v-margins
  808. navToggleDiv.style.userSelect = 'none' // prevent highlighting
  809. navToggleDiv.style.cursor = 'pointer' // add finger cursor
  810. navToggle.update() // create children
  811. if (ui.firstLink) { // borrow/assign CLASSES from sidebar div
  812. const firstIcon = ui.firstLink.querySelector('div:first-child'),
  813. firstLabel = ui.firstLink.querySelector('div:nth-child(2)')
  814. navToggleDiv.classList.add(...ui.firstLink.classList, ...(firstLabel?.classList || []))
  815. navToggleDiv.querySelector('img')?.classList.add(...(firstIcon?.classList || []))
  816. }
  817. navToggle.insert()
  818. // Add LISTENER to toggle switch/label/config/menu
  819. navToggleDiv.onclick = () => {
  820. const toggleInput = document.getElementById('infinity-toggle-input')
  821. toggleInput.checked = !toggleInput.checked
  822. settings.save('infinityMode', toggleInput.checked)
  823. infinity.toggle()
  824. }
  825. // Auto-start if enabled
  826. if (config.autoStart) infinity.activate()
  827. // Monitor <html> to maintain NAV TOGGLE VISIBILITY on node changes
  828. new MutationObserver(mutations => mutations.forEach(mutation => {
  829. if (mutation.type == 'childList' && mutation.addedNodes.length && !config.toggleHidden)
  830. navToggle.insert()
  831. })).observe(document.documentElement, { childList: true, subtree: true })
  832. // Disable distracting SIDEBAR CLICK-ZOOM effect
  833. if (!document.querySelector('[sidebar-click-zoom-observed]')) {
  834. new MutationObserver(mutations => mutations.forEach(({ target }) => {
  835. if (target.closest('[class*="sidebar"]') // include sidebar divs
  836. && !target.id.endsWith('-knob-span') // exclude our navToggle
  837. && target.style.transform != 'none' // click-zoom occurred
  838. ) target.style.transform = 'none'
  839. })).observe(document.body, { attributes: true, subtree: true, attributeFilter: [ 'style' ]})
  840. document.documentElement.setAttribute('sidebar-click-zoom-observed', true)
  841. }
  842. })()