Repository: qyjoy/AI-worker Branch: main Commit: e0d0eeb8eb25 Files: 23 Total size: 256.0 KB Directory structure: gitextract_dmkitj7p/ ├── .github/ │ └── ISSUE_TEMPLATE/ │ ├── cn.yaml │ ├── config.yml │ ├── en.yaml │ └── ru.yaml ├── All in one Portable(outdated)/ │ └── AI-WorkerOldRelease.js ├── LICENSE ├── README.md ├── V3(stable)/ │ ├── api-handler.js │ ├── html-rendererv3.js │ ├── request-handler.js │ ├── utils.js │ └── worker.js ├── V4 EX(For mobile support Expand)/ │ ├── api-handler.js │ ├── html-renderer.js │ ├── request-handler.js │ ├── utils.js │ └── worker.js ├── V4(latest)/ │ ├── api-handler.js │ ├── html-renderer.js │ ├── request-handler.js │ ├── utils.js │ └── worker.js └── autoRenice.sh ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/ISSUE_TEMPLATE/cn.yaml ================================================ name: ⚠功能性問題回報 description: 回報一個明確的功能性錯誤,例如按鈕無效或邏輯錯誤 title: "標題:請簡要描述問題" labels: [enhancement, question, documentation, invalid, help wanted, functional] body: - type: markdown attributes: value: | 感謝你的提交!請確認你回報的是一個 **功能性問題(functional problem)**,而不是效能、體驗或個人意見等非功能性問題。 - type: dropdown id: issue-type attributes: label: 問題類型 description: 請選擇你回報的問題類型 options: - 功能性(F:Functional)問題(功能邏輯錯誤、按鈕無作用等) - 非功能性(NF:Non-Functional)問題(UI不佳、速度慢、體驗建議等)❌請勿在此提交 default: 0 validations: required: true - type: input id: environment attributes: label: 運行環境 description: 請提供你的瀏覽器、作業系統、版本等資訊 placeholder: 例如:Chrome 123 / macOS 14.4 validations: required: true - type: textarea id: reproduce-steps attributes: label: 重現步驟 description: 請詳述重現問題的步驟 placeholder: | 1. 打開頁面 2. 點擊按鈕X 3. 發生了問題Y validations: required: true - type: textarea id: expected-behavior attributes: label: 預期行為(至少25字,太短可能會被AI自動退回) description: 描述你原本期望看到的結果 validations: required: true - type: textarea id: actual-behavior attributes: label: 實際行為(提供截圖,至少25字,太短可能會被AI自動退回) description: 描述實際出現的狀況(提供截圖) validations: required: true - type: checkboxes id: confirmations attributes: label: 提交確認(如果你確定此issue為BUG,可在標籤label勾選加上'BUG') options: - label: 我確認:這是一個功能性問題,而不是建議或非功能性問題 required: true - label: 我承認並同意:本issue的分類與處理(如Close、標記為invalid)最終解釋權歸本項目貢獻者與維護者所有 required: true ================================================ FILE: .github/ISSUE_TEMPLATE/config.yml ================================================ blank_issues_enabled: false contact_links: - name: ⛔ [RU]Пожалуйста, не отправляйте нефункциональные проблемы здесь url: https://github.com/qyjoy/Gemini-CFworker/discussions about: Для отзывов и предложений по производительности используйте Discussions - name: ⛔ [CN]請勿在此提交非功能性問題 url: https://github.com/qyjoy/Gemini-CFworker/discussions about: 體驗問題、效能建議請移步 Discussions 區域 - name: ⛔ [EN]You are not allowed to report non-functional issues here url: https://github.com/qyjoy/Gemini-CFworker/discussions about: For feedback or performance suggestions, use Discussions ================================================ FILE: .github/ISSUE_TEMPLATE/en.yaml ================================================ name: ⚠Functional Issue Report description: Report a clear functional error, such as a button not working or a logic bug title: "Title: Please briefly describe the issue" labels: [enhancement, question, documentation, invalid, help wanted, functional] body: - type: markdown attributes: value: | Thank you for your submission! Please make sure you're reporting a **functional issue**, not a performance concern, UI feedback, or personal suggestion. - type: dropdown id: issue-type attributes: label: Type of Issue description: Please select the type of problem you're reporting options: - Functional (F): Functional error such as logic bugs or non-working buttons - Non-Functional (NF): UI/UX issues, slowness, suggestions etc. ❌ Please do NOT submit here default: 0 validations: required: true - type: input id: environment attributes: label: Runtime Environment description: Provide your browser, OS, and version placeholder: e.g. Chrome 123 / macOS 14.4 validations: required: true - type: textarea id: reproduce-steps attributes: label: Steps to Reproduce description: Provide detailed steps to reproduce the issue placeholder: | 1. Open the page 2. Click button X 3. Problem Y occurs validations: required: true - type: textarea id: expected-behavior attributes: label: Expected Behavior (at least 50 EN characters, too short may be auto-rejected by AI) description: Describe what you expected to happen validations: required: true - type: textarea id: actual-behavior attributes: label: Actual Behavior (attach screenshot, at least 50 EN characters, too short may be auto-rejected by AI) description: Describe what actually happened (attach screenshot) validations: required: true - type: checkboxes id: confirmations attributes: label: Submission Confirmation (If you’re sure this is a bug, you can add the 'BUG' label) options: - label: I confirm this is a functional issue, not a suggestion or non-functional feedback required: true - label: I acknowledge and agree that the final interpretation and handling (e.g. Close, mark as invalid) of this issue lies with the project contributors and maintainers required: true ================================================ FILE: .github/ISSUE_TEMPLATE/ru.yaml ================================================ name: ⚠Сообщение о функциональной проблеме description: Сообщите о чёткой функциональной ошибке, например, неработающей кнопке или сбое в логике title: "Заголовок: кратко опишите проблему" labels: [enhancement, question, documentation, invalid, help wanted, functional] body: - type: markdown attributes: value: | Спасибо за ваше сообщение! Убедитесь, что вы сообщаете именно о **функциональной проблеме**, а не об общей производительности, удобстве или субъективных предложениях. - type: dropdown id: issue-type attributes: label: Тип проблемы description: Пожалуйста, выберите тип ошибки options: - "Функциональная (F): Ошибки логики, неработающие кнопки и т.п." - "Нефункциональная (NF): UI-проблемы, медленная работа, предложения и т.д. ❌ Не отправлять здесь" default: 0 validations: required: true - type: input id: environment attributes: label: Окружение description: Укажите ваш браузер, операционную систему и версию placeholder: "Chrome 123 / macOS 14.4" validations: required: true - type: textarea id: reproduce-steps attributes: label: Шаги для воспроизведения placeholder: | 1. Откройте страницу 2. Нажмите кнопку X 3. Произошла ошибка Y validations: required: true - type: textarea id: expected-behavior attributes: label: Ожидаемое поведение (минимум 30 символов) validations: required: true maxLength: 200 - type: textarea id: actual-behavior attributes: label: Фактическое поведение (с приложением скриншота) validations: required: true - type: checkboxes id: confirmations attributes: label: Подтверждение отправки options: - label: "Я подтверждаю, что это функциональная проблема" required: true - label: "Я согласен с политикой обработки issue" required: true ================================================ FILE: All in one Portable(outdated)/AI-WorkerOldRelease.js ================================================ // Helper Function for CORS Headers function corsHeaders() {return { "Access-Control-Allow-Origin": "*", // WARNING: Restrict this in production "Access-Control-Allow-Methods": "GET, POST, OPTIONS", "Access-Control-Allow-Headers": "Content-Type", // Add any other headers your client might send }; } function renderHTML() { return ` 輕音Joy-AI公益站

Ultra Gemini ☁ Cloudflare 輕音Joy-AI公益站

抖音 | Bilibili | Youtube | 小红书 | 公众号: 輕音Joy
AI: 你好!请选择一个模型并输入你的请求。

Powered By Cloudflare Worker Serverless(BETA) | © 2025 輕音Joy

`; // End of the main template literal } // End of renderHTML // ========================================================================== // // ===================== CLOUDFLARE WORKER ENTRY POINT ====================== // // ========================================================================== // export default { async fetch(request, env, ctx) { // Assign a unique ID for request tracing const requestId = request.headers.get('cf-ray') || crypto.randomUUID(); const logPrefix = `[${requestId}]`; console.log(`${logPrefix} Worker received request: ${request.method} ${request.url}`); // --- Hardcoded API Key (FOR TESTING ONLY - INSECURE) --- // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> // >>>>>>>> IMPORTANT: REPLACE WITH YOUR ACTUAL VALID API KEY <<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> const GEMINI_API_KEY = env.GEMINI_API_KEY; // 检查环境变量是否配置 if (!GEMINI_API_KEY || GEMINI_API_KEY.length < 30) { console.error(`${logPrefix} CRITICAL ERROR: API Key 未配置或无效`); return new Response("Server Configuration Error: Invalid API Key.", { status: 500, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() } }); } // --- CORS Preflight --- if (request.method === "OPTIONS") { console.log(`${logPrefix} Responding to OPTIONS request.`); return new Response(null, { status: 204, headers: corsHeaders() }); } // --- Serve HTML for GET --- if (request.method === "GET") { console.log(`${logPrefix} Responding to GET request with HTML.`); try { const html = renderHTML(); return new Response(html, { headers: { "Content-Type": "text/html; charset=utf-8", ...corsHeaders() }, }); } catch (e) { console.error(`${logPrefix} Error rendering HTML:`, e); return new Response("Internal Server Error rendering page.", { status: 500 }); } } // --- Handle POST for API calls --- if (request.method === "POST") { console.log(`${logPrefix} Processing POST request.`); let requestBody; try { requestBody = await request.json(); // Avoid logging full prompt if sensitive, log excerpt or confirmation console.log(`${logPrefix} Parsed request body. Model: ${requestBody?.model}, Prompt starts with: ${String(requestBody?.prompt).substring(0,30)}...`); } catch (e) { console.error(`${logPrefix} Invalid JSON body received:`, e); return new Response("Invalid JSON body.", { status: 400, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() } }); } const { prompt, model } = requestBody; if (!prompt || !model) { console.error(`${logPrefix} Missing prompt or model in request body.`); return new Response("Missing prompt or model in request body.", { status: 400, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() } }); } const allowedModels = ["imagen-3.0-generate-002", "gemini-2.5-flash-preview-04-17"]; if (!allowedModels.includes(model)) { console.error(`${logPrefix} Invalid model selected: ${model}`); return new Response(`Invalid model selected: ${model}. Allowed: ${allowedModels.join(", ")}`, { status: 400, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() } }); } // --- Prepare Google API Request --- const isImagen = model.startsWith("imagen"); const apiEndpoint = isImagen ? 'generateContent' : 'streamGenerateContent'; const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/${model}:${apiEndpoint}?key=${GEMINI_API_KEY}${isImagen ? '' : '&alt=sse'}`; console.log(`${logPrefix} Target API URL: ${apiUrl}`); // Log URL (Key is visible here, acceptable for testing logs) const apiRequestBody = isImagen ? { contents: [{ role: "user", parts: [{ text: prompt }] }], generationConfig: { candidateCount: 1 } } // Request 1 image for Imagen : { contents: [{ parts: [{ text: prompt }] }] }; // Simple content for Gemini // --- Call Google API --- try { console.log(`${logPrefix} Sending request to Google API...`); const apiResponse = await fetch(apiUrl, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(apiRequestBody) }); console.log(`${logPrefix} Google API response status: ${apiResponse.status}, ok: ${apiResponse.ok}`); // --- Handle API Error Response --- if (!apiResponse.ok) { const errorBodyText = await apiResponse.text(); // Read error body console.error(`${logPrefix} Google API Error (${apiResponse.status}): ${errorBodyText}`); let userFriendlyError = `Google API Error (${apiResponse.status})`; try { // Attempt to parse standard Google API error JSON const errorJson = JSON.parse(errorBodyText); userFriendlyError += `: ${errorJson.error?.message || 'Unknown error structure.'}`; } catch (e) { // Fallback to raw text if not JSON userFriendlyError += `: ${errorBodyText.substring(0, 200)}${errorBodyText.length > 200 ? "..." : ""}`; } // Return error TO CLIENT in appropriate format if (isImagen) { // Imagen expects JSON response return new Response(JSON.stringify({ images: [], message: userFriendlyError }), { status: apiResponse.status, // Use original Google status code headers: { "Content-Type": "application/json", ...corsHeaders() } }); } else { // Gemini streaming expects text/event-stream on success, return plain text error return new Response(userFriendlyError, { status: apiResponse.status, // Use original Google status code headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() } }); } } // End API Error Handling // --- Handle API Success Response --- if (isImagen) { // Process Imagen JSON response console.log(`${logPrefix} Processing successful Imagen response.`); const responseBodyText = await apiResponse.text(); let data; try { data = JSON.parse(responseBodyText); // Avoid logging potentially large base64 data unless necessary console.log(`${logPrefix} Parsed Imagen JSON successfully. Candidates count: ${data.candidates?.length}`); } catch (parseError) { console.error(`${logPrefix} Error parsing Imagen JSON response:`, parseError, "Body snippet:", responseBodyText.substring(0, 500)); return new Response(JSON.stringify({ images: [], message: "Internal Server Error: Failed to parse Imagen API response." }), { status: 500, headers: { "Content-Type": "application/json", ...corsHeaders() } }); } // Check for safety blocks or other issues within the 'successful' response if (data.promptFeedback?.blockReason) { console.warn(`${logPrefix} Imagen request blocked: ${data.promptFeedback.blockReason}`); return new Response(JSON.stringify({ images: [], message: `请求被阻止: ${data.promptFeedback.blockReason}` }), { status: 200, // Technically API call succeeded, but content blocked headers: { "Content-Type": "application/json", ...corsHeaders() } }); } // Check if candidates array exists and has content if (!data.candidates || data.candidates.length === 0 || !data.candidates[0].content?.parts) { console.warn(`${logPrefix} Imagen response ok, but no valid candidates/parts found.`); return new Response(JSON.stringify({ images: [], message: "API success, but no generated images found in response." }), { status: 200, headers: { "Content-Type": "application/json", ...corsHeaders() } }); } // Extract image data const imageUrls = data.candidates[0].content.parts .filter(part => part.inlineData?.mimeType?.startsWith("image/")) .map(part => `data:${part.inlineData.mimeType};base64,${part.inlineData.data}`); if (imageUrls.length > 0) { console.log(`${logPrefix} Found ${imageUrls.length} images. Sending JSON response.`); return new Response(JSON.stringify({ images: imageUrls }), { headers: { "Content-Type": "application/json", ...corsHeaders() } }); } else { console.warn(`${logPrefix} Imagen response ok and candidates exist, but no image parts found.`); return new Response(JSON.stringify({ images: [], message: "API success, but no image data found in response parts." }), { status: 200, headers: { "Content-Type": "application/json", ...corsHeaders() } }); } } else { // Stream Gemini SSE response console.log(`${logPrefix} Streaming Gemini response back to client.`); // Use TransformStream for pass-through const { readable, writable } = new TransformStream(); // Pipe the response body to the writable end. Handle potential errors during piping. apiResponse.body.pipeTo(writable).catch(err => { console.error(`${logPrefix} Error piping Gemini stream:`, err); // Difficult to signal error back to client once headers are sent }); // Set appropriate headers for SSE const responseHeaders = new Headers({ "Content-Type": "text/event-stream; charset=utf-8", "Cache-Control": "no-cache", "Connection": "keep-alive", ...corsHeaders() // Apply CORS headers }); // Return the readable end of the stream return new Response(readable, { status: 200, // Successful stream initiation headers: responseHeaders }); } // End Gemini Streaming } catch (error) { // Catch network errors during fetch to Google API console.error(`${logPrefix} Worker fetch error calling Google API:`, error); const errorMsg = `Internal Server Error calling Google API: ${error.message}`; if (isImagen) { return new Response(JSON.stringify({ images: [], message: errorMsg }), { status: 500, headers: { "Content-Type": "application/json", ...corsHeaders() } }); } else { return new Response(errorMsg, { status: 500, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() } }); } } } // End POST handler // --- Method Not Allowed --- console.log(`${logPrefix} Method Not Allowed: ${request.method}`); return new Response("Method Not Allowed", { status: 405, headers: { "Allow": "GET, POST, OPTIONS", ...corsHeaders() } }); } // End async fetch }; // End export default ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================

Cloudflare Workers

Ultra Cloudflare☁️Serverless AI worker

EN: A simple yet powerful Cloudflare Worker to proxy requests to APIs. Enables access to advanced AI models from the edge, securely managing API keys and bypassing regional restrictions.Also available for others popular worker.Gonna have R2 and D2 in the later versions
ZH: 一个简洁而强大的Cloudflare Worker,用于转发API请求至各大AI平台,并且将全球各地的计算节点靠近用户部署,使得您可以从边缘访问高级AI模型,结合KV安全管理API密钥,并绕过地域限制同时支持其他主流平台worker,后期将拓展R2和D1数据库支持
RU:Простой, но мощный Cloudflare Worker для проксирования запросов API. Обеспечивает доступ к передовым ИИ-моделям с периферии, безопасно управляя API-ключами и обходя региональные ограничения. Поддерживает интеграцию с другими Worker-платформами, в будущем планируется расширение с использованием баз данных R2 и D1.

chat GitHub Stars GitHub Issues License Cloudflare Workers Ready Google GeminiGemini

Free, Private Gemini Access via Cloudflare. No VPN needed for restricted Countries. Full Control, with GPL 3.0 protocol
通过Cloudflare免费、私有化访问和管理Gemini~摆脱地域限制无烦恼,完全由自己掌控,原生gemini等AI模型,支持上传图片,录音等

## 🌐 Overview | 概述 Cloudflare Workers
**EN:** This Cloudflare Worker allows you to: * Access Google's powerful AI models from anywhere, including regions where direct access might be challenging. * Securely manage your Google AI API key using Cloudflare's environment variables, keeping it out of client-side code. * Provide a simple, customizable HTML interface for interacting with the AI. * Leverage Cloudflare's global network for potentially lower latency and high scalability. ![image](pic/1.png)
Before: Your area > Not allow to access > AI ×
Now : Your area > Cloudflare Worker > AI √
**ZH:** 此Cloudflare Worker允许您: * 从任何地方访问Google强大的AI模型,包括那些可能难以直接访问的地区。 * 使用Cloudflare的环境变量安全地管理您的AI API(Gemini,ChatGPT等)密钥,避免其暴露在客户端代码中。 * 提供一个简单、可定制的HTML界面与AI进行交互。 * 利用Cloudflare的全球网络实现潜在的低延迟和高可扩展性。 ## 🎈 Features | 功能 ![image](pic/2.png) * **🎯 Proxy AI Requests / 转发AI请求:** * EN:Or you could say it's"Forward AI request", whatever, anyway → Securely routes requests to AIchat and Imagen APIs. * ZH: 安全地将请求API转发到AI源站点 * **🔑 API Key Management / API密钥管理:** * EN: Store your API key securely in Cloudflare Worker environment variables. * ZH: 将您的API密钥安全地存储在Cloudflare Worker环境变量中。 * **📄 Simple HTML Interface / 简单的HTML界面:** * EN: Includes a user-friendly HTML front-end with theme selection for easy interaction. * ZH: 包含一个用户友好的HTML前端,并提供主题选择,方便交互。 * **🔄 CORS Handling / CORS处理:** * EN: Pre-configured to handle Cross-Origin Resource Sharing. * ZH: 已预先配置处理跨域资源共享(CORS)。 * **💨 Supports Streaming / 支持流式传输:** * EN: Handles streaming text responses from models like Gemini/GPT for real-time output. * ZH: 支持从Gemini/GPT等模型获取流式文本响应,实现实时输出。 * **🖼️ Supports Image Generation / 支持图像生成:** * EN: Handles image generation requests and displays results from Imagen. * ZH: 支持处理图像生成请求并显示来自Imagen的结果。 * **🌍 No VPN Proxy Required / 访问无需翻牆挂代理:** * EN: For users in regions with restricted access, this proxy on Cloudflare's network can enable access without a VPN for the end-user. * ZH: 对于某些地区可能无法直接访问Google API的用户,在Cloudflare的网络上部署此代理可以让最终用户无需翻墙即可访问。 ![image](pic/3.jpg) ## 👍 Advantages of using Cloudflare Workers | 使用Cloudflare Worker的优点 **EN:** * **💸 Serverless & Cost-Effective:** No server management needed. The free tier is often generous enough for personal projects. * **⚡ Edge Deployment:** Runs closer to your users, reducing latency and DDos attack barely register thanks to Cloudflare's auto mitigation * **📈 Scalability:** Automatically scales with traffic. * **🚀 Ease of Deployment:** Deploy directly from the Cloudflare dashboard or via Wrangler CLI. * **🔒 Secure API Key Handling:** Keep your API keys safe using encrypted environment variables. ![image](pic/4.png) **ZH:** * **💸 无服务器且经济高效:** 无需管理服务器。免费套餐通常足以满足个人项目需求。 * **⚡ 边缘部署:** 更接近用户运行,减少延迟,抗DDos,支持多种平台worker * **📈 可扩展性:** 随流量自动扩展。 * **🚀 易于部署:** 可直接通过Cloudflare等平台控制台或Wrangler CLI部署。 * **🔒 安全的API密钥处理:** 使用加密的环境变量安全保管您的API密钥。 ## 🚀 Setup & Deployment | 设置与部署 cloudflare icon Follow these steps to deploy your own instance: 请按照以下步骤部署您自己的实例: 1. **Create a Cloudflare Worker | 创建Cloudflare Worker:** * EN: Log in to your Cloudflare dashboard, navigate to "Workers & Pages", and click "Create application", then "Create Worker". Give it a name (e.g., `ultra-ai-proxy`). * ZH: 登录到您的Cloudflare控制台,导航到“Workers & Pages”,点击“创建应用程序”,然后选择“创建Worker”。为其命名(例如 `ultra-ai-proxy`)。 2. **Configure the Worker | 配置Worker:** * EN: Click "Configure Worker" or "Quick edit" for your newly created worker. * ZH: 点击新创建Worker的“配置Worker”或“快速编辑”。 3. **Paste the Code Files | 粘贴代码文件:** * EN: The project is modular. You'll need to create/replace the following files in the Cloudflare online editor with the provided code: * `worker.js` (or `index.js` if that's your main file name in the editor) * `request-handler.js` * `api-handler.js` * `html-renderer.js` * `utils.js` * ZH: 本项目是模块化的。您需要在Cloudflare在线编辑器中创建/替换以下文件,并使用本项目提供的代码: * `worker.js` (如果在编辑器中您的主文件名是 `index.js`,则使用该名称) * `request-handler.js` * `api-handler.js` * `html-renderer.js` * `utils.js` * *(You can find the code for these files in this repository or from where you received them.)* 4. **Add Environment Variable for API Key | 添加API密钥环境变量:** * EN: Go to your Worker's **Settings** tab, then **Variables**. * Under **Environment Variables**, click **"Add variable"**. * **Variable name:** `GEMINI_API_KEY` * **Value:** Your actual Google AI Studio or Google Cloud Vertex AI API Key. * **IMPORTANT:** Click the **"Encrypt"** button next to the value field to secure your API key. ![image](pic/api.png) * ZH: 进入Worker的 **设置 (Settings)** 选项卡, 然后选择 **变量 (Variables)**。 * 在 **环境变量 (Environment Variables)** 部分, 点击 **"添加变量 (Add variable)"**。 * **变量名称 (Variable name):** `GEMINI_API_KEY` * **值 (Value):** 您真实的 Google AI Studio 或 Google Cloud Vertex AI API 密钥。 * **重要:** 点击值字段旁边的 **"加密 (Encrypt)"** 按钮以保护您的API密钥。 5. **Save and Deploy | 保存并部署:** * EN: After adding the code and the environment variable, click the **"Save and Deploy"** button in the editor or on the Worker's settings page. * ZH: 添加代码和环境变量后,在编辑器或Worker的设置页面点击 **"保存并部署 (Save and Deploy)"** 按钮。 Your AI proxy should now be live at the URL provided by Cloudflare (e.g., `your-worker-name.your-subdomain.workers.dev`). 您的AI代理现在应该已在Cloudflare提供的URL上激活(例如 `your-worker-name.your-subdomain.workers.dev`)。 ## 🛠️ Usage | 使用方法 * **EN:** Simply navigate to your Worker's URL in a web browser. You'll see the HTML interface. * Select a model from the dropdown. * Choose a theme. * Type your prompt or image description into the textarea. * Click "发送 Post". * **ZH:** 在网页浏览器中直接访问您的Worker URL。您将看到HTML界面。 * 从下拉菜单中选择一个模型。 * 选择一个主题。 * 在文本区域输入您的问题或画面描述。 * 点击“发送 Post”按钮。 ### Customization | 自定义 * **HTML & CSS:** Modify `html-renderer.js` to change the look and feel of the front-end. * **Models:** Update the `allowedModels` array in `api-handler.js` if new Gemini/Imagen models are released or if you want to restrict options. * **Themes:** Add or modify themes in the `themeConfig` object within the client-side script in `html-renderer.js`. ### 🔄 贡献指南/Contributer 请基于 `discover` 分支开发您的功能并提交 Pull Request。会定期从 `discover` 中精选高质量的更改合并进 `main`。 或联系开发者邮箱:dev@qyjoy.vip ### ⚠️ 澄清:“API 转发 / API 代理” ≠ “网络代理”Clarification: “API Forwarding / API Proxy” ≠ “Network Proxy” **ZH** 有些用户担心本项目因“代理”字样是否违反 Cloudflare 服务条款,这里做一个清晰的技术澄清: 本项目属于**API 转发 / API 代理(API forwarder / proxy)**,**不是网络代理(Network Proxy)**。 - ✅ 它仅转发请求到**特定的公开 API(如 Google 的 Gemini 和 Imagen)** - ❌ 它不支持访问任意网站 - ❌ 它不提供 VPN、SOCKS5、Shadowsocks、Trojan 等网络代理协议或服务 Cloudflare 所禁止的“网络代理”,指的是通用数据转发或翻墙用途的工具。而本项目只是通过 Cloudflare Worker 将 Web 前端请求安全透明地转发给合法 API 服务,功能专一、无滥用空间。 因此,本项目**完全符合 Cloudflare 使用政策**,是 Cloudflare Worker 的标准合规用例。 --- ### 📊 API 转发 vs. 网络代理 对比表 | 特性 / Feature | API Forward (API Proxy) | Network Proxy (VPN/SOCKS/Shadowsocks 等) | |-------------------------------------------|------------------------------------------------|----------------------------------------------| | 🔌 访问范围 | 指定 API 服务(如 Gemini,Imagen,GPT 等) | 任意网站、应用程序、通用网络流量 | | 🔍 ISO Layer | 基于7层的应用转发 | 基于4层的网络包代理 | | 📦 数据内容 | 请求和响应均为结构化 API 数据(如 JSON) | 原始 IP 包或加密流量(如 TCP、UDP) | | 🧠 用途 | 前端→Worker→API 安全转发,用于接口调用 | 匿名访问、翻墙、绕过网络限制 | | 🔐 安全性 | 精确控制目标 API,不可滥用 | 可被用于非法流量、IP 池攻击、绕过审查等 | | 🛠️ 底层协议 | HTTPS 请求转发 | TCP/IP 层或自定义加密隧道协议(如 VPN) | | ☁️ Cloudflare 是否允许使用 | ✅ 是,属于 Cloudflare Worker 正常用途 | ❌ 否,违反 Acceptable Use Policy | | ⚙️ 部署复杂度 | 低:纯 Worker 脚本 + API 配置 | 高:需要服务端、端口映射、防火墙规则等 | | 🎯 示例项目 | Cloudflare Worker 转发 Gemini/chatGPT等 API | Clash、Trojan、V2Ray、Shadowsocks 等工具 | > ✅ 本项目使用的是 **API Forward** 模式,完全符合 Cloudflare 的服务政策,安全、可控、稳定。 **EN:** Some users have asked whether this project violates Cloudflare's Terms of Service because of the term "proxy" being used. Let's clarify: This project is an **API forwarder / API proxy**, not a **network proxy**. - ✅ It only relays requests to **specific public APIs** (e.g., Google Gemini, Imagen, etc.) - ❌ It does **not** allow general access to arbitrary websites - ❌ It does **not** provide tunnels, SOCKS5, Shadowsocks, or VPN-like services In Cloudflare’s terms, a **network proxy** refers to tools that allow general traffic routing and circumvention of regional restrictions. This project does none of that. Therefore, this project **fully complies** with Cloudflare’s Acceptable Use Policy and is a **legitimate use of Cloudflare Workers** to route frontend API requests through serverless infrastructure. > 🔒 This is safe, legal, and compliant. 安全合规,放心部署。 ## 📝 License | 许可证 **EN:** This project is free software: you can redistribute it and/or modify it under the terms of the **GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . **ZH:** 本项目是自由软件:您可以根据 **自由软件基金会发布的GNU通用公共许可证的条款重新分发和/或修改它,无论是许可证的第3版,还是(根据您的选择)任何更高版本。** 分发本程序是希望它能有用,但没有任何担保;甚至没有对适销性或特定用途适用性的暗示担保。更多详情请参阅GNU通用公共许可证。 您应该已经随本程序收到一份GNU通用公共许可证的副本。如果没有,请参阅 。 You can find the full license text in the [LICENSE](LICENSE) file. 您可以在 [LICENSE](LICENSE) 文件中找到完整的许可证文本。 --- ## Star History [![Star History Chart](https://api.star-history.com/svg?repos=qyjoy/AI-Worker&type=Date)](https://star-history.com/#qyjoy/AI-Worker&Date) ![](https://count.getloli.com/get/@qyjoy.github.readme)

Made with ❤️ by 輕音Joy with AI Optimization
If you find this useful, please consider giving a ⭐!

================================================ FILE: V3(stable)/api-handler.js ================================================ // api-handler.js // Handles communication with the Google Generative AI API. import { corsHeaders } from './utils.js'; export async function handleApiCall(request, env, logPrefix) { console.log(`${logPrefix} Processing POST request for API call.`); let requestBody; try { requestBody = await request.json(); console.log(`${logPrefix} Parsed request body. Model: ${requestBody?.model}, Prompt starts with: ${String(requestBody?.prompt).substring(0, 30)}...`); } catch (e) { console.error(`${logPrefix} Invalid JSON body received:`, e); return new Response("Invalid JSON body.", { status: 400, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() } }); } const { prompt, model } = requestBody; if (!prompt || !model) { console.error(`${logPrefix} Missing prompt or model in request body.`); return new Response("Missing prompt or model in request body.", { status: 400, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() } }); } // Extended list of models based on comments in original HTML const allowedModels = [ "gemini-2.5-flash-preview-04-17", // Default and explicitly mentioned "gemini-1.5-pro-preview-0409", "gemini-1.5-flash-preview-0514", "gemini-pro", "gemini-pro-vision", "imagen-3.0-generate-002" // Example Imagen model // Add other specific Imagen model versions if known, e.g., "imagen-..." ]; if (!allowedModels.includes(model) && !model.startsWith("imagen")) { // Allow any model starting with "imagen" for flexibility console.error(`${logPrefix} Invalid model selected: ${model}`); return new Response(`Invalid model selected: ${model}. Allowed: ${allowedModels.join(", ")} or any 'imagen-...' model.`, { status: 400, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() } }); } const GEMINI_API_KEY = env.GEMINI_API_KEY; const isImagen = model.startsWith("imagen"); const apiEndpoint = isImagen ? 'generateContent' : 'streamGenerateContent'; // Note: v1beta is used. For stable versions, it might be v1. const apiVersion = "v1beta"; // Or "v1" if you are using stable models without "preview" in their names. const apiUrl = `https://generativelanguage.googleapis.com/${apiVersion}/models/${model}:${apiEndpoint}?key=${GEMINI_API_KEY}${isImagen ? '' : '&alt=sse'}`; console.log(`${logPrefix} Target API URL: ${apiUrl}`); const apiRequestBody = isImagen ? { contents: [{ role: "user", parts: [{ text: prompt }] }], generationConfig: { candidateCount: 1 } } : { contents: [{ parts: [{ text: prompt }] }] }; try { console.log(`${logPrefix} Sending request to Google API...`); const apiResponse = await fetch(apiUrl, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(apiRequestBody) }); console.log(`${logPrefix} Google API response status: ${apiResponse.status}, ok: ${apiResponse.ok}`); if (!apiResponse.ok) { const errorBodyText = await apiResponse.text(); console.error(`${logPrefix} Google API Error (${apiResponse.status}): ${errorBodyText}`); let userFriendlyError = `Google API Error (${apiResponse.status})`; try { const errorJson = JSON.parse(errorBodyText); userFriendlyError += `: ${errorJson.error?.message || 'Unknown error structure.'}`; } catch (e) { userFriendlyError += `: ${errorBodyText.substring(0, 200)}${errorBodyText.length > 200 ? "..." : ""}`; } if (isImagen) { return new Response(JSON.stringify({ images: [], message: userFriendlyError }), { status: apiResponse.status, headers: { "Content-Type": "application/json", ...corsHeaders() } }); } else { return new Response(userFriendlyError, { status: apiResponse.status, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() } }); } } if (isImagen) { console.log(`${logPrefix} Processing successful Imagen response.`); const responseBodyText = await apiResponse.text(); let data; try { data = JSON.parse(responseBodyText); console.log(`${logPrefix} Parsed Imagen JSON successfully. Candidates count: ${data.candidates?.length}`); } catch (parseError) { console.error(`${logPrefix} Error parsing Imagen JSON response:`, parseError, "Body snippet:", responseBodyText.substring(0, 500)); return new Response(JSON.stringify({ images: [], message: "Internal Server Error: Failed to parse Imagen API response." }), { status: 500, headers: { "Content-Type": "application/json", ...corsHeaders() } }); } if (data.promptFeedback?.blockReason) { console.warn(`${logPrefix} Imagen request blocked: ${data.promptFeedback.blockReason}`); return new Response(JSON.stringify({ images: [], message: `请求被阻止: ${data.promptFeedback.blockReason}` }), { status: 200, headers: { "Content-Type": "application/json", ...corsHeaders() } }); } if (!data.candidates || data.candidates.length === 0 || !data.candidates[0].content?.parts) { console.warn(`${logPrefix} Imagen response ok, but no valid candidates/parts found.`); return new Response(JSON.stringify({ images: [], message: "API success, but no generated images found in response." }), { status: 200, headers: { "Content-Type": "application/json", ...corsHeaders() } }); } const imageUrls = data.candidates[0].content.parts .filter(part => part.inlineData?.mimeType?.startsWith("image/")) .map(part => `data:${part.inlineData.mimeType};base64,${part.inlineData.data}`); if (imageUrls.length > 0) { console.log(`${logPrefix} Found ${imageUrls.length} images. Sending JSON response.`); return new Response(JSON.stringify({ images: imageUrls }), { headers: { "Content-Type": "application/json", ...corsHeaders() } }); } else { console.warn(`${logPrefix} Imagen response ok and candidates exist, but no image parts found.`); return new Response(JSON.stringify({ images: [], message: "API success, but no image data found in response parts." }), { status: 200, headers: { "Content-Type": "application/json", ...corsHeaders() } }); } } else { // Gemini SSE stream console.log(`${logPrefix} Streaming Gemini response back to client.`); const { readable, writable } = new TransformStream(); apiResponse.body.pipeTo(writable).catch(err => { console.error(`${logPrefix} Error piping Gemini stream:`, err); }); const responseHeaders = new Headers({ "Content-Type": "text/event-stream; charset=utf-8", "Cache-Control": "no-cache", "Connection": "keep-alive", ...corsHeaders() }); return new Response(readable, { status: 200, headers: responseHeaders }); } } catch (error) { console.error(`${logPrefix} Worker fetch error calling Google API:`, error); const errorMsg = `Internal Server Error calling Google API: ${error.message}`; if (isImagen) { return new Response(JSON.stringify({ images: [], message: errorMsg }), { status: 500, headers: { "Content-Type": "application/json", ...corsHeaders() } }); } else { return new Response(errorMsg, { status: 500, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() } }); } } } ================================================ FILE: V3(stable)/html-rendererv3.js ================================================ // html-renderer.js// Generates the complete HTML page, including CSS and client-side JavaScript.// CSS styles for the page const getStyles = () => ` `; // Client-side JavaScript const getClientScript = () => ` `; // Main HTML structure export function renderHTML() { const styles = getStyles(); const clientScript = getClientScript(); return ` 輕音Joy-AI公益站 ${styles}

Ultra AI ☁ Cloudflare 輕音Joy-AI公益站

抖音 | Bilibili | Youtube | 小红书 | 公众号: 輕音Joy
AI:你好!请选择一个模型并输入任意问题😀

Hi! Get started by selecting any models and input whatever you want!

Powered By Cloudflare ☁ Serverless | © 2025 輕音Joy

${clientScript} `; } ================================================ FILE: V3(stable)/request-handler.js ================================================ // request-handler.js // Handles incoming requests, routing, and basic validation. import { renderHTML } from './html-renderer.js'; import { handleApiCall } from './api-handler.js'; import { corsHeaders } from './utils.js'; export async function handleRequest(request, env, ctx, logPrefix) { // --- API Key Check --- const GEMINI_API_KEY = env.GEMINI_API_KEY; if (!GEMINI_API_KEY || GEMINI_API_KEY.length < 30) { console.error(`${logPrefix} CRITICAL ERROR: API Key 未配置或无效`); return new Response("Server Configuration Error: Invalid API Key.", { status: 500, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() } }); } // --- CORS Preflight --- if (request.method === "OPTIONS") { console.log(`${logPrefix} Responding to OPTIONS request.`); return new Response(null, { status: 204, headers: corsHeaders() }); } // --- Serve HTML for GET --- if (request.method === "GET") { console.log(`${logPrefix} Responding to GET request with HTML.`); try { const html = renderHTML(); return new Response(html, { headers: { "Content-Type": "text/html; charset=utf-8", ...corsHeaders() }, }); } catch (e) { console.error(`${logPrefix} Error rendering HTML:`, e); return new Response("Internal Server Error rendering page.", { status: 500, headers: corsHeaders() }); } } // --- Handle POST for API calls --- if (request.method === "POST") { return handleApiCall(request, env, logPrefix); } // --- Method Not Allowed --- console.log(`${logPrefix} Method Not Allowed: ${request.method}`); return new Response("Method Not Allowed", { status: 405, headers: { "Allow": "GET, POST, OPTIONS", ...corsHeaders() } }); } ================================================ FILE: V3(stable)/utils.js ================================================ // utils.js // Utility functions for the worker. export function corsHeaders() { return { "Access-Control-Allow-Origin": "*", // WARNING: Restrict this in production for security "Access-Control-Allow-Methods": "GET, POST, OPTIONS", "Access-Control-Allow-Headers": "Content-Type, Authorization", // Added Authorization as an example, include any other custom headers }; } ================================================ FILE: V3(stable)/worker.js ================================================ // worker.js // Main entry point for the Cloudflare Worker. import { handleRequest } from './request-handler.js'; export default { async fetch(request, env, ctx) { // Assign a unique ID for request tracing const requestId = request.headers.get('cf-ray') || crypto.randomUUID(); const logPrefix = `[${requestId}]`; console.log(`${logPrefix} Worker received request: ${request.method} ${request.url}`); // Delegate to the request handler return handleRequest(request, env, ctx, logPrefix); } }; ================================================ FILE: V4 EX(For mobile support Expand)/api-handler.js ================================================ import { corsHeaders } from './utils.js'; export async function handleApiCall(request, env, logPrefix) { console.log(logPrefix + " Processing POST request for API call."); let requestBody; try { requestBody = await request.json(); console.log(logPrefix + " Parsed request body. Model: " + requestBody?.model); } catch (e) { console.error(logPrefix + " Invalid JSON body received:", e); return new Response("Invalid JSON body.", { status: 400, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() } }); } const { model, history, currentTurnParts, customApiKey } = requestBody; if (!model || !currentTurnParts || !Array.isArray(currentTurnParts)) { console.error(logPrefix + " Missing model or currentTurnParts in request body."); return new Response("Missing model or currentTurnParts in request body.", { status: 400, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() } }); } const allowedModels = [ "gemini-2.0-flash", "gemini-2.5-flash-preview-05-20", "gemini-2.5-pro-preview-06-05", "gemini-2.0-flash-preview-image-generation", "veo-2.0-generate-001" ]; if (!allowedModels.includes(model)) { console.error(logPrefix + " Invalid model selected: " + model); return new Response("Invalid model selected: " + model + ". Allowed: " + allowedModels.join(", "), { status: 400, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() } }); } const GEMINI_API_KEY = customApiKey || env.GEMINI_API_KEY; if (!GEMINI_API_KEY) { console.error(logPrefix + " CRITICAL ERROR: API Key not available (neither custom nor server default)."); return new Response("Server Configuration Error: API Key not available.", { status: 500, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() } }); } let apiEndpoint = "streamGenerateContent"; let isStreaming = true; if (model === "gemini-2.0-flash-preview-image-generation") { apiEndpoint = "generateContent"; isStreaming = false; } else if (model === "veo-2.0-generate-001") { apiEndpoint = "generateVideo"; isStreaming = false; } const apiVersion = "v1beta"; const apiUrl = `https://generativelanguage.googleapis.com/${apiVersion}/models/${model}:${apiEndpoint}?key=${GEMINI_API_KEY}` + (isStreaming ? "&alt=sse" : ""); console.log(logPrefix + " Target API URL: " + apiUrl); const contentsForApi = []; if (history && Array.isArray(history)) { history.forEach(turn => { if (turn.role && turn.parts) { contentsForApi.push({ role: turn.role, parts: turn.parts }); } }); } const systemPrompt = "answer in 中文"; // 这里可以根据需要修改提示词 you can set your own prompt here let promptedUserParts = [...currentTurnParts]; if (promptedUserParts.length > 0 && typeof promptedUserParts[0].text === 'string') { promptedUserParts[0] = { ...promptedUserParts[0], text: systemPrompt + " " + promptedUserParts[0].text }; } else { promptedUserParts.unshift({ text: systemPrompt }); } contentsForApi.push({ role: "user", parts: promptedUserParts }); const apiRequestBody = {contents: contentsForApi,}; try { console.log(logPrefix + " Sending request to Google API..."); const apiResponse = await fetch(apiUrl, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(apiRequestBody) }); console.log(logPrefix + " Google API response status: " + apiResponse.status + ", ok: " + apiResponse.ok); if (!apiResponse.ok) { const errorBodyText = await apiResponse.text(); console.error(logPrefix + " Google API Error (" + apiResponse.status + "): " + errorBodyText); let userFriendlyError = "Google API Error (" + apiResponse.status + ")"; try { const errorJson = JSON.parse(errorBodyText); if (errorJson.error && errorJson.error.message) { userFriendlyError += ": " + errorJson.error.message; } else { userFriendlyError += ": " + errorBodyText.substring(0, 200) + (errorBodyText.length > 200 ? "..." : ""); } } catch (e) { userFriendlyError += ": " + errorBodyText.substring(0, 200) + (errorBodyText.length > 200 ? "..." : ""); } return new Response(userFriendlyError, { status: apiResponse.status, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() } }); } console.log(logPrefix + " Streaming Gemini response back to client."); const { readable, writable } = new TransformStream(); apiResponse.body.pipeTo(writable).catch(err => { console.error(logPrefix + " Error piping Gemini stream:", err); }); const responseHeaders = new Headers({ "Content-Type": "text/event-stream; charset=utf-8", "Cache-Control": "no-cache", "Connection": "keep-alive", ...corsHeaders() }); return new Response(readable, { status: 200, headers: responseHeaders }); } catch (error) { console.error(logPrefix + " Worker fetch error calling Google API:", error); const errorMsg = "Internal Server Error calling Google API: " + error.message; return new Response(errorMsg, { status: 500, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() } }); } } ================================================ FILE: V4 EX(For mobile support Expand)/html-renderer.js ================================================ const getStyles = () => ` `; const getClientScript = () => ` `; // Main HTML structure export function renderHTML(isMobile) { const styles = getStyles(); const clientScript = getClientScript(); const viewportMeta = isMobile ? ' ' : ''; return ` ${viewportMeta} 輕音Joy-AI公益站 ` + styles + `
` + clientScript + ` `; } ================================================ FILE: V4 EX(For mobile support Expand)/request-handler.js ================================================ // request-handler.js // Handles incoming requests, routing, and basic validation. import { renderHTML } from './html-renderer.js'; import { handleApiCall } from './api-handler.js'; import { corsHeaders } from './utils.js'; export async function handleRequest(request, env, ctx, logPrefix, isMobile) { // --- API Key Check (for default key) --- const DEFAULT_GEMINI_API_KEY = env.GEMINI_API_KEY; if (!DEFAULT_GEMINI_API_KEY || DEFAULT_GEMINI_API_KEY.length < 30) { // This is a warning if not set, as user can provide their own. // However, if it's set but invalid, that's a config issue. console.warn(logPrefix + " Default GEMINI_API_KEY is not configured or appears invalid. Users must provide their own key for the service to function without a custom key."); // The service can still run if users provide their own key. // If you want to make default key mandatory for the service to even start, then make this an error. } // --- CORS Preflight --- if (request.method === "OPTIONS") { console.log(logPrefix + " Responding to OPTIONS request."); return new Response(null, { status: 204, headers: corsHeaders() }); } // --- Serve HTML for GET --- if (request.method === "GET") { console.log(logPrefix + " Responding to GET request with HTML."); try { const html = renderHTML(isMobile); return new Response(html, { headers: { "Content-Type": "text/html; charset=utf-8", ...corsHeaders() }, }); } catch (e) { console.error(logPrefix + " Error rendering HTML:", e); return new Response("Internal Server Error rendering page.", { status: 500, headers: corsHeaders() }); } } // --- Handle POST for API calls --- if (request.method === "POST") { return handleApiCall(request, env, logPrefix); } // --- Method Not Allowed --- console.log(logPrefix + " Method Not Allowed: " + request.method); return new Response("Method Not Allowed", { status: 405, headers: { "Allow": "GET, POST, OPTIONS", ...corsHeaders() } }); } ================================================ FILE: V4 EX(For mobile support Expand)/utils.js ================================================ // utils.js // Utility functions for the worker. export function corsHeaders() { return { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, OPTIONS", "Access-Control-Allow-Headers": "Content-Type, Authorization", }; } ================================================ FILE: V4 EX(For mobile support Expand)/worker.js ================================================ // worker.js // Main entry point for the Cloudflare Worker. import { handleRequest } from './request-handler.js'; export default { async fetch(request, env, ctx) { const requestId = request.headers.get('cf-ray') || crypto.randomUUID(); const logPrefix = "[" + requestId + "]"; const userAgent = request.headers.get('User-Agent') || ''; // Simple mobile detection const isMobile = /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(userAgent); console.log(logPrefix + " Worker received request: " + request.method + " " + request.url + (isMobile ? " (Mobile UA detected)" : "")); // Pass the isMobile flag to handleRequest return handleRequest(request, env, ctx, logPrefix, isMobile); } }; ================================================ FILE: V4(latest)/api-handler.js ================================================ // api-handler.js // Handles communication with the Google Generative AI API. import { corsHeaders } from './utils.js'; export async function handleApiCall(request, env, logPrefix) { console.log(logPrefix + " Processing POST request for API call."); let requestBody; try { requestBody = await request.json(); console.log(logPrefix + " Parsed request body. Model: " + requestBody?.model); } catch (e) { console.error(logPrefix + " Invalid JSON body received:", e); return new Response("Invalid JSON body.", { status: 400, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() } }); } const { model, history, currentTurnParts, customApiKey } = requestBody; // 'prompt' from requestBody is not directly used for API call structure, // 'currentTurnParts' and 'history' are used instead. if (!model || !currentTurnParts || !Array.isArray(currentTurnParts)) { console.error(logPrefix + " Missing model or currentTurnParts in request body."); return new Response("Missing model or currentTurnParts in request body.", { status: 400, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() } }); } const allowedModels = [ "gemini-2.5-flash-preview-04-17", "gemini-2.5-pro-preview-05-06" ]; if (!allowedModels.includes(model)) { console.error(logPrefix + " Invalid model selected: " + model); return new Response("Invalid model selected: " + model + ". Allowed: " + allowedModels.join(", "), { status: 400, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() } }); } const GEMINI_API_KEY = customApiKey || env.GEMINI_API_KEY; if (!GEMINI_API_KEY) { console.error(logPrefix + " CRITICAL ERROR: API Key not available (neither custom nor server default)."); return new Response("Server Configuration Error: API Key not available.", { status: 500, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() } }); } const apiEndpoint = 'streamGenerateContent'; // Always streaming for these models const apiVersion = "v1beta"; const apiUrl = "https://generativelanguage.googleapis.com/" + apiVersion + "/models/" + model + ":" + apiEndpoint + "?key=" + GEMINI_API_KEY + "&alt=sse"; console.log(logPrefix + " Target API URL: " + apiUrl); const contentsForApi = []; if (history && Array.isArray(history)) { history.forEach(turn => { if (turn.role && turn.parts) { contentsForApi.push({ role: turn.role, parts: turn.parts }); } }); } // Add current user turn contentsForApi.push({ role: "user", parts: currentTurnParts }); // Log contents structure before sending for debugging // console.log(logPrefix + " API Request Contents: " + JSON.stringify(contentsForApi, null, 2)); const apiRequestBody = { contents: contentsForApi, // Optional: Add generationConfig if needed // generationConfig: { // temperature: 0.7, // topK: 1, // topP: 1, // maxOutputTokens: 2048, // } }; try { console.log(logPrefix + " Sending request to Google API..."); const apiResponse = await fetch(apiUrl, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(apiRequestBody) }); console.log(logPrefix + " Google API response status: " + apiResponse.status + ", ok: " + apiResponse.ok); if (!apiResponse.ok) { const errorBodyText = await apiResponse.text(); console.error(logPrefix + " Google API Error (" + apiResponse.status + "): " + errorBodyText); let userFriendlyError = "Google API Error (" + apiResponse.status + ")"; try { const errorJson = JSON.parse(errorBodyText); if (errorJson.error && errorJson.error.message) { userFriendlyError += ": " + errorJson.error.message; } else { userFriendlyError += ": " + errorBodyText.substring(0, 200) + (errorBodyText.length > 200 ? "..." : ""); } } catch (e) { userFriendlyError += ": " + errorBodyText.substring(0, 200) + (errorBodyText.length > 200 ? "..." : ""); } return new Response(userFriendlyError, { status: apiResponse.status, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() } }); } console.log(logPrefix + " Streaming Gemini response back to client."); const { readable, writable } = new TransformStream(); apiResponse.body.pipeTo(writable).catch(err => { console.error(logPrefix + " Error piping Gemini stream:", err); }); const responseHeaders = new Headers({ "Content-Type": "text/event-stream; charset=utf-8", "Cache-Control": "no-cache", "Connection": "keep-alive", ...corsHeaders() }); return new Response(readable, { status: 200, headers: responseHeaders }); } catch (error) { console.error(logPrefix + " Worker fetch error calling Google API:", error); const errorMsg = "Internal Server Error calling Google API: " + error.message; return new Response(errorMsg, { status: 500, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() } }); } } ================================================ FILE: V4(latest)/html-renderer.js ================================================ // html-renderer.js // Generates the complete HTML page, including CSS and client-side JavaScript. // CSS styles for the page const getStyles = () => ` `; // Client-side JavaScript const getClientScript = () => ` `; // Main HTML structure export function renderHTML() { const styles = getStyles(); const clientScript = getClientScript(); return ` 輕音Joy-AI公益站 ` + styles + `

Ultra AI ☁ Cloudflare 輕音Joy-AI公益站

抖音 | Bilibili | Youtube | 小红书 | 公众号: 輕音Joy

Powered By Cloudflare ☁ Serverless | © 2025 輕音Joy

` + clientScript + ` `; } ================================================ FILE: V4(latest)/request-handler.js ================================================ // request-handler.js // Handles incoming requests, routing, and basic validation. import { renderHTML } from './html-renderer.js'; import { handleApiCall } from './api-handler.js'; import { corsHeaders } from './utils.js'; export async function handleRequest(request, env, ctx, logPrefix) { // --- API Key Check (for default key) --- const DEFAULT_GEMINI_API_KEY = env.GEMINI_API_KEY; if (!DEFAULT_GEMINI_API_KEY || DEFAULT_GEMINI_API_KEY.length < 30) { // This is a warning if not set, as user can provide their own. // However, if it's set but invalid, that's a config issue. console.warn(logPrefix + " Default GEMINI_API_KEY is not configured or appears invalid. Users must provide their own key for the service to function without a custom key."); // The service can still run if users provide their own key. // If you want to make default key mandatory for the service to even start, then make this an error. } // --- CORS Preflight --- if (request.method === "OPTIONS") { console.log(logPrefix + " Responding to OPTIONS request."); return new Response(null, { status: 204, headers: corsHeaders() }); } // --- Serve HTML for GET --- if (request.method === "GET") { console.log(logPrefix + " Responding to GET request with HTML."); try { const html = renderHTML(); return new Response(html, { headers: { "Content-Type": "text/html; charset=utf-8", ...corsHeaders() }, }); } catch (e) { console.error(logPrefix + " Error rendering HTML:", e); return new Response("Internal Server Error rendering page.", { status: 500, headers: corsHeaders() }); } } // --- Handle POST for API calls --- if (request.method === "POST") { return handleApiCall(request, env, logPrefix); } // --- Method Not Allowed --- console.log(logPrefix + " Method Not Allowed: " + request.method); return new Response("Method Not Allowed", { status: 405, headers: { "Allow": "GET, POST, OPTIONS", ...corsHeaders() } }); } ================================================ FILE: V4(latest)/utils.js ================================================ // utils.js // Utility functions for the worker. export function corsHeaders() { return { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, OPTIONS", "Access-Control-Allow-Headers": "Content-Type, Authorization", }; } ================================================ FILE: V4(latest)/worker.js ================================================ // worker.js // Main entry point for the Cloudflare Worker. import { handleRequest } from './request-handler.js'; export default { async fetch(request, env, ctx) { const requestId = request.headers.get('cf-ray') || crypto.randomUUID(); const logPrefix = "[" + requestId + "]"; console.log(logPrefix + " Worker received request: " + request.method + " " + request.url); return handleRequest(request, env, ctx, logPrefix); } }; ================================================ FILE: autoRenice.sh ================================================ #!/bin/bash set -e set -o pipefail PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin export PATH # Color definitions RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[0;33m' BLUE='\033[0;34m' FONT_RESET='\033[0m' # Supported video extensions VIDEO_EXTENSIONS=("mp4" "mkv" "webm" "avi" "mov" "flv" "ts" "mpg" "mpeg" "wmv") command_exists() { command -v "$1" >/dev/null 2>&1; } ffmpeg_check_install() { if command_exists ffmpeg; then echo -e "${GREEN}FFmpeg is already installed.${FONT_RESET}" if [ -x /usr/bin/ffmpeg ]; then FFMPEG_PATH="/usr/bin/ffmpeg" elif [ -x /usr/local/bin/ffmpeg ]; then FFMPEG_PATH="/usr/local/bin/ffmpeg" else FFMPEG_PATH=$(command -v ffmpeg) fi echo -e "${GREEN}Current FFmpeg version:${FONT_RESET}" "$FFMPEG_PATH" -version | head -n 1 read -p "$(echo -e "${YELLOW}Skip FFmpeg installation/update? (yes/no, default: yes): ${FONT_RESET}")" skip_ffmpeg_install skip_ffmpeg_install=${skip_ffmpeg_install:-yes} if [[ "${skip_ffmpeg_install,,}" == "no" ]]; then install_latest_ffmpeg else echo -e "${GREEN}Skipping FFmpeg installation/update.${FONT_RESET}" fi else echo -e "${YELLOW}FFmpeg not found.${FONT_RESET}" install_latest_ffmpeg fi } install_latest_ffmpeg() { echo -e "${BLUE}Installing/updating FFmpeg (John Van Sickle static build)...${FONT_RESET}" echo -e "${YELLOW}This downloads a pre-compiled static build for best codec support.${FONT_RESET}" read -p "$(echo -e "${YELLOW}Proceed with download/install? (yes/no): ${FONT_RESET}")" confirm_install if [[ "${confirm_install,,}" != "yes" ]]; then echo -e "${RED}Aborted by user. The script may not work without FFmpeg.${FONT_RESET}" return 1 fi local SUDO_CMD="" if command_exists sudo; then SUDO_CMD="sudo" elif [ "$(id -u)" -ne 0 ]; then echo -e "${RED}sudo not found and not root. Please install sudo or run as root.${FONT_RESET}" return 1 fi $SUDO_CMD apt update $SUDO_CMD apt install -y wget tar xz-utils curl ARCH=$(uname -m) FFMPEG_STATIC_URL="" if [ "$ARCH" = "x86_64" ]; then FFMPEG_STATIC_URL="https://johnvansickle.com/ffmpeg/releases/ffmpeg-release-amd64-static.tar.xz" elif [ "$ARCH" = "aarch64" ]; then FFMPEG_STATIC_URL="https://johnvansickle.com/ffmpeg/releases/ffmpeg-release-arm64-static.tar.xz" else echo -e "${RED}Unsupported architecture: $ARCH. Install FFmpeg manually.${FONT_RESET}" return 1 fi echo -e "${BLUE}Downloading FFmpeg from ${FFMPEG_STATIC_URL}...${FONT_RESET}" cd /tmp if wget -q --show-progress --progress=bar:force:noscroll -O ffmpeg-static.tar.xz "$FFMPEG_STATIC_URL"; then echo -e "${GREEN}Download complete. Extracting...${FONT_RESET}" rm -rf ffmpeg-*-static if tar -xf ffmpeg-static.tar.xz; then EXTRACTED_DIR=$(find . -maxdepth 1 -type d -name "ffmpeg-*-static" -print -quit) if [ -d "$EXTRACTED_DIR" ]; then echo -e "${GREEN}Moving ffmpeg and ffprobe to /usr/local/bin/...${FONT_RESET}" $SUDO_CMD mv "$EXTRACTED_DIR/ffmpeg" /usr/local/bin/ $SUDO_CMD mv "$EXTRACTED_DIR/ffprobe" /usr/local/bin/ $SUDO_CMD chmod +x /usr/local/bin/ffmpeg /usr/local/bin/ffprobe echo -e "${GREEN}FFmpeg installed/updated successfully!${FONT_RESET}" ffmpeg -version | head -n 1 else echo -e "${RED}Extracted FFmpeg directory not found.${FONT_RESET}"; rm -f ffmpeg-static.tar.xz; return 1 fi rm -rf "$EXTRACTED_DIR" ffmpeg-static.tar.xz; cd - > /dev/null else echo -e "${RED}Failed to extract FFmpeg archive.${FONT_RESET}"; rm -f ffmpeg-static.tar.xz; return 1 fi else echo -e "${RED}Failed to download FFmpeg.${FONT_RESET}"; return 1 fi } stream_start() { echo -e "${BLUE}Stream setup...${FONT_RESET}" local full_rtmp_url video_folder while true; do read -p "$(echo -e "${YELLOW}Enter full RTMP URL (e.g., rtmp://a.rtmp.youtube.com/live2/xxxx-xxxx): ${FONT_RESET}")" full_rtmp_url_raw # 去除前后空格、不可见字符 full_rtmp_url=$(echo "$full_rtmp_url_raw" | tr -d '\r\n\t' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//') # 基本校验 if [[ "$full_rtmp_url" =~ ^rtmp(s)?://.+ ]]; then # 自动去除多余的重复斜杠(比如/xxxx//xxxx -> /xxxx/xxxx) full_rtmp_url=$(echo "$full_rtmp_url" | sed 's#//*#/#g;s#:/#://#') echo -e "${GREEN}RTMP URL: ${BLUE}${full_rtmp_url}${FONT_RESET}" break else echo -e "${RED}Invalid RTMP URL. Must start with 'rtmp://' or 'rtmps://'. Try again.${FONT_RESET}" fi done while true; do read -p "$(echo -e "${YELLOW}Enter video directory (absolute path, e.g., /opt/videos): ${FONT_RESET}")" video_folder if [ -d "$video_folder" ]; then echo -e "${GREEN}Video directory: $video_folder${FONT_RESET}"; break else echo -e "${RED}Directory not found: $video_folder. Try again.${FONT_RESET}" fi done echo -e "${BLUE}Starting infinite streaming loop. Press Ctrl+C to stop.${FONT_RESET}" while true; do echo -e "${GREEN}Searching and shuffling videos in '$video_folder'...${FONT_RESET}" local find_options_str="" for ext_idx in "${!VIDEO_EXTENSIONS[@]}"; do if [ "$ext_idx" -eq 0 ]; then find_options_str="-iname \"*.${VIDEO_EXTENSIONS[$ext_idx]}\"" else find_options_str="$find_options_str -o -iname \"*.${VIDEO_EXTENSIONS[$ext_idx]}\"" fi done mapfile -t video_files < <(eval "find \"$video_folder\" -type f \( $find_options_str \) -print0" | shuf -z | xargs -0 -r printf "%s\n") if [ ${#video_files[@]} -eq 0 ]; then echo -e "${RED}No video files found. Waiting 15s...${FONT_RESET}"; sleep 15; continue fi echo -e "${GREEN}Found ${#video_files[@]} video files. Starting playback cycle.${FONT_RESET}" for video_file in "${video_files[@]}"; do echo -e "${BLUE}--------------------------------------------------${FONT_RESET}" echo -e "${GREEN}Streaming: $video_file${FONT_RESET}" echo -e "${GREEN}RTMP: $full_rtmp_url${FONT_RESET}" ffmpeg -hide_banner \ -nostdin \ -analyzeduration 10M -probesize 10M \ -i "$video_file" -vf "scale=1280:720" -r 35 \ -c:v libx264 -preset ultrafast -tune zerolatency -pix_fmt yuv420p \ -maxrate 4250k -bufsize 80000k -g 70 -keyint_min 70 -sc_threshold 0 \ -c:a aac -b:a 128k -ar 44100 \ -threads 0 \ -f flv "$full_rtmp_url" & pid=$! echo -e "${YELLOW}FFmpeg PID: $pid${FONT_RESET}" sleep 3 ionice -c 2 -n 0 -p "$pid" renice -n -20 -p "$pid" >/dev/null wait "$pid" echo -e "${BLUE}---------------- FFmpeg ended --------------------${FONT_RESET}" sleep 0 done echo -e "${YELLOW}Cycle complete. Re-shuffling and starting again...${FONT_RESET}" sleep 0 done } stream_stop() { echo -e "${YELLOW}Stopping FFmpeg processes...${FONT_RESET}" local killed_processes=false if pgrep -f "ffmpeg -hide_banner -re -nostdin.*-f flv rtmp(s)?://" > /dev/null; then echo -e "${BLUE}Attempting graceful stop (SIGTERM)...${FONT_RESET}" pkill -SIGTERM -f "ffmpeg -hide_banner -re -nostdin.*-f flv rtmp(s)?://" && sleep 2 if pgrep -f "ffmpeg -hide_banner -re -nostdin.*-f flv rtmp(s)?://" > /dev/null; then echo -e "${YELLOW}Forceful stop (SIGKILL)...${FONT_RESET}" pkill -SIGKILL -f "ffmpeg -hide_banner -re -nostdin.*-f flv rtmp(s)?://" fi echo -e "${GREEN}Targeted FFmpeg processes stopped.${FONT_RESET}" killed_processes=true fi if ! $killed_processes; then if pgrep ffmpeg > /dev/null; then echo -e "${YELLOW}No stream processes found. Trying 'killall ffmpeg'...${FONT_RESET}" if killall ffmpeg > /dev/null 2>&1; then echo -e "${GREEN}All FFmpeg processes stopped.${FONT_RESET}" else echo -e "${RED}killall ffmpeg failed or no processes found.${FONT_RESET}" fi else echo -e "${GREEN}No FFmpeg processes running.${FONT_RESET}" fi fi echo -e "${YELLOW}If using screen/tmux, manually terminate the session as well.${FONT_RESET}" } main_menu() { clear echo -e "${YELLOW}Ubuntu FFmpeg Unattended Loop Streamer (Clean NoLog Edition)${FONT_RESET}" echo -e "${RED}IMPORTANT: For long streams, run inside 'screen' or 'tmux'!${FONT_RESET}" echo -e "${GREEN}Example: screen -S stream_session bash $(basename "$0")${FONT_RESET}" echo -e "--------------------------------------------" echo -e "${BLUE}1. Check/Install/Update FFmpeg${FONT_RESET}" echo -e "${BLUE}2. Start Unattended Loop Streaming${FONT_RESET}" echo -e "${BLUE}3. Stop Streaming (kills FFmpeg processes)${FONT_RESET}" echo -e "${BLUE}4. Exit${FONT_RESET}" echo -e "--------------------------------------------" read -p "$(echo -e "${YELLOW}Enter your choice (1-4): ${FONT_RESET}")" choice case "$choice" in 1) ffmpeg_check_install ;; 2) if ! command_exists ffmpeg; then echo -e "${RED}FFmpeg not found. Install via option 1 first.${FONT_RESET}" else echo -e "${YELLOW}Starting stream. To stop, use Option 3 from this menu, or Ctrl+C if not in screen/tmux.${FONT_RESET}" stream_start fi ;; 3) stream_stop ;; 4) echo -e "${GREEN}Exiting.${FONT_RESET}"; exit 0 ;; *) echo -e "${RED}Invalid choice (1-4).${FONT_RESET}" ;; esac echo ""; read -p "Press Enter for main menu..." main_menu } main_menu