[
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "content": "---\nname: 报告问题\nabout: 使用简练详细的语言描述你遇到的问题\ntitle: ''\nlabels: bug\nassignees: ''\n\n---\n\n**温馨提示: 未`star`项目会被自动关闭issue哦!**\n\n**例行检查**\n\n+ [ ] 我已确认目前没有类似 issue\n+ [ ] 我已确认我已升级到最新版本\n+ [ ] 我理解并愿意跟进此 issue,协助测试和提供反馈\n+ [ ] 我理解并认可上述内容,并理解项目维护者精力有限,不遵循规则的 issue 可能会被无视或直接关闭\n\n**问题描述**\n\n**复现步骤**\n\n**预期结果**\n\n**相关截图**\n如果没有的话,请删除此节。"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "content": "blank_issues_enabled: false\ncontact_links:\n  - name: 赞赏支持\n    #    url:\n    about: 请作者喝杯咖啡,以激励作者持续开发\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "content": "---\nname: 功能请求\nabout: 使用简练详细的语言描述希望加入的新功能\ntitle: ''\nlabels: enhancement\nassignees: ''\n\n---\n\n**温馨提示: 未`star`项目会被自动关闭issue哦!**\n\n**例行检查**\n\n+ [ ] 我已确认目前没有类似 issue\n+ [ ] 我已确认我已升级到最新版本\n+ [ ] 我理解并愿意跟进此 issue,协助测试和提供反馈\n+ [ ] 我理解并认可上述内容,并理解项目维护者精力有限,不遵循规则的 issue 可能会被无视或直接关闭\n\n**功能描述**\n\n**应用场景**\n"
  },
  {
    "path": ".github/close_issue.py",
    "content": "import os\nimport requests\n\nissue_labels = ['no respect']\ngithub_repo = 'deanxv/genspark2api'\ngithub_token = os.getenv(\"GITHUB_TOKEN\")\nheaders = {\n    'Authorization': 'Bearer ' + github_token,\n    'Accept': 'application/vnd.github+json',\n    'X-GitHub-Api-Version': '2022-11-28',\n}\n\n\ndef get_stargazers(repo):\n    page = 1\n    _stargazers = {}\n    while True:\n        queries = {\n            'per_page': 100,\n            'page': page,\n        }\n        url = 'https://api.github.com/repos/{}/stargazers?'.format(repo)\n\n        resp = requests.get(url, headers=headers, params=queries)\n        if resp.status_code != 200:\n            raise Exception('Error get stargazers: ' + resp.text)\n\n        data = resp.json()\n        if not data:\n            break\n\n        for stargazer in data:\n            _stargazers[stargazer['login']] = True\n        page += 1\n\n    print('list stargazers done, total: ' + str(len(_stargazers)))\n    return _stargazers\n\n\ndef get_issues(repo):\n    page = 1\n    _issues = []\n    while True:\n        queries = {\n            'state': 'open',\n            'sort': 'created',\n            'direction': 'desc',\n            'per_page': 100,\n            'page': page,\n        }\n        url = 'https://api.github.com/repos/{}/issues?'.format(repo)\n\n        resp = requests.get(url, headers=headers, params=queries)\n        if resp.status_code != 200:\n            raise Exception('Error get issues: ' + resp.text)\n\n        data = resp.json()\n        if not data:\n            break\n\n        _issues += data\n        page += 1\n\n    print('list issues done, total: ' + str(len(_issues)))\n    return _issues\n\n\ndef close_issue(repo, issue_number):\n    url = 'https://api.github.com/repos/{}/issues/{}'.format(repo, issue_number)\n    data = {\n        'state': 'closed',\n        'state_reason': 'not_planned',\n        'labels': issue_labels,\n    }\n    resp = requests.patch(url, headers=headers, json=data)\n    if resp.status_code != 200:\n        raise Exception('Error close issue: ' + resp.text)\n\n    print('issue: {} closed'.format(issue_number))\n\n\ndef lock_issue(repo, issue_number):\n    url = 'https://api.github.com/repos/{}/issues/{}/lock'.format(repo, issue_number)\n    data = {\n        'lock_reason': 'spam',\n    }\n    resp = requests.put(url, headers=headers, json=data)\n    if resp.status_code != 204:\n        raise Exception('Error lock issue: ' + resp.text)\n\n    print('issue: {} locked'.format(issue_number))\n\n\nif '__main__' == __name__:\n    stargazers = get_stargazers(github_repo)\n\n    issues = get_issues(github_repo)\n    for issue in issues:\n        login = issue['user']['login']\n        if login not in stargazers:\n            print('issue: {}, login: {} not in stargazers'.format(issue['number'], login))\n            close_issue(github_repo, issue['number'])\n            lock_issue(github_repo, issue['number'])\n\n    print('done')\n"
  },
  {
    "path": ".github/workflows/CloseIssue.yml",
    "content": "name: CloseIssue\n\non:\n  workflow_dispatch:\n  issues:\n    types: [ opened ]\n\njobs:\n  run-python-script:\n    runs-on: ubuntu-latest\n\n    steps:\n      - uses: actions/checkout@v3\n      - uses: actions/setup-python@v4\n        with:\n          python-version: \"3.10\"\n\n      - name: Install Dependencies\n        run: pip install requests\n\n      - name: Run close_issue.py Script\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n        run: python .github/close_issue.py"
  },
  {
    "path": ".github/workflows/docker-image-amd64.yml",
    "content": "name: Publish Docker image (amd64)\n\non:\n  push:\n    tags:\n      - '*'\n  workflow_dispatch:\n    inputs:\n      name:\n        description: 'reason'\n        required: false\njobs:\n  push_to_registries:\n    name: Push Docker image to multiple registries\n    runs-on: ubuntu-latest\n    environment: github-pages\n    permissions:\n      packages: write\n      contents: read\n    steps:\n      - name: Check out the repo\n        uses: actions/checkout@v3\n\n      - name: Save version info\n        run: |\n          git describe --tags > VERSION \n\n      - name: Log in to Docker Hub\n        uses: docker/login-action@v2\n        with:\n          username: ${{ secrets.DOCKERHUB_USERNAME }}\n          password: ${{ secrets.DOCKERHUB_TOKEN }}\n\n      - name: Log in to the Container registry\n        uses: docker/login-action@v2\n        with:\n          registry: ghcr.io\n          username: ${{ github.actor }}\n          password: ${{ secrets.GITHUB_TOKEN }}\n\n      - name: Extract metadata (tags, labels) for Docker\n        id: meta\n        uses: docker/metadata-action@v4\n        with:\n          images: |\n            deanxv/genspark2api\n            ghcr.io/${{ github.repository }}\n\n      - name: Build and push Docker images\n        uses: docker/build-push-action@v3\n        with:\n          context: .\n          push: true\n          tags: ${{ steps.meta.outputs.tags }}\n          labels: ${{ steps.meta.outputs.labels }}"
  },
  {
    "path": ".github/workflows/docker-image-arm64.yml",
    "content": "name: Publish Docker image (arm64)\n\non:\n  push:\n    tags:\n      - '*'\n      - '!*-alpha*'\n  workflow_dispatch:\n    inputs:\n      name:\n        description: 'reason'\n        required: false\njobs:\n  push_to_registries:\n    name: Push Docker image to multiple registries\n    runs-on: ubuntu-latest\n    environment: github-pages\n    permissions:\n      packages: write\n      contents: read\n    steps:\n      - name: Check out the repo\n        uses: actions/checkout@v3\n\n      - name: Save version info\n        run: |\n          git describe --tags > VERSION \n\n      - name: Set up QEMU\n        uses: docker/setup-qemu-action@v2\n\n      - name: Set up Docker Buildx\n        uses: docker/setup-buildx-action@v2\n\n      - name: Log in to Docker Hub\n        uses: docker/login-action@v2\n        with:\n          username: ${{ secrets.DOCKERHUB_USERNAME }}\n          password: ${{ secrets.DOCKERHUB_TOKEN }}\n\n      - name: Log in to the Container registry\n        uses: docker/login-action@v2\n        with:\n          registry: ghcr.io\n          username: ${{ github.actor }}\n          password: ${{ secrets.GITHUB_TOKEN }}\n\n      - name: Extract metadata (tags, labels) for Docker\n        id: meta\n        uses: docker/metadata-action@v4\n        with:\n          images: |\n            deanxv/genspark2api\n            ghcr.io/${{ github.repository }}\n\n      - name: Build and push Docker images\n        uses: docker/build-push-action@v3\n        with:\n          context: .\n          platforms: linux/amd64,linux/arm64\n          push: true\n          tags: ${{ steps.meta.outputs.tags }}\n          labels: ${{ steps.meta.outputs.labels }}"
  },
  {
    "path": ".github/workflows/github-pages.yml",
    "content": "name: Build GitHub Pages\non:\n  workflow_dispatch:\n    inputs:\n      name:\n        description: 'Reason'\n        required: false\njobs:\n  build-and-deploy:\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout 🛎️\n        uses: actions/checkout@v2 # If you're using actions/checkout@v2 you must set persist-credentials to false in most cases for the deployment to work correctly.\n        with:\n          persist-credentials: false\n      - name: Install and Build 🔧 # This example project is built using npm and outputs the result to the 'build' folder. Replace with the commands required to build your project, or remove this step entirely if your site is pre-built.\n        env:\n          CI: \"\"\n        run: |\n          cd web\n          npm install\n          npm run build\n\n      - name: Deploy 🚀\n        uses: JamesIves/github-pages-deploy-action@releases/v3\n        with:\n          ACCESS_TOKEN: ${{ secrets.ACCESS_TOKEN }}\n          BRANCH: gh-pages # The branch the action should deploy to.\n          FOLDER: web/build # The folder the action should deploy."
  },
  {
    "path": ".github/workflows/linux-release.yml",
    "content": "name: Linux Release\npermissions:\n  contents: write\n\non:\n  push:\n    tags:\n      - '*'\n      - '!*-alpha*'\njobs:\n  release:\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout\n        uses: actions/checkout@v3\n        with:\n          fetch-depth: 0\n      - uses: actions/setup-node@v3\n        with:\n          node-version: 16\n      - name: Set up Go\n        uses: actions/setup-go@v3\n        with:\n          go-version: '>=1.18.0'\n      - name: Build Backend (amd64)\n        run: |\n          go mod download\n          go build -ldflags \"-s -w -X 'genspark2api/common.Version=$(git describe --tags)' -extldflags '-static'\" -o genspark2api\n\n      - name: Build Backend (arm64)\n        run: |\n          sudo apt-get update\n          sudo apt-get install gcc-aarch64-linux-gnu\n          CC=aarch64-linux-gnu-gcc CGO_ENABLED=1 GOOS=linux GOARCH=arm64 go build -ldflags \"-s -w -X 'genspark2api/common.Version=$(git describe --tags)' -extldflags '-static'\" -o genspark2api-arm64\n\n      - name: Release\n        uses: softprops/action-gh-release@v1\n        if: startsWith(github.ref, 'refs/tags/')\n        with:\n          files: |\n            genspark2api\n            genspark2api-arm64\n          draft: false\n          generate_release_notes: true\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}"
  },
  {
    "path": ".github/workflows/macos-release.yml",
    "content": "name: macOS Release\npermissions:\n  contents: write\n\non:\n  push:\n    tags:\n      - '*'\n      - '!*-alpha*'\njobs:\n  release:\n    runs-on: macos-latest\n    steps:\n      - name: Checkout\n        uses: actions/checkout@v3\n        with:\n          fetch-depth: 0\n      - uses: actions/setup-node@v3\n        with:\n          node-version: 16\n      - name: Set up Go\n        uses: actions/setup-go@v3\n        with:\n          go-version: '>=1.18.0'\n      - name: Build Backend\n        run: |\n          go mod download\n          go build -ldflags \"-X 'genspark2api/common.Version=$(git describe --tags)'\" -o genspark2api-macos\n      - name: Release\n        uses: softprops/action-gh-release@v1\n        if: startsWith(github.ref, 'refs/tags/')\n        with:\n          files: genspark2api-macos\n          draft: false\n          generate_release_notes: true\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n"
  },
  {
    "path": ".github/workflows/windows-release.yml",
    "content": "name: Windows Release\npermissions:\n  contents: write\n\non:\n  push:\n    tags:\n      - '*'\n      - '!*-alpha*'\njobs:\n  release:\n    runs-on: windows-latest\n    defaults:\n      run:\n        shell: bash\n    steps:\n      - name: Checkout\n        uses: actions/checkout@v3\n        with:\n          fetch-depth: 0\n      - uses: actions/setup-node@v3\n        with:\n          node-version: 16\n      - name: Set up Go\n        uses: actions/setup-go@v3\n        with:\n          go-version: '>=1.18.0'\n      - name: Build Backend\n        run: |\n          go mod download\n          go build -ldflags \"-s -w -X 'genspark2api/common.Version=$(git describe --tags)'\" -o genspark2api.exe\n      - name: Release\n        uses: softprops/action-gh-release@v1\n        if: startsWith(github.ref, 'refs/tags/')\n        with:\n          files: genspark2api.exe\n          draft: false\n          generate_release_notes: true\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}"
  },
  {
    "path": ".gitignore",
    "content": ".idea\n.vscode\nupload\n*.exe\n*.db\nbuild"
  },
  {
    "path": "Dockerfile",
    "content": "# 使用 Golang 镜像作为构建阶段\nFROM golang AS builder\n\n# 设置环境变量\nENV GO111MODULE=on \\\n    CGO_ENABLED=0 \\\n    GOOS=linux\n\n# 设置工作目录\nWORKDIR /build\n\n# 复制 go.mod 和 go.sum 文件,先下载依赖\nCOPY go.mod go.sum ./\n#ENV GOPROXY=https://goproxy.cn,direct\nRUN go mod download\n\n# 复制整个项目并构建可执行文件\nCOPY . .\nRUN go build -o /genspark2api\n\n# 使用 Alpine 镜像作为最终镜像\nFROM alpine\n\n# 安装基本的运行时依赖\nRUN apk --no-cache add ca-certificates tzdata\n\n# 从构建阶段复制可执行文件\nCOPY --from=builder /genspark2api .\n\n# 暴露端口\nEXPOSE 7055\n# 工作目录\nWORKDIR /app/genspark2api/data\n# 设置入口命令\nENTRYPOINT [\"/genspark2api\"]\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "<p align=\"right\">\n   <strong>中文</strong> \n</p>\n<div align=\"center\">\n\n# Genspark2API\n\n_觉得有点意思的话 别忘了点个 ⭐_\n\n<a href=\"https://t.me/+raL5ppEzDIFmZTY1\">\n  <img src=\"https://img.shields.io/badge/Telegram-AI Wave交流群-0088cc?style=for-the-badge&logo=telegram&logoColor=white\" alt=\"Telegram 交流群\" />\n</a>\n\n<sup><i>AI Wave 社群</i></sup> · <sup><i>(群内提供公益API、AI机器人)</i></sup>\n\n\n</div>\n\n> ⚠️目前官方强制校验`ReCaptchaV3`\n> 不通过则模型降智/生图异常,请参考[genspark-playwright-prxoy服务过V3验证](#genspark-playwright-prxoy服务过V3验证)并配置环境变量\n`RECAPTCHA_PROXY_URL`。\n\n## 功能\n\n- [x] 支持对话接口(流式/非流式)(`/chat/completions`)(请求非以下列表的模型会触发`Mixture-of-Agents`模式)\n    - **gpt-5-minimal**\n    - **gpt-5**\n    - **gpt-5-high**\n    - **gpt-5-pro**\n    - **gpt-4.1**\n    - **o1**\n    - **o3**\n    - **o3-pro**\n    - **o4-mini-high**\n    - **claude-3-7-sonnet-thinking**\n    - **claude-3-7-sonnet**\n    - **claude-sonnet-4-5**\n    - **claude-sonnet-4-thinking**\n    - **claude-sonnet-4**\n    - **claude-opus-4-1**\n    - **claude-opus-4**\n    - **gemini-2.5-pro**\n    - **gemini-2.5-flash**\n    - **gemini-2.0-flash**\n    - **deep-seek-v3**\n    - **deep-seek-r1**\n    - **grok-4-0709**\n- [x] 支持**联网搜索**,在模型名后添加`-search`即可(如:`gpt-4o-search`)\n- [x] 支持识别**图片**/**文件**多轮对话\n- [x] 支持文生图接口(`/images/generations`)\n    - **fal-ai/nano-banana**\n    - **fal-ai/bytedance/seedream/v4**\n    - **gpt-image-1**\n    - **flux-pro/ultra**\n    - **flux-pro/kontext/pro**\n    - **imagen4**\n- [x] 支持文/图生视频接口(`/videos/generations`),详情查看[文/图生视频请求格式](#生视频请求格式)\n- [x] 支持自定义请求头校验值(Authorization)\n- [x] 支持cookie池(随机)\n- [x] 支持请求失败自动切换cookie重试(需配置cookie池)\n- [x] 可配置自动删除对话记录\n- [x] 可配置代理请求(环境变量`PROXY_URL`)\n- [x] 可配置Model绑定Chat(解决模型自动切换导致**降智**),详细请看[进阶配置](#解决模型自动切换导致降智问题)。\n\n### 接口文档:\n\n略\n\n### 示例:\n\n<span><img src=\"docs/img2.png\" width=\"800\"/></span>\n\n## 如何使用\n\n略\n\n## 如何集成NextChat\n\n填 接口地址(ip:端口/域名) 及 API-Key(`PROXY_SECRET`),其它的随便填随便选。\n\n> 如果自己没有搭建NextChat面板,这里有个已经搭建好的可以使用 [NeatChat](https://ai.aytsao.cn/)\n\n<span><img src=\"docs/img5.png\" width=\"800\"/></span>\n\n## 如何集成one-api\n\n填 `BaseURL`(ip:端口/域名) 及 密钥(`PROXY_SECRET`),其它的随便填随便选。\n\n<span><img src=\"docs/img3.png\" width=\"800\"/></span>\n\n## 部署\n\n### 基于 Docker-Compose(All In One) 进行部署\n\n```shell\ndocker-compose pull && docker-compose up -d\n```\n\n#### docker-compose.yml\n\n```docker\nversion: '3.4'\n\nservices:\n  genspark2api:\n    image: deanxv/genspark2api:latest\n    container_name: genspark2api\n    restart: always\n    ports:\n      - \"7055:7055\"\n    volumes:\n      - ./data:/app/genspark2api/data\n    environment:\n      - GS_COOKIE=******  # cookie (多个请以,分隔)\n      - API_SECRET=123456  # [可选]接口密钥-修改此行为请求头校验的值(多个请以,分隔)\n      - TZ=Asia/Shanghai\n```\n\n### 基于 Docker 进行部署\n\n```docker\ndocker run --name genspark2api -d --restart always \\\n-p 7055:7055 \\\n-v $(pwd)/data:/app/genspark2api/data \\\n-e GS_COOKIE=***** \\\n-e API_SECRET=\"123456\" \\\n-e TZ=Asia/Shanghai \\\ndeanxv/genspark2api\n```\n\n其中`API_SECRET`、`GS_COOKIE`修改为自己的。\n\n如果上面的镜像无法拉取,可以尝试使用 GitHub 的 Docker 镜像,将上面的`deanxv/genspark2api`替换为\n`ghcr.io/deanxv/genspark2api`即可。\n\n### 部署到第三方平台\n\n<details>\n<summary><strong>部署到 Zeabur</strong></summary>\n<div>\n\n[![Deployed on Zeabur](https://zeabur.com/deployed-on-zeabur-dark.svg)](https://zeabur.com?referralCode=deanxv&utm_source=deanxv)\n\n> Zeabur 的服务器在国外,自动解决了网络的问题,~~同时免费的额度也足够个人使用~~\n\n1. 首先 **fork** 一份代码。\n2. 进入 [Zeabur](https://zeabur.com?referralCode=deanxv),使用github登录,进入控制台。\n3. 在 Service -> Add Service,选择 Git（第一次使用需要先授权）,选择你 fork 的仓库。\n4. Deploy 会自动开始,先取消。\n5. 添加环境变量\n\n   `GS_COOKIE:******`  cookie (多个请以,分隔)\n\n   `API_SECRET:123456` [可选]接口密钥-修改此行为请求头校验的值(多个请以,分隔)(与openai-API-KEY用法一致)\n\n保存。\n\n6. 选择 Redeploy。\n\n</div>\n\n\n</details>\n\n<details>\n<summary><strong>部署到 Render</strong></summary>\n<div>\n\n> Render 提供免费额度,绑卡后可以进一步提升额度\n\nRender 可以直接部署 docker 镜像,不需要 fork 仓库：[Render](https://dashboard.render.com)\n\n</div>\n</details>\n\n## 配置\n\n### 环境变量\n\n1. `PORT=7055`  [可选]端口,默认为7055\n2. `DEBUG=true`  [可选]DEBUG模式,可打印更多信息[true:打开、false:关闭]\n3. `API_SECRET=123456`  [可选]接口密钥-修改此行为请求头(Authorization)校验的值(同API-KEY)(多个请以,分隔)\n4. `GS_COOKIE=******`  cookie (多个请以,分隔)\n5. `AUTO_DEL_CHAT=0`  [可选]对话完成自动删除(默认:0)[0:关闭,1:开启]\n6. `REQUEST_RATE_LIMIT=60`  [可选]每分钟下的单ip请求速率限制,默认:60次/min\n7. `PROXY_URL=http://127.0.0.1:10801`  [可选]代理\n8. `RECAPTCHA_PROXY_URL=http://127.0.0.1:7022`  [可选]genspark-playwright-prxoy验证服务地址，仅填写域名或ip:端口即可。(\n   示例:`RECAPTCHA_PROXY_URL=https://genspark-playwright-prxoy.com`或`RECAPTCHA_PROXY_URL=http://127.0.0.1:7022`)\n   ,详情请看[genspark-playwright-prxoy服务过V3验证](#genspark-playwright-prxoy服务过V3验证)\n9. `AUTO_MODEL_CHAT_MAP_TYPE=1`  [可选]自动配置Model绑定Chat(默认:1)[0:关闭,1:开启]\n10. `MODEL_CHAT_MAP=claude-3-7-sonnet=a649******00fa,gpt-4o=su74******47hd`  [可选]Model绑定Chat(多个请以,分隔)\n    ,详细请看[进阶配置](#解决模型自动切换导致降智问题)\n11. `ROUTE_PREFIX=hf`  [可选]路由前缀,默认为空,添加该变量后的接口示例:`/hf/v1/chat/completions`\n12. `RATE_LIMIT_COOKIE_LOCK_DURATION=600`  [可选]到达速率限制的cookie禁用时间,默认为600s\n13. `REASONING_HIDE=0`  [可选]**隐藏**推理过程(默认:0)[0:关闭,1:开启]\n\n~~14.\n`SESSION_IMAGE_CHAT_MAP=aed9196b-********-4ed6e32f7e4d=0c6785e6-********-7ff6e5a2a29c,aefwer6b-********-casds22=fda234-********-sfaw123`  [可选]\nSession绑定Image-Chat(多个请以,分隔),详细请看[进阶配置](#生图模型配置)~~\n\n~~15. `YES_CAPTCHA_CLIENT_KEY=******`  [可选]YesCaptcha Client Key\n过谷歌验证,详细请看[使用YesCaptcha过谷歌验证](#使用YesCaptcha过谷歌验证)~~\n\n### cookie获取方式\n\n1. 打开**F12**开发者工具。\n2. 发起对话。\n3. 点击ask请求,请求头中的**cookie**即为环境变量**GS_COOKIE**所需值。\n\n> **【注】** 其中`session_id=f9c60******cb6d`是必须的,其他内容可要可不要,即环境变量`GS_COOKIE=session_id=f9c60******cb6d`\n\n\n![img.png](docs/img.png)\n\n## 进阶配置\n\n### 解决模型自动切换导致降智问题\n\n#### 方案一 (默认启用此配置)【推荐】\n\n> 配置环境变量 **AUTO_MODEL_CHAT_MAP_TYPE=1**\n>\n> 此配置下,会在调用模型时获取对话的id,并绑定模型。\n\n#### 方案二\n\n> 配置环境变量 MODEL_CHAT_MAP\n>\n> 【作用】指定对话,解决模型自动切换导致降智问题。\n\n1. 打开**F12**开发者工具。\n2. 选择需要绑定的对话的模型(示例:`claude-3-7-sonnet`),发起对话。\n3. 点击ask请求,此时最上方url中的`id`(或响应中的`id`)即为此对话唯一id。\n   ![img.png](docs/img4.png)\n4. 配置环境变量 `MODEL_CHAT_MAP=claude-3-7-sonnet=3cdcc******474c5` (多个请以,分隔)\n\n### genspark-playwright-prxoy服务过V3验证\n\n1. docker部署genspark-playwright-prxoy\n\n#### docker\n\n```docker \ndocker run --name genspark-playwright-proxy -d --restart always \\\n-p 7022:7022 \\\n-v $(pwd)/data:/app/genspark-playwright-proxy/data \\\n-e PROXY_URL=http://account:pwd@ip:port #  [可选] 推荐(住宅)动态代理,配置代理后过验证概率更高,但响应会变慢。\n-e TZ=Asia/Shanghai \\\ndeanxv/genspark-playwright-proxy\n```\n\n#### docker-compose\n\n```docker-compose\nversion: '3.4'\n\nservices:\n  genspark-playwright-prxoy:\n    image: deanxv/genspark-playwright-proxy:latest\n    container_name: genspark-playwright-prxoy\n    restart: always\n    ports:\n      - \"7022:7022\"\n    volumes:\n      - ./data:/app/genspark-playwright-prxoy/data\n    environment:\n      - PROXY_URL=http://account:pwd@ip:port #  [可选] 推荐(住宅)动态代理,配置代理后过验证概率更高,但响应会变慢。\n```\n\n2. 部署后配置`genspark2api`环境变量`RECAPTCHA_PROXY_URL`，仅填写域名或ip:端口即可。(示例:\n   `RECAPTCHA_PROXY_URL=https://genspark-playwright-prxoy.com`或`RECAPTCHA_PROXY_URL=http://127.0.0.1:7022`)\n\n3. 重启`genspark2api`服务。\n\n#### 接入自定义Recaptcha服务\n\n###### 接口：获取令牌\n\n###### 基本信息\n\n- **接口地址**：`/genspark`\n- **请求方式**：GET\n- **接口描述**：获取用户认证令牌\n\n###### 请求参数\n\n###### 请求头\n\n| 参数名    | 必选 | 类型     | 说明     |\n|--------|----|--------|--------|\n| cookie | 是  | string | 用户会话凭证 |\n\n###### 响应参数\n\n###### 响应示例\n\n```json\n{\n  \"code\": 200,\n  \"token\": \"ey********pe\"\n}\n```\n\n## 报错排查\n\n> `Detected Cloudflare Challenge Page`\n>\n\n被Cloudflare拦截出5s盾,可配置`PROXY_URL`。\n\n(【推荐方案】[自建ipv6代理池绕过cf对ip的速率限制及5s盾](https://linux.do/t/topic/367413)\n或购买[IProyal](https://iproyal.cn/?r=244330))\n\n> `Genspark Service Unavailable`\n>\nGenspark官方服务不可用,请稍后再试。\n\n> `All cookies are temporarily unavailable.`\n>\n所有用户(cookie)均到达速率限制,更换用户cookie或稍后再试。\n\n## 生视频请求格式\n\n### Request\n\n**Endpoint**: `POST /v1/videos/generations`\n\n**Content-Type**: `application/json`\n\n#### Request Parameters\n\n| 字段 Field     | 类型 Type | 必填 Required | 描述 Description            | 可选值 Accepted Values                                                                             |\n|--------------|---------|-------------|---------------------------|-------------------------------------------------------------------------------------------------|\n| model        | string  | 是           | 使用的视频生成模型                 | 模型列表: `sora-2`\\|`sora-2-pro`\\|`gemini/veo3`\\|`gemini/veo3/fast`\\|`kling/v2.5-turbo/pro`\\|`fal-ai/bytedance/seedance/v1/pro`\\|`minimax/hailuo-02/standard`\\|`pixverse/v5`\\|`fal-ai/bytedance/seedance/v1/lite`\\|`gemini/veo2`\\|`wan/v2.2`\\|`hunyuan`\\|`vidu/start-end-to-video`\\|`runway/gen4_turbo` |\n| aspect_ratio | string  | 是           | 视频宽高比                     | `9:16` \\| `16:9` \\| `3:4` \\|`1:1` \\| `4:3`                                                      |\n| duration     | int     | 是           | 视频时长（单位：秒）                | 正整数                                                                                             |\n| prompt       | string  | 是           | 生成视频的文本描述                 | -                                                                                               |\n| auto_prompt  | bool    | 是           | 是否自动优化提示词                 | `true` \\| `false`                                                                               |\n| image        | string  | 否           | 用于视频生成的基底图片（Base64编码/url） | Base64字符串/url                                                                                   |\n\n---\n\n### Response\n\n#### Response Object\n\n```json\n{\n  \"created\": 1677664796,\n  \"data\": [\n    {\n      \"url\": \"https://example.com/video.mp4\"\n    }\n  ]\n}\n```\n\n## 其他\n\n**Genspark**(\n注册领取1个月Plus): [https://www.genspark.ai](https://www.genspark.ai/invite?invite_code=YjVjMGRkYWVMZmE4YUw5MDc0TDM1ODlMZDYwMzQ4OTJlNmEx)\n"
  },
  {
    "path": "check/check.go",
    "content": "package check\n\nimport (\n\t\"genspark2api/common\"\n\t\"genspark2api/common/config\"\n\tlogger \"genspark2api/common/loggger\"\n\t\"github.com/samber/lo\"\n\t\"regexp\"\n\t\"strings\"\n)\n\nfunc CheckEnvVariable() {\n\tlogger.SysLog(\"environment variable checking...\")\n\n\tif config.GSCookie == \"\" {\n\t\tlogger.FatalLog(\"环境变量 GS_COOKIE 未设置\")\n\t}\n\tif config.YesCaptchaClientKey == \"\" {\n\t\t//logger.SysLog(\"环境变量 YES_CAPTCHA_CLIENT_KEY 未设置，将无法使用 YesCaptcha 过谷歌验证，导致无法调用文生图模型 \\n ClientKey获取地址：https://yescaptcha.com/i/021iAE\")\n\t}\n\tif config.ModelChatMapStr != \"\" {\n\t\tpattern := `^([a-zA-Z0-9\\-\\/]+=([a-zA-Z0-9\\-\\.]+))(,[a-zA-Z0-9\\-\\/]+=([a-zA-Z0-9\\-\\.]+))*`\n\t\tmatch, _ := regexp.MatchString(pattern, config.ModelChatMapStr)\n\t\tif !match {\n\t\t\tlogger.FatalLog(\"环境变量 MODEL_CHAT_MAP 设置有误\")\n\t\t} else {\n\t\t\tmodelChatMap := make(map[string]string)\n\t\t\tpairs := strings.Split(config.ModelChatMapStr, \",\")\n\n\t\t\tfor _, pair := range pairs {\n\t\t\t\tkv := strings.Split(pair, \"=\")\n\t\t\t\tif !lo.Contains(common.DefaultOpenaiModelList, kv[0]) {\n\t\t\t\t\tlogger.FatalLog(\"环境变量 MODEL_CHAT_MAP 中 MODEL 有误\")\n\t\t\t\t}\n\t\t\t\tmodelChatMap[kv[0]] = kv[1]\n\t\t\t}\n\n\t\t\tconfig.ModelChatMap = modelChatMap\n\n\t\t\tif config.AutoModelChatMapType == 1 {\n\t\t\t\tlogger.FatalLog(\"环境变量 MODEL_CHAT_MAP 有值时,环境变量 AUTO_MODEL_CHAT_MAP_TYPE 不能设置为1\")\n\t\t\t}\n\n\t\t}\n\t}\n\n\tif config.SessionImageChatMapStr != \"\" {\n\t\tpattern := `^([a-zA-Z0-9\\-\\/]+=([a-zA-Z0-9\\-\\.]+))(,[a-zA-Z0-9\\-\\/]+=([a-zA-Z0-9\\-\\.]+))*`\n\t\tmatch, _ := regexp.MatchString(pattern, config.SessionImageChatMapStr)\n\t\tif !match {\n\t\t\tlogger.FatalLog(\"环境变量 SESSION_IMAGE_CHAT_MAP 设置有误\")\n\t\t} else {\n\t\t\tsessionImageChatMap := make(map[string]string)\n\t\t\tpairs := strings.Split(config.SessionImageChatMapStr, \",\")\n\n\t\t\tfor _, pair := range pairs {\n\t\t\t\tkv := strings.Split(pair, \"=\")\n\t\t\t\tsessionImageChatMap[\"session_id=\"+kv[0]] = kv[1]\n\t\t\t}\n\n\t\t\tconfig.SessionImageChatMap = sessionImageChatMap\n\t\t}\n\t} else {\n\t\t//logger.SysLog(\"环境变量 SESSION_IMAGE_CHAT_MAP 未设置，生图可能会异常\")\n\t}\n\n\tlogger.SysLog(\"environment variable check passed.\")\n}\n"
  },
  {
    "path": "common/config/config.go",
    "content": "package config\n\nimport (\n\t\"errors\"\n\t\"genspark2api/common/env\"\n\t\"genspark2api/yescaptcha\"\n\t\"math/rand\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar ApiSecret = os.Getenv(\"API_SECRET\")\nvar ApiSecrets = strings.Split(os.Getenv(\"API_SECRET\"), \",\")\n\nvar GSCookie = os.Getenv(\"GS_COOKIE\")\n\n//var GSCookies = strings.Split(os.Getenv(\"GS_COOKIE\"), \",\")\n\n// var IpBlackList = os.Getenv(\"IP_BLACK_LIST\")\nvar IpBlackList = strings.Split(os.Getenv(\"IP_BLACK_LIST\"), \",\")\n\nvar AutoDelChat = env.Int(\"AUTO_DEL_CHAT\", 0)\nvar ProxyUrl = env.String(\"PROXY_URL\", \"\")\nvar AutoModelChatMapType = env.Int(\"AUTO_MODEL_CHAT_MAP_TYPE\", 1)\nvar YesCaptchaClientKey = env.String(\"YES_CAPTCHA_CLIENT_KEY\", \"\")\n\n// var CheatUrl = env.String(\"CHEAT_URL\", \"https://gs-cheat.aytsao.cn/genspark/create/req/body\")\nvar RecaptchaProxyUrl = env.String(\"RECAPTCHA_PROXY_URL\", \"\")\n\n// 隐藏思考过程\nvar ReasoningHide = env.Int(\"REASONING_HIDE\", 0)\n\n// 前置message\nvar PRE_MESSAGES_JSON = env.String(\"PRE_MESSAGES_JSON\", \"\")\n\nvar RateLimitCookieLockDuration = env.Int(\"RATE_LIMIT_COOKIE_LOCK_DURATION\", 10*60)\n\n// 路由前缀\nvar RoutePrefix = env.String(\"ROUTE_PREFIX\", \"\")\nvar ModelChatMapStr = env.String(\"MODEL_CHAT_MAP\", \"\")\nvar ModelChatMap = make(map[string]string)\nvar SessionImageChatMap = make(map[string]string)\nvar GlobalSessionManager *SessionManager\n\nvar SessionImageChatMapStr = env.String(\"SESSION_IMAGE_CHAT_MAP\", \"\")\nvar YescaptchaClient *yescaptcha.Client\n\nvar AllDialogRecordEnable = os.Getenv(\"ALL_DIALOG_RECORD_ENABLE\")\nvar RequestOutTime = os.Getenv(\"REQUEST_OUT_TIME\")\nvar StreamRequestOutTime = os.Getenv(\"STREAM_REQUEST_OUT_TIME\")\nvar SwaggerEnable = os.Getenv(\"SWAGGER_ENABLE\")\nvar OnlyOpenaiApi = os.Getenv(\"ONLY_OPENAI_API\")\n\nvar DebugEnabled = os.Getenv(\"DEBUG\") == \"true\"\n\nvar RateLimitKeyExpirationDuration = 20 * time.Minute\n\nvar RequestOutTimeDuration = 5 * time.Minute\n\nvar (\n\tRequestRateLimitNum            = env.Int(\"REQUEST_RATE_LIMIT\", 60)\n\tRequestRateLimitDuration int64 = 1 * 60\n)\n\ntype RateLimitCookie struct {\n\tExpirationTime time.Time // 过期时间\n}\n\nvar (\n\trateLimitCookies sync.Map // 使用 sync.Map 管理限速 Cookie\n)\n\nfunc AddRateLimitCookie(cookie string, expirationTime time.Time) {\n\trateLimitCookies.Store(cookie, RateLimitCookie{\n\t\tExpirationTime: expirationTime,\n\t})\n\t//fmt.Printf(\"Storing cookie: %s with value: %+v\\n\", cookie, RateLimitCookie{ExpirationTime: expirationTime})\n}\n\ntype CookieManager struct {\n\tCookies      []string\n\tcurrentIndex int\n\tmu           sync.Mutex\n}\n\nvar (\n\tGSCookies    []string   // 存储所有的 cookies\n\tcookiesMutex sync.Mutex // 保护 GSCookies 的互斥锁\n)\n\n// InitGSCookies 初始化 GSCookies\nfunc InitGSCookies() {\n\tcookiesMutex.Lock()\n\tdefer cookiesMutex.Unlock()\n\n\tGSCookies = []string{}\n\n\t// 从环境变量中读取 GS_COOKIE 并拆分为切片\n\tcookieStr := os.Getenv(\"GS_COOKIE\")\n\tif cookieStr != \"\" {\n\n\t\tfor _, cookie := range strings.Split(cookieStr, \",\") {\n\t\t\t// 如果 cookie 不包含 \"session_id=\"，则添加前缀\n\t\t\tif !strings.Contains(cookie, \"session_id=\") {\n\t\t\t\tcookie = \"session_id=\" + cookie\n\t\t\t}\n\t\t\tGSCookies = append(GSCookies, cookie)\n\t\t}\n\t}\n}\n\n// RemoveCookie 删除指定的 cookie（支持并发）\nfunc RemoveCookie(cookieToRemove string) {\n\tcookiesMutex.Lock()\n\tdefer cookiesMutex.Unlock()\n\n\t// 创建一个新的切片，过滤掉需要删除的 cookie\n\tvar newCookies []string\n\tfor _, cookie := range GetGSCookies() {\n\t\tif cookie != cookieToRemove {\n\t\t\tnewCookies = append(newCookies, cookie)\n\t\t}\n\t}\n\n\t// 更新 GSCookies\n\tGSCookies = newCookies\n}\n\n// GetGSCookies 获取 GSCookies 的副本\nfunc GetGSCookies() []string {\n\t//cookiesMutex.Lock()\n\t//defer cookiesMutex.Unlock()\n\n\t// 返回 GSCookies 的副本，避免外部直接修改\n\tcookiesCopy := make([]string, len(GSCookies))\n\tcopy(cookiesCopy, GSCookies)\n\treturn cookiesCopy\n}\n\n// NewCookieManager 创建 CookieManager\nfunc NewCookieManager() *CookieManager {\n\tvar validCookies []string\n\t// 遍历 GSCookies\n\tfor _, cookie := range GetGSCookies() {\n\t\tcookie = strings.TrimSpace(cookie)\n\t\tif cookie == \"\" {\n\t\t\tcontinue // 忽略空字符串\n\t\t}\n\n\t\t// 检查是否在 RateLimitCookies 中\n\t\tif value, ok := rateLimitCookies.Load(cookie); ok {\n\t\t\trateLimitCookie, ok := value.(RateLimitCookie) // 正确转换为 RateLimitCookie\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif rateLimitCookie.ExpirationTime.After(time.Now()) {\n\t\t\t\t// 如果未过期，忽略该 cookie\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\t// 如果已过期，从 RateLimitCookies 中删除\n\t\t\t\trateLimitCookies.Delete(cookie)\n\t\t\t}\n\t\t}\n\n\t\t// 添加到有效 cookie 列表\n\t\tvalidCookies = append(validCookies, cookie)\n\t}\n\n\treturn &CookieManager{\n\t\tCookies:      validCookies,\n\t\tcurrentIndex: 0,\n\t}\n}\n\nfunc IsRateLimited(cookie string) bool {\n\tif value, ok := rateLimitCookies.Load(cookie); ok {\n\t\trateLimitCookie := value.(RateLimitCookie)\n\t\treturn rateLimitCookie.ExpirationTime.After(time.Now())\n\t}\n\treturn false\n}\n\nfunc (cm *CookieManager) RemoveCookie(cookieToRemove string) error {\n\tcm.mu.Lock()\n\tdefer cm.mu.Unlock()\n\n\tif len(cm.Cookies) == 0 {\n\t\treturn errors.New(\"no cookies available\")\n\t}\n\n\t// 查找要删除的cookie的索引\n\tindex := -1\n\tfor i, cookie := range cm.Cookies {\n\t\tif cookie == cookieToRemove {\n\t\t\tindex = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// 如果没找到要删除的cookie\n\tif index == -1 {\n\t\treturn errors.New(\"RemoveCookie -> cookie not found\")\n\t}\n\n\t// 从切片中删除cookie\n\tcm.Cookies = append(cm.Cookies[:index], cm.Cookies[index+1:]...)\n\n\t// 如果当前索引大于或等于删除后的切片长度，重置为0\n\tif cm.currentIndex >= len(cm.Cookies) {\n\t\tcm.currentIndex = 0\n\t}\n\n\treturn nil\n}\n\nfunc (cm *CookieManager) GetNextCookie() (string, error) {\n\tcm.mu.Lock()\n\tdefer cm.mu.Unlock()\n\n\tif len(cm.Cookies) == 0 {\n\t\treturn \"\", errors.New(\"no cookies available\")\n\t}\n\n\tcm.currentIndex = (cm.currentIndex + 1) % len(cm.Cookies)\n\treturn cm.Cookies[cm.currentIndex], nil\n}\n\nfunc (cm *CookieManager) GetRandomCookie() (string, error) {\n\tcm.mu.Lock()\n\tdefer cm.mu.Unlock()\n\n\tif len(cm.Cookies) == 0 {\n\t\treturn \"\", errors.New(\"no cookies available\")\n\t}\n\n\t// 生成随机索引\n\trandomIndex := rand.Intn(len(cm.Cookies))\n\t// 更新当前索引\n\tcm.currentIndex = randomIndex\n\n\treturn cm.Cookies[randomIndex], nil\n}\n\n// SessionKey 定义复合键结构\ntype SessionKey struct {\n\tCookie string\n\tModel  string\n}\n\n// SessionManager 会话管理器\ntype SessionManager struct {\n\tsessions map[SessionKey]string\n\tmutex    sync.RWMutex\n}\n\n// NewSessionManager 创建新的会话管理器\nfunc NewSessionManager() *SessionManager {\n\treturn &SessionManager{\n\t\tsessions: make(map[SessionKey]string),\n\t}\n}\n\n// AddSession 添加会话记录（写操作，需要写锁）\nfunc (sm *SessionManager) AddSession(cookie string, model string, chatID string) {\n\tsm.mutex.Lock()\n\tdefer sm.mutex.Unlock()\n\n\tkey := SessionKey{\n\t\tCookie: cookie,\n\t\tModel:  model,\n\t}\n\tsm.sessions[key] = chatID\n}\n\n// GetChatID 获取会话ID（读操作，使用读锁）\nfunc (sm *SessionManager) GetChatID(cookie string, model string) (string, bool) {\n\tsm.mutex.RLock()\n\tdefer sm.mutex.RUnlock()\n\n\tkey := SessionKey{\n\t\tCookie: cookie,\n\t\tModel:  model,\n\t}\n\tchatID, exists := sm.sessions[key]\n\treturn chatID, exists\n}\n\n// DeleteSession 删除会话记录（写操作，需要写锁）\nfunc (sm *SessionManager) DeleteSession(cookie string, model string) {\n\tsm.mutex.Lock()\n\tdefer sm.mutex.Unlock()\n\n\tkey := SessionKey{\n\t\tCookie: cookie,\n\t\tModel:  model,\n\t}\n\tdelete(sm.sessions, key)\n}\n\n// GetChatIDsByCookie 获取指定cookie关联的所有chatID列表(读操作,使用读锁)\nfunc (sm *SessionManager) GetChatIDsByCookie(cookie string) []string {\n\tsm.mutex.RLock()\n\tdefer sm.mutex.RUnlock()\n\n\tvar chatIDs []string\n\tfor key, chatID := range sm.sessions {\n\t\tif key.Cookie == cookie {\n\t\t\tchatIDs = append(chatIDs, chatID)\n\t\t}\n\t}\n\treturn chatIDs\n}\n\ntype SessionMapManager struct {\n\tsessionMap   map[string]string\n\tkeys         []string\n\tcurrentIndex int\n\tmu           sync.Mutex\n}\n\nfunc NewSessionMapManager() *SessionMapManager {\n\t// 从初始map中提取所有的key\n\tkeys := make([]string, 0, len(SessionImageChatMap))\n\tfor k := range SessionImageChatMap {\n\t\tkeys = append(keys, k)\n\t}\n\n\treturn &SessionMapManager{\n\t\tsessionMap:   SessionImageChatMap,\n\t\tkeys:         keys,\n\t\tcurrentIndex: 0,\n\t}\n}\n\n// GetCurrentKeyValue 获取当前索引对应的键值对\nfunc (sm *SessionMapManager) GetCurrentKeyValue() (string, string, error) {\n\tsm.mu.Lock()\n\tdefer sm.mu.Unlock()\n\n\tif len(sm.keys) == 0 {\n\t\treturn \"\", \"\", errors.New(\"no sessions available\")\n\t}\n\n\tcurrentKey := sm.keys[sm.currentIndex]\n\treturn currentKey, sm.sessionMap[currentKey], nil\n}\n\n// GetNextKeyValue 获取下一个键值对\nfunc (sm *SessionMapManager) GetNextKeyValue() (string, string, error) {\n\tsm.mu.Lock()\n\tdefer sm.mu.Unlock()\n\n\tif len(sm.keys) == 0 {\n\t\treturn \"\", \"\", errors.New(\"no sessions available\")\n\t}\n\n\tsm.currentIndex = (sm.currentIndex + 1) % len(sm.keys)\n\tcurrentKey := sm.keys[sm.currentIndex]\n\treturn currentKey, sm.sessionMap[currentKey], nil\n}\n\n// GetRandomKeyValue 随机获取一个键值对\nfunc (sm *SessionMapManager) GetRandomKeyValue() (string, string, error) {\n\tsm.mu.Lock()\n\tdefer sm.mu.Unlock()\n\n\tif len(sm.keys) == 0 {\n\t\treturn \"\", \"\", errors.New(\"no sessions available\")\n\t}\n\n\trandomIndex := rand.Intn(len(sm.keys))\n\tsm.currentIndex = randomIndex\n\tcurrentKey := sm.keys[randomIndex]\n\treturn currentKey, sm.sessionMap[currentKey], nil\n}\n\n// AddKeyValue 添加新的键值对\nfunc (sm *SessionMapManager) AddKeyValue(key, value string) {\n\tsm.mu.Lock()\n\tdefer sm.mu.Unlock()\n\n\t// 如果key不存在，则添加到keys切片中\n\tif _, exists := sm.sessionMap[key]; !exists {\n\t\tsm.keys = append(sm.keys, key)\n\t}\n\tsm.sessionMap[key] = value\n}\n\n// RemoveKey 删除指定的键值对\nfunc (sm *SessionMapManager) RemoveKey(key string) {\n\tsm.mu.Lock()\n\tdefer sm.mu.Unlock()\n\n\tif _, exists := sm.sessionMap[key]; !exists {\n\t\treturn\n\t}\n\n\t// 从map中删除\n\tdelete(sm.sessionMap, key)\n\n\t// 从keys切片中删除\n\tfor i, k := range sm.keys {\n\t\tif k == key {\n\t\t\tsm.keys = append(sm.keys[:i], sm.keys[i+1:]...)\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// 调整currentIndex如果需要\n\tif sm.currentIndex >= len(sm.keys) && len(sm.keys) > 0 {\n\t\tsm.currentIndex = len(sm.keys) - 1\n\t}\n}\n\n// GetSize 获取当前map的大小\nfunc (sm *SessionMapManager) GetSize() int {\n\tsm.mu.Lock()\n\tdefer sm.mu.Unlock()\n\treturn len(sm.keys)\n}\n"
  },
  {
    "path": "common/constants.go",
    "content": "package common\n\nimport \"time\"\n\nvar StartTime = time.Now().Unix() // unit: second\n\nvar Version = \"v1.12.6\" // this hard coding will be replaced automatically when building, no need to manually change\n\nvar DefaultOpenaiModelList = []string{\n\t\"gpt-5-pro\",\n\t\"gpt-5.1-low\",\n\t\"gpt-5.2\",\n\t\"gpt-5.2-pro\",\n\t\"o3-pro\",\n\t\"claude-sonnet-4-6\",\n\t\"claude-sonnet-4-5\",\n\t\"claude-opus-4-6\",\n\t\"claude-opus-4-5\",\n\t\"claude-4-5-haiku\",\n\t\"gemini-2.5-pro\",\n\t\"gemini-3-flash-preview\",\n\t\"gemini-3.1-pro-preview\",\n\t\"gemini-3-pro-preview\",\n\t\"grok-4-0709\",\n\n\t\"nano-banana-pro\",\n\t\"nano-banana-2\",\n\t\"fal-ai/bytedance/seedream/v5/lite\",\n\t\"fal-ai/flux-2\",\n\t\"fal-ai/flux-2-pro\",\n\t\"fal-ai/z-image/turbo\",\n\t\"fal-ai/gpt-image-1.5\",\n\t\"recraft-v3\",\n\t\"ideogram/V_3\",\n\t\"qwen-image\",\n\t\"fal-ai/recraft-clarity-upscale\",\n\t\"fal-bria-rmbg\",\n\t\"fal-ai/image-editing/text-removal\",\n\n\t\"gemini/veo3.1\",\n\t\"gemini/veo3.1/reference-to-video\",\n\t\"gemini/veo3.1/first-last-frame-to-video\",\n\t\"sora-2\",\n\t\"sora-2-pro\",\n\t\"gemini/veo3\",\n\t\"kling/v3\",\n\t\"kling/v2.6/standard/motion-control\",\n\t\"kling/o3/image-to-video\",\n\t\"kling/o3/reference-to-video\",\n\t\"fal-ai/bytedance/seedance/v1.5/pro\",\n\t\"xai/grok-imagine-video\",\n\t\"minimax/hailuo-2.3/standard\",\n\t\"official/pixverse/v5\",\n\t\"fal-ai/bytedance/seedance/v1/pro/fast\",\n\t\"fal-ai/sync-lipsync/v2\",\n\t\"wan/v2.6\",\n\t\"vidu/q3\",\n\t\"runway/gen4_turbo\",\n\t\"fal-ai/bytedance-upscaler/upscale/video\",\n}\n\nvar TextModelList = []string{\n\t\"gpt-5-pro\",\n\t\"gpt-5.1-low\",\n\t\"gpt-5.2\",\n\t\"gpt-5.2-pro\",\n\t\"o3-pro\",\n\t\"claude-sonnet-4-6\",\n\t\"claude-sonnet-4-5\",\n\t\"claude-opus-4-6\",\n\t\"claude-opus-4-5\",\n\t\"claude-4-5-haiku\",\n\t\"gemini-2.5-pro\",\n\t\"gemini-3-flash-preview\",\n\t\"gemini-3.1-pro-preview\",\n\t\"gemini-3-pro-preview\",\n\t\"grok-4-0709\",\n}\n\nvar MixtureModelList = []string{\n\t\"gpt-5.1-low\",\n\t\"claude-sonnet-4-5\",\n\t\"gemini-3-pro-preview\",\n}\n\nvar ImageModelList = []string{\n\t\"nano-banana-pro\",\n\t\"nano-banana-2\",\n\t\"fal-ai/bytedance/seedream/v5/lite\",\n\t\"fal-ai/flux-2\",\n\t\"fal-ai/flux-2-pro\",\n\t\"fal-ai/z-image/turbo\",\n\t\"fal-ai/gpt-image-1.5\",\n\t\"recraft-v3\",\n\t\"ideogram/V_3\",\n\t\"qwen-image\",\n\t\"fal-ai/recraft-clarity-upscale\",\n\t\"fal-bria-rmbg\",\n\t\"fal-ai/image-editing/text-removal\",\n}\n\nvar VideoModelList = []string{\n\t\"gemini/veo3.1\",\n\t\"gemini/veo3.1/reference-to-video\",\n\t\"gemini/veo3.1/first-last-frame-to-video\",\n\t\"sora-2\",\n\t\"sora-2-pro\",\n\t\"gemini/veo3\",\n\t\"kling/v3\",\n\t\"kling/v2.6/standard/motion-control\",\n\t\"kling/o3/image-to-video\",\n\t\"kling/o3/reference-to-video\",\n\t\"fal-ai/bytedance/seedance/v1.5/pro\",\n\t\"xai/grok-imagine-video\",\n\t\"minimax/hailuo-2.3/standard\",\n\t\"official/pixverse/v5\",\n\t\"fal-ai/bytedance/seedance/v1/pro/fast\",\n\t\"fal-ai/sync-lipsync/v2\",\n\t\"wan/v2.6\",\n\t\"vidu/q3\",\n\t\"runway/gen4_turbo\",\n\t\"fal-ai/bytedance-upscaler/upscale/video\",\n}\n\n//\n"
  },
  {
    "path": "common/env/helper.go",
    "content": "package env\n\nimport (\n\t\"os\"\n\t\"strconv\"\n)\n\nfunc Bool(env string, defaultValue bool) bool {\n\tif env == \"\" || os.Getenv(env) == \"\" {\n\t\treturn defaultValue\n\t}\n\treturn os.Getenv(env) == \"true\"\n}\n\nfunc Int(env string, defaultValue int) int {\n\tif env == \"\" || os.Getenv(env) == \"\" {\n\t\treturn defaultValue\n\t}\n\tnum, err := strconv.Atoi(os.Getenv(env))\n\tif err != nil {\n\t\treturn defaultValue\n\t}\n\treturn num\n}\n\nfunc Float64(env string, defaultValue float64) float64 {\n\tif env == \"\" || os.Getenv(env) == \"\" {\n\t\treturn defaultValue\n\t}\n\tnum, err := strconv.ParseFloat(os.Getenv(env), 64)\n\tif err != nil {\n\t\treturn defaultValue\n\t}\n\treturn num\n}\n\nfunc String(env string, defaultValue string) string {\n\tif env == \"\" || os.Getenv(env) == \"\" {\n\t\treturn defaultValue\n\t}\n\treturn os.Getenv(env)\n}\n"
  },
  {
    "path": "common/helper/helper.go",
    "content": "package helper\n\nimport (\n\t\"fmt\"\n\t\"genspark2api/common/random\"\n\t\"github.com/gin-gonic/gin\"\n\t\"html/template\"\n\t\"log\"\n\t\"net\"\n\t\"os/exec\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc OpenBrowser(url string) {\n\tvar err error\n\n\tswitch runtime.GOOS {\n\tcase \"linux\":\n\t\terr = exec.Command(\"xdg-open\", url).Start()\n\tcase \"windows\":\n\t\terr = exec.Command(\"rundll32\", \"url.dll,FileProtocolHandler\", url).Start()\n\tcase \"darwin\":\n\t\terr = exec.Command(\"open\", url).Start()\n\t}\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n}\n\nfunc GetIp() (ip string) {\n\tips, err := net.InterfaceAddrs()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn ip\n\t}\n\n\tfor _, a := range ips {\n\t\tif ipNet, ok := a.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {\n\t\t\tif ipNet.IP.To4() != nil {\n\t\t\t\tip = ipNet.IP.String()\n\t\t\t\tif strings.HasPrefix(ip, \"10\") {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif strings.HasPrefix(ip, \"172\") {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif strings.HasPrefix(ip, \"192.168\") {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tip = \"\"\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\nvar sizeKB = 1024\nvar sizeMB = sizeKB * 1024\nvar sizeGB = sizeMB * 1024\n\nfunc Bytes2Size(num int64) string {\n\tnumStr := \"\"\n\tunit := \"B\"\n\tif num/int64(sizeGB) > 1 {\n\t\tnumStr = fmt.Sprintf(\"%.2f\", float64(num)/float64(sizeGB))\n\t\tunit = \"GB\"\n\t} else if num/int64(sizeMB) > 1 {\n\t\tnumStr = fmt.Sprintf(\"%d\", int(float64(num)/float64(sizeMB)))\n\t\tunit = \"MB\"\n\t} else if num/int64(sizeKB) > 1 {\n\t\tnumStr = fmt.Sprintf(\"%d\", int(float64(num)/float64(sizeKB)))\n\t\tunit = \"KB\"\n\t} else {\n\t\tnumStr = fmt.Sprintf(\"%d\", num)\n\t}\n\treturn numStr + \" \" + unit\n}\n\nfunc Interface2String(inter interface{}) string {\n\tswitch inter := inter.(type) {\n\tcase string:\n\t\treturn inter\n\tcase int:\n\t\treturn fmt.Sprintf(\"%d\", inter)\n\tcase float64:\n\t\treturn fmt.Sprintf(\"%f\", inter)\n\t}\n\treturn \"Not Implemented\"\n}\n\nfunc UnescapeHTML(x string) interface{} {\n\treturn template.HTML(x)\n}\n\nfunc IntMax(a int, b int) int {\n\tif a >= b {\n\t\treturn a\n\t} else {\n\t\treturn b\n\t}\n}\n\nfunc GenRequestID() string {\n\treturn GetTimeString() + random.GetRandomNumberString(8)\n}\n\nfunc GetResponseID(c *gin.Context) string {\n\tlogID := c.GetString(RequestIdKey)\n\treturn fmt.Sprintf(\"chatcmpl-%s\", logID)\n}\n\nfunc Max(a int, b int) int {\n\tif a >= b {\n\t\treturn a\n\t} else {\n\t\treturn b\n\t}\n}\n\nfunc AssignOrDefault(value string, defaultValue string) string {\n\tif len(value) != 0 {\n\t\treturn value\n\t}\n\treturn defaultValue\n}\n\nfunc MessageWithRequestId(message string, id string) string {\n\treturn fmt.Sprintf(\"%s (request id: %s)\", message, id)\n}\n\nfunc String2Int(str string) int {\n\tnum, err := strconv.Atoi(str)\n\tif err != nil {\n\t\treturn 0\n\t}\n\treturn num\n}\n"
  },
  {
    "path": "common/helper/key.go",
    "content": "package helper\n\nconst (\n\tRequestIdKey = \"X-Request-Id\"\n)\n"
  },
  {
    "path": "common/helper/time.go",
    "content": "package helper\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc GetTimestamp() int64 {\n\treturn time.Now().Unix()\n}\n\nfunc GetTimeString() string {\n\tnow := time.Now()\n\treturn fmt.Sprintf(\"%s%d\", now.Format(\"20060102150405\"), now.UnixNano()%1e9)\n}\n"
  },
  {
    "path": "common/init.go",
    "content": "package common\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\nvar (\n\tPort         = flag.Int(\"port\", 7055, \"the listening port\")\n\tPrintVersion = flag.Bool(\"version\", false, \"print version and exit\")\n\tPrintHelp    = flag.Bool(\"help\", false, \"print help and exit\")\n\tLogDir       = flag.String(\"log-dir\", \"\", \"specify the log directory\")\n)\n\n// UploadPath Maybe override by ENV_VAR\nvar UploadPath = \"upload\"\n\nfunc printHelp() {\n\tfmt.Println(\"genspark2api\" + Version + \"\")\n\tfmt.Println(\"Copyright (C) 2024 Dean. All rights reserved.\")\n\tfmt.Println(\"GitHub: https://github.com/deanxv/genspark2api \")\n\tfmt.Println(\"Usage: genspark2api [--port <port>] [--log-dir <log directory>] [--version] [--help]\")\n}\n\nfunc init() {\n\tflag.Parse()\n\n\tif *PrintVersion {\n\t\tfmt.Println(Version)\n\t\tos.Exit(0)\n\t}\n\n\tif *PrintHelp {\n\t\tprintHelp()\n\t\tos.Exit(0)\n\t}\n\n\tif os.Getenv(\"UPLOAD_PATH\") != \"\" {\n\t\tUploadPath = os.Getenv(\"UPLOAD_PATH\")\n\t}\n\tif *LogDir != \"\" {\n\t\tvar err error\n\t\t*LogDir, err = filepath.Abs(*LogDir)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tif _, err := os.Stat(*LogDir); os.IsNotExist(err) {\n\t\t\terr = os.Mkdir(*LogDir, 0777)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "common/loggger/constants.go",
    "content": "package logger\n\nvar LogDir string\n"
  },
  {
    "path": "common/loggger/logger.go",
    "content": "package logger\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"genspark2api/common/config\"\n\t\"genspark2api/common/helper\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\nconst (\n\tloggerDEBUG = \"DEBUG\"\n\tloggerINFO  = \"INFO\"\n\tloggerWarn  = \"WARN\"\n\tloggerError = \"ERR\"\n)\n\nvar setupLogOnce sync.Once\n\nfunc SetupLogger() {\n\tsetupLogOnce.Do(func() {\n\t\tif LogDir != \"\" {\n\t\t\tlogPath := filepath.Join(LogDir, fmt.Sprintf(\"genspark2api-%s.log\", time.Now().Format(\"20060102\")))\n\t\t\tfd, err := os.OpenFile(logPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(\"failed to open log file\")\n\t\t\t}\n\t\t\tgin.DefaultWriter = io.MultiWriter(os.Stdout, fd)\n\t\t\tgin.DefaultErrorWriter = io.MultiWriter(os.Stderr, fd)\n\t\t}\n\t})\n}\n\nfunc SysLog(s string) {\n\tt := time.Now()\n\t_, _ = fmt.Fprintf(gin.DefaultWriter, \"[SYS] %v | %s \\n\", t.Format(\"2006/01/02 - 15:04:05\"), s)\n}\n\nfunc SysError(s string) {\n\tt := time.Now()\n\t_, _ = fmt.Fprintf(gin.DefaultErrorWriter, \"[SYS] %v | %s \\n\", t.Format(\"2006/01/02 - 15:04:05\"), s)\n}\n\nfunc Debug(ctx context.Context, msg string) {\n\tif config.DebugEnabled {\n\t\tlogHelper(ctx, loggerDEBUG, msg)\n\t}\n}\n\nfunc Info(ctx context.Context, msg string) {\n\tlogHelper(ctx, loggerINFO, msg)\n}\n\nfunc Warn(ctx context.Context, msg string) {\n\tlogHelper(ctx, loggerWarn, msg)\n}\n\nfunc Error(ctx context.Context, msg string) {\n\tlogHelper(ctx, loggerError, msg)\n}\n\nfunc Debugf(ctx context.Context, format string, a ...any) {\n\tDebug(ctx, fmt.Sprintf(format, a...))\n}\n\nfunc Infof(ctx context.Context, format string, a ...any) {\n\tInfo(ctx, fmt.Sprintf(format, a...))\n}\n\nfunc Warnf(ctx context.Context, format string, a ...any) {\n\tWarn(ctx, fmt.Sprintf(format, a...))\n}\n\nfunc Errorf(ctx context.Context, format string, a ...any) {\n\tError(ctx, fmt.Sprintf(format, a...))\n}\n\nfunc logHelper(ctx context.Context, level string, msg string) {\n\twriter := gin.DefaultErrorWriter\n\tif level == loggerINFO {\n\t\twriter = gin.DefaultWriter\n\t}\n\tid := ctx.Value(helper.RequestIdKey)\n\tif id == nil {\n\t\tid = helper.GenRequestID()\n\t}\n\tnow := time.Now()\n\t_, _ = fmt.Fprintf(writer, \"[%s] %v | %s | %s \\n\", level, now.Format(\"2006/01/02 - 15:04:05\"), id, msg)\n\tSetupLogger()\n}\n\nfunc FatalLog(v ...any) {\n\tt := time.Now()\n\t_, _ = fmt.Fprintf(gin.DefaultErrorWriter, \"[FATAL] %v | %v \\n\", t.Format(\"2006/01/02 - 15:04:05\"), v)\n\tos.Exit(1)\n}\n"
  },
  {
    "path": "common/random/main.go",
    "content": "package random\n\nimport (\n\t\"github.com/google/uuid\"\n\t\"math/rand\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc GetUUID() string {\n\tcode := uuid.New().String()\n\tcode = strings.Replace(code, \"-\", \"\", -1)\n\treturn code\n}\n\nconst keyChars = \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nconst keyNumbers = \"0123456789\"\n\nfunc init() {\n\trand.Seed(time.Now().UnixNano())\n}\n\nfunc GenerateKey() string {\n\trand.Seed(time.Now().UnixNano())\n\tkey := make([]byte, 48)\n\tfor i := 0; i < 16; i++ {\n\t\tkey[i] = keyChars[rand.Intn(len(keyChars))]\n\t}\n\tuuid_ := GetUUID()\n\tfor i := 0; i < 32; i++ {\n\t\tc := uuid_[i]\n\t\tif i%2 == 0 && c >= 'a' && c <= 'z' {\n\t\t\tc = c - 'a' + 'A'\n\t\t}\n\t\tkey[i+16] = c\n\t}\n\treturn string(key)\n}\n\nfunc GetRandomString(length int) string {\n\trand.Seed(time.Now().UnixNano())\n\tkey := make([]byte, length)\n\tfor i := 0; i < length; i++ {\n\t\tkey[i] = keyChars[rand.Intn(len(keyChars))]\n\t}\n\treturn string(key)\n}\n\nfunc GetRandomNumberString(length int) string {\n\trand.Seed(time.Now().UnixNano())\n\tkey := make([]byte, length)\n\tfor i := 0; i < length; i++ {\n\t\tkey[i] = keyNumbers[rand.Intn(len(keyNumbers))]\n\t}\n\treturn string(key)\n}\n\n// RandRange returns a random number between min and max (max is not included)\nfunc RandRange(min, max int) int {\n\treturn min + rand.Intn(max-min)\n}\n"
  },
  {
    "path": "common/rate-limit.go",
    "content": "package common\n\nimport (\n\t\"sync\"\n\t\"time\"\n)\n\ntype InMemoryRateLimiter struct {\n\tstore              map[string]*[]int64\n\tmutex              sync.Mutex\n\texpirationDuration time.Duration\n}\n\nfunc (l *InMemoryRateLimiter) Init(expirationDuration time.Duration) {\n\tif l.store == nil {\n\t\tl.mutex.Lock()\n\t\tif l.store == nil {\n\t\t\tl.store = make(map[string]*[]int64)\n\t\t\tl.expirationDuration = expirationDuration\n\t\t\tif expirationDuration > 0 {\n\t\t\t\tgo l.clearExpiredItems()\n\t\t\t}\n\t\t}\n\t\tl.mutex.Unlock()\n\t}\n}\n\nfunc (l *InMemoryRateLimiter) clearExpiredItems() {\n\tfor {\n\t\ttime.Sleep(l.expirationDuration)\n\t\tl.mutex.Lock()\n\t\tnow := time.Now().Unix()\n\t\tfor key := range l.store {\n\t\t\tqueue := l.store[key]\n\t\t\tsize := len(*queue)\n\t\t\tif size == 0 || now-(*queue)[size-1] > int64(l.expirationDuration.Seconds()) {\n\t\t\t\tdelete(l.store, key)\n\t\t\t}\n\t\t}\n\t\tl.mutex.Unlock()\n\t}\n}\n\n// Request parameter duration's unit is seconds\nfunc (l *InMemoryRateLimiter) Request(key string, maxRequestNum int, duration int64) bool {\n\tl.mutex.Lock()\n\tdefer l.mutex.Unlock()\n\t// [old <-- new]\n\tqueue, ok := l.store[key]\n\tnow := time.Now().Unix()\n\tif ok {\n\t\tif len(*queue) < maxRequestNum {\n\t\t\t*queue = append(*queue, now)\n\t\t\treturn true\n\t\t} else {\n\t\t\tif now-(*queue)[0] >= duration {\n\t\t\t\t*queue = (*queue)[1:]\n\t\t\t\t*queue = append(*queue, now)\n\t\t\t\treturn true\n\t\t\t} else {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t} else {\n\t\ts := make([]int64, 0, maxRequestNum)\n\t\tl.store[key] = &s\n\t\t*(l.store[key]) = append(*(l.store[key]), now)\n\t}\n\treturn true\n}\n"
  },
  {
    "path": "common/token.go",
    "content": "package common\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\tlogger \"genspark2api/common/loggger\"\n\t\"genspark2api/model\"\n\t\"github.com/pkoukk/tiktoken-go\"\n\t\"strings\"\n)\n\n// tokenEncoderMap won't grow after initialization\nvar tokenEncoderMap = map[string]*tiktoken.Tiktoken{}\nvar defaultTokenEncoder *tiktoken.Tiktoken\n\nfunc InitTokenEncoders() {\n\tlogger.SysLog(\"initializing token encoders...\")\n\tgpt35TokenEncoder, err := tiktoken.EncodingForModel(\"gpt-3.5-turbo\")\n\tif err != nil {\n\t\tlogger.FatalLog(fmt.Sprintf(\"failed to get gpt-3.5-turbo token encoder: %s\", err.Error()))\n\t}\n\tdefaultTokenEncoder = gpt35TokenEncoder\n\tgpt4oTokenEncoder, err := tiktoken.EncodingForModel(\"gpt-4o\")\n\tif err != nil {\n\t\tlogger.FatalLog(fmt.Sprintf(\"failed to get gpt-4o token encoder: %s\", err.Error()))\n\t}\n\tgpt4TokenEncoder, err := tiktoken.EncodingForModel(\"gpt-4\")\n\tif err != nil {\n\t\tlogger.FatalLog(fmt.Sprintf(\"failed to get gpt-4 token encoder: %s\", err.Error()))\n\t}\n\tfor _, model := range DefaultOpenaiModelList {\n\t\tif strings.HasPrefix(model, \"gpt-3.5\") {\n\t\t\ttokenEncoderMap[model] = gpt35TokenEncoder\n\t\t} else if strings.HasPrefix(model, \"gpt-4o\") {\n\t\t\ttokenEncoderMap[model] = gpt4oTokenEncoder\n\t\t} else if strings.HasPrefix(model, \"gpt-4\") {\n\t\t\ttokenEncoderMap[model] = gpt4TokenEncoder\n\t\t} else {\n\t\t\ttokenEncoderMap[model] = nil\n\t\t}\n\t}\n\tlogger.SysLog(\"token encoders initialized.\")\n}\n\nfunc getTokenEncoder(model string) *tiktoken.Tiktoken {\n\ttokenEncoder, ok := tokenEncoderMap[model]\n\tif ok && tokenEncoder != nil {\n\t\treturn tokenEncoder\n\t}\n\tif ok {\n\t\ttokenEncoder, err := tiktoken.EncodingForModel(model)\n\t\tif err != nil {\n\t\t\t//logger.SysError(fmt.Sprintf(\"[IGNORE] | failed to get token encoder for model %s: %s, using encoder for gpt-3.5-turbo\", model, err.Error()))\n\t\t\ttokenEncoder = defaultTokenEncoder\n\t\t}\n\t\ttokenEncoderMap[model] = tokenEncoder\n\t\treturn tokenEncoder\n\t}\n\treturn defaultTokenEncoder\n}\n\nfunc getTokenNum(tokenEncoder *tiktoken.Tiktoken, text string) int {\n\treturn len(tokenEncoder.Encode(text, nil, nil))\n}\n\nfunc CountTokenMessages(messages []model.OpenAIChatMessage, model string) int {\n\ttokenEncoder := getTokenEncoder(model)\n\t// Reference:\n\t// https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb\n\t// https://github.com/pkoukk/tiktoken-go/issues/6\n\t//\n\t// Every message follows <|start|>{role/name}\\n{content}<|end|>\\n\n\tvar tokensPerMessage int\n\tif model == \"gpt-3.5-turbo-0301\" {\n\t\ttokensPerMessage = 4\n\t} else {\n\t\ttokensPerMessage = 3\n\t}\n\ttokenNum := 0\n\tfor _, message := range messages {\n\t\ttokenNum += tokensPerMessage\n\t\tswitch v := message.Content.(type) {\n\t\tcase string:\n\t\t\ttokenNum += getTokenNum(tokenEncoder, v)\n\t\tcase []any:\n\t\t\tfor _, it := range v {\n\t\t\t\tm := it.(map[string]any)\n\t\t\t\tswitch m[\"type\"] {\n\t\t\t\tcase \"text\":\n\t\t\t\t\tif textValue, ok := m[\"text\"]; ok {\n\t\t\t\t\t\tif textString, ok := textValue.(string); ok {\n\t\t\t\t\t\t\ttokenNum += getTokenNum(tokenEncoder, textString)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tcase \"image_url\":\n\t\t\t\t\timageUrl, ok := m[\"image_url\"].(map[string]any)\n\t\t\t\t\tif ok {\n\t\t\t\t\t\turl := imageUrl[\"url\"].(string)\n\t\t\t\t\t\tdetail := \"\"\n\t\t\t\t\t\tif imageUrl[\"detail\"] != nil {\n\t\t\t\t\t\t\tdetail = imageUrl[\"detail\"].(string)\n\t\t\t\t\t\t}\n\t\t\t\t\t\timageTokens, err := countImageTokens(url, detail, model)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tlogger.SysError(\"error counting image tokens: \" + err.Error())\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\ttokenNum += imageTokens\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttokenNum += getTokenNum(tokenEncoder, message.Role)\n\t}\n\ttokenNum += 3 // Every reply is primed with <|start|>assistant<|message|>\n\treturn tokenNum\n}\n\nconst (\n\tlowDetailCost         = 85\n\thighDetailCostPerTile = 170\n\tadditionalCost        = 85\n\t// gpt-4o-mini cost higher than other model\n\tgpt4oMiniLowDetailCost  = 2833\n\tgpt4oMiniHighDetailCost = 5667\n\tgpt4oMiniAdditionalCost = 2833\n)\n\n// https://platform.openai.com/docs/guides/vision/calculating-costs\n// https://github.com/openai/openai-cookbook/blob/05e3f9be4c7a2ae7ecf029a7c32065b024730ebe/examples/How_to_count_tokens_with_tiktoken.ipynb\nfunc countImageTokens(url string, detail string, model string) (_ int, err error) {\n\t// Reference: https://platform.openai.com/docs/guides/vision/low-or-high-fidelity-image-understanding\n\t// detail == \"auto\" is undocumented on how it works, it just said the model will use the auto setting which will look at the image input size and decide if it should use the low or high setting.\n\t// According to the official guide, \"low\" disable the high-res model,\n\t// and only receive low-res 512px x 512px version of the image, indicating\n\t// that image is treated as low-res when size is smaller than 512px x 512px,\n\t// then we can assume that image size larger than 512px x 512px is treated\n\t// as high-res. Then we have the following logic:\n\t// if detail == \"\" || detail == \"auto\" {\n\t// \twidth, height, err = image.GetImageSize(url)\n\t// \tif err != nil {\n\t// \t\treturn 0, err\n\t// \t}\n\t// \tfetchSize = false\n\t// \t// not sure if this is correct\n\t// \tif width > 512 || height > 512 {\n\t// \t\tdetail = \"high\"\n\t// \t} else {\n\t// \t\tdetail = \"low\"\n\t// \t}\n\t// }\n\n\t// However, in my test, it seems to be always the same as \"high\".\n\t// The following image, which is 125x50, is still treated as high-res, taken\n\t// 255 tokens in the response of non-stream chat completion api.\n\t// https://upload.wikimedia.org/wikipedia/commons/1/10/18_Infantry_Division_Messina.jpg\n\tif detail == \"\" || detail == \"auto\" {\n\t\t// assume by test, not sure if this is correct\n\t\tdetail = \"low\"\n\t}\n\tswitch detail {\n\tcase \"low\":\n\t\tif strings.HasPrefix(model, \"gpt-4o-mini\") {\n\t\t\treturn gpt4oMiniLowDetailCost, nil\n\t\t}\n\t\treturn lowDetailCost, nil\n\tdefault:\n\t\treturn 0, errors.New(\"invalid detail option\")\n\t}\n}\n\nfunc CountTokenInput(input any, model string) int {\n\tswitch v := input.(type) {\n\tcase string:\n\t\treturn CountTokenText(v, model)\n\tcase []string:\n\t\ttext := \"\"\n\t\tfor _, s := range v {\n\t\t\ttext += s\n\t\t}\n\t\treturn CountTokenText(text, model)\n\t}\n\treturn 0\n}\n\nfunc CountTokenText(text string, model string) int {\n\ttokenEncoder := getTokenEncoder(model)\n\treturn getTokenNum(tokenEncoder, text)\n}\n\nfunc CountToken(text string) int {\n\treturn CountTokenInput(text, \"gpt-3.5-turbo\")\n}\n"
  },
  {
    "path": "common/utils.go",
    "content": "package common\n\nimport (\n\t\"encoding/base64\"\n\t\"fmt\"\n\t\"github.com/google/uuid\"\n\tjsoniter \"github.com/json-iterator/go\"\n\t_ \"github.com/pkoukk/tiktoken-go\"\n\t\"math/rand\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\t\"unicode/utf8\"\n)\n\n// splitStringByBytes 将字符串按照指定的字节数进行切割\nfunc SplitStringByBytes(s string, size int) []string {\n\tvar result []string\n\n\tfor len(s) > 0 {\n\t\t// 初始切割点\n\t\tl := size\n\t\tif l > len(s) {\n\t\t\tl = len(s)\n\t\t}\n\n\t\t// 确保不在字符中间切割\n\t\tfor l > 0 && !utf8.ValidString(s[:l]) {\n\t\t\tl--\n\t\t}\n\n\t\t// 如果 l 减到 0，说明 size 太小，无法容纳一个完整的字符\n\t\tif l == 0 {\n\t\t\tl = len(s)\n\t\t\tfor l > 0 && !utf8.ValidString(s[:l]) {\n\t\t\t\tl--\n\t\t\t}\n\t\t}\n\n\t\tresult = append(result, s[:l])\n\t\ts = s[l:]\n\t}\n\n\treturn result\n}\n\nfunc Obj2Bytes(obj interface{}) ([]byte, error) {\n\t// 创建一个jsonIter的Encoder\n\tconfigCompatibleWithStandardLibrary := jsoniter.ConfigCompatibleWithStandardLibrary\n\t// 将结构体转换为JSON文本并保持顺序\n\tbytes, err := configCompatibleWithStandardLibrary.Marshal(obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn bytes, nil\n}\n\nfunc GetUUID() string {\n\tcode := uuid.New().String()\n\tcode = strings.Replace(code, \"-\", \"\", -1)\n\treturn code\n}\n\n// RandomElement 返回给定切片中的随机元素\nfunc RandomElement[T any](slice []T) (T, error) {\n\tif len(slice) == 0 {\n\t\tvar zero T\n\t\treturn zero, fmt.Errorf(\"empty slice\")\n\t}\n\n\t// 确保每次随机都不一样\n\trand.Seed(time.Now().UnixNano())\n\n\t// 随机选择一个索引\n\tindex := rand.Intn(len(slice))\n\treturn slice[index], nil\n}\n\nfunc SliceContains(slice []string, str string) bool {\n\tfor _, item := range slice {\n\t\tif strings.Contains(str, item) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc IsImageBase64(s string) bool {\n\t// 检查字符串是否符合数据URL的格式\n\tif !strings.HasPrefix(s, \"data:image/\") || !strings.Contains(s, \";base64,\") {\n\t\treturn false\n\t}\n\n\tif !strings.Contains(s, \";base64,\") {\n\t\treturn false\n\t}\n\n\t// 获取\";base64,\"后的Base64编码部分\n\tdataParts := strings.Split(s, \";base64,\")\n\tif len(dataParts) != 2 {\n\t\treturn false\n\t}\n\tbase64Data := dataParts[1]\n\n\t// 尝试Base64解码\n\t_, err := base64.StdEncoding.DecodeString(base64Data)\n\treturn err == nil\n}\n\nfunc IsBase64(s string) bool {\n\t// 检查字符串是否符合数据URL的格式\n\t//if !strings.HasPrefix(s, \"data:image/\") || !strings.Contains(s, \";base64,\") {\n\t//\treturn false\n\t//}\n\n\tif !strings.Contains(s, \";base64,\") {\n\t\treturn false\n\t}\n\n\t// 获取\";base64,\"后的Base64编码部分\n\tdataParts := strings.Split(s, \";base64,\")\n\tif len(dataParts) != 2 {\n\t\treturn false\n\t}\n\tbase64Data := dataParts[1]\n\n\t// 尝试Base64解码\n\t_, err := base64.StdEncoding.DecodeString(base64Data)\n\treturn err == nil\n}\n\n//<h1 data-translate=\"block_headline\">Sorry, you have been blocked</h1>\n\nfunc IsCloudflareBlock(data string) bool {\n\tif strings.Contains(data, `<h1 data-translate=\"block_headline\">Sorry, you have been blocked</h1>`) {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc IsCloudflareChallenge(data string) bool {\n\t// 检查基本的 HTML 结构\n\thtmlPattern := `^<!DOCTYPE html><html.*?><head>.*?</head><body.*?>.*?</body></html>$`\n\n\t// 检查 Cloudflare 特征\n\tcfPatterns := []string{\n\t\t`<title>Just a moment\\.\\.\\.</title>`,          // 标题特征\n\t\t`window\\._cf_chl_opt`,                         // CF 配置对象\n\t\t`challenge-platform/h/b/orchestrate/chl_page`, // CF challenge 路径\n\t\t`cdn-cgi/challenge-platform`,                  // CDN 路径特征\n\t\t`<meta http-equiv=\"refresh\" content=\"\\d+\">`,   // 刷新 meta 标签\n\t}\n\n\t// 首先检查整体 HTML 结构\n\tmatched, _ := regexp.MatchString(htmlPattern, strings.TrimSpace(data))\n\tif !matched {\n\t\treturn false\n\t}\n\n\t// 检查是否包含 Cloudflare 特征\n\tfor _, pattern := range cfPatterns {\n\t\tif matched, _ := regexp.MatchString(pattern, data); matched {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc IsRateLimit(data string) bool {\n\tif data == \"Rate limit exceeded cf1\" || data == \"Rate limit exceeded cf2\" {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc IsNotLogin(data string) bool {\n\tif strings.Contains(data, `{\"status\":-5,\"message\":\"not login\",\"data\":{}}`) {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc IsServerError(data string) bool {\n\tif data == \"Internal Server Error\" {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc IsServerOverloaded(data string) bool {\n\tif strings.Contains(data, `data: {\"id\": \"\", \"role\": \"assistant\", \"content\": \"Server overloaded, please try again later.\", \"action\": null, \"recommend_actions\": null, \"is_prompt\": false, \"render_template\": null, \"session_state\": null, \"message_type\": null, \"type\": \"message_result\"}`) {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc IsFreeLimit(data string) bool {\n\tif strings.Contains(data, `data: {\"id\": \"\", \"role\": \"assistant\", \"content\": \"You've reached your free usage limit today\", \"action\": {\"type\": \"ACTION_QUOTA_EXCEEDED\", \"query_string\": null, \"update_flow_data\": null, \"label\": null, \"user_s_input\": null, \"action_params\": null}, \"recommend_actions\": null, \"is_prompt\": true, \"render_template\": null, \"session_state\": {\"consume_usage_quota_exceeded\": true}, \"message_type\": null, \"type\": \"message_result\"}`) {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc IsServiceUnavailablePage(data string) bool {\n\t// 检查基本的 HTML 结构\n\thtmlPattern := `^<!doctype html><html.*?><head>.*?</head><body.*?>.*?</body></html>`\n\n\t// 检查 Service Unavailable 页面特征\n\tsuPatterns := []string{\n\t\t`<title>Genspark</title>`,                           // 标题特征\n\t\t`Service\\s+Unavailable`,                             // 错误信息\n\t\t`class=\"bb\".*?class=\"s1\".*?class=\"s2\".*?class=\"s3\"`, // 特征性类名结构\n\t\t`genspark_logo\\.png`,                                // Logo 图片\n\t\t`gensparkpublicblob-cdn.*?\\.azurefd\\.net`,           // CDN 域名\n\t\t`<div class=\"tt\">Service Unavailable</div>`,         // 错误信息容器\n\t}\n\n\t// 首先检查整体 HTML 结构\n\tmatched, _ := regexp.MatchString(htmlPattern, strings.TrimSpace(data))\n\tif !matched {\n\t\treturn false\n\t}\n\n\t// 检查特征模式，至少匹配其中的 3 个才认为是目标页面\n\tmatchCount := 0\n\tfor _, pattern := range suPatterns {\n\t\tif matched, _ := regexp.MatchString(pattern, data); matched {\n\t\t\tmatchCount++\n\t\t}\n\t}\n\n\treturn matchCount >= 3\n}\n\n//<!doctype html><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no\"><title>Genspark</title><link rel=\"icon\" href=\"https://gensparkpublicblob-cdn-e6g4btgjavb5a7gh.z03.azurefd.net/user-upload-image/manual/favicon.ico\"><style>body,html{margin:0;padding:0;font-family:Arial}.bb{width:100vw;height:100vh;position:absolute;overflow:hidden}.logo img{margin:20px 0 0 24px;height:24px}.iw{display:flex;flex-direction:column;height:100vh;width:100%}.s1{position:absolute;top:0;left:0;margin-top:-5%;margin-left:15%;width:289px;height:289px;border-radius:289px;opacity:.6;background:radial-gradient(55.64% 49.84%,#2c10d6 0,rgba(44,16,214,.36) 100%);filter:blur(120px)}.s2{position:absolute;top:0;left:0;margin-top:10%;margin-left:50%;width:204.845px;height:204.845px;transform:rotate(-131.346deg);flex-shrink:0;background:radial-gradient(55.64% 49.84%,#7fd1ff 0,rgba(44,16,214,.36) 100%);filter:blur(120px)}.s3{position:absolute;bottom:0;right:0;margin-bottom:10%;margin-right:10%;width:251px;height:251px;border-radius:289.093px;background:radial-gradient(88.27% 88.27% at 90.98% 61.04%,#ce7fff 0,#ffe4af 100%);filter:blur(120px)}.cc{display:flex;justify-content:center;align-items:center;height:100%;width:100%}.hh{align-items:center;display:flex;width:100vw}.dd{margin-top:-200px}.tt{color:#000;text-align:center;font-size:40px;font-style:normal;font-weight:700}@media (max-width:800px){.tt{font-size:30px}}</style></head><body><div class=\"bb\"><div class=\"s1\"></div><div class=\"s2\"></div><div class=\"s3\"></div></div><div class=\"iw\"><div class=\"hh\"><div class=\"logo\"><img src=\"https://gensparkpublicblob-cdn-e6g4btgjavb5a7gh.z03.azurefd.net/user-upload-image/manual/genspark_logo.png\" alt=\"logo\"></div></div><div class=\"cc\"><div class=\"dd\"><div class=\"tt\">Service Unavailable</div></div></div></div></body></html>\n//<!doctype html><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no\"><title>Genspark</title><link rel=\"icon\" href=\"https://gensparkpublicblob-cdn-e6g4btgjavb5a7gh.z03.azurefd.net/user-upload-image/manual/favicon.ico\"><style>body,html{margin:0;padding:0;font-family:Arial}.bb{width:100vw;height:100vh;position:absolute;overflow:hidden}.logo img{margin:20px 0 0 24px;height:24px}.iw{display:flex;flex-direction:column;height:100vh;width:100%!}(MISSING).s1{position:absolute;top:0;left:0;margin-top:-5%!;(MISSING)margin-left:15%!;(MISSING)width:289px;height:289px;border-radius:289px;opacity:.6;background:radial-gradient(55.64%,#2c10d6 0,rgba(44,16,214,.36) 100%!)(MISSING);filter:blur(120px)}.s2{position:absolute;top:0;left:0;margin-top:10%!;(MISSING)margin-left:50%!;(MISSING)width:204.845px;height:204.845px;transform:rotate(-131.346deg);flex-shrink:0;background:radial-gradient(55.64%,#7fd1ff 0,rgba(44,16,214,.36) 100%!)(MISSING);filter:blur(120px)}.s3{position:absolute;bottom:0;right:0;margin-bottom:10%!;(MISSING)margin-right:10%!;(MISSING)width:251px;height:251px;border-radius:289.093px;background:radial-gradient(88.27% at 90.98%,#ce7fff 0,#ffe4af 100%!)(MISSING);filter:blur(120px)}.cc{display:flex;justify-content:center;align-items:center;height:100%!;(MISSING)width:100%!}(MISSING).hh{align-items:center;display:flex;width:100vw}.dd{margin-top:-200px}.tt{color:#000;text-align:center;font-size:40px;font-style:normal;font-weight:700}@media (max-width:800px){.tt{font-size:30px}}</style></head><body><div class=\"bb\"><div class=\"s1\"></div><div class=\"s2\"></div><div class=\"s3\"></div></div><div class=\"iw\"><div class=\"hh\"><div class=\"logo\"><img src=\"https://gensparkpublicblob-cdn-e6g4btgjavb5a7gh.z03.azurefd.net/user-upload-image/manual/genspark_logo.png\" alt=\"logo\"></div></div><div class=\"cc\"><div class=\"dd\"><div class=\"tt\">Service Unavailable</div></div></div></div></body></html>\n"
  },
  {
    "path": "controller/api.go",
    "content": "package controller\n\nimport (\n\t\"github.com/deanxv/CycleTLS/cycletls\"\n\t\"github.com/gin-gonic/gin\"\n)\n\n// ChatForOpenAI 处理OpenAI聊天请求\nfunc InitModelChatMap(c *gin.Context) {\n\tclient := cycletls.Init()\n\tdefer safeClose(client)\n\n\t// TODO\n}\n"
  },
  {
    "path": "controller/chat.go",
    "content": "package controller\n\nimport (\n\t\"bufio\"\n\t\"crypto/tls\"\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"genspark2api/common\"\n\t\"genspark2api/common/config\"\n\tlogger \"genspark2api/common/loggger\"\n\t\"genspark2api/model\"\n\t\"github.com/deanxv/CycleTLS/cycletls\"\n\t\"github.com/gin-gonic/gin\"\n\t\"github.com/samber/lo\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\terrNoValidCookies = \"No valid cookies available\"\n)\n\nconst (\n\tbaseURL          = \"https://www.genspark.ai\"\n\tapiEndpoint      = baseURL + \"/api/copilot/ask\"\n\tdeleteEndpoint   = baseURL + \"/api/project/delete?project_id=%s\"\n\tuploadEndpoint   = baseURL + \"/api/get_upload_personal_image_url\"\n\tchatType         = \"COPILOT_MOA_CHAT\"\n\timageType        = \"COPILOT_MOA_IMAGE\"\n\tvideoType        = \"COPILOT_MOA_VIDEO\"\n\tresponseIDFormat = \"chatcmpl-%s\"\n)\n\ntype OpenAIChatMessage struct {\n\tRole    string      `json:\"role\"`\n\tContent interface{} `json:\"content\"`\n}\n\ntype OpenAIChatCompletionRequest struct {\n\tMessages []OpenAIChatMessage\n\tModel    string\n}\n\n// ChatForOpenAI 处理OpenAI聊天请求\nfunc ChatForOpenAI(c *gin.Context) {\n\tclient := cycletls.Init()\n\tdefer safeClose(client)\n\n\tvar openAIReq model.OpenAIChatCompletionRequest\n\tif err := c.BindJSON(&openAIReq); err != nil {\n\t\tlogger.Errorf(c.Request.Context(), err.Error())\n\t\tc.JSON(http.StatusInternalServerError, model.OpenAIErrorResponse{\n\t\t\tOpenAIError: model.OpenAIError{\n\t\t\t\tMessage: \"Invalid request parameters\",\n\t\t\t\tType:    \"request_error\",\n\t\t\t\tCode:    \"500\",\n\t\t\t},\n\t\t})\n\t\treturn\n\t}\n\n\t// 模型映射\n\tif strings.HasPrefix(openAIReq.Model, \"deepseek\") {\n\t\topenAIReq.Model = strings.Replace(openAIReq.Model, \"deepseek\", \"deep-seek\", 1)\n\t}\n\n\t// 初始化cookie\n\n\tcookieManager := config.NewCookieManager()\n\tcookie, err := cookieManager.GetRandomCookie()\n\tif err != nil {\n\t\tlogger.Errorf(c.Request.Context(), \"Failed to get initial cookie: %v\", err)\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": errNoValidCookies})\n\t\treturn\n\t}\n\n\tif lo.Contains(common.ImageModelList, openAIReq.Model) {\n\t\tresponseId := fmt.Sprintf(responseIDFormat, time.Now().Format(\"20060102150405\"))\n\n\t\tif len(openAIReq.GetUserContent()) == 0 {\n\t\t\tlogger.Errorf(c.Request.Context(), \"user content is null\")\n\t\t\tc.JSON(http.StatusInternalServerError, model.OpenAIErrorResponse{\n\t\t\t\tOpenAIError: model.OpenAIError{\n\t\t\t\t\tMessage: \"Invalid request parameters\",\n\t\t\t\t\tType:    \"request_error\",\n\t\t\t\t\tCode:    \"500\",\n\t\t\t\t},\n\t\t\t})\n\t\t\treturn\n\t\t}\n\n\t\tjsonData, err := json.Marshal(openAIReq.GetUserContent()[0])\n\t\tif err != nil {\n\t\t\tlogger.Errorf(c.Request.Context(), err.Error())\n\t\t\tc.JSON(500, gin.H{\"error\": \"Failed to marshal request body\"})\n\t\t\treturn\n\t\t}\n\t\tresp, err := ImageProcess(c, client, model.OpenAIImagesGenerationRequest{\n\t\t\tModel:  openAIReq.Model,\n\t\t\tPrompt: openAIReq.GetUserContent()[0],\n\t\t})\n\n\t\tif err != nil {\n\t\t\tlogger.Errorf(c.Request.Context(), err.Error())\n\t\t\tc.JSON(http.StatusInternalServerError, model.OpenAIErrorResponse{\n\t\t\t\tOpenAIError: model.OpenAIError{\n\t\t\t\t\tMessage: err.Error(),\n\t\t\t\t\tType:    \"request_error\",\n\t\t\t\t\tCode:    \"500\",\n\t\t\t\t},\n\t\t\t})\n\t\t\treturn\n\t\t} else {\n\t\t\tdata := resp.Data\n\t\t\tvar content []string\n\t\t\tfor _, item := range data {\n\t\t\t\tcontent = append(content, fmt.Sprintf(\"![Image](%s)\", item.URL))\n\t\t\t}\n\n\t\t\tif openAIReq.Stream {\n\t\t\t\tstreamResp := createStreamResponse(responseId, openAIReq.Model, jsonData, model.OpenAIDelta{Content: strings.Join(content, \"\\n\"), Role: \"assistant\"}, nil)\n\t\t\t\terr := sendSSEvent(c, streamResp)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Errorf(c.Request.Context(), err.Error())\n\t\t\t\t\tc.JSON(http.StatusInternalServerError, model.OpenAIErrorResponse{\n\t\t\t\t\t\tOpenAIError: model.OpenAIError{\n\t\t\t\t\t\t\tMessage: err.Error(),\n\t\t\t\t\t\t\tType:    \"request_error\",\n\t\t\t\t\t\t\tCode:    \"500\",\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tc.SSEvent(\"\", \" [DONE]\")\n\t\t\t\treturn\n\t\t\t} else {\n\n\t\t\t\tjsonBytes, _ := json.Marshal(openAIReq.Messages)\n\t\t\t\tpromptTokens := common.CountTokenText(string(jsonBytes), openAIReq.Model)\n\t\t\t\tcompletionTokens := common.CountTokenText(strings.Join(content, \"\\n\"), openAIReq.Model)\n\n\t\t\t\tfinishReason := \"stop\"\n\t\t\t\t// 创建并返回 OpenAIChatCompletionResponse 结构\n\t\t\t\tresp := model.OpenAIChatCompletionResponse{\n\t\t\t\t\tID:      fmt.Sprintf(responseIDFormat, time.Now().Format(\"20060102150405\")),\n\t\t\t\t\tObject:  \"chat.completion\",\n\t\t\t\t\tCreated: time.Now().Unix(),\n\t\t\t\t\tModel:   openAIReq.Model,\n\t\t\t\t\tChoices: []model.OpenAIChoice{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tMessage: model.OpenAIMessage{\n\t\t\t\t\t\t\t\tRole:    \"assistant\",\n\t\t\t\t\t\t\t\tContent: strings.Join(content, \"\\n\"),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tFinishReason: &finishReason,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tUsage: model.OpenAIUsage{\n\t\t\t\t\t\tPromptTokens:     promptTokens,\n\t\t\t\t\t\tCompletionTokens: completionTokens,\n\t\t\t\t\t\tTotalTokens:      promptTokens + completionTokens,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tc.JSON(200, resp)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t}\n\t}\n\n\tvar isSearchModel bool\n\tif strings.HasSuffix(openAIReq.Model, \"-search\") {\n\t\tisSearchModel = true\n\t}\n\n\trequestBody, err := createRequestBody(c, client, cookie, &openAIReq)\n\n\tif err != nil {\n\t\tc.JSON(500, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\n\t//jsonData, err := json.Marshal(requestBody)\n\t//if err != nil {\n\t//\tc.JSON(500, gin.H{\"error\": \"Failed to marshal request body\"})\n\t//\treturn\n\t//}\n\n\tif openAIReq.Stream {\n\t\thandleStreamRequest(c, client, cookie, cookieManager, requestBody, openAIReq.Model, isSearchModel)\n\t} else {\n\t\thandleNonStreamRequest(c, client, cookie, cookieManager, requestBody, openAIReq.Model, isSearchModel)\n\t}\n\n}\n\nfunc processMessages(c *gin.Context, client cycletls.CycleTLS, cookie string, messages []model.OpenAIChatMessage) error {\n\t//client := cycletls.Init()\n\t//defer client.Close()\n\n\tfor i, message := range messages {\n\t\tif contentArray, ok := message.Content.([]interface{}); ok {\n\t\t\tfor j, content := range contentArray {\n\t\t\t\tif contentMap, ok := content.(map[string]interface{}); ok {\n\t\t\t\t\tif contentType, ok := contentMap[\"type\"].(string); ok && contentType == \"image_url\" {\n\t\t\t\t\t\tif imageMap, ok := contentMap[\"image_url\"].(map[string]interface{}); ok {\n\t\t\t\t\t\t\tif url, ok := imageMap[\"url\"].(string); ok {\n\t\t\t\t\t\t\t\terr := processUrl(c, client, cookie, url, imageMap, j, contentArray)\n\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\tlogger.Errorf(c.Request.Context(), fmt.Sprintf(\"processUrl err  %v\\n\", err))\n\t\t\t\t\t\t\t\t\treturn fmt.Errorf(\"processUrl err: %v\", err)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tmessages[i].Content = contentArray\n\t\t}\n\t}\n\treturn nil\n}\nfunc processUrl(c *gin.Context, client cycletls.CycleTLS, cookie string, url string, imageMap map[string]interface{}, index int, contentArray []interface{}) error {\n\t// 判断是否为URL\n\tif strings.HasPrefix(url, \"http://\") || strings.HasPrefix(url, \"https://\") {\n\t\t// 下载文件\n\t\tbytes, err := fetchImageBytes(url)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(c.Request.Context(), fmt.Sprintf(\"fetchImageBytes err  %v\\n\", err))\n\t\t\treturn fmt.Errorf(\"fetchImageBytes err  %v\\n\", err)\n\t\t}\n\n\t\terr = processBytes(c, client, cookie, bytes, imageMap, index, contentArray)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(c.Request.Context(), fmt.Sprintf(\"processBytes err  %v\\n\", err))\n\t\t\treturn fmt.Errorf(\"processBytes err  %v\\n\", err)\n\t\t}\n\t} else {\n\t\t// 尝试解析base64\n\t\tvar bytes []byte\n\t\tvar err error\n\n\t\t// 处理可能包含 data:image/ 前缀的base64\n\t\tbase64Str := url\n\t\tif strings.Contains(url, \";base64,\") {\n\t\t\tbase64Str = strings.Split(url, \";base64,\")[1]\n\t\t}\n\n\t\tbytes, err = base64.StdEncoding.DecodeString(base64Str)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(c.Request.Context(), fmt.Sprintf(\"base64.StdEncoding.DecodeString err  %v\\n\", err))\n\t\t\treturn fmt.Errorf(\"base64.StdEncoding.DecodeString err: %v\\n\", err)\n\t\t}\n\n\t\terr = processBytes(c, client, cookie, bytes, imageMap, index, contentArray)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(c.Request.Context(), fmt.Sprintf(\"processBytes err  %v\\n\", err))\n\t\t\treturn fmt.Errorf(\"processBytes err: %v\\n\", err)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc processBytes(c *gin.Context, client cycletls.CycleTLS, cookie string, bytes []byte, imageMap map[string]interface{}, index int, contentArray []interface{}) error {\n\t// 检查是否为图片类型\n\tcontentType := http.DetectContentType(bytes)\n\tif strings.HasPrefix(contentType, \"image/\") {\n\t\t// 是图片类型，转换为base64\n\t\tbase64Data := \"data:image/jpeg;base64,\" + base64.StdEncoding.EncodeToString(bytes)\n\t\timageMap[\"url\"] = base64Data\n\t} else {\n\t\tresponse, err := makeGetUploadUrlRequest(client, cookie)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(c.Request.Context(), fmt.Sprintf(\"makeGetUploadUrlRequest err  %v\\n\", err))\n\t\t\treturn fmt.Errorf(\"makeGetUploadUrlRequest err: %v\\n\", err)\n\t\t}\n\n\t\tvar jsonResponse map[string]interface{}\n\t\tif err := json.Unmarshal([]byte(response.Body), &jsonResponse); err != nil {\n\t\t\tlogger.Errorf(c.Request.Context(), fmt.Sprintf(\"Unmarshal err  %v\\n\", err))\n\t\t\treturn fmt.Errorf(\"Unmarshal err: %v\\n\", err)\n\t\t}\n\n\t\tuploadImageUrl, ok := jsonResponse[\"data\"].(map[string]interface{})[\"upload_image_url\"].(string)\n\t\tprivateStorageUrl, ok := jsonResponse[\"data\"].(map[string]interface{})[\"private_storage_url\"].(string)\n\n\t\tif !ok {\n\t\t\t//fmt.Println(\"Failed to extract upload_image_url\")\n\t\t\treturn fmt.Errorf(\"Failed to extract upload_image_url\")\n\t\t}\n\n\t\t// 发送OPTIONS预检请求\n\t\t//_, err = makeOptionsRequest(client, uploadImageUrl)\n\t\t//if err != nil {\n\t\t//\treturn\n\t\t//}\n\t\t// 上传文件\n\t\t_, err = makeUploadRequest(client, uploadImageUrl, bytes)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(c.Request.Context(), fmt.Sprintf(\"makeUploadRequest err  %v\\n\", err))\n\t\t\treturn fmt.Errorf(\"makeUploadRequest err: %v\\n\", err)\n\t\t}\n\t\t//fmt.Println(resp)\n\n\t\t// 创建新的 private_file 格式的内容\n\t\tprivateFile := map[string]interface{}{\n\t\t\t\"type\": \"private_file\",\n\t\t\t\"private_file\": map[string]interface{}{\n\t\t\t\t\"name\":                \"file\", // 你可能需要从原始文件名或其他地方获取\n\t\t\t\t\"type\":                contentType,\n\t\t\t\t\"size\":                len(bytes),\n\t\t\t\t\"ext\":                 strings.Split(contentType, \"/\")[1], // 简单处理，可能需要更复杂的逻辑\n\t\t\t\t\"private_storage_url\": privateStorageUrl,\n\t\t\t},\n\t\t}\n\n\t\t// 替换数组中的元素\n\t\tcontentArray[index] = privateFile\n\t}\n\treturn nil\n}\n\n// 获取文件字节数组的函数\nfunc fetchImageBytes(url string) ([]byte, error) {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"http.Get err: %v\\n\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\treturn ioutil.ReadAll(resp.Body)\n}\n\nfunc createRequestBody(c *gin.Context, client cycletls.CycleTLS, cookie string, openAIReq *model.OpenAIChatCompletionRequest) (map[string]interface{}, error) {\n\topenAIReq.SystemMessagesProcess(openAIReq.Model)\n\tif config.PRE_MESSAGES_JSON != \"\" {\n\t\terr := openAIReq.PrependMessagesFromJSON(config.PRE_MESSAGES_JSON)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"PrependMessagesFromJSON err: %v PrependMessagesFromJSON:\", err, config.PRE_MESSAGES_JSON)\n\t\t}\n\t}\n\n\t// 处理消息中的图像 URL\n\terr := processMessages(c, client, cookie, openAIReq.Messages)\n\tif err != nil {\n\t\tlogger.Errorf(c.Request.Context(), \"processMessages err: %v\", err)\n\t\treturn nil, fmt.Errorf(\"processMessages err: %v\", err)\n\t}\n\n\tcurrentQueryString := fmt.Sprintf(\"type=%s\", chatType)\n\t//查找 key 对应的 value\n\tif chatId, ok := config.ModelChatMap[openAIReq.Model]; ok {\n\t\tcurrentQueryString = fmt.Sprintf(\"id=%s&type=%s\", chatId, chatType)\n\t} else if chatId, ok := config.GlobalSessionManager.GetChatID(cookie, openAIReq.Model); ok {\n\t\tcurrentQueryString = fmt.Sprintf(\"id=%s&type=%s\", chatId, chatType)\n\t} else {\n\t\topenAIReq.FilterUserMessage()\n\t}\n\trequestWebKnowledge := false\n\tmodels := []string{openAIReq.Model}\n\tif strings.HasSuffix(openAIReq.Model, \"-search\") {\n\t\topenAIReq.Model = strings.Replace(openAIReq.Model, \"-search\", \"\", 1)\n\t\trequestWebKnowledge = true\n\t\tmodels = []string{openAIReq.Model}\n\t}\n\tif !lo.Contains(common.TextModelList, openAIReq.Model) {\n\t\tmodels = common.MixtureModelList\n\t}\n\n\t// 创建请求体\n\trequestBody := map[string]interface{}{\n\t\t\"type\":                 chatType,\n\t\t\"current_query_string\": currentQueryString,\n\t\t\"messages\":             openAIReq.Messages,\n\t\t\"action_params\":        map[string]interface{}{},\n\t\t\"extra_data\": map[string]interface{}{\n\t\t\t\"models\":                 models,\n\t\t\t\"run_with_another_model\": false,\n\t\t\t\"writingContent\":         nil,\n\t\t\t\"request_web_knowledge\":  requestWebKnowledge,\n\t\t},\n\t}\n\n\tlogger.Debug(c.Request.Context(), fmt.Sprintf(\"RequestBody: %v\", requestBody))\n\n\treturn requestBody, nil\n}\n\nfunc createImageRequestBody(c *gin.Context, cookie string, openAIReq *model.OpenAIImagesGenerationRequest, chatId string) (map[string]interface{}, error) {\n\n\tif openAIReq.Model == \"dall-e-3\" {\n\t\topenAIReq.Model = \"dalle-3\"\n\t}\n\t// 创建模型配置\n\tmodelConfigs := []map[string]interface{}{\n\t\t{\n\t\t\t\"model\":                   openAIReq.Model,\n\t\t\t\"aspect_ratio\":            \"auto\",\n\t\t\t\"use_personalized_models\": false,\n\t\t\t\"fashion_profile_id\":      nil,\n\t\t\t\"hd\":                      false,\n\t\t\t\"reflection_enabled\":      false,\n\t\t\t\"style\":                   \"auto\",\n\t\t},\n\t}\n\n\t// 创建消息数组\n\tvar messages []map[string]interface{}\n\n\tif openAIReq.Image != \"\" {\n\t\tvar base64Data string\n\n\t\tif strings.HasPrefix(openAIReq.Image, \"http://\") || strings.HasPrefix(openAIReq.Image, \"https://\") {\n\t\t\t// 下载文件\n\t\t\tbytes, err := fetchImageBytes(openAIReq.Image)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorf(c.Request.Context(), fmt.Sprintf(\"fetchImageBytes err  %v\\n\", err))\n\t\t\t\treturn nil, fmt.Errorf(\"fetchImageBytes err  %v\\n\", err)\n\t\t\t}\n\n\t\t\tcontentType := http.DetectContentType(bytes)\n\t\t\tif strings.HasPrefix(contentType, \"image/\") {\n\t\t\t\t// 是图片类型，转换为base64\n\t\t\t\tbase64Data = \"data:image/jpeg;base64,\" + base64.StdEncoding.EncodeToString(bytes)\n\t\t\t}\n\t\t} else if common.IsImageBase64(openAIReq.Image) {\n\t\t\t// 如果已经是 base64 格式\n\t\t\tif !strings.HasPrefix(openAIReq.Image, \"data:image\") {\n\t\t\t\tbase64Data = \"data:image/jpeg;base64,\" + openAIReq.Image\n\t\t\t} else {\n\t\t\t\tbase64Data = openAIReq.Image\n\t\t\t}\n\t\t}\n\n\t\t// 构建包含图片的消息\n\t\tif base64Data != \"\" {\n\t\t\tmessages = []map[string]interface{}{\n\t\t\t\t{\n\t\t\t\t\t\"role\": \"user\",\n\t\t\t\t\t\"content\": []map[string]interface{}{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"type\": \"image_url\",\n\t\t\t\t\t\t\t\"image_url\": map[string]interface{}{\n\t\t\t\t\t\t\t\t\"url\": base64Data,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"type\": \"text\",\n\t\t\t\t\t\t\t\"text\": openAIReq.Prompt,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t}\n\n\t// 如果没有图片或处理图片失败，使用纯文本消息\n\tif len(messages) == 0 {\n\t\tmessages = []map[string]interface{}{\n\t\t\t{\n\t\t\t\t\"role\":    \"user\",\n\t\t\t\t\"content\": openAIReq.Prompt,\n\t\t\t},\n\t\t}\n\t}\n\tvar currentQueryString string\n\tif len(chatId) != 0 {\n\t\tcurrentQueryString = fmt.Sprintf(\"id=%s&type=%s\", chatId, imageType)\n\t} else {\n\t\tcurrentQueryString = fmt.Sprintf(\"type=%s\", imageType)\n\t}\n\n\t// 创建请求体\n\trequestBody := map[string]interface{}{\n\t\t\"type\": \"COPILOT_MOA_IMAGE\",\n\t\t//\"current_query_string\": \"type=COPILOT_MOA_IMAGE\",\n\t\t\"current_query_string\": currentQueryString,\n\t\t\"messages\":             messages,\n\t\t\"user_s_input\":         openAIReq.Prompt,\n\t\t\"action_params\":        map[string]interface{}{},\n\t\t\"extra_data\": map[string]interface{}{\n\t\t\t\"model_configs\":  modelConfigs,\n\t\t\t\"llm_model\":      \"gpt-4o\",\n\t\t\t\"imageModelMap\":  map[string]interface{}{},\n\t\t\t\"writingContent\": nil,\n\t\t},\n\t}\n\n\tlogger.Debug(c.Request.Context(), fmt.Sprintf(\"RequestBody: %v\", requestBody))\n\n\tif strings.TrimSpace(config.RecaptchaProxyUrl) == \"\" ||\n\t\t(!strings.HasPrefix(config.RecaptchaProxyUrl, \"http://\") &&\n\t\t\t!strings.HasPrefix(config.RecaptchaProxyUrl, \"https://\")) {\n\t\treturn requestBody, nil\n\t} else {\n\n\t\ttr := &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t}\n\t\tclient := &http.Client{Transport: tr}\n\n\t\t// 检查并补充 RecaptchaProxyUrl 的末尾斜杠\n\t\tif !strings.HasSuffix(config.RecaptchaProxyUrl, \"/\") {\n\t\t\tconfig.RecaptchaProxyUrl += \"/\"\n\t\t}\n\n\t\t// 创建请求\n\t\treq, err := http.NewRequest(\"GET\", fmt.Sprintf(\"%sgenspark\", config.RecaptchaProxyUrl), nil)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(c.Request.Context(), fmt.Sprintf(\"创建/genspark请求失败   %v\\n\", err))\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// 设置请求头\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t\treq.Header.Set(\"Cookie\", cookie)\n\n\t\t// 发送请求\n\t\tresp, err := client.Do(req)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(c.Request.Context(), fmt.Sprintf(\"发送/genspark请求失败   %v\\n\", err))\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer resp.Body.Close()\n\n\t\t// 读取响应体\n\t\tbody, err := io.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(c.Request.Context(), fmt.Sprintf(\"读取/genspark响应失败   %v\\n\", err))\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttype Response struct {\n\t\t\tCode    int    `json:\"code\"`\n\t\t\tToken   string `json:\"token\"`\n\t\t\tMessage string `json:\"message\"`\n\t\t}\n\n\t\tif resp.StatusCode == 200 {\n\t\t\tvar response Response\n\t\t\tif err := json.Unmarshal(body, &response); err != nil {\n\t\t\t\tlogger.Errorf(c.Request.Context(), fmt.Sprintf(\"读取/genspark JSON 失败   %v\\n\", err))\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif response.Code == 200 {\n\t\t\t\tlogger.Debugf(c.Request.Context(), fmt.Sprintf(\"g_recaptcha_token: %v\\n\", response.Token))\n\t\t\t\trequestBody[\"g_recaptcha_token\"] = response.Token\n\t\t\t\tlogger.Infof(c.Request.Context(), fmt.Sprintf(\"cheat success!\"))\n\t\t\t\treturn requestBody, nil\n\t\t\t} else {\n\t\t\t\tlogger.Errorf(c.Request.Context(), fmt.Sprintf(\"读取/genspark token 失败   %v\\n\", err))\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\tlogger.Errorf(c.Request.Context(), fmt.Sprintf(\"请求/genspark失败   %v\\n\", err))\n\t\t\treturn nil, err\n\t\t}\n\t}\n}\n\n// createStreamResponse 创建流式响应\nfunc createStreamResponse(responseId, modelName string, jsonData []byte, delta model.OpenAIDelta, finishReason *string) model.OpenAIChatCompletionResponse {\n\tpromptTokens := common.CountTokenText(string(jsonData), modelName)\n\tcompletionTokens := common.CountTokenText(delta.Content, modelName)\n\treturn model.OpenAIChatCompletionResponse{\n\t\tID:      responseId,\n\t\tObject:  \"chat.completion.chunk\",\n\t\tCreated: time.Now().Unix(),\n\t\tModel:   modelName,\n\t\tChoices: []model.OpenAIChoice{\n\t\t\t{\n\t\t\t\tIndex:        0,\n\t\t\t\tDelta:        delta,\n\t\t\t\tFinishReason: finishReason,\n\t\t\t},\n\t\t},\n\t\tUsage: model.OpenAIUsage{\n\t\t\tPromptTokens:     promptTokens,\n\t\t\tCompletionTokens: completionTokens,\n\t\t\tTotalTokens:      promptTokens + completionTokens,\n\t\t},\n\t}\n}\n\n// handleMessageFieldDelta 处理消息字段增量\nfunc handleMessageFieldDelta(c *gin.Context, event map[string]interface{}, responseId, modelName string, jsonData []byte) error {\n\tfieldName, ok := event[\"field_name\"].(string)\n\tif !ok {\n\t\treturn nil\n\t}\n\n\t// 基础允许列表（所有配置下都需要处理的字段）\n\tbaseAllowed := fieldName == \"session_state.answer\" ||\n\t\tstrings.Contains(fieldName, \"session_state.streaming_detail_answer\") ||\n\t\tfieldName == \"session_state.streaming_markmap\"\n\n\t// 需要显示思考过程时需要额外处理的字段\n\tif config.ReasoningHide != 1 {\n\t\tbaseAllowed = baseAllowed ||\n\t\t\tfieldName == \"session_state.answerthink_is_started\" ||\n\t\t\tfieldName == \"session_state.answerthink\" ||\n\t\t\tfieldName == \"session_state.answerthink_is_finished\"\n\t}\n\n\tif !baseAllowed {\n\t\treturn nil\n\t}\n\n\t// 获取 delta 内容\n\tvar delta string\n\tswitch {\n\tcase (modelName == \"o1\" || modelName == \"o3-mini-high\") && fieldName == \"session_state.answer\":\n\t\tdelta, _ = event[\"field_value\"].(string)\n\tdefault:\n\t\tdelta, _ = event[\"delta\"].(string)\n\t}\n\n\t// 创建基础响应\n\tcreateResponse := func(content string) model.OpenAIChatCompletionResponse {\n\t\treturn createStreamResponse(\n\t\t\tresponseId,\n\t\t\tmodelName,\n\t\t\tjsonData,\n\t\t\tmodel.OpenAIDelta{Content: content, Role: \"assistant\"},\n\t\t\tnil,\n\t\t)\n\t}\n\n\t// 发送基础事件\n\tvar err error\n\tif err = sendSSEvent(c, createResponse(delta)); err != nil {\n\t\treturn err\n\t}\n\n\t// 处理思考过程标记\n\tif config.ReasoningHide != 1 {\n\t\tswitch fieldName {\n\t\tcase \"session_state.answerthink_is_started\":\n\t\t\terr = sendSSEvent(c, createResponse(\"<think>\\n\"))\n\t\tcase \"session_state.answerthink_is_finished\":\n\t\t\terr = sendSSEvent(c, createResponse(\"\\n</think>\"))\n\t\t}\n\t}\n\n\treturn err\n}\n\ntype Content struct {\n\tDetailAnswer string `json:\"detailAnswer\"`\n}\n\nfunc getDetailAnswer(eventMap map[string]interface{}) (string, error) {\n\t// 获取 content 字段的值\n\tcontentStr, ok := eventMap[\"content\"].(string)\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"content is not a string\")\n\t}\n\n\t// 解析内层的 JSON\n\tvar content Content\n\tif err := json.Unmarshal([]byte(contentStr), &content); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn content.DetailAnswer, nil\n}\n\n// handleMessageResult 处理消息结果\nfunc handleMessageResult(c *gin.Context, event map[string]interface{}, responseId, modelName string, jsonData []byte, searchModel bool) bool {\n\tfinishReason := \"stop\"\n\tvar delta string\n\tvar err error\n\tif modelName == \"o1\" && searchModel {\n\t\tdelta, err = getDetailAnswer(event)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(c.Request.Context(), \"getDetailAnswer err: %v\", err)\n\t\t\treturn false\n\t\t}\n\t}\n\n\tstreamResp := createStreamResponse(responseId, modelName, jsonData, model.OpenAIDelta{Content: delta, Role: \"assistant\"}, &finishReason)\n\tif err := sendSSEvent(c, streamResp); err != nil {\n\t\tlogger.Warnf(c.Request.Context(), \"sendSSEvent err: %v\", err)\n\t\treturn false\n\t}\n\tc.SSEvent(\"\", \" [DONE]\")\n\treturn false\n}\n\n// sendSSEvent 发送SSE事件\nfunc sendSSEvent(c *gin.Context, response model.OpenAIChatCompletionResponse) error {\n\tjsonResp, err := json.Marshal(response)\n\tif err != nil {\n\t\tlogger.Errorf(c.Request.Context(), \"Failed to marshal response: %v\", err)\n\t\treturn err\n\t}\n\tc.SSEvent(\"\", \" \"+string(jsonResp))\n\tc.Writer.Flush()\n\treturn nil\n}\n\n// makeRequest 发送HTTP请求\nfunc makeRequest(client cycletls.CycleTLS, jsonData []byte, cookie string, isStream bool) (cycletls.Response, error) {\n\taccept := \"application/json\"\n\tif isStream {\n\t\taccept = \"text/event-stream\"\n\t}\n\n\treturn client.Do(apiEndpoint, cycletls.Options{\n\t\tTimeout: 10 * 60 * 60,\n\t\tProxy:   config.ProxyUrl, // 在每个请求中设置代理\n\t\tBody:    string(jsonData),\n\t\tMethod:  \"POST\",\n\t\tHeaders: map[string]string{\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\"Accept\":       accept,\n\t\t\t\"Origin\":       baseURL,\n\t\t\t\"Referer\":      baseURL + \"/\",\n\t\t\t\"Cookie\":       cookie,\n\t\t\t\"User-Agent\":   \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome\",\n\t\t},\n\t}, \"POST\")\n}\n\n// makeRequest 发送HTTP请求\nfunc makeImageRequest(client cycletls.CycleTLS, jsonData []byte, cookie string) (cycletls.Response, error) {\n\n\taccept := \"*/*\"\n\n\treturn client.Do(apiEndpoint, cycletls.Options{\n\t\tUserAgent: \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome\",\n\t\tTimeout:   10 * 60 * 60,\n\t\tProxy:     config.ProxyUrl, // 在每个请求中设置代理\n\t\tBody:      string(jsonData),\n\t\tMethod:    \"POST\",\n\t\tHeaders: map[string]string{\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\"Accept\":       accept,\n\t\t\t\"Origin\":       baseURL,\n\t\t\t\"Referer\":      baseURL + \"/\",\n\t\t\t\"Cookie\":       cookie,\n\t\t\t\"User-Agent\":   \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome\",\n\t\t},\n\t}, \"POST\")\n}\n\nfunc makeDeleteRequest(client cycletls.CycleTLS, cookie, projectId string) (cycletls.Response, error) {\n\n\t// 不删除环境变量中的map中的对话\n\n\tfor _, v := range config.ModelChatMap {\n\t\tif v == projectId {\n\t\t\treturn cycletls.Response{}, nil\n\t\t}\n\t}\n\tfor _, v := range config.GlobalSessionManager.GetChatIDsByCookie(cookie) {\n\t\tif v == projectId {\n\t\t\treturn cycletls.Response{}, nil\n\t\t}\n\t}\n\tfor _, v := range config.SessionImageChatMap {\n\t\tif v == projectId {\n\t\t\treturn cycletls.Response{}, nil\n\t\t}\n\t}\n\n\taccept := \"application/json\"\n\n\treturn client.Do(fmt.Sprintf(deleteEndpoint, projectId), cycletls.Options{\n\t\tTimeout: 10 * 60 * 60,\n\t\tProxy:   config.ProxyUrl, // 在每个请求中设置代理\n\t\tMethod:  \"GET\",\n\t\tHeaders: map[string]string{\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\"Accept\":       accept,\n\t\t\t\"Origin\":       baseURL,\n\t\t\t\"Referer\":      baseURL + \"/\",\n\t\t\t\"Cookie\":       cookie,\n\t\t\t\"User-Agent\":   \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome\",\n\t\t},\n\t}, \"GET\")\n}\n\nfunc makeGetUploadUrlRequest(client cycletls.CycleTLS, cookie string) (cycletls.Response, error) {\n\n\taccept := \"*/*\"\n\n\treturn client.Do(fmt.Sprintf(uploadEndpoint), cycletls.Options{\n\t\tTimeout: 10 * 60 * 60,\n\t\tProxy:   config.ProxyUrl, // 在每个请求中设置代理\n\t\tMethod:  \"GET\",\n\t\tHeaders: map[string]string{\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\"Accept\":       accept,\n\t\t\t\"Origin\":       baseURL,\n\t\t\t\"Referer\":      baseURL + \"/\",\n\t\t\t\"Cookie\":       cookie,\n\t\t\t\"User-Agent\":   \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome\",\n\t\t},\n\t}, \"GET\")\n}\n\n//func makeOptionsRequest(client cycletls.CycleTLS, uploadUrl string) (cycletls.Response, error) {\n//\treturn client.Do(uploadUrl, cycletls.Options{\n//\t\tMethod: \"OPTIONS\",\n//\t\tHeaders: map[string]string{\n//\t\t\t\"Accept\":                         \"*/*\",\n//\t\t\t\"Access-Control-Request-Headers\": \"x-ms-blob-type\",\n//\t\t\t\"Access-Control-Request-Method\":  \"PUT\",\n//\t\t\t\"Origin\":                         \"https://www.genspark.ai\",\n//\t\t\t\"Sec-Fetch-Dest\":                 \"empty\",\n//\t\t\t\"Sec-Fetch-Mode\":                 \"cors\",\n//\t\t\t\"Sec-Fetch-Site\":                 \"cross-site\",\n//\t\t},\n//\t\tUserAgent: \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36\",\n//\t}, \"OPTIONS\")\n//}\n\nfunc makeUploadRequest(client cycletls.CycleTLS, uploadUrl string, fileBytes []byte) (cycletls.Response, error) {\n\treturn client.Do(uploadUrl, cycletls.Options{\n\t\tTimeout: 10 * 60 * 60,\n\t\tProxy:   config.ProxyUrl, // 在每个请求中设置代理\n\t\tMethod:  \"PUT\",\n\t\tBody:    string(fileBytes),\n\t\tHeaders: map[string]string{\n\t\t\t\"Accept\":         \"*/*\",\n\t\t\t\"x-ms-blob-type\": \"BlockBlob\",\n\t\t\t\"Content-Type\":   \"application/octet-stream\",\n\t\t\t\"Content-Length\": fmt.Sprintf(\"%d\", len(fileBytes)),\n\t\t\t\"Origin\":         \"https://www.genspark.ai\",\n\t\t\t\"Sec-Fetch-Dest\": \"empty\",\n\t\t\t\"Sec-Fetch-Mode\": \"cors\",\n\t\t\t\"Sec-Fetch-Site\": \"cross-site\",\n\t\t},\n\t}, \"PUT\")\n}\n\n// handleStreamRequest 处理流式请求\n//func handleStreamRequest(c *gin.Context, client cycletls.CycleTLS, cookie string, jsonData []byte, model string) {\n//\tc.Header(\"Content-Type\", \"text/event-stream\")\n//\tc.Header(\"Cache-Control\", \"no-cache\")\n//\tc.Header(\"Connection\", \"keep-alive\")\n//\n//\tresponseId := fmt.Sprintf(responseIDFormat, time.Now().Format(\"20060102150405\"))\n//\n//\tc.Stream(func(w io.Writer) bool {\n//\t\tsseChan, err := makeStreamRequest(c, client, jsonData, cookie)\n//\t\tif err != nil {\n//\t\t\tlogger.Errorf(c.Request.Context(), \"makeStreamRequest err: %v\", err)\n//\t\t\treturn false\n//\t\t}\n//\n//\t\treturn handleStreamResponse(c, sseChan, responseId, cookie, model, jsonData)\n//\t})\n//}\n\nfunc handleStreamRequest(c *gin.Context, client cycletls.CycleTLS, cookie string, cookieManager *config.CookieManager, requestBody map[string]interface{}, modelName string, searchModel bool) {\n\tconst (\n\t\terrNoValidCookies         = \"No valid cookies available\"\n\t\terrCloudflareChallengeMsg = \"Detected Cloudflare Challenge Page\"\n\t\terrCloudflareBlock        = \"CloudFlare: Sorry, you have been blocked\"\n\t\terrServerErrMsg           = \"An error occurred with the current request, please try again.\"\n\t\terrServiceUnavailable     = \"Genspark Service Unavailable\"\n\t)\n\n\tc.Header(\"Content-Type\", \"text/event-stream\")\n\tc.Header(\"Cache-Control\", \"no-cache\")\n\tc.Header(\"Connection\", \"keep-alive\")\n\n\tresponseId := fmt.Sprintf(responseIDFormat, time.Now().Format(\"20060102150405\"))\n\tctx := c.Request.Context()\n\tmaxRetries := len(cookieManager.Cookies)\n\n\tc.Stream(func(w io.Writer) bool {\n\t\tfor attempt := 0; attempt < maxRetries; attempt++ {\n\n\t\t\trequestBody, err := cheat(requestBody, c, cookie)\n\t\t\tif err != nil {\n\t\t\t\tc.JSON(500, gin.H{\"error\": err.Error()})\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tjsonData, err := json.Marshal(requestBody)\n\t\t\tif err != nil {\n\t\t\t\tc.JSON(500, gin.H{\"error\": \"Failed to marshal request body\"})\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tsseChan, err := makeStreamRequest(c, client, jsonData, cookie)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorf(ctx, \"makeStreamRequest err on attempt %d: %v\", attempt+1, err)\n\t\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": err.Error()})\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tvar projectId string\n\t\t\tisRateLimit := false\n\t\tSSELoop:\n\t\t\tfor response := range sseChan {\n\t\t\t\tif response.Done {\n\t\t\t\t\tlogger.Debugf(ctx, response.Data)\n\t\t\t\t\treturn false\n\t\t\t\t}\n\n\t\t\t\tdata := response.Data\n\t\t\t\tif data == \"\" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tlogger.Debug(ctx, strings.TrimSpace(data))\n\n\t\t\t\tswitch {\n\t\t\t\tcase common.IsCloudflareChallenge(data):\n\t\t\t\t\tlogger.Errorf(ctx, errCloudflareChallengeMsg)\n\t\t\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": errCloudflareChallengeMsg})\n\t\t\t\t\treturn false\n\t\t\t\tcase common.IsCloudflareBlock(data):\n\t\t\t\t\tlogger.Errorf(ctx, errCloudflareBlock)\n\t\t\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": errCloudflareBlock})\n\t\t\t\t\treturn false\n\t\t\t\tcase common.IsServiceUnavailablePage(data):\n\t\t\t\t\tlogger.Errorf(ctx, errServiceUnavailable)\n\t\t\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": errServiceUnavailable})\n\t\t\t\t\treturn false\n\t\t\t\tcase common.IsServerError(data):\n\t\t\t\t\tlogger.Errorf(ctx, errServerErrMsg)\n\t\t\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": errServerErrMsg})\n\t\t\t\t\treturn false\n\t\t\t\tcase common.IsRateLimit(data):\n\t\t\t\t\tisRateLimit = true\n\t\t\t\t\tlogger.Warnf(ctx, \"Cookie rate limited, switching to next cookie, attempt %d/%d, COOKIE:%s\", attempt+1, maxRetries, cookie)\n\t\t\t\t\tconfig.AddRateLimitCookie(cookie, time.Now().Add(time.Duration(config.RateLimitCookieLockDuration)*time.Second))\n\t\t\t\t\tbreak SSELoop // 使用 label 跳出 SSE 循环\n\t\t\t\tcase common.IsFreeLimit(data):\n\t\t\t\t\tisRateLimit = true\n\t\t\t\t\tlogger.Warnf(ctx, \"Cookie free rate limited, switching to next cookie, attempt %d/%d, COOKIE:%s\", attempt+1, maxRetries, cookie)\n\t\t\t\t\tconfig.AddRateLimitCookie(cookie, time.Now().Add(24*60*60*time.Second))\n\t\t\t\t\t// 删除cookie\n\t\t\t\t\t//config.RemoveCookie(cookie)\n\t\t\t\t\tbreak SSELoop // 使用 label 跳出 SSE 循环\n\t\t\t\tcase common.IsNotLogin(data):\n\t\t\t\t\tisRateLimit = true\n\t\t\t\t\tlogger.Warnf(ctx, \"Cookie Not Login, switching to next cookie, attempt %d/%d, COOKIE:%s\", attempt+1, maxRetries, cookie)\n\t\t\t\t\t// 删除cookie\n\t\t\t\t\tconfig.RemoveCookie(cookie)\n\t\t\t\t\tbreak SSELoop // 使用 label 跳出 SSE 循环\n\t\t\t\t}\n\n\t\t\t\t// 处理事件流数据\n\t\t\t\tif shouldContinue := processStreamData(c, data, &projectId, cookie, responseId, modelName, jsonData, searchModel); !shouldContinue {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !isRateLimit {\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\t// 获取下一个可用的cookie继续尝试\n\t\t\tcookie, err = cookieManager.GetNextCookie()\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorf(ctx, \"No more valid cookies available after attempt %d\", attempt+1)\n\t\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": errNoValidCookies})\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\t// requestBody重制chatId\n\t\t\tcurrentQueryString := fmt.Sprintf(\"type=%s\", chatType)\n\t\t\tif chatId, ok := config.GlobalSessionManager.GetChatID(cookie, modelName); ok {\n\t\t\t\tcurrentQueryString = fmt.Sprintf(\"id=%s&type=%s\", chatId, chatType)\n\t\t\t}\n\t\t\trequestBody[\"current_query_string\"] = currentQueryString\n\t\t}\n\n\t\tlogger.Errorf(ctx, \"All cookies exhausted after %d attempts\", maxRetries)\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": \"All cookies are temporarily unavailable.\"})\n\t\treturn false\n\t})\n}\n\nfunc cheat(requestBody map[string]interface{}, c *gin.Context, cookie string) (map[string]interface{}, error) {\n\tif strings.TrimSpace(config.RecaptchaProxyUrl) == \"\" ||\n\t\t(!strings.HasPrefix(config.RecaptchaProxyUrl, \"http://\") &&\n\t\t\t!strings.HasPrefix(config.RecaptchaProxyUrl, \"https://\")) {\n\t\treturn requestBody, nil\n\t} else {\n\n\t\ttr := &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t}\n\t\tclient := &http.Client{Transport: tr}\n\n\t\t// 检查并补充 RecaptchaProxyUrl 的末尾斜杠\n\t\tif !strings.HasSuffix(config.RecaptchaProxyUrl, \"/\") {\n\t\t\tconfig.RecaptchaProxyUrl += \"/\"\n\t\t}\n\n\t\t// 创建请求\n\t\treq, err := http.NewRequest(\"GET\", fmt.Sprintf(\"%sgenspark\", config.RecaptchaProxyUrl), nil)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(c.Request.Context(), fmt.Sprintf(\"创建/genspark请求失败   %v\\n\", err))\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// 设置请求头\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t\treq.Header.Set(\"Cookie\", cookie)\n\n\t\t// 发送请求\n\t\tresp, err := client.Do(req)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(c.Request.Context(), fmt.Sprintf(\"发送/genspark请求失败   %v\\n\", err))\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer resp.Body.Close()\n\n\t\t// 读取响应体\n\t\tbody, err := io.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(c.Request.Context(), fmt.Sprintf(\"读取/genspark响应失败   %v\\n\", err))\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttype Response struct {\n\t\t\tCode    int    `json:\"code\"`\n\t\t\tToken   string `json:\"token\"`\n\t\t\tMessage string `json:\"message\"`\n\t\t}\n\n\t\tif resp.StatusCode == 200 {\n\t\t\tvar response Response\n\t\t\tif err := json.Unmarshal(body, &response); err != nil {\n\t\t\t\tlogger.Errorf(c.Request.Context(), fmt.Sprintf(\"读取/genspark JSON 失败   %v\\n\", err))\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif response.Code == 200 {\n\t\t\t\tlogger.Debugf(c.Request.Context(), fmt.Sprintf(\"g_recaptcha_token: %v\\n\", response.Token))\n\t\t\t\trequestBody[\"g_recaptcha_token\"] = response.Token\n\t\t\t\tlogger.Infof(c.Request.Context(), fmt.Sprintf(\"cheat success!\"))\n\t\t\t\treturn requestBody, nil\n\t\t\t} else {\n\t\t\t\tlogger.Errorf(c.Request.Context(), fmt.Sprintf(\"读取/genspark token 失败,查看 playwright-proxy log\"))\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\tlogger.Errorf(c.Request.Context(), fmt.Sprintf(\"请求/genspark失败,查看 playwright-proxy log\"))\n\t\t\treturn nil, err\n\t\t}\n\t}\n}\n\n// 处理流式数据的辅助函数，返回bool表示是否继续处理\nfunc processStreamData(c *gin.Context, data string, projectId *string, cookie, responseId, model string, jsonData []byte, searchModel bool) bool {\n\tdata = strings.TrimSpace(data)\n\t//if !strings.HasPrefix(data, \"data: \") {\n\t//\treturn true\n\t//}\n\tdata = strings.TrimPrefix(data, \"data: \")\n\tif !strings.HasPrefix(data, \"{\\\"id\\\":\") && !strings.HasPrefix(data, \"{\\\"message_id\\\":\") {\n\t\treturn true\n\t}\n\tvar event map[string]interface{}\n\tif err := json.Unmarshal([]byte(data), &event); err != nil {\n\t\tlogger.Errorf(c.Request.Context(), \"Failed to unmarshal event: %v\", err)\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": err.Error()})\n\t\treturn false\n\t}\n\n\teventType, ok := event[\"type\"].(string)\n\tif !ok {\n\t\treturn true\n\t}\n\n\tswitch eventType {\n\tcase \"project_start\":\n\t\t*projectId, _ = event[\"id\"].(string)\n\tcase \"message_field\":\n\t\tif err := handleMessageFieldDelta(c, event, responseId, model, jsonData); err != nil {\n\t\t\tlogger.Errorf(c.Request.Context(), \"handleMessageFieldDelta err: %v\", err)\n\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": err.Error()})\n\t\t\treturn false\n\t\t}\n\tcase \"message_field_delta\":\n\t\tif err := handleMessageFieldDelta(c, event, responseId, model, jsonData); err != nil {\n\t\t\tlogger.Errorf(c.Request.Context(), \"handleMessageFieldDelta err: %v\", err)\n\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": err.Error()})\n\t\t\treturn false\n\t\t}\n\tcase \"message_result\":\n\t\tgo func() {\n\t\t\tif config.AutoModelChatMapType == 1 {\n\t\t\t\t// 保存映射\n\t\t\t\tconfig.GlobalSessionManager.AddSession(cookie, model, *projectId)\n\t\t\t} else {\n\t\t\t\tif config.AutoDelChat == 1 {\n\t\t\t\t\tclient := cycletls.Init()\n\t\t\t\t\tdefer safeClose(client)\n\t\t\t\t\tmakeDeleteRequest(client, cookie, *projectId)\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\treturn handleMessageResult(c, event, responseId, model, jsonData, searchModel)\n\t}\n\n\treturn true\n}\n\nfunc makeStreamRequest(c *gin.Context, client cycletls.CycleTLS, jsonData []byte, cookie string) (<-chan cycletls.SSEResponse, error) {\n\n\toptions := cycletls.Options{\n\t\tTimeout: 10 * 60 * 60,\n\t\tProxy:   config.ProxyUrl, // 在每个请求中设置代理\n\t\tBody:    string(jsonData),\n\t\tMethod:  \"POST\",\n\t\tHeaders: map[string]string{\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\"Accept\":       \"text/event-stream\",\n\t\t\t\"Origin\":       baseURL,\n\t\t\t\"Referer\":      baseURL + \"/\",\n\t\t\t\"Cookie\":       cookie,\n\t\t\t\"User-Agent\":   \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome\",\n\t\t},\n\t}\n\n\tlogger.Debug(c.Request.Context(), fmt.Sprintf(\"cookie: %v\", cookie))\n\n\tsseChan, err := client.DoSSE(apiEndpoint, options, \"POST\")\n\tif err != nil {\n\t\tlogger.Errorf(c, \"Failed to make stream request: %v\", err)\n\t\treturn nil, fmt.Errorf(\"Failed to make stream request: %v\", err)\n\t}\n\treturn sseChan, nil\n}\n\n// handleNonStreamRequest 处理非流式请求\n//\n//\tfunc handleNonStreamRequest(c *gin.Context, client cycletls.CycleTLS, cookie string, jsonData []byte, modelName string) {\n//\t\tresponse, err := makeRequest(client, jsonData, cookie, false)\n//\t\tif err != nil {\n//\t\t\tlogger.Errorf(c.Request.Context(), \"makeRequest err: %v\", err)\n//\t\t\tc.JSON(500, gin.H{\"error\": err.Error()})\n//\t\t\treturn\n//\t\t}\n//\n//\t\treader := strings.NewReader(response.Body)\n//\t\tscanner := bufio.NewScanner(reader)\n//\n//\t\tvar content string\n//\t\tvar firstline string\n//\t\tfor scanner.Scan() {\n//\t\t\tline := scanner.Text()\n//\t\t\tfirstline = line\n//\t\t\tlogger.Debug(c.Request.Context(), strings.TrimSpace(line))\n//\n//\t\t\tif common.IsCloudflareChallenge(line) {\n//\t\t\t\tlogger.Errorf(c.Request.Context(), \"Detected Cloudflare Challenge Page\")\n//\t\t\t\tc.JSON(500, gin.H{\"error\": \"Detected Cloudflare Challenge Page\"})\n//\t\t\t\treturn\n//\t\t\t}\n//\n//\t\t\tif common.IsRateLimit(line) {\n//\t\t\t\tlogger.Errorf(c.Request.Context(), \"Cookie has reached the rate Limit\")\n//\t\t\t\tc.JSON(500, gin.H{\"error\": \"Cookie has reached the rate Limit\"})\n//\t\t\t\treturn\n//\t\t\t}\n//\n//\t\t\tif strings.HasPrefix(line, \"data: \") {\n//\t\t\t\tdata := strings.TrimPrefix(line, \"data: \")\n//\t\t\t\tvar parsedResponse struct {\n//\t\t\t\t\tType      string `json:\"type\"`\n//\t\t\t\t\tFieldName string `json:\"field_name\"`\n//\t\t\t\t\tContent   string `json:\"content\"`\n//\t\t\t\t}\n//\t\t\t\tif err := json.Unmarshal([]byte(data), &parsedResponse); err != nil {\n//\t\t\t\t\tlogger.Warnf(c.Request.Context(), \"Failed to unmarshal response: %v\", err)\n//\t\t\t\t\tcontinue\n//\t\t\t\t}\n//\t\t\t\tif parsedResponse.Type == \"message_result\" {\n//\t\t\t\t\tcontent = parsedResponse.Content\n//\t\t\t\t\tbreak\n//\t\t\t\t}\n//\t\t\t}\n//\t\t}\n//\n//\t\tif content == \"\" {\n//\t\t\tlogger.Errorf(c.Request.Context(), firstline)\n//\t\t\tc.JSON(500, gin.H{\"error\": \"No valid response content\"})\n//\t\t\treturn\n//\t\t}\n//\n//\t\tpromptTokens := common.CountTokenText(string(jsonData), modelName)\n//\t\tcompletionTokens := common.CountTokenText(content, modelName)\n//\n//\t\tfinishReason := \"stop\"\n//\t\t// 创建并返回 OpenAIChatCompletionResponse 结构\n//\t\tresp := model.OpenAIChatCompletionResponse{\n//\t\t\tID:      fmt.Sprintf(responseIDFormat, time.Now().Format(\"20060102150405\")),\n//\t\t\tObject:  \"chat.completion\",\n//\t\t\tCreated: time.Now().Unix(),\n//\t\t\tModel:   modelName,\n//\t\t\tChoices: []model.OpenAIChoice{\n//\t\t\t\t{\n//\t\t\t\t\tMessage: model.OpenAIMessage{\n//\t\t\t\t\t\tRole:    \"assistant\",\n//\t\t\t\t\t\tContent: content,\n//\t\t\t\t\t},\n//\t\t\t\t\tFinishReason: &finishReason,\n//\t\t\t\t},\n//\t\t\t},\n//\t\t\tUsage: model.OpenAIUsage{\n//\t\t\t\tPromptTokens:     promptTokens,\n//\t\t\t\tCompletionTokens: completionTokens,\n//\t\t\t\tTotalTokens:      promptTokens + completionTokens,\n//\t\t\t},\n//\t\t}\n//\n//\t\tc.JSON(200, resp)\n//\t}\nfunc handleNonStreamRequest(c *gin.Context, client cycletls.CycleTLS, cookie string, cookieManager *config.CookieManager, requestBody map[string]interface{}, modelName string, searchModel bool) {\n\tconst (\n\t\terrCloudflareChallengeMsg = \"Detected Cloudflare Challenge Page\"\n\t\terrCloudflareBlock        = \"CloudFlare: Sorry, you have been blocked\"\n\t\terrServerErrMsg           = \"An error occurred with the current request, please try again.\"\n\t\terrServiceUnavailable     = \"Genspark Service Unavailable\"\n\t\terrNoValidResponseContent = \"No valid response content\"\n\t)\n\n\tctx := c.Request.Context()\n\tmaxRetries := len(cookieManager.Cookies)\n\n\tfor attempt := 0; attempt < maxRetries; attempt++ {\n\t\trequestBody, err := cheat(requestBody, c, cookie)\n\t\tif err != nil {\n\t\t\tc.JSON(500, gin.H{\"error\": err.Error()})\n\t\t\treturn\n\t\t}\n\t\tjsonData, err := json.Marshal(requestBody)\n\t\tif err != nil {\n\t\t\tc.JSON(500, gin.H{\"error\": \"Failed to marshal request body\"})\n\t\t\treturn\n\t\t}\n\t\tresponse, err := makeRequest(client, jsonData, cookie, false)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(ctx, \"makeRequest err: %v\", err)\n\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": err.Error()})\n\t\t\treturn\n\t\t}\n\n\t\tscanner := bufio.NewScanner(strings.NewReader(response.Body))\n\t\tvar content string\n\t\tvar answerThink string\n\t\tvar firstLine string\n\t\tvar projectId string\n\t\tisRateLimit := false\n\n\t\tfor scanner.Scan() {\n\t\t\tline := scanner.Text()\n\t\t\tif firstLine == \"\" {\n\t\t\t\tfirstLine = line\n\t\t\t}\n\t\t\tif line == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlogger.Debug(ctx, strings.TrimSpace(line))\n\n\t\t\tswitch {\n\t\t\tcase common.IsCloudflareChallenge(line):\n\t\t\t\tlogger.Errorf(ctx, errCloudflareChallengeMsg)\n\t\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": errCloudflareChallengeMsg})\n\t\t\t\treturn\n\t\t\tcase common.IsCloudflareBlock(line):\n\t\t\t\tlogger.Errorf(ctx, errCloudflareBlock)\n\t\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": errCloudflareBlock})\n\t\t\t\treturn\n\t\t\tcase common.IsRateLimit(line):\n\t\t\t\tisRateLimit = true\n\t\t\t\tlogger.Warnf(ctx, \"Cookie rate limited, switching to next cookie, attempt %d/%d, COOKIE:%s\", attempt+1, maxRetries, cookie)\n\t\t\t\tconfig.AddRateLimitCookie(cookie, time.Now().Add(time.Duration(config.RateLimitCookieLockDuration)*time.Second))\n\t\t\t\tbreak\n\t\t\tcase common.IsFreeLimit(line):\n\t\t\t\tisRateLimit = true\n\t\t\t\tlogger.Warnf(ctx, \"Cookie free rate limited, switching to next cookie, attempt %d/%d, COOKIE:%s\", attempt+1, maxRetries, cookie)\n\t\t\t\tconfig.AddRateLimitCookie(cookie, time.Now().Add(24*60*60*time.Second))\n\t\t\t\t// 删除cookie\n\t\t\t\t//config.RemoveCookie(cookie)\n\t\t\t\tbreak\n\t\t\tcase common.IsNotLogin(line):\n\t\t\t\tisRateLimit = true\n\t\t\t\tlogger.Warnf(ctx, \"Cookie Not Login, switching to next cookie, attempt %d/%d, COOKIE:%s\", attempt+1, maxRetries, cookie)\n\t\t\t\t// 删除cookie\n\t\t\t\tconfig.RemoveCookie(cookie)\n\t\t\t\tbreak\n\t\t\tcase common.IsServiceUnavailablePage(line):\n\t\t\t\tlogger.Errorf(ctx, errServiceUnavailable)\n\t\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": errServiceUnavailable})\n\t\t\t\treturn\n\t\t\tcase common.IsServerError(line):\n\t\t\t\tlogger.Errorf(ctx, errServerErrMsg)\n\t\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": errServerErrMsg})\n\t\t\t\treturn\n\t\t\tcase strings.HasPrefix(line, \"data: \"):\n\n\t\t\t\tdata := strings.TrimPrefix(line, \"data: \")\n\t\t\t\tvar parsedResponse struct {\n\t\t\t\t\tType      string `json:\"type\"`\n\t\t\t\t\tFieldName string `json:\"field_name\"`\n\t\t\t\t\tContent   string `json:\"content\"`\n\t\t\t\t\tId        string `json:\"id\"`\n\t\t\t\t\tDelta     string `json:\"delta\"`\n\t\t\t\t}\n\t\t\t\tif err := json.Unmarshal([]byte(data), &parsedResponse); err != nil {\n\t\t\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": err.Error()})\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif parsedResponse.Type == \"project_start\" {\n\t\t\t\t\tprojectId = parsedResponse.Id\n\t\t\t\t}\n\t\t\t\tif parsedResponse.Type == \"message_field\" {\n\t\t\t\t\t// 提取思考过程\n\t\t\t\t\tif config.ReasoningHide != 1 {\n\t\t\t\t\t\tif parsedResponse.FieldName == \"session_state.answerthink_is_started\" {\n\t\t\t\t\t\t\tanswerThink = \"<think>\\n\"\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif parsedResponse.FieldName == \"session_state.answerthink_is_finished\" {\n\t\t\t\t\t\t\tanswerThink = answerThink + \"\\n</think>\"\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif parsedResponse.Type == \"message_field_delta\" {\n\t\t\t\t\t// 提取思考过程\n\t\t\t\t\tif config.ReasoningHide != 1 {\n\t\t\t\t\t\tif parsedResponse.FieldName == \"session_state.answerthink\" {\n\t\t\t\t\t\t\tanswerThink = answerThink + parsedResponse.Delta\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif parsedResponse.Type == \"message_result\" {\n\t\t\t\t\t// 删除临时会话\n\t\t\t\t\tgo func() {\n\t\t\t\t\t\tif config.AutoModelChatMapType == 1 {\n\t\t\t\t\t\t\t// 保存映射\n\t\t\t\t\t\t\tconfig.GlobalSessionManager.AddSession(cookie, modelName, projectId)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif config.AutoDelChat == 1 {\n\t\t\t\t\t\t\t\tclient := cycletls.Init()\n\t\t\t\t\t\t\t\tdefer safeClose(client)\n\t\t\t\t\t\t\t\tmakeDeleteRequest(client, cookie, projectId)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}()\n\t\t\t\t\tif modelName == \"o1\" && searchModel {\n\t\t\t\t\t\t// 解析内层的 JSON\n\t\t\t\t\t\tvar content Content\n\t\t\t\t\t\tif err := json.Unmarshal([]byte(parsedResponse.Content), &content); err != nil {\n\t\t\t\t\t\t\tlogger.Errorf(ctx, \"Failed to unmarshal response content: %v err %s\", parsedResponse.Content, err.Error())\n\t\t\t\t\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": \"Failed to unmarshal response content\"})\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tparsedResponse.Content = content.DetailAnswer\n\t\t\t\t\t}\n\t\t\t\t\tcontent = strings.TrimSpace(answerThink + parsedResponse.Content)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif !isRateLimit {\n\t\t\tif content == \"\" {\n\t\t\t\tlogger.Warnf(ctx, firstLine)\n\t\t\t\t//c.JSON(http.StatusInternalServerError, gin.H{\"error\": errNoValidResponseContent})\n\t\t\t} else {\n\t\t\t\tpromptTokens := common.CountTokenText(string(jsonData), modelName)\n\t\t\t\tcompletionTokens := common.CountTokenText(content, modelName)\n\t\t\t\tfinishReason := \"stop\"\n\n\t\t\t\tc.JSON(http.StatusOK, model.OpenAIChatCompletionResponse{\n\t\t\t\t\tID:      fmt.Sprintf(responseIDFormat, time.Now().Format(\"20060102150405\")),\n\t\t\t\t\tObject:  \"chat.completion\",\n\t\t\t\t\tCreated: time.Now().Unix(),\n\t\t\t\t\tModel:   modelName,\n\t\t\t\t\tChoices: []model.OpenAIChoice{{\n\t\t\t\t\t\tMessage: model.OpenAIMessage{\n\t\t\t\t\t\t\tRole:    \"assistant\",\n\t\t\t\t\t\t\tContent: content,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tFinishReason: &finishReason,\n\t\t\t\t\t}},\n\t\t\t\t\tUsage: model.OpenAIUsage{\n\t\t\t\t\t\tPromptTokens:     promptTokens,\n\t\t\t\t\t\tCompletionTokens: completionTokens,\n\t\t\t\t\t\tTotalTokens:      promptTokens + completionTokens,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tcookie, err = cookieManager.GetNextCookie()\n\t\tif err != nil {\n\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": \"No more valid cookies available\"})\n\t\t\treturn\n\t\t}\n\t\t// requestBody重制chatId\n\t\tcurrentQueryString := fmt.Sprintf(\"type=%s\", chatType)\n\t\tif chatId, ok := config.GlobalSessionManager.GetChatID(cookie, modelName); ok {\n\t\t\tcurrentQueryString = fmt.Sprintf(\"id=%s&type=%s\", chatId, chatType)\n\t\t}\n\t\trequestBody[\"current_query_string\"] = currentQueryString\n\t}\n\n\tlogger.Errorf(ctx, \"All cookies exhausted after %d attempts\", maxRetries)\n\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": \"All cookies are temporarily unavailable.\"})\n}\n\nfunc OpenaiModels(c *gin.Context) {\n\tvar modelsResp []string\n\n\tmodelsResp = common.DefaultOpenaiModelList\n\n\tvar openaiModelListResponse model.OpenaiModelListResponse\n\tvar openaiModelResponse []model.OpenaiModelResponse\n\topenaiModelListResponse.Object = \"list\"\n\n\tfor _, modelResp := range modelsResp {\n\t\topenaiModelResponse = append(openaiModelResponse, model.OpenaiModelResponse{\n\t\t\tID:     modelResp,\n\t\t\tObject: \"model\",\n\t\t})\n\t}\n\topenaiModelListResponse.Data = openaiModelResponse\n\tc.JSON(http.StatusOK, openaiModelListResponse)\n\treturn\n}\n\nfunc ImagesForOpenAI(c *gin.Context) {\n\n\tclient := cycletls.Init()\n\tdefer safeClose(client)\n\n\tvar openAIReq model.OpenAIImagesGenerationRequest\n\tif err := c.BindJSON(&openAIReq); err != nil {\n\t\tc.JSON(400, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\t// 初始化cookie\n\t//cookieManager := config.NewCookieManager()\n\t//cookie, err := cookieManager.GetRandomCookie()\n\t//\n\t//if err != nil {\n\t//\tlogger.Errorf(c.Request.Context(), \"Failed to get initial cookie: %v\", err)\n\t//\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": errNoValidCookies})\n\t//\treturn\n\t//}\n\n\tresp, err := ImageProcess(c, client, openAIReq)\n\tif err != nil {\n\t\tlogger.Errorf(c.Request.Context(), fmt.Sprintf(\"ImageProcess err  %v\\n\", err))\n\t\tc.JSON(http.StatusInternalServerError, model.OpenAIErrorResponse{\n\t\t\tOpenAIError: model.OpenAIError{\n\t\t\t\tMessage: err.Error(),\n\t\t\t\tType:    \"request_error\",\n\t\t\t\tCode:    \"500\",\n\t\t\t},\n\t\t})\n\t\treturn\n\t} else {\n\t\tc.JSON(200, resp)\n\t}\n\n}\n\nfunc ImageProcess(c *gin.Context, client cycletls.CycleTLS, openAIReq model.OpenAIImagesGenerationRequest) (*model.OpenAIImagesGenerationResponse, error) {\n\tconst (\n\t\terrNoValidCookies = \"No valid cookies available\"\n\t\terrRateLimitMsg   = \"Rate limit reached, please try again later\"\n\t\terrServerErrMsg   = \"An error occurred with the current request, please try again\"\n\t\terrNoValidTaskIDs = \"No valid task IDs received\"\n\t)\n\n\tvar (\n\t\tsessionImageChatManager *config.SessionMapManager\n\t\tmaxRetries              int\n\t\tcookie                  string\n\t\tchatId                  string\n\t)\n\n\tcookieManager := config.NewCookieManager()\n\tsessionImageChatManager = config.NewSessionMapManager()\n\tctx := c.Request.Context()\n\n\t// Initialize session manager and get initial cookie\n\tif len(config.SessionImageChatMap) == 0 {\n\t\t//logger.Warnf(ctx, \"未配置环境变量 SESSION_IMAGE_CHAT_MAP, 可能会生图失败!\")\n\t\tmaxRetries = len(cookieManager.Cookies)\n\n\t\tvar err error\n\t\tcookie, err = cookieManager.GetRandomCookie()\n\t\tif err != nil {\n\t\t\tlogger.Errorf(ctx, \"Failed to get initial cookie: %v\", err)\n\t\t\treturn nil, fmt.Errorf(errNoValidCookies)\n\t\t}\n\t} else {\n\t\tmaxRetries = sessionImageChatManager.GetSize()\n\t\tcookie, chatId, _ = sessionImageChatManager.GetRandomKeyValue()\n\t}\n\n\tfor attempt := 0; attempt < maxRetries; attempt++ {\n\t\t// Create request body\n\t\trequestBody, err := createImageRequestBody(c, cookie, &openAIReq, chatId)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(ctx, \"Failed to create request body: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Marshal request body\n\t\tjsonData, err := json.Marshal(requestBody)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(ctx, \"Failed to marshal request body: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Make request\n\t\tresponse, err := makeImageRequest(client, jsonData, cookie)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(ctx, \"Failed to make image request: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\tbody := response.Body\n\n\t\t// Handle different response cases\n\t\tswitch {\n\t\tcase common.IsRateLimit(body):\n\t\t\tlogger.Warnf(ctx, \"Cookie rate limited, switching to next cookie, attempt %d/%d, COOKIE:%s\", attempt+1, maxRetries, cookie)\n\t\t\t//if sessionImageChatManager != nil {\n\t\t\t//\tcookie, chatId, err = sessionImageChatManager.GetNextKeyValue()\n\t\t\t//\tif err != nil {\n\t\t\t//\t\tlogger.Errorf(ctx, \"No more valid cookies available after attempt %d\", attempt+1)\n\t\t\t//\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": errNoValidCookies})\n\t\t\t//\t\treturn nil, fmt.Errorf(errNoValidCookies)\n\t\t\t//\t}\n\t\t\t//} else {\n\t\t\t//cookieManager := config.NewCookieManager()\n\t\t\tconfig.AddRateLimitCookie(cookie, time.Now().Add(time.Duration(config.RateLimitCookieLockDuration)*time.Second))\n\t\t\tcookie, err = cookieManager.GetNextCookie()\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorf(ctx, \"No more valid cookies available after attempt %d\", attempt+1)\n\t\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": errNoValidCookies})\n\t\t\t\treturn nil, fmt.Errorf(errNoValidCookies)\n\t\t\t\t//}\n\t\t\t}\n\t\t\tcontinue\n\t\tcase common.IsFreeLimit(body):\n\t\t\tlogger.Warnf(ctx, \"Cookie free rate limited, switching to next cookie, attempt %d/%d, COOKIE:%s\", attempt+1, maxRetries, cookie)\n\t\t\t//if sessionImageChatManager != nil {\n\t\t\t//\tcookie, chatId, err = sessionImageChatManager.GetNextKeyValue()\n\t\t\t//\tif err != nil {\n\t\t\t//\t\tlogger.Errorf(ctx, \"No more valid cookies available after attempt %d\", attempt+1)\n\t\t\t//\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": errNoValidCookies})\n\t\t\t//\t\treturn nil, fmt.Errorf(errNoValidCookies)\n\t\t\t//\t}\n\t\t\t//} else {\n\t\t\t//cookieManager := config.NewCookieManager()\n\t\t\tconfig.AddRateLimitCookie(cookie, time.Now().Add(24*60*60*time.Second))\n\t\t\t// 删除cookie\n\t\t\t//config.RemoveCookie(cookie)\n\t\t\tcookie, err = cookieManager.GetNextCookie()\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorf(ctx, \"No more valid cookies available after attempt %d\", attempt+1)\n\t\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": errNoValidCookies})\n\t\t\t\treturn nil, fmt.Errorf(errNoValidCookies)\n\t\t\t\t//}\n\t\t\t}\n\t\t\tcontinue\n\t\tcase common.IsNotLogin(body):\n\t\t\tlogger.Warnf(ctx, \"Cookie Not Login, switching to next cookie, attempt %d/%d, COOKIE:%s\", attempt+1, maxRetries, cookie)\n\t\t\t//if sessionImageChatManager != nil {\n\t\t\t//\t//sessionImageChatManager.RemoveKey(cookie)\n\t\t\t//\tcookie, chatId, err = sessionImageChatManager.GetNextKeyValue()\n\t\t\t//\tif err != nil {\n\t\t\t//\t\tlogger.Errorf(ctx, \"No more valid cookies available after attempt %d\", attempt+1)\n\t\t\t//\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": errNoValidCookies})\n\t\t\t//\t\treturn nil, fmt.Errorf(errNoValidCookies)\n\t\t\t//\t}\n\t\t\t//} else {\n\t\t\t//cookieManager := config.NewCookieManager()\n\t\t\t//err := cookieManager.RemoveCookie(cookie)\n\t\t\t//if err != nil {\n\t\t\t//\tlogger.Errorf(ctx, \"Failed to remove cookie: %v\", err)\n\t\t\t//}\n\t\t\tcookie, err = cookieManager.GetNextCookie()\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorf(ctx, \"No more valid cookies available after attempt %d\", attempt+1)\n\t\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": errNoValidCookies})\n\t\t\t\treturn nil, fmt.Errorf(errNoValidCookies)\n\t\t\t\t//}\n\n\t\t\t}\n\t\t\tcontinue\n\t\tcase common.IsServerError(body):\n\t\t\tlogger.Errorf(ctx, errServerErrMsg)\n\t\t\treturn nil, fmt.Errorf(errServerErrMsg)\n\t\tcase common.IsServerOverloaded(body):\n\t\t\t//logger.Errorf(ctx, fmt.Sprintf(\"Server overloaded, please try again later.%s\", \"官方服务超载或环境变量 SESSION_IMAGE_CHAT_MAP 未配置\"))\n\t\t\tlogger.Errorf(ctx, fmt.Sprintf(\"Server overloaded, please try again later.%s\", \"官方服务超载\"))\n\t\t\treturn nil, fmt.Errorf(\"Server overloaded, please try again later.\")\n\t\t}\n\n\t\t// Extract task IDs\n\t\tprojectId, taskIDs := extractTaskIDs(response.Body)\n\t\tif len(taskIDs) == 0 {\n\t\t\tlogger.Errorf(ctx, \"Response body: %s\", response.Body)\n\t\t\treturn nil, fmt.Errorf(errNoValidTaskIDs)\n\t\t}\n\n\t\t// Poll for image URLs\n\t\timageURLs := pollTaskStatus(c, client, taskIDs, cookie)\n\t\tif len(imageURLs) == 0 {\n\t\t\tlogger.Warnf(ctx, \"No image URLs received, retrying with next cookie\")\n\t\t\tcontinue\n\t\t}\n\n\t\t// Create response object\n\t\tresult := &model.OpenAIImagesGenerationResponse{\n\t\t\tCreated: time.Now().Unix(),\n\t\t\tData:    make([]*model.OpenAIImagesGenerationDataResponse, 0, len(imageURLs)),\n\t\t}\n\n\t\t// Process image URLs\n\t\tfor _, url := range imageURLs {\n\t\t\tdata := &model.OpenAIImagesGenerationDataResponse{\n\t\t\t\tURL:           url,\n\t\t\t\tRevisedPrompt: openAIReq.Prompt,\n\t\t\t}\n\n\t\t\tif openAIReq.ResponseFormat == \"b64_json\" {\n\t\t\t\tbase64Str, err := getBase64ByUrl(data.URL)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Errorf(ctx, \"getBase64ByUrl error: %v\", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tdata.B64Json = \"data:image/webp;base64,\" + base64Str\n\t\t\t}\n\n\t\t\tresult.Data = append(result.Data, data)\n\t\t}\n\n\t\t// Handle successful case\n\t\tif len(result.Data) > 0 {\n\t\t\t// Delete temporary session if needed\n\t\t\tif config.AutoDelChat == 1 {\n\t\t\t\tgo func() {\n\t\t\t\t\tclient := cycletls.Init()\n\t\t\t\t\tdefer safeClose(client)\n\t\t\t\t\tmakeDeleteRequest(client, cookie, projectId)\n\t\t\t\t}()\n\t\t\t}\n\t\t\treturn result, nil\n\t\t}\n\t}\n\n\t// All retries exhausted\n\tlogger.Errorf(ctx, \"All cookies exhausted after %d attempts\", maxRetries)\n\treturn nil, fmt.Errorf(\"all cookies are temporarily unavailable\")\n}\nfunc extractTaskIDs(responseBody string) (string, []string) {\n\tvar taskIDs []string\n\tvar projectId string\n\n\t// 分行处理响应\n\tlines := strings.Split(responseBody, \"\\n\")\n\tfor _, line := range lines {\n\n\t\t// 找到包含project_id的行\n\t\tif strings.Contains(line, \"project_start\") {\n\t\t\t// 去掉\"data: \"前缀\n\t\t\tjsonStr := strings.TrimPrefix(line, \"data: \")\n\n\t\t\t// 解析JSON\n\t\t\tvar jsonResp struct {\n\t\t\t\tProjectID string `json:\"id\"`\n\t\t\t}\n\t\t\tif err := json.Unmarshal([]byte(jsonStr), &jsonResp); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// 保存project_id\n\t\t\tprojectId = jsonResp.ProjectID\n\t\t}\n\n\t\t// 找到包含task_id的行\n\t\tif strings.Contains(line, \"task_id\") {\n\t\t\t// 去掉\"data: \"前缀\n\t\t\tjsonStr := strings.TrimPrefix(line, \"data: \")\n\n\t\t\t// 解析外层JSON\n\t\t\tvar outerJSON struct {\n\t\t\t\tContent string `json:\"content\"`\n\t\t\t}\n\t\t\tif err := json.Unmarshal([]byte(jsonStr), &outerJSON); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// 解析内层JSON (content字段)\n\t\t\tvar innerJSON struct {\n\t\t\t\tGeneratedImages []struct {\n\t\t\t\t\tTaskID string `json:\"task_id\"`\n\t\t\t\t} `json:\"generated_images\"`\n\t\t\t}\n\t\t\tif err := json.Unmarshal([]byte(outerJSON.Content), &innerJSON); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// 提取所有task_id\n\t\t\tfor _, img := range innerJSON.GeneratedImages {\n\t\t\t\tif img.TaskID != \"\" {\n\t\t\t\t\ttaskIDs = append(taskIDs, img.TaskID)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn projectId, taskIDs\n}\n\nfunc pollTaskStatus(c *gin.Context, client cycletls.CycleTLS, taskIDs []string, cookie string) []string {\n\tvar imageURLs []string\n\n\trequestData := map[string]interface{}{\n\t\t\"task_ids\": taskIDs,\n\t}\n\n\tjsonData, err := json.Marshal(requestData)\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": \"Failed to marshal request data\"})\n\t\treturn imageURLs\n\t}\n\n\tsseChan, err := client.DoSSE(\"https://www.genspark.ai/api/ig_tasks_status\", cycletls.Options{\n\t\tTimeout: 10 * 60 * 60,\n\t\tProxy:   config.ProxyUrl, // 在每个请求中设置代理\n\t\tBody:    string(jsonData),\n\t\tMethod:  \"POST\",\n\t\tHeaders: map[string]string{\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\"Accept\":       \"*/*\",\n\t\t\t\"Origin\":       baseURL,\n\t\t\t\"Referer\":      baseURL + \"/\",\n\t\t\t\"Cookie\":       cookie,\n\t\t\t\"User-Agent\":   \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome\",\n\t\t},\n\t}, \"POST\")\n\tif err != nil {\n\t\tlogger.Errorf(c, \"Failed to make stream request: %v\", err)\n\t\treturn imageURLs\n\t}\n\tfor response := range sseChan {\n\t\tif response.Done {\n\t\t\t//logger.Warnf(c.Request.Context(), response.Data)\n\t\t\treturn imageURLs\n\t\t}\n\n\t\tdata := response.Data\n\t\tif data == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tlogger.Debug(c.Request.Context(), strings.TrimSpace(data))\n\n\t\tvar responseData map[string]interface{}\n\t\tif err := json.Unmarshal([]byte(data), &responseData); err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif responseData[\"type\"] == \"TASKS_STATUS_COMPLETE\" {\n\t\t\tif finalStatus, ok := responseData[\"final_status\"].(map[string]interface{}); ok {\n\t\t\t\tfor _, taskID := range taskIDs {\n\t\t\t\t\tif task, exists := finalStatus[taskID].(map[string]interface{}); exists {\n\t\t\t\t\t\tif status, ok := task[\"status\"].(string); ok && status == \"SUCCESS\" {\n\t\t\t\t\t\t\tif urls, ok := task[\"image_urls\"].([]interface{}); ok && len(urls) > 0 {\n\t\t\t\t\t\t\t\tif imageURL, ok := urls[0].(string); ok {\n\t\t\t\t\t\t\t\t\timageURLs = append(imageURLs, imageURL)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn imageURLs\n}\n\nfunc getBase64ByUrl(url string) (string, error) {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to fetch image: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn \"\", fmt.Errorf(\"received non-200 status code: %d\", resp.StatusCode)\n\t}\n\n\timgData, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to read image data: %w\", err)\n\t}\n\n\t// Encode the image data to Base64\n\tbase64Str := base64.StdEncoding.EncodeToString(imgData)\n\treturn base64Str, nil\n}\n\nfunc safeClose(client cycletls.CycleTLS) {\n\tif client.ReqChan != nil {\n\t\tclose(client.ReqChan)\n\t}\n\tif client.RespChan != nil {\n\t\tclose(client.RespChan)\n\t}\n}\n"
  },
  {
    "path": "controller/video.go",
    "content": "package controller\n\nimport (\n\t\"crypto/tls\"\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"genspark2api/common\"\n\t\"genspark2api/common/config\"\n\tlogger \"genspark2api/common/loggger\"\n\t\"genspark2api/model\"\n\t\"github.com/deanxv/CycleTLS/cycletls\"\n\t\"github.com/gin-gonic/gin\"\n\t\"github.com/samber/lo\"\n\t\"io\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc VideosForOpenAI(c *gin.Context) {\n\n\tclient := cycletls.Init()\n\tdefer safeClose(client)\n\n\tvar openAIReq model.VideosGenerationRequest\n\tif err := c.BindJSON(&openAIReq); err != nil {\n\t\tc.JSON(400, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\n\tif lo.Contains(common.VideoModelList, openAIReq.Model) == false {\n\t\tc.JSON(400, gin.H{\"error\": \"Invalid model\"})\n\t\treturn\n\t}\n\n\tresp, err := VideoProcess(c, client, openAIReq)\n\tif err != nil {\n\t\tlogger.Errorf(c.Request.Context(), fmt.Sprintf(\"VideoProcess err  %v\\n\", err))\n\t\tc.JSON(http.StatusInternalServerError, model.OpenAIErrorResponse{\n\t\t\tOpenAIError: model.OpenAIError{\n\t\t\t\tMessage: err.Error(),\n\t\t\t\tType:    \"request_error\",\n\t\t\t\tCode:    \"500\",\n\t\t\t},\n\t\t})\n\t\treturn\n\t} else {\n\t\tc.JSON(200, resp)\n\t}\n\n}\n\nfunc VideoProcess(c *gin.Context, client cycletls.CycleTLS, openAIReq model.VideosGenerationRequest) (*model.VideosGenerationResponse, error) {\n\tconst (\n\t\terrNoValidCookies = \"No valid cookies available\"\n\t\terrServerErrMsg   = \"An error occurred with the current request, please try again\"\n\t\terrNoValidTaskIDs = \"No valid task IDs received\"\n\t)\n\n\tvar (\n\t\tmaxRetries int\n\t\tcookie     string\n\t\tchatId     string\n\t)\n\n\tcookieManager := config.NewCookieManager()\n\tctx := c.Request.Context()\n\n\t// Initialize session manager and get initial cookie\n\tif len(config.SessionImageChatMap) == 0 {\n\t\t//logger.Warnf(ctx, \"未配置环境变量 SESSION_IMAGE_CHAT_MAP, 可能会生图失败!\")\n\t\tmaxRetries = len(cookieManager.Cookies)\n\n\t\tvar err error\n\t\tcookie, err = cookieManager.GetRandomCookie()\n\t\tif err != nil {\n\t\t\tlogger.Errorf(ctx, \"Failed to get initial cookie: %v\", err)\n\t\t\treturn nil, fmt.Errorf(errNoValidCookies)\n\t\t}\n\t}\n\n\tfor attempt := 0; attempt < maxRetries; attempt++ {\n\t\t// Create request body\n\t\trequestBody, err := createVideoRequestBody(c, cookie, &openAIReq, chatId)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(ctx, \"Failed to create request body: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Marshal request body\n\t\tjsonData, err := json.Marshal(requestBody)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(ctx, \"Failed to marshal request body: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Make request\n\t\tresponse, err := makeVideoRequest(client, jsonData, cookie)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(ctx, \"Failed to make video request: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\tbody := response.Body\n\n\t\tswitch {\n\t\tcase common.IsRateLimit(body):\n\t\t\tlogger.Warnf(ctx, \"Cookie rate limited, switching to next cookie, attempt %d/%d, COOKIE:%s\", attempt+1, maxRetries, cookie)\n\t\t\tconfig.AddRateLimitCookie(cookie, time.Now().Add(time.Duration(config.RateLimitCookieLockDuration)*time.Second))\n\t\t\tcookie, err = cookieManager.GetNextCookie()\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorf(ctx, \"No more valid cookies available after attempt %d\", attempt+1)\n\t\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": errNoValidCookies})\n\t\t\t\treturn nil, fmt.Errorf(errNoValidCookies)\n\t\t\t}\n\t\t\tcontinue\n\t\tcase common.IsFreeLimit(body):\n\t\t\tlogger.Warnf(ctx, \"Cookie free rate limited, switching to next cookie, attempt %d/%d, COOKIE:%s\", attempt+1, maxRetries, cookie)\n\t\t\tconfig.AddRateLimitCookie(cookie, time.Now().Add(24*60*60*time.Second))\n\t\t\tcookie, err = cookieManager.GetNextCookie()\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorf(ctx, \"No more valid cookies available after attempt %d\", attempt+1)\n\t\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": errNoValidCookies})\n\t\t\t\treturn nil, fmt.Errorf(errNoValidCookies)\n\t\t\t}\n\t\t\tcontinue\n\t\tcase common.IsNotLogin(body):\n\t\t\tlogger.Warnf(ctx, \"Cookie Not Login, switching to next cookie, attempt %d/%d, COOKIE:%s\", attempt+1, maxRetries, cookie)\n\t\t\tcookie, err = cookieManager.GetNextCookie()\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorf(ctx, \"No more valid cookies available after attempt %d\", attempt+1)\n\t\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": errNoValidCookies})\n\t\t\t\treturn nil, fmt.Errorf(errNoValidCookies)\n\t\t\t}\n\t\t\tcontinue\n\t\tcase common.IsServerError(body):\n\t\t\tlogger.Errorf(ctx, errServerErrMsg)\n\t\t\treturn nil, fmt.Errorf(errServerErrMsg)\n\t\tcase common.IsServerOverloaded(body):\n\t\t\tlogger.Errorf(ctx, fmt.Sprintf(\"Server overloaded, please try again later.%s\", \"官方服务超载\"))\n\t\t\treturn nil, fmt.Errorf(\"Server overloaded, please try again later.\")\n\t\t}\n\n\t\tprojectId, taskIDs := extractVideoTaskIDs(response.Body)\n\t\tif len(taskIDs) == 0 {\n\t\t\tlogger.Errorf(ctx, \"Response body: %s\", response.Body)\n\t\t\treturn nil, fmt.Errorf(errNoValidTaskIDs)\n\t\t}\n\n\t\t// Poll for image URLs\n\t\timageURLs := pollVideoTaskStatus(c, client, taskIDs, cookie)\n\t\tif len(imageURLs) == 0 {\n\t\t\tlogger.Warnf(ctx, \"No image URLs received, retrying with next cookie\")\n\t\t\tcontinue\n\t\t}\n\n\t\t// Create response object\n\t\tresult := &model.VideosGenerationResponse{\n\t\t\tCreated: time.Now().Unix(),\n\t\t\tData:    make([]*model.VideosGenerationDataResponse, 0, len(imageURLs)),\n\t\t}\n\n\t\t// Process image URLs\n\t\tfor _, url := range imageURLs {\n\t\t\tdata := &model.VideosGenerationDataResponse{\n\t\t\t\tURL:           url,\n\t\t\t\tRevisedPrompt: openAIReq.Prompt,\n\t\t\t}\n\n\t\t\t//if openAIReq.ResponseFormat == \"b64_json\" {\n\t\t\t//\tbase64Str, err := getBase64ByUrl(data.URL)\n\t\t\t//\tif err != nil {\n\t\t\t//\t\tlogger.Errorf(ctx, \"getBase64ByUrl error: %v\", err)\n\t\t\t//\t\tcontinue\n\t\t\t//\t}\n\t\t\t//\tdata.B64Json = \"data:image/webp;base64,\" + base64Str\n\t\t\t//}\n\n\t\t\tresult.Data = append(result.Data, data)\n\t\t}\n\n\t\t// Handle successful case\n\t\tif len(result.Data) > 0 {\n\t\t\t// Delete temporary session if needed\n\t\t\tif config.AutoDelChat == 1 {\n\t\t\t\tgo func() {\n\t\t\t\t\tclient := cycletls.Init()\n\t\t\t\t\tdefer safeClose(client)\n\t\t\t\t\tmakeDeleteRequest(client, cookie, projectId)\n\t\t\t\t}()\n\t\t\t}\n\t\t\treturn result, nil\n\t\t}\n\t}\n\n\t// All retries exhausted\n\tlogger.Errorf(ctx, \"All cookies exhausted after %d attempts\", maxRetries)\n\treturn nil, fmt.Errorf(\"all cookies are temporarily unavailable\")\n}\n\nfunc createVideoRequestBody(c *gin.Context, cookie string, openAIReq *model.VideosGenerationRequest, chatId string) (map[string]interface{}, error) {\n\n\t// 创建模型配置\n\tmodelConfigs := []map[string]interface{}{\n\t\t{\n\t\t\t\"model\":              openAIReq.Model,\n\t\t\t\"aspect_ratio\":       openAIReq.AspectRatio,\n\t\t\t\"reflection_enabled\": openAIReq.AutoPrompt,\n\t\t\t\"duration\":           openAIReq.Duration,\n\t\t},\n\t}\n\n\t// 创建消息数组\n\tvar messages []map[string]interface{}\n\n\tif openAIReq.Image != \"\" {\n\t\tvar base64Data string\n\n\t\tif strings.HasPrefix(openAIReq.Image, \"http://\") || strings.HasPrefix(openAIReq.Image, \"https://\") {\n\t\t\t// 下载文件\n\t\t\tbytes, err := fetchImageBytes(openAIReq.Image)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorf(c.Request.Context(), fmt.Sprintf(\"fetchImageBytes err  %v\\n\", err))\n\t\t\t\treturn nil, fmt.Errorf(\"fetchImageBytes err  %v\\n\", err)\n\t\t\t}\n\n\t\t\tcontentType := http.DetectContentType(bytes)\n\t\t\tif strings.HasPrefix(contentType, \"image/\") {\n\t\t\t\t// 是图片类型，转换为base64\n\t\t\t\tbase64Data = \"data:image/jpeg;base64,\" + base64.StdEncoding.EncodeToString(bytes)\n\t\t\t}\n\t\t} else if common.IsImageBase64(openAIReq.Image) {\n\t\t\t// 如果已经是 base64 格式\n\t\t\tif !strings.HasPrefix(openAIReq.Image, \"data:image\") {\n\t\t\t\tbase64Data = \"data:image/jpeg;base64,\" + openAIReq.Image\n\t\t\t} else {\n\t\t\t\tbase64Data = openAIReq.Image\n\t\t\t}\n\t\t}\n\n\t\t// 构建包含图片的消息\n\t\tif base64Data != \"\" {\n\t\t\tmessages = []map[string]interface{}{\n\t\t\t\t{\n\t\t\t\t\t\"role\": \"user\",\n\t\t\t\t\t\"content\": []map[string]interface{}{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"type\": \"image_url\",\n\t\t\t\t\t\t\t\"image_url\": map[string]interface{}{\n\t\t\t\t\t\t\t\t\"url\": base64Data,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"type\": \"text\",\n\t\t\t\t\t\t\t\"text\": openAIReq.Prompt,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t}\n\n\t// 如果没有图片或处理图片失败，使用纯文本消息\n\tif len(messages) == 0 {\n\t\tmessages = []map[string]interface{}{\n\t\t\t{\n\t\t\t\t\"role\":    \"user\",\n\t\t\t\t\"content\": openAIReq.Prompt,\n\t\t\t},\n\t\t}\n\t}\n\tvar currentQueryString string\n\tif len(chatId) != 0 {\n\t\tcurrentQueryString = fmt.Sprintf(\"id=%s&type=%s\", chatId, videoType)\n\t} else {\n\t\tcurrentQueryString = fmt.Sprintf(\"type=%s\", videoType)\n\t}\n\n\t// 创建请求体\n\trequestBody := map[string]interface{}{\n\t\t\"type\": \"COPILOT_MOA_VIDEO\",\n\t\t//\"current_query_string\": \"type=COPILOT_MOA_IMAGE\",\n\t\t\"current_query_string\": currentQueryString,\n\t\t\"messages\":             messages,\n\t\t\"user_s_input\":         openAIReq.Prompt,\n\t\t\"action_params\":        map[string]interface{}{},\n\t\t\"extra_data\": map[string]interface{}{\n\t\t\t\"model_configs\": modelConfigs,\n\t\t\t\"imageModelMap\": map[string]interface{}{},\n\t\t},\n\t}\n\n\tlogger.Debug(c.Request.Context(), fmt.Sprintf(\"RequestBody: %v\", requestBody))\n\n\tif strings.TrimSpace(config.RecaptchaProxyUrl) == \"\" ||\n\t\t(!strings.HasPrefix(config.RecaptchaProxyUrl, \"http://\") &&\n\t\t\t!strings.HasPrefix(config.RecaptchaProxyUrl, \"https://\")) {\n\t\treturn requestBody, nil\n\t} else {\n\n\t\ttr := &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t}\n\t\tclient := &http.Client{Transport: tr}\n\n\t\t// 检查并补充 RecaptchaProxyUrl 的末尾斜杠\n\t\tif !strings.HasSuffix(config.RecaptchaProxyUrl, \"/\") {\n\t\t\tconfig.RecaptchaProxyUrl += \"/\"\n\t\t}\n\n\t\t// 创建请求\n\t\treq, err := http.NewRequest(\"GET\", fmt.Sprintf(\"%sgenspark\", config.RecaptchaProxyUrl), nil)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(c.Request.Context(), fmt.Sprintf(\"创建/genspark请求失败   %v\\n\", err))\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// 设置请求头\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t\treq.Header.Set(\"Cookie\", cookie)\n\n\t\t// 发送请求\n\t\tresp, err := client.Do(req)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(c.Request.Context(), fmt.Sprintf(\"发送/genspark请求失败   %v\\n\", err))\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer resp.Body.Close()\n\n\t\t// 读取响应体\n\t\tbody, err := io.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(c.Request.Context(), fmt.Sprintf(\"读取/genspark响应失败   %v\\n\", err))\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttype Response struct {\n\t\t\tCode    int    `json:\"code\"`\n\t\t\tToken   string `json:\"token\"`\n\t\t\tMessage string `json:\"message\"`\n\t\t}\n\n\t\tif resp.StatusCode == 200 {\n\t\t\tvar response Response\n\t\t\tif err := json.Unmarshal(body, &response); err != nil {\n\t\t\t\tlogger.Errorf(c.Request.Context(), fmt.Sprintf(\"读取/genspark JSON 失败   %v\\n\", err))\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif response.Code == 200 {\n\t\t\t\tlogger.Debugf(c.Request.Context(), fmt.Sprintf(\"g_recaptcha_token: %v\\n\", response.Token))\n\t\t\t\trequestBody[\"g_recaptcha_token\"] = response.Token\n\t\t\t\tlogger.Infof(c.Request.Context(), fmt.Sprintf(\"cheat success!\"))\n\t\t\t\treturn requestBody, nil\n\t\t\t} else {\n\t\t\t\tlogger.Errorf(c.Request.Context(), fmt.Sprintf(\"读取/genspark token 失败   %v\\n\", err))\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\tlogger.Errorf(c.Request.Context(), fmt.Sprintf(\"请求/genspark失败   %v\\n\", err))\n\t\t\treturn nil, err\n\t\t}\n\t}\n}\n\nfunc makeVideoRequest(client cycletls.CycleTLS, jsonData []byte, cookie string) (cycletls.Response, error) {\n\n\taccept := \"*/*\"\n\n\treturn client.Do(apiEndpoint, cycletls.Options{\n\t\tUserAgent: \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome\",\n\t\tTimeout:   10 * 60 * 60,\n\t\tProxy:     config.ProxyUrl, // 在每个请求中设置代理\n\t\tBody:      string(jsonData),\n\t\tMethod:    \"POST\",\n\t\tHeaders: map[string]string{\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\"Accept\":       accept,\n\t\t\t\"Origin\":       baseURL,\n\t\t\t\"Referer\":      baseURL + \"/\",\n\t\t\t\"Cookie\":       cookie,\n\t\t\t\"User-Agent\":   \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome\",\n\t\t},\n\t}, \"POST\")\n}\n\nfunc extractVideoTaskIDs(responseBody string) (string, []string) {\n\tvar taskIDs []string\n\tvar projectId string\n\n\t// 分行处理响应\n\tlines := strings.Split(responseBody, \"\\n\")\n\tfor _, line := range lines {\n\n\t\t// 找到包含project_id的行\n\t\tif strings.Contains(line, \"project_start\") {\n\t\t\t// 去掉\"data: \"前缀\n\t\t\tjsonStr := strings.TrimPrefix(line, \"data: \")\n\n\t\t\t// 解析JSON\n\t\t\tvar jsonResp struct {\n\t\t\t\tProjectID string `json:\"id\"`\n\t\t\t}\n\t\t\tif err := json.Unmarshal([]byte(jsonStr), &jsonResp); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// 保存project_id\n\t\t\tprojectId = jsonResp.ProjectID\n\t\t}\n\n\t\t// 找到包含task_id的行\n\t\tif strings.Contains(line, \"task_id\") {\n\t\t\t// 去掉\"data: \"前缀\n\t\t\tjsonStr := strings.TrimPrefix(line, \"data: \")\n\n\t\t\t// 解析外层JSON\n\t\t\tvar outerJSON struct {\n\t\t\t\tContent string `json:\"content\"`\n\t\t\t}\n\t\t\tif err := json.Unmarshal([]byte(jsonStr), &outerJSON); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// 解析内层JSON (content字段)\n\t\t\tvar innerJSON struct {\n\t\t\t\tGeneratedVideos []struct {\n\t\t\t\t\tTaskID string `json:\"task_id\"`\n\t\t\t\t} `json:\"generated_videos\"`\n\t\t\t}\n\t\t\tif err := json.Unmarshal([]byte(outerJSON.Content), &innerJSON); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// 提取所有task_id\n\t\t\tfor _, img := range innerJSON.GeneratedVideos {\n\t\t\t\tif img.TaskID != \"\" {\n\t\t\t\t\ttaskIDs = append(taskIDs, img.TaskID)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn projectId, taskIDs\n}\n\nfunc pollVideoTaskStatus(c *gin.Context, client cycletls.CycleTLS, taskIDs []string, cookie string) []string {\n\tvar imageURLs []string\n\n\trequestData := map[string]interface{}{\n\t\t\"task_ids\": taskIDs,\n\t}\n\n\tjsonData, err := json.Marshal(requestData)\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": \"Failed to marshal request data\"})\n\t\treturn imageURLs\n\t}\n\n\tsseChan, err := client.DoSSE(\"https://www.genspark.ai/api/vg_tasks_status\", cycletls.Options{\n\t\tTimeout: 10 * 60 * 60,\n\t\tProxy:   config.ProxyUrl, // 在每个请求中设置代理\n\t\tBody:    string(jsonData),\n\t\tMethod:  \"POST\",\n\t\tHeaders: map[string]string{\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\"Accept\":       \"*/*\",\n\t\t\t\"Origin\":       baseURL,\n\t\t\t\"Referer\":      baseURL + \"/\",\n\t\t\t\"Cookie\":       cookie,\n\t\t\t\"User-Agent\":   \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome\",\n\t\t},\n\t}, \"POST\")\n\tif err != nil {\n\t\tlogger.Errorf(c, \"Failed to make stream request: %v\", err)\n\t\treturn imageURLs\n\t}\n\tfor response := range sseChan {\n\t\tif response.Done {\n\t\t\t//logger.Warnf(c.Request.Context(), response.Data)\n\t\t\treturn imageURLs\n\t\t}\n\n\t\tdata := response.Data\n\t\tif data == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tlogger.Debug(c.Request.Context(), strings.TrimSpace(data))\n\n\t\tvar responseData map[string]interface{}\n\t\tif err := json.Unmarshal([]byte(data), &responseData); err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif responseData[\"type\"] == \"TASKS_STATUS_COMPLETE\" {\n\t\t\tif finalStatus, ok := responseData[\"final_status\"].(map[string]interface{}); ok {\n\t\t\t\tfor _, taskID := range taskIDs {\n\t\t\t\t\tif task, exists := finalStatus[taskID].(map[string]interface{}); exists {\n\t\t\t\t\t\tif status, ok := task[\"status\"].(string); ok && status == \"SUCCESS\" {\n\t\t\t\t\t\t\tif urls, ok := task[\"video_urls\"].([]interface{}); ok && len(urls) > 0 {\n\t\t\t\t\t\t\t\tif imageURL, ok := urls[0].(string); ok {\n\t\t\t\t\t\t\t\t\timageURLs = append(imageURLs, imageURL)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn imageURLs\n}\n"
  },
  {
    "path": "docker-compose.yml",
    "content": "version: '3.4'\n\nservices:\n  genspark2api:\n    image: deanxv/genspark2api:latest\n    container_name: genspark2api\n    restart: always\n    ports:\n      - \"7055:7055\"\n    volumes:\n      - ./data:/app/genspark2api/data\n    environment:\n      - GS_COOKIE=******  # cookie (多个请以,分隔)\n      - API_SECRET=123456  # [可选]接口密钥-修改此行为请求头校验的值(多个请以,分隔)\n      - TZ=Asia/Shanghai"
  },
  {
    "path": "go.mod",
    "content": "module genspark2api\n\ngo 1.23.0\n\ntoolchain go1.23.2\n\nrequire (\n\tgithub.com/deanxv/CycleTLS/cycletls v0.0.0-20250208071223-7956a8a6a221\n\tgithub.com/gin-contrib/cors v1.7.3\n\tgithub.com/gin-gonic/gin v1.10.0\n\tgithub.com/google/uuid v1.6.0\n\tgithub.com/json-iterator/go v1.1.12\n\tgithub.com/pkoukk/tiktoken-go v0.1.7\n\tgithub.com/samber/lo v1.49.1\n)\n\nrequire (\n\tgithub.com/Danny-Dasilva/fhttp v0.0.0-20240217042913-eeeb0b347ce1 // indirect\n\tgithub.com/andybalholm/brotli v1.1.1 // indirect\n\tgithub.com/bytedance/sonic v1.12.9 // indirect\n\tgithub.com/bytedance/sonic/loader v0.2.3 // indirect\n\tgithub.com/cloudflare/circl v1.6.0 // indirect\n\tgithub.com/cloudwego/base64x v0.1.5 // indirect\n\tgithub.com/dlclark/regexp2 v1.11.5 // indirect\n\tgithub.com/gabriel-vasile/mimetype v1.4.8 // indirect\n\tgithub.com/gin-contrib/sse v1.0.0 // indirect\n\tgithub.com/go-playground/locales v0.14.1 // indirect\n\tgithub.com/go-playground/universal-translator v0.18.1 // indirect\n\tgithub.com/go-playground/validator/v10 v10.25.0 // indirect\n\tgithub.com/goccy/go-json v0.10.5 // indirect\n\tgithub.com/google/go-cmp v0.6.0 // indirect\n\tgithub.com/gorilla/websocket v1.5.3 // indirect\n\tgithub.com/klauspost/compress v1.18.0 // indirect\n\tgithub.com/klauspost/cpuid/v2 v2.2.10 // indirect\n\tgithub.com/kr/pretty v0.3.1 // indirect\n\tgithub.com/leodido/go-urn v1.4.0 // indirect\n\tgithub.com/mattn/go-isatty v0.0.20 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.2 // indirect\n\tgithub.com/pelletier/go-toml/v2 v2.2.3 // indirect\n\tgithub.com/refraction-networking/utls v1.6.7 // indirect\n\tgithub.com/rogpeppe/go-internal v1.11.0 // indirect\n\tgithub.com/twitchyliquid64/golang-asm v0.15.1 // indirect\n\tgithub.com/ugorji/go/codec v1.2.12 // indirect\n\tgolang.org/x/arch v0.14.0 // indirect\n\tgolang.org/x/crypto v0.35.0 // indirect\n\tgolang.org/x/net v0.35.0 // indirect\n\tgolang.org/x/sys v0.30.0 // indirect\n\tgolang.org/x/text v0.22.0 // indirect\n\tgoogle.golang.org/protobuf v1.36.5 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n\th12.io/socks v1.0.3 // indirect\n)\n"
  },
  {
    "path": "go.sum",
    "content": "cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=\ncloud.google.com/go v0.31.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=\ncloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=\ncloud.google.com/go v0.37.0/go.mod h1:TS1dMSSfndXH133OKGwekG838Om/cQT0BUHV3HcBgoo=\ndmitri.shuralyov.com/app/changes v0.0.0-20180602232624-0a106ad413e3/go.mod h1:Yl+fi1br7+Rr3LqpNJf1/uxUdtRUV+Tnj0o93V2B9MU=\ndmitri.shuralyov.com/html/belt v0.0.0-20180602232347-f7d459c86be0/go.mod h1:JLBrvjyP0v+ecvNYvCpyZgu5/xkfAUhi6wJj28eUfSU=\ndmitri.shuralyov.com/service/change v0.0.0-20181023043359-a85b471d5412/go.mod h1:a1inKt/atXimZ4Mv927x+r7UpyzRUf4emIoiiSC2TN4=\ndmitri.shuralyov.com/state v0.0.0-20180228185332-28bcc343414c/go.mod h1:0PRwlb0D6DFvNNtx+9ybjezNCa8XF0xaYcETyp6rHWU=\ngit.apache.org/thrift.git v0.0.0-20180902110319-2566ecd5d999/go.mod h1:fPE2ZNJGynbRyZ4dJvy6G277gSllfV2HJqblrnkyeyg=\ngithub.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=\ngithub.com/Danny-Dasilva/fhttp v0.0.0-20240217042913-eeeb0b347ce1 h1:/lqhaiz7xdPr6kuaW1tQ/8DdpWdxkdyd9W/6EHz4oRw=\ngithub.com/Danny-Dasilva/fhttp v0.0.0-20240217042913-eeeb0b347ce1/go.mod h1:Hvab/V/YKCDXsEpKYKHjAXH5IFOmoq9FsfxjztEqvDc=\ngithub.com/andybalholm/brotli v1.0.5/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=\ngithub.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA=\ngithub.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA=\ngithub.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239/go.mod h1:2FmKhYUyUczH0OGQWaF5ceTx0UBShxjsH6f8oGKYe2c=\ngithub.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=\ngithub.com/bradfitz/go-smtpd v0.0.0-20170404230938-deb6d6237625/go.mod h1:HYsPBTaaSFSlLx/70C2HPIMNZpVV8+vt/A+FMnYP11g=\ngithub.com/buger/jsonparser v0.0.0-20181115193947-bf1c66bbce23/go.mod h1:bbYlZJ7hK1yFx9hf58LP0zeX7UjIGs20ufpu3evjr+s=\ngithub.com/bwesterb/go-ristretto v1.2.3/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0=\ngithub.com/bytedance/sonic v1.12.9 h1:Od1BvK55NnewtGaJsTDeAOSnLVO2BTSLOe0+ooKokmQ=\ngithub.com/bytedance/sonic v1.12.9/go.mod h1:uVvFidNmlt9+wa31S1urfwwthTWteBgG0hWuoKAXTx8=\ngithub.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=\ngithub.com/bytedance/sonic/loader v0.2.3 h1:yctD0Q3v2NOGfSWPLPvG2ggA2kV6TS6s4wioyEqssH0=\ngithub.com/bytedance/sonic/loader v0.2.3/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI=\ngithub.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=\ngithub.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=\ngithub.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=\ngithub.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=\ngithub.com/cloudflare/circl v1.3.3/go.mod h1:5XYMA4rFBvNIrhs50XuiBJ15vF2pZn4nnUKZrLbUZFA=\ngithub.com/cloudflare/circl v1.6.0 h1:cr5JKic4HI+LkINy2lg3W2jF8sHCVTBncJr5gIIq7qk=\ngithub.com/cloudflare/circl v1.6.0/go.mod h1:uddAzsPgqdMAYatqJ0lsjX1oECcQLIlRpzZh3pJrofs=\ngithub.com/cloudwego/base64x v0.1.5 h1:XPciSp1xaq2VCSt6lF0phncD4koWyULpl5bUxbfCyP4=\ngithub.com/cloudwego/base64x v0.1.5/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=\ngithub.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=\ngithub.com/coreos/go-systemd v0.0.0-20181012123002-c6f51f82210d/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=\ngithub.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/deanxv/CycleTLS/cycletls v0.0.0-20250208071223-7956a8a6a221 h1:zykIpPFKX7DsNfsK3UpwN78oec/x9fND1hZrib7zod8=\ngithub.com/deanxv/CycleTLS/cycletls v0.0.0-20250208071223-7956a8a6a221/go.mod h1:eAyIp7Lbyq6WnJDGicqf7nYr0bTj5FQ0HXQbIesuuJ8=\ngithub.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ=\ngithub.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=\ngithub.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=\ngithub.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc=\ngithub.com/francoispqt/gojay v1.2.13/go.mod h1:ehT5mTG4ua4581f1++1WLG0vPdaA9HaiDsoyrBGkyDY=\ngithub.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=\ngithub.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=\ngithub.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM=\ngithub.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8=\ngithub.com/gaukas/godicttls v0.0.4/go.mod h1:l6EenT4TLWgTdwslVb4sEMOCf7Bv0JAK67deKr9/NCI=\ngithub.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=\ngithub.com/gin-contrib/cors v1.7.3 h1:hV+a5xp8hwJoTw7OY+a70FsL8JkVVFTXw9EcfrYUdns=\ngithub.com/gin-contrib/cors v1.7.3/go.mod h1:M3bcKZhxzsvI+rlRSkkxHyljJt1ESd93COUvemZ79j4=\ngithub.com/gin-contrib/sse v1.0.0 h1:y3bT1mUWUxDpW4JLQg/HnTqV4rozuW4tC9eFKTxYI9E=\ngithub.com/gin-contrib/sse v1.0.0/go.mod h1:zNuFdwarAygJBht0NTKiSi3jRf6RbqeILZ9Sp6Slhe0=\ngithub.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=\ngithub.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=\ngithub.com/gliderlabs/ssh v0.1.1/go.mod h1:U7qILu1NlMHj9FlMhZLlkCdDnU1DBEAqr0aevW3Awn0=\ngithub.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q=\ngithub.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.2.4/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=\ngithub.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=\ngithub.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=\ngithub.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=\ngithub.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=\ngithub.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=\ngithub.com/go-playground/validator/v10 v10.25.0 h1:5Dh7cjvzR7BRZadnsVOzPhWsrwUr0nmsZJxEAnFLNO8=\ngithub.com/go-playground/validator/v10 v10.25.0/go.mod h1:GGzBIJMuE98Ic/kJsBXbz1x/7cByt++cQ+YOuDM5wus=\ngithub.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE=\ngithub.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572/go.mod h1:9Pwr4B2jHnOSGXyyzV8ROjYa2ojvAY6HCGYYfMoC3Ls=\ngithub.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=\ngithub.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=\ngithub.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=\ngithub.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=\ngithub.com/golang/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:tluoj9z5200jBnyusfRPU2LqT6J+DAorxEvtC7LHB+E=\ngithub.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=\ngithub.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=\ngithub.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs=\ngithub.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=\ngithub.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=\ngithub.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=\ngithub.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=\ngithub.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=\ngithub.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=\ngithub.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=\ngithub.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=\ngithub.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=\ngithub.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=\ngithub.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=\ngithub.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=\ngithub.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=\ngithub.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=\ngithub.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=\ngithub.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=\ngithub.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=\ngithub.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=\ngithub.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=\ngithub.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=\ngithub.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=\ngithub.com/google/go-github v17.0.0+incompatible/go.mod h1:zLgOLi98H3fifZn+44m+umXrS52loVEgC2AApnigrVQ=\ngithub.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=\ngithub.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=\ngithub.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/googleapis/gax-go v2.0.0+incompatible/go.mod h1:SFVmujtThgffbyetf+mdk2eWhX2bMyUtNHzFKcPA9HY=\ngithub.com/googleapis/gax-go/v2 v2.0.3/go.mod h1:LLvjysVCY1JZeum8Z6l8qUty8fiNwE08qbEPm1M08qg=\ngithub.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=\ngithub.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=\ngithub.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=\ngithub.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA=\ngithub.com/grpc-ecosystem/grpc-gateway v1.5.0/go.mod h1:RSKVYQBd5MCa4OVpNdGskqpgL2+G+NZTnrVHpWWfpdw=\ngithub.com/h12w/go-socks5 v0.0.0-20200522160539-76189e178364 h1:5XxdakFhqd9dnXoAZy1Mb2R/DZ6D1e+0bGC/JhucGYI=\ngithub.com/h12w/go-socks5 v0.0.0-20200522160539-76189e178364/go.mod h1:eDJQioIyy4Yn3MVivT7rv/39gAJTrA7lgmYr8EW950c=\ngithub.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=\ngithub.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=\ngithub.com/jellevandenhooff/dkim v0.0.0-20150330215556-f50fe3d243e1/go.mod h1:E0B/fFc00Y+Rasa88328GlI/XbtyysCtTHZS8h7IrBU=\ngithub.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU=\ngithub.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=\ngithub.com/klauspost/compress v1.16.7/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE=\ngithub.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=\ngithub.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=\ngithub.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=\ngithub.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE=\ngithub.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=\ngithub.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=\ngithub.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=\ngithub.com/kr/pty v1.1.3/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=\ngithub.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=\ngithub.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=\ngithub.com/lunixbochs/vtclean v1.0.0/go.mod h1:pHhQNgMf3btfWnGBVipUOjRYhoOsdGqdm/+2c2E2WMI=\ngithub.com/mailru/easyjson v0.0.0-20190312143242-1de009706dbe/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=\ngithub.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=\ngithub.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=\ngithub.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=\ngithub.com/microcosm-cc/bluemonday v1.0.1/go.mod h1:hsXNsILzKxV+sX77C5b8FSuKF00vh2OMYv+xgHpAMF4=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=\ngithub.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/neelance/astrewrite v0.0.0-20160511093645-99348263ae86/go.mod h1:kHJEU3ofeGjhHklVoIGuVj85JJwZ6kWPaJwCIxgnFmo=\ngithub.com/neelance/sourcemap v0.0.0-20151028013722-8c68805598ab/go.mod h1:Qr6/a/Q4r9LP1IltGz7tA7iOK1WonHEYhu1HRBA7ZiM=\ngithub.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=\ngithub.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU=\ngithub.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=\ngithub.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk=\ngithub.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0=\ngithub.com/onsi/ginkgo/v2 v2.1.3/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c=\ngithub.com/onsi/ginkgo/v2 v2.1.4/go.mod h1:um6tUpWM/cxCK3/FK8BXqEiUMUwRgSM4JXG47RKZmLU=\ngithub.com/onsi/ginkgo/v2 v2.1.6/go.mod h1:MEH45j8TBi6u9BMogfbp0stKC5cdGjumZj5Y7AG4VIk=\ngithub.com/onsi/ginkgo/v2 v2.2.0/go.mod h1:MEH45j8TBi6u9BMogfbp0stKC5cdGjumZj5Y7AG4VIk=\ngithub.com/onsi/ginkgo/v2 v2.3.0/go.mod h1:Eew0uilEqZmIEZr8JrvYlvOM7Rr6xzTmMV8AyFNU9d0=\ngithub.com/onsi/ginkgo/v2 v2.4.0/go.mod h1:iHkDK1fKGcBoEHT5W7YBq4RFWaQulw+caOMkAt4OrFo=\ngithub.com/onsi/ginkgo/v2 v2.5.0/go.mod h1:Luc4sArBICYCS8THh8v3i3i5CuSZO+RaQRaJoeNwomw=\ngithub.com/onsi/ginkgo/v2 v2.7.0/go.mod h1:yjiuMwPokqY1XauOgju45q3sJt6VzQ/Fict1LFVcsAo=\ngithub.com/onsi/ginkgo/v2 v2.8.1/go.mod h1:N1/NbDngAFcSLdyZ+/aYTYGSlq9qMCS/cNKGJjy+csc=\ngithub.com/onsi/ginkgo/v2 v2.9.0/go.mod h1:4xkjoL/tZv4SMWeww56BU5kAt19mVB47gTWxmrTcxyk=\ngithub.com/onsi/ginkgo/v2 v2.9.1/go.mod h1:FEcmzVcCHl+4o9bQZVab+4dC9+j+91t2FHSzmGAPfuo=\ngithub.com/onsi/ginkgo/v2 v2.9.2/go.mod h1:WHcJJG2dIlcCqVfBAwUCrJxSPFb6v4azBwgxeMeDuts=\ngithub.com/onsi/ginkgo/v2 v2.9.5/go.mod h1:tvAoo1QUJwNEU2ITftXTpR7R1RbCzoZUOs3RonqW57k=\ngithub.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=\ngithub.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=\ngithub.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY=\ngithub.com/onsi/gomega v1.19.0/go.mod h1:LY+I3pBVzYsTBU1AnDwOSxaYi9WoWiqgwooUqq9yPro=\ngithub.com/onsi/gomega v1.20.1/go.mod h1:DtrZpjmvpn2mPm4YWQa0/ALMDj9v4YxLgojwPeREyVo=\ngithub.com/onsi/gomega v1.21.1/go.mod h1:iYAIXgPSaDHak0LCMA+AWBpIKBr8WZicMxnE8luStNc=\ngithub.com/onsi/gomega v1.22.1/go.mod h1:x6n7VNe4hw0vkyYUM4mjIXx3JbLiPaBPNgB7PRQ1tuM=\ngithub.com/onsi/gomega v1.24.0/go.mod h1:Z/NWtiqwBrwUt4/2loMmHL63EDLnYHmVbuBpDr2vQAg=\ngithub.com/onsi/gomega v1.24.1/go.mod h1:3AOiACssS3/MajrniINInwbfOOtfZvplPzuRSmvt1jM=\ngithub.com/onsi/gomega v1.26.0/go.mod h1:r+zV744Re+DiYCIPRlYOTxn0YkOLcAnW8k1xXdMPGhM=\ngithub.com/onsi/gomega v1.27.1/go.mod h1:aHX5xOykVYzWOV4WqQy0sy8BQptgukenXpCXfadcIAw=\ngithub.com/onsi/gomega v1.27.3/go.mod h1:5vG284IBtfDAmDyrK+eGyZmUgUlmi+Wngqo557cZ6Gw=\ngithub.com/onsi/gomega v1.27.4/go.mod h1:riYq/GJKh8hhoM01HN6Vmuy93AarCXCBGpvFDK3q3fQ=\ngithub.com/onsi/gomega v1.27.6/go.mod h1:PIQNjfQwkP3aQAH7lf7j87O/5FiNr+ZR8+ipb+qQlhg=\ngithub.com/openzipkin/zipkin-go v0.1.1/go.mod h1:NtoC/o8u3JlF1lSlyPNswIbeQH9bJTmOf0Erfk+hxe8=\ngithub.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M=\ngithub.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc=\ngithub.com/phayes/freeport v0.0.0-20180830031419-95f893ade6f2 h1:JhzVVoYvbOACxoUmOs6V/G4D5nPVUW73rKvXxP4XUJc=\ngithub.com/phayes/freeport v0.0.0-20180830031419-95f893ade6f2/go.mod h1:iIss55rKnNBTvrwdmkUpLnDpZoAHvWaiq5+iMmen4AE=\ngithub.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=\ngithub.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=\ngithub.com/pkoukk/tiktoken-go v0.1.7 h1:qOBHXX4PHtvIvmOtyg1EeKlwFRiMKAcoMp4Q+bLQDmw=\ngithub.com/pkoukk/tiktoken-go v0.1.7/go.mod h1:9NiV+i9mJKGj1rYOT+njbv+ZwA/zJxYdewGl6qVatpg=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/prometheus/client_golang v0.8.0/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=\ngithub.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=\ngithub.com/prometheus/common v0.0.0-20180801064454-c7de2306084e/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro=\ngithub.com/prometheus/procfs v0.0.0-20180725123919-05ee40e3a273/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=\ngithub.com/quic-go/qpack v0.4.0/go.mod h1:UZVnYIfi5GRk+zI9UMaCPsmZ2xKJP7XBUvVyT1Knj9A=\ngithub.com/quic-go/qtls-go1-20 v0.3.1/go.mod h1:X9Nh97ZL80Z+bX/gUXMbipO6OxdiDi58b/fMC9mAL+k=\ngithub.com/quic-go/quic-go v0.37.4/go.mod h1:YsbH1r4mSHPJcLF4k4zruUkLBqctEMBDR6VPvcYjIsU=\ngithub.com/refraction-networking/utls v1.5.4/go.mod h1:SPuDbBmgLGp8s+HLNc83FuavwZCFoMmExj+ltUHiHUw=\ngithub.com/refraction-networking/utls v1.6.7 h1:zVJ7sP1dJx/WtVuITug3qYUq034cDq9B2MR1K67ULZM=\ngithub.com/refraction-networking/utls v1.6.7/go.mod h1:BC3O4vQzye5hqpmDTWUqi4P5DDhzJfkV1tdqtawQIH0=\ngithub.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=\ngithub.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M=\ngithub.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA=\ngithub.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g=\ngithub.com/samber/lo v1.49.1 h1:4BIFyVfuQSEpluc7Fua+j1NolZHiEHEpaSEKdsH0tew=\ngithub.com/samber/lo v1.49.1/go.mod h1:dO6KHFzUKXgP8LDhU0oI8d2hekjXnGOu0DB8Jecxd6o=\ngithub.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=\ngithub.com/shurcooL/component v0.0.0-20170202220835-f88ec8f54cc4/go.mod h1:XhFIlyj5a1fBNx5aJTbKoIq0mNaPvOagO+HjB3EtxrY=\ngithub.com/shurcooL/events v0.0.0-20181021180414-410e4ca65f48/go.mod h1:5u70Mqkb5O5cxEA8nxTsgrgLehJeAw6Oc4Ab1c/P1HM=\ngithub.com/shurcooL/github_flavored_markdown v0.0.0-20181002035957-2122de532470/go.mod h1:2dOwnU2uBioM+SGy2aZoq1f/Sd1l9OkAeAUvjSyvgU0=\ngithub.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk=\ngithub.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ=\ngithub.com/shurcooL/gofontwoff v0.0.0-20180329035133-29b52fc0a18d/go.mod h1:05UtEgK5zq39gLST6uB0cf3NEHjETfB4Fgr3Gx5R9Vw=\ngithub.com/shurcooL/gopherjslib v0.0.0-20160914041154-feb6d3990c2c/go.mod h1:8d3azKNyqcHP1GaQE/c6dDgjkgSx2BZ4IoEi4F1reUI=\ngithub.com/shurcooL/highlight_diff v0.0.0-20170515013008-09bb4053de1b/go.mod h1:ZpfEhSmds4ytuByIcDnOLkTHGUI6KNqRNPDLHDk+mUU=\ngithub.com/shurcooL/highlight_go v0.0.0-20181028180052-98c3abbbae20/go.mod h1:UDKB5a1T23gOMUJrI+uSuH0VRDStOiUVSjBTRDVBVag=\ngithub.com/shurcooL/home v0.0.0-20181020052607-80b7ffcb30f9/go.mod h1:+rgNQw2P9ARFAs37qieuu7ohDNQ3gds9msbT2yn85sg=\ngithub.com/shurcooL/htmlg v0.0.0-20170918183704-d01228ac9e50/go.mod h1:zPn1wHpTIePGnXSHpsVPWEktKXHr6+SS6x/IKRb7cpw=\ngithub.com/shurcooL/httperror v0.0.0-20170206035902-86b7830d14cc/go.mod h1:aYMfkZ6DWSJPJ6c4Wwz3QtW22G7mf/PEgaB9k/ik5+Y=\ngithub.com/shurcooL/httpfs v0.0.0-20171119174359-809beceb2371/go.mod h1:ZY1cvUeJuFPAdZ/B6v7RHavJWZn2YPVFQ1OSXhCGOkg=\ngithub.com/shurcooL/httpgzip v0.0.0-20180522190206-b1c53ac65af9/go.mod h1:919LwcH0M7/W4fcZ0/jy0qGght1GIhqyS/EgWGH2j5Q=\ngithub.com/shurcooL/issues v0.0.0-20181008053335-6292fdc1e191/go.mod h1:e2qWDig5bLteJ4fwvDAc2NHzqFEthkqn7aOZAOpj+PQ=\ngithub.com/shurcooL/issuesapp v0.0.0-20180602232740-048589ce2241/go.mod h1:NPpHK2TI7iSaM0buivtFUc9offApnI0Alt/K8hcHy0I=\ngithub.com/shurcooL/notifications v0.0.0-20181007000457-627ab5aea122/go.mod h1:b5uSkrEVM1jQUspwbixRBhaIjIzL2xazXp6kntxYle0=\ngithub.com/shurcooL/octicon v0.0.0-20181028054416-fa4f57f9efb2/go.mod h1:eWdoE5JD4R5UVWDucdOPg1g2fqQRq78IQa9zlOV1vpQ=\ngithub.com/shurcooL/reactions v0.0.0-20181006231557-f2e0b4ca5b82/go.mod h1:TCR1lToEk4d2s07G3XGfz2QrgHXg4RJBvjrOozvoWfk=\ngithub.com/shurcooL/sanitized_anchor_name v0.0.0-20170918181015-86672fcb3f95/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=\ngithub.com/shurcooL/users v0.0.0-20180125191416-49c67e49c537/go.mod h1:QJTqeLYEDaXHZDBsXlPCDqdhQuJkuw4NOtaxYe3xii4=\ngithub.com/shurcooL/webdavfs v0.0.0-20170829043945-18c3829fa133/go.mod h1:hKmq5kWdCj2z2KEozexVbfEZIWiTjhE0+UjmZgPqehw=\ngithub.com/sourcegraph/annotate v0.0.0-20160123013949-f4cad6c6324d/go.mod h1:UdhH50NIW0fCiwBSr0co2m7BnFLdv4fQTgdqdJTHFeE=\ngithub.com/sourcegraph/syntaxhighlight v0.0.0-20170531221838-bd320f5d308e/go.mod h1:HuIsMU8RRBOtsCgI77wP899iHVBQpCmg4ErYMZB+2IA=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=\ngithub.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=\ngithub.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=\ngithub.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=\ngithub.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=\ngithub.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=\ngithub.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=\ngithub.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=\ngithub.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=\ngithub.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=\ngithub.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=\ngithub.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=\ngithub.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07/go.mod h1:kDXzergiv9cbyO7IOYJZWg1U88JhDg3PB6klq9Hg2pA=\ngithub.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=\ngithub.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=\ngithub.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=\ngithub.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=\ngithub.com/viant/assertly v0.4.8/go.mod h1:aGifi++jvCrUaklKEKT0BU95igDNaqkvz+49uaYMPRU=\ngithub.com/viant/toolbox v0.24.0/go.mod h1:OxMCG57V0PXuIP2HNQrtJf2CjqdmbrOx5EkMILuUhzM=\ngithub.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=\ngithub.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=\ngithub.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=\ngithub.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=\ngithub.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=\ngithub.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=\ngo.opencensus.io v0.18.0/go.mod h1:vKdFvxhtzZ9onBp9VKHK8z/sRpBMnKAsufL7wlDrCOA=\ngo4.org v0.0.0-20180809161055-417644f6feb5/go.mod h1:MkTOUMDaeVYJUOUsaDXIhWPZYa1yOyC1qaOBpL57BhE=\ngolang.org/x/arch v0.14.0 h1:z9JUEZWr8x4rR0OU6c4/4t6E6jOZ8/QBS2bBYBm4tx4=\ngolang.org/x/arch v0.14.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=\ngolang.org/x/build v0.0.0-20190111050920-041ab4dc3f9d/go.mod h1:OWs+y06UdEOHN4y+MfF/py+xQ/tYqIWW03b70/CG9Rw=\ngolang.org/x/crypto v0.0.0-20181030102418-4d3f4d9ffa16/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=\ngolang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=\ngolang.org/x/crypto v0.0.0-20190313024323-a1f597ede03a/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=\ngolang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=\ngolang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=\ngolang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=\ngolang.org/x/crypto v0.1.0/go.mod h1:RecgLatLF4+eUMCP1PoPZQb+cVrJcOPbHkTkbkB9sbw=\ngolang.org/x/crypto v0.3.1-0.20221117191849-2c476679df9a/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4=\ngolang.org/x/crypto v0.4.0/go.mod h1:3quD/ATkf6oY+rnes5c3ExXTbLc8mueNue5/DoinL80=\ngolang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98yw=\ngolang.org/x/crypto v0.35.0 h1:b15kiHdrGCHrP6LvwaQ3c03kgNhhiMgvlhxHQhmg2Xs=\ngolang.org/x/crypto v0.35.0/go.mod h1:dy7dXNW32cAb/6/PRuTNsix8T+vJAqvuIy5Bli/x0YQ=\ngolang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=\ngolang.org/x/exp v0.0.0-20221205204356-47842c84f3db/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc=\ngolang.org/x/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=\ngolang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=\ngolang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=\ngolang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=\ngolang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=\ngolang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY=\ngolang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=\ngolang.org/x/mod v0.6.0/go.mod h1:4mET923SAdbXp2ki8ey+zGs1SLqsuM2Y0uvdZR/fUNI=\ngolang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=\ngolang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=\ngolang.org/x/mod v0.9.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=\ngolang.org/x/mod v0.10.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=\ngolang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=\ngolang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=\ngolang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=\ngolang.org/x/net v0.0.0-20181029044818-c44066c5c816/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=\ngolang.org/x/net v0.0.0-20181106065722-10aee1819953/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=\ngolang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=\ngolang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=\ngolang.org/x/net v0.0.0-20190313220215-9f648a60d977/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=\ngolang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=\ngolang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=\ngolang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=\ngolang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=\ngolang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=\ngolang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=\ngolang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk=\ngolang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=\ngolang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=\ngolang.org/x/net v0.0.0-20220425223048-2871e0cb64e4/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=\ngolang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=\ngolang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco=\ngolang.org/x/net v0.2.0/go.mod h1:KqCZLdyyvdV855qA2rE3GC2aiw5xGR5TEjj8smXukLY=\ngolang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE=\ngolang.org/x/net v0.5.0/go.mod h1:DivGGAXEgPSlEBzxGzZI+ZLohi+xUj054jfeKui00ws=\ngolang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=\ngolang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=\ngolang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc=\ngolang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=\ngolang.org/x/net v0.14.0/go.mod h1:PpSgVXXLK0OxS0F31C1/tv6XNguvCrnXIDrFMspZIUI=\ngolang.org/x/net v0.35.0 h1:T5GQRQb2y08kTAByq9L4/bz8cipCdA8FbRTXewonqY8=\ngolang.org/x/net v0.35.0/go.mod h1:EglIi67kWsHKlRzzVMUD93VMSWGFOMSZgxFjparz1Qk=\ngolang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=\ngolang.org/x/oauth2 v0.0.0-20181017192945-9dcd33a902f4/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=\ngolang.org/x/oauth2 v0.0.0-20181203162652-d668ce993890/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=\ngolang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=\ngolang.org/x/perf v0.0.0-20180704124530-6e6d33e29852/go.mod h1:JLpeXjPJfIyPr5TlbXLkXWLhP8nz10XfvxElABhCtcw=\ngolang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\ngolang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\ngolang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\ngolang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\ngolang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\ngolang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\ngolang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\ngolang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\ngolang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\ngolang.org/x/sync v0.2.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\ngolang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=\ngolang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=\ngolang.org/x/sys v0.0.0-20181029174526-d69651ed3497/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=\ngolang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=\ngolang.org/x/sys v0.0.0-20190316082340-a2f829d7f35f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.0.0-20220319134239-a9b59b0215f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.0.0-20220422013727-9388b58f7150/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=\ngolang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=\ngolang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=\ngolang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=\ngolang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=\ngolang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc=\ngolang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA=\ngolang.org/x/term v0.4.0/go.mod h1:9P2UbLfCdcvo3p/nzKvsmas4TnlujnuoV9hGgYzW1lQ=\ngolang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=\ngolang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U=\ngolang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=\ngolang.org/x/term v0.11.0/go.mod h1:zC9APTIj3jG3FdV/Ons+XE1riIZXG4aZ4GTHiPZJPIU=\ngolang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=\ngolang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=\ngolang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=\ngolang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=\ngolang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=\ngolang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=\ngolang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=\ngolang.org/x/text v0.6.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=\ngolang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=\ngolang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=\ngolang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=\ngolang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=\ngolang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=\ngolang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=\ngolang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=\ngolang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=\ngolang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=\ngolang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=\ngolang.org/x/tools v0.0.0-20181030000716-a0a13e073c7b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=\ngolang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=\ngolang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=\ngolang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=\ngolang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=\ngolang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=\ngolang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E=\ngolang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=\ngolang.org/x/tools v0.2.0/go.mod h1:y4OqIKeOV/fWJetJ8bXPU1sEVniLMIyDAZWeHdV+NTA=\ngolang.org/x/tools v0.4.0/go.mod h1:UE5sM2OK9E/d67R0ANs2xJizIymRP5gJU295PvKXxjQ=\ngolang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=\ngolang.org/x/tools v0.7.0/go.mod h1:4pg6aUX35JBAogB10C9AtvVL+qowtN4pT3CGSQex14s=\ngolang.org/x/tools v0.9.1/go.mod h1:owI94Op576fPu3cIGQeHs3joujW/2Oc6MtlxbF5dfNc=\ngolang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=\ngolang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=\ngolang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=\ngolang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=\ngoogle.golang.org/api v0.0.0-20180910000450-7ca32eb868bf/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0=\ngoogle.golang.org/api v0.0.0-20181030000543-1d582fd0359e/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0=\ngoogle.golang.org/api v0.1.0/go.mod h1:UGEZY7KEX120AnNLIHFMKIo4obdJhkp2tPbaPlQx13Y=\ngoogle.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=\ngoogle.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=\ngoogle.golang.org/appengine v1.3.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=\ngoogle.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=\ngoogle.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=\ngoogle.golang.org/genproto v0.0.0-20180831171423-11092d34479b/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=\ngoogle.golang.org/genproto v0.0.0-20181029155118-b69ba1387ce2/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=\ngoogle.golang.org/genproto v0.0.0-20181202183823-bd91e49a0898/go.mod h1:7Ep/1NZk928CDR8SjdVbjWNpdIf6nzjE3BTgJDr2Atg=\ngoogle.golang.org/genproto v0.0.0-20190306203927-b5d61aea6440/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=\ngoogle.golang.org/grpc v1.14.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw=\ngoogle.golang.org/grpc v1.16.0/go.mod h1:0JHn/cJsOMiMfNA9+DeHDlAU7KAAB5GDlYFpa9MZMio=\ngoogle.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs=\ngoogle.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=\ngoogle.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=\ngoogle.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=\ngoogle.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=\ngoogle.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=\ngoogle.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=\ngoogle.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=\ngoogle.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=\ngoogle.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=\ngoogle.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=\ngoogle.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM=\ngoogle.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=\ngopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw=\ngopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=\ngopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=\ngopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=\ngopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=\ngopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=\ngopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=\ngopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\ngrpc.go4.org v0.0.0-20170609214715-11d0a25b4919/go.mod h1:77eQGdRu53HpSqPFJFmuJdjuHRquDANNeA4x7B8WQ9o=\nh12.io/socks v1.0.3 h1:Ka3qaQewws4j4/eDQnOdpr4wXsC//dXtWvftlIcCQUo=\nh12.io/socks v1.0.3/go.mod h1:AIhxy1jOId/XCz9BO+EIgNL2rQiPTBNnOfnVnQ+3Eck=\nhonnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=\nhonnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=\nhonnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=\nnullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=\nsourcegraph.com/sourcegraph/go-diff v0.5.0/go.mod h1:kuch7UrkMzY0X+p9CRK03kfuPQ2zzQcaEFbx8wA8rck=\nsourcegraph.com/sqs/pbtypes v0.0.0-20180604144634-d3ebe8f20ae4/go.mod h1:ketZ/q3QxT9HOBeFhu6RdvsftgpsbFHBF5Cas6cDKZ0=\n"
  },
  {
    "path": "job/cookie.go",
    "content": "package job\n\nimport (\n\t\"genspark2api/common/config\"\n\tlogger \"genspark2api/common/loggger\"\n\t\"math/rand\"\n\t\"time\"\n)\n\nfunc LoadCookieTask() {\n\tfor {\n\t\tsource := rand.NewSource(time.Now().UnixNano())\n\t\trandomNumber := rand.New(source).Intn(60) // 生成0到60之间的随机整数\n\n\t\t// 计算距离下一个时间间隔\n\t\tnow := time.Now()\n\t\tnext := time.Date(now.Year(), now.Month(), now.Day(), 17, 5, 0, 0, now.Location())\n\n\t\t// 如果当前时间已经超过9点，那么等待到第二天的9点\n\t\tif now.After(next) {\n\t\t\tnext = next.Add(24 * time.Hour)\n\t\t}\n\n\t\tdelay := next.Sub(now)\n\n\t\t// 等待直到下一个间隔\n\t\ttime.Sleep(delay + time.Duration(randomNumber)*time.Second)\n\n\t\tlogger.SysLog(\"genspark2api Scheduled LoadCookieTask Task Job Start!\")\n\n\t\tconfig.InitGSCookies()\n\n\t\tlogger.SysLog(\"genspark2api Scheduled LoadCookieTask Task Job  End!\")\n\t}\n}\n"
  },
  {
    "path": "main.go",
    "content": "package main\n\nimport (\n\t\"fmt\"\n\t\"genspark2api/check\"\n\t\"genspark2api/common\"\n\t\"genspark2api/common/config\"\n\tlogger \"genspark2api/common/loggger\"\n\t\"genspark2api/middleware\"\n\t\"genspark2api/router\"\n\t\"genspark2api/yescaptcha\"\n\t\"github.com/gin-gonic/gin\"\n\t\"os\"\n\t\"strconv\"\n)\n\nfunc main() {\n\tlogger.SetupLogger()\n\tlogger.SysLog(fmt.Sprintf(\"genspark2api %s starting...\", common.Version))\n\n\tcheck.CheckEnvVariable()\n\n\tif os.Getenv(\"GIN_MODE\") != \"debug\" {\n\t\tgin.SetMode(gin.ReleaseMode)\n\t}\n\n\tvar err error\n\n\tcommon.InitTokenEncoders()\n\tconfig.InitGSCookies()\n\tconfig.YescaptchaClient = yescaptcha.NewClient(config.YesCaptchaClientKey, nil)\n\n\tconfig.GlobalSessionManager = config.NewSessionManager()\n\n\t// 定时任务 每天9点整重载GS_COOKIES\n\t//go job.LoadCookieTask()\n\n\tserver := gin.New()\n\tserver.Use(gin.Recovery())\n\tserver.Use(middleware.RequestId())\n\tmiddleware.SetUpLogger(server)\n\n\trouter.SetRouter(server)\n\tvar port = os.Getenv(\"PORT\")\n\tif port == \"\" {\n\t\tport = strconv.Itoa(*common.Port)\n\t}\n\n\tif config.DebugEnabled {\n\t\tlogger.SysLog(\"running in DEBUG mode.\")\n\t}\n\n\tlogger.SysLog(\"genspark2api start success. enjoy it! ^_^\\n\")\n\n\terr = server.Run(\":\" + port)\n\n\tif err != nil {\n\t\tlogger.FatalLog(\"failed to start HTTP server: \" + err.Error())\n\t}\n\n}\n"
  },
  {
    "path": "middleware/auth.go",
    "content": "package middleware\n\nimport (\n\t\"genspark2api/common/config\"\n\t\"genspark2api/model\"\n\t\"github.com/gin-gonic/gin\"\n\t\"github.com/samber/lo\"\n\t\"net/http\"\n\t\"strings\"\n)\n\nfunc isValidSecret(secret string) bool {\n\treturn config.ApiSecret != \"\" && !lo.Contains(config.ApiSecrets, secret)\n}\n\nfunc authHelper(c *gin.Context) {\n\tsecret := c.Request.Header.Get(\"proxy-secret\")\n\tif isValidSecret(secret) {\n\t\tc.JSON(http.StatusUnauthorized, gin.H{\n\t\t\t\"success\": false,\n\t\t\t\"message\": \"无权进行此操作,未提供正确的 api-secret\",\n\t\t})\n\t\tc.Abort()\n\t\treturn\n\t}\n\tc.Next()\n\treturn\n}\n\nfunc authHelperForOpenai(c *gin.Context) {\n\tsecret := c.Request.Header.Get(\"Authorization\")\n\tsecret = strings.Replace(secret, \"Bearer \", \"\", 1)\n\tif isValidSecret(secret) {\n\t\tc.JSON(http.StatusUnauthorized, model.OpenAIErrorResponse{\n\t\t\tOpenAIError: model.OpenAIError{\n\t\t\t\tMessage: \"authorization(api-secret)校验失败\",\n\t\t\t\tType:    \"invalid_request_error\",\n\t\t\t\tCode:    \"invalid_authorization\",\n\t\t\t},\n\t\t})\n\t\tc.Abort()\n\t\treturn\n\t}\n\n\tif config.ApiSecret == \"\" {\n\t\tc.Request.Header.Set(\"Authorization\", \"\")\n\t}\n\n\tc.Next()\n\treturn\n}\n\nfunc Auth() func(c *gin.Context) {\n\treturn func(c *gin.Context) {\n\t\tauthHelper(c)\n\t}\n}\n\nfunc OpenAIAuth() func(c *gin.Context) {\n\treturn func(c *gin.Context) {\n\t\tauthHelperForOpenai(c)\n\t}\n}\n"
  },
  {
    "path": "middleware/cors.go",
    "content": "package middleware\n\nimport (\n\t\"github.com/gin-contrib/cors\"\n\t\"github.com/gin-gonic/gin\"\n)\n\nfunc CORS() gin.HandlerFunc {\n\tconfig := cors.DefaultConfig()\n\tconfig.AllowAllOrigins = true\n\tconfig.AllowCredentials = true\n\tconfig.AllowMethods = []string{\"GET\", \"POST\", \"PUT\", \"DELETE\", \"OPTIONS\"}\n\tconfig.AllowHeaders = []string{\"*\"}\n\treturn cors.New(config)\n}\n"
  },
  {
    "path": "middleware/ip-list.go",
    "content": "package middleware\n\nimport (\n\t\"genspark2api/common/config\"\n\t\"github.com/gin-gonic/gin\"\n\t\"net/http\"\n\t\"strings\"\n)\n\n// IPBlacklistMiddleware 检查请求的IP是否在黑名单中\nfunc IPBlacklistMiddleware() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\t// 获取请求的IP地址\n\t\tclientIP := c.ClientIP()\n\n\t\t// 检查IP是否在黑名单中\n\t\tfor _, blockedIP := range config.IpBlackList {\n\t\t\tif strings.TrimSpace(blockedIP) == clientIP {\n\t\t\t\t// 如果在黑名单中，返回403 Forbidden\n\t\t\t\tc.AbortWithStatusJSON(http.StatusForbidden, gin.H{\"error\": \"Forbidden\"})\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\t// 如果不在黑名单中，继续处理请求\n\t\tc.Next()\n\t}\n}\n"
  },
  {
    "path": "middleware/logger.go",
    "content": "package middleware\n\nimport (\n\t\"fmt\"\n\t\"genspark2api/common/helper\"\n\t\"github.com/gin-gonic/gin\"\n)\n\nfunc SetUpLogger(server *gin.Engine) {\n\tserver.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {\n\t\tvar requestID string\n\t\tif param.Keys != nil {\n\t\t\trequestID = param.Keys[helper.RequestIdKey].(string)\n\t\t}\n\t\treturn fmt.Sprintf(\"[GIN] %s | %s | %3d | %13v | %15s | %7s %s\\n\",\n\t\t\tparam.TimeStamp.Format(\"2006/01/02 - 15:04:05\"),\n\t\t\trequestID,\n\t\t\tparam.StatusCode,\n\t\t\tparam.Latency,\n\t\t\tparam.ClientIP,\n\t\t\tparam.Method,\n\t\t\tparam.Path,\n\t\t)\n\t}))\n}\n"
  },
  {
    "path": "middleware/rate-limit.go",
    "content": "package middleware\n\nimport (\n\t\"genspark2api/common\"\n\t\"genspark2api/common/config\"\n\t\"github.com/gin-gonic/gin\"\n\t\"net/http\"\n)\n\nvar timeFormat = \"2006-01-02T15:04:05.000Z\"\n\nvar inMemoryRateLimiter common.InMemoryRateLimiter\n\nfunc memoryRateLimiter(c *gin.Context, maxRequestNum int, duration int64, mark string) {\n\tkey := mark + c.ClientIP()\n\tif !inMemoryRateLimiter.Request(key, maxRequestNum, duration) {\n\t\tc.JSON(http.StatusTooManyRequests, gin.H{\n\t\t\t\"success\": false,\n\t\t\t\"message\": \"请求过于频繁,请稍后再试\",\n\t\t})\n\t\tc.Abort()\n\t\treturn\n\t}\n}\n\nfunc rateLimitFactory(maxRequestNum int, duration int64, mark string) func(c *gin.Context) {\n\t// It's safe to call multi times.\n\tinMemoryRateLimiter.Init(config.RateLimitKeyExpirationDuration)\n\treturn func(c *gin.Context) {\n\t\tmemoryRateLimiter(c, maxRequestNum, duration, mark)\n\t}\n}\n\nfunc RequestRateLimit() func(c *gin.Context) {\n\treturn rateLimitFactory(config.RequestRateLimitNum, config.RequestRateLimitDuration, \"REQUEST_RATE_LIMIT\")\n}\n"
  },
  {
    "path": "middleware/request-id.go",
    "content": "package middleware\n\nimport (\n\t\"context\"\n\t\"genspark2api/common/helper\"\n\t\"github.com/gin-gonic/gin\"\n)\n\nfunc RequestId() func(c *gin.Context) {\n\treturn func(c *gin.Context) {\n\t\tid := helper.GenRequestID()\n\t\tc.Set(helper.RequestIdKey, id)\n\t\tctx := context.WithValue(c.Request.Context(), helper.RequestIdKey, id)\n\t\tc.Request = c.Request.WithContext(ctx)\n\t\tc.Header(helper.RequestIdKey, id)\n\t\tc.Next()\n\t}\n}\n"
  },
  {
    "path": "model/openai.go",
    "content": "package model\n\nimport \"encoding/json\"\n\ntype OpenAIChatCompletionRequest struct {\n\tModel    string              `json:\"model\"`\n\tStream   bool                `json:\"stream\"`\n\tMessages []OpenAIChatMessage `json:\"messages\"`\n\tOpenAIChatCompletionExtraRequest\n}\n\ntype OpenAIChatCompletionExtraRequest struct {\n\tChannelId *string `json:\"channelId\"`\n}\n\ntype SessionState struct {\n\tModels           []string `json:\"models\"`\n\tLayers           int      `json:\"layers\"`\n\tAnswer           string   `json:\"answer\"`\n\tAnswerIsFinished bool     `json:\"answer_is_finished\"`\n}\ntype OpenAIChatMessage struct {\n\tRole         string        `json:\"role\"`\n\tContent      interface{}   `json:\"content\"`\n\tIsPrompt     bool          `json:\"is_prompt\"`\n\tSessionState *SessionState `json:\"session_state\"`\n}\n\nfunc (r *OpenAIChatCompletionRequest) AddMessage(message OpenAIChatMessage) {\n\tr.Messages = append([]OpenAIChatMessage{message}, r.Messages...)\n}\n\nfunc (r *OpenAIChatCompletionRequest) PrependMessagesFromJSON(jsonString string) error {\n\tvar newMessages []OpenAIChatMessage\n\terr := json.Unmarshal([]byte(jsonString), &newMessages)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// 查找最后一个 system role 的索引\n\tvar insertIndex int\n\tfor i := len(r.Messages) - 1; i >= 0; i-- {\n\t\tif r.Messages[i].Role == \"system\" {\n\t\t\tinsertIndex = i + 1\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// 将 newMessages 插入到找到的索引后面\n\tr.Messages = append(r.Messages[:insertIndex], append(newMessages, r.Messages[insertIndex:]...)...)\n\treturn nil\n}\n\nfunc (r *OpenAIChatCompletionRequest) SystemMessagesProcess(model string) {\n\tif r.Messages == nil {\n\t\treturn\n\t}\n\n\tif model == \"deep-seek-r1\" {\n\t\tfor i := range r.Messages {\n\t\t\tif r.Messages[i].Role == \"system\" {\n\t\t\t\tr.Messages[i].Role = \"user\"\n\t\t\t}\n\t\t\tif r.Messages[i].Role == \"assistant\" {\n\t\t\t\tr.Messages[i].IsPrompt = false\n\t\t\t\tr.Messages[i].SessionState = &SessionState{\n\t\t\t\t\tModels: []string{model},\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (r *OpenAIChatCompletionRequest) FilterUserMessage() {\n\tif r.Messages == nil {\n\t\treturn\n\t}\n\n\t// 返回最后一个role为user的元素\n\tfor i := len(r.Messages) - 1; i >= 0; i-- {\n\t\tif r.Messages[i].Role == \"user\" {\n\t\t\tr.Messages = r.Messages[i:]\n\t\t\tbreak\n\t\t}\n\t}\n}\n\ntype OpenAIErrorResponse struct {\n\tOpenAIError OpenAIError `json:\"error\"`\n}\n\ntype OpenAIError struct {\n\tMessage string `json:\"message\"`\n\tType    string `json:\"type\"`\n\tParam   string `json:\"param\"`\n\tCode    string `json:\"code\"`\n}\n\ntype OpenAIChatCompletionResponse struct {\n\tID                string         `json:\"id\"`\n\tObject            string         `json:\"object\"`\n\tCreated           int64          `json:\"created\"`\n\tModel             string         `json:\"model\"`\n\tChoices           []OpenAIChoice `json:\"choices\"`\n\tUsage             OpenAIUsage    `json:\"usage\"`\n\tSystemFingerprint *string        `json:\"system_fingerprint\"`\n\tSuggestions       []string       `json:\"suggestions\"`\n}\n\ntype OpenAIChoice struct {\n\tIndex        int           `json:\"index\"`\n\tMessage      OpenAIMessage `json:\"message\"`\n\tLogProbs     *string       `json:\"logprobs\"`\n\tFinishReason *string       `json:\"finish_reason\"`\n\tDelta        OpenAIDelta   `json:\"delta\"`\n}\n\ntype OpenAIMessage struct {\n\tRole    string `json:\"role\"`\n\tContent string `json:\"content\"`\n}\n\ntype OpenAIUsage struct {\n\tPromptTokens     int `json:\"prompt_tokens\"`\n\tCompletionTokens int `json:\"completion_tokens\"`\n\tTotalTokens      int `json:\"total_tokens\"`\n}\n\ntype OpenAIDelta struct {\n\tContent string `json:\"content\"`\n\tRole    string `json:\"role\"`\n}\n\ntype OpenAIImagesGenerationRequest struct {\n\tOpenAIChatCompletionExtraRequest\n\tModel          string `json:\"model\"`\n\tPrompt         string `json:\"prompt\"`\n\tResponseFormat string `json:\"response_format\"`\n\tImage          string `json:\"image\"`\n}\n\ntype VideosGenerationRequest struct {\n\tResponseFormat string `json:\"response_format\"`\n\tModel          string `json:\"model\"`\n\tAspectRatio    string `json:\"aspect_ratio\"`\n\tDuration       int    `json:\"duration\"`\n\tPrompt         string `json:\"prompt\"`\n\tAutoPrompt     bool   `json:\"auto_prompt\"`\n\tImage          string `json:\"image\"`\n}\n\ntype VideosGenerationResponse struct {\n\tCreated int64                           `json:\"created\"`\n\tData    []*VideosGenerationDataResponse `json:\"data\"`\n}\n\ntype VideosGenerationDataResponse struct {\n\tURL           string `json:\"url\"`\n\tRevisedPrompt string `json:\"revised_prompt\"`\n\tB64Json       string `json:\"b64_json\"`\n}\n\ntype OpenAIImagesGenerationResponse struct {\n\tCreated     int64                                 `json:\"created\"`\n\tDailyLimit  bool                                  `json:\"dailyLimit\"`\n\tData        []*OpenAIImagesGenerationDataResponse `json:\"data\"`\n\tSuggestions []string                              `json:\"suggestions\"`\n}\n\ntype OpenAIImagesGenerationDataResponse struct {\n\tURL           string `json:\"url\"`\n\tRevisedPrompt string `json:\"revised_prompt\"`\n\tB64Json       string `json:\"b64_json\"`\n}\n\ntype OpenAIGPT4VImagesReq struct {\n\tType     string `json:\"type\"`\n\tText     string `json:\"text\"`\n\tImageURL struct {\n\t\tURL string `json:\"url\"`\n\t} `json:\"image_url\"`\n}\n\ntype GetUserContent interface {\n\tGetUserContent() []string\n}\n\ntype OpenAIModerationRequest struct {\n\tInput string `json:\"input\"`\n}\n\ntype OpenAIModerationResponse struct {\n\tID      string `json:\"id\"`\n\tModel   string `json:\"model\"`\n\tResults []struct {\n\t\tFlagged        bool               `json:\"flagged\"`\n\t\tCategories     map[string]bool    `json:\"categories\"`\n\t\tCategoryScores map[string]float64 `json:\"category_scores\"`\n\t} `json:\"results\"`\n}\n\ntype OpenaiModelResponse struct {\n\tID     string `json:\"id\"`\n\tObject string `json:\"object\"`\n\t//Created time.Time `json:\"created\"`\n\t//OwnedBy string    `json:\"owned_by\"`\n}\n\n// ModelList represents a list of models.\ntype OpenaiModelListResponse struct {\n\tObject string                `json:\"object\"`\n\tData   []OpenaiModelResponse `json:\"data\"`\n}\n\nfunc (r *OpenAIChatCompletionRequest) GetUserContent() []string {\n\tvar userContent []string\n\n\tfor i := len(r.Messages) - 1; i >= 0; i-- {\n\t\tif r.Messages[i].Role == \"user\" {\n\t\t\tswitch contentObj := r.Messages[i].Content.(type) {\n\t\t\tcase string:\n\t\t\t\tuserContent = append(userContent, contentObj)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn userContent\n}\n"
  },
  {
    "path": "router/api-router.go",
    "content": "package router\n\nimport (\n\t\"fmt\"\n\t\"genspark2api/common/config\"\n\t\"genspark2api/controller\"\n\t\"genspark2api/middleware\"\n\t\"github.com/gin-gonic/gin\"\n\t\"strings\"\n)\n\nfunc SetApiRouter(router *gin.Engine) {\n\trouter.Use(middleware.CORS())\n\t//router.Use(gzip.Gzip(gzip.DefaultCompression))\n\trouter.Use(middleware.IPBlacklistMiddleware())\n\trouter.Use(middleware.RequestRateLimit())\n\n\trouter.GET(\"/\")\n\n\t//router.GET(\"/api/init/model/chat/map\", controller.InitModelChatMap)\n\t//https://api.openai.com/v1/images/generations\n\tv1Router := router.Group(fmt.Sprintf(\"%s/v1\", ProcessPath(config.RoutePrefix)))\n\tv1Router.Use(middleware.OpenAIAuth())\n\tv1Router.POST(\"/chat/completions\", controller.ChatForOpenAI)\n\tv1Router.POST(\"/images/generations\", controller.ImagesForOpenAI)\n\tv1Router.POST(\"/videos/generations\", controller.VideosForOpenAI)\n\tv1Router.GET(\"/models\", controller.OpenaiModels)\n}\n\nfunc ProcessPath(path string) string {\n\t// 判断字符串是否为空\n\tif path == \"\" {\n\t\treturn \"\"\n\t}\n\n\t// 判断开头是否为/，不是则添加\n\tif !strings.HasPrefix(path, \"/\") {\n\t\tpath = \"/\" + path\n\t}\n\n\t// 判断结尾是否为/，是则去掉\n\tif strings.HasSuffix(path, \"/\") {\n\t\tpath = path[:len(path)-1]\n\t}\n\n\treturn path\n}\n"
  },
  {
    "path": "router/main.go",
    "content": "package router\n\nimport (\n\t\"github.com/gin-gonic/gin\"\n)\n\nfunc SetRouter(router *gin.Engine) {\n\tSetApiRouter(router)\n}\n"
  },
  {
    "path": "yescaptcha/main.go",
    "content": "package yescaptcha\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"time\"\n)\n\nconst (\n\tdefaultAPIEndpoint = \"https://api.yescaptcha.com\"\n\tcreateTaskPath     = \"/createTask\"\n\tgetResultPath      = \"/getTaskResult\"\n\tmaxRetries         = 20\n\tpollingInterval    = 3 * time.Second\n)\n\n// Client represents a YesCaptcha API client\ntype Client struct {\n\tclientKey   string\n\tapiEndpoint string\n\thttpClient  *http.Client\n}\n\n// Options contains configuration options for the YesCaptcha client\ntype Options struct {\n\tAPIEndpoint string\n\tHTTPClient  *http.Client\n}\n\n// NewClient creates a new YesCaptcha client with the given client key and options\nfunc NewClient(clientKey string, opts *Options) *Client {\n\tclient := &Client{\n\t\tclientKey:   clientKey,\n\t\tapiEndpoint: defaultAPIEndpoint,\n\t\thttpClient:  &http.Client{Timeout: 30 * time.Second},\n\t}\n\n\tif opts != nil {\n\t\tif opts.APIEndpoint != \"\" {\n\t\t\tclient.apiEndpoint = opts.APIEndpoint\n\t\t}\n\t\tif opts.HTTPClient != nil {\n\t\t\tclient.httpClient = opts.HTTPClient\n\t\t}\n\t}\n\n\treturn client\n}\n\n// RecaptchaV3Request contains the parameters for solving a ReCaptcha V3 challenge\ntype RecaptchaV3Request struct {\n\tWebsiteURL string\n\tWebsiteKey string\n\tPageAction string\n\tMinScore   float64\n\tSoftID     string\n\tCallback   string\n}\n\ntype createTaskRequest struct {\n\tClientKey string `json:\"clientKey\"`\n\tTask      task   `json:\"task\"`\n}\n\ntype task struct {\n\tType       string  `json:\"type\"`\n\tWebsiteURL string  `json:\"websiteURL\"`\n\tWebsiteKey string  `json:\"websiteKey\"`\n\tPageAction string  `json:\"pageAction\"`\n\tMinScore   float64 `json:\"minScore,omitempty\"`\n\tSoftID     string  `json:\"softId,omitempty\"`\n\tCallback   string  `json:\"callback,omitempty\"`\n}\n\ntype createTaskResponse struct {\n\tErrorID          int    `json:\"errorId\"`\n\tErrorCode        string `json:\"errorCode\"`\n\tErrorDescription string `json:\"errorDescription\"`\n\tTaskID           string `json:\"taskId\"`\n}\n\ntype getResultRequest struct {\n\tClientKey string `json:\"clientKey\"`\n\tTaskID    string `json:\"taskId\"`\n}\n\ntype getResultResponse struct {\n\tErrorID          int      `json:\"errorId\"`\n\tErrorCode        string   `json:\"errorCode\"`\n\tErrorDescription string   `json:\"errorDescription\"`\n\tStatus           string   `json:\"status\"`\n\tSolution         solution `json:\"solution\"`\n}\n\ntype solution struct {\n\tGRecaptchaResponse string `json:\"gRecaptchaResponse\"`\n}\n\n// SolveRecaptchaV3 solves a ReCaptcha V3 challenge with context\nfunc (c *Client) SolveRecaptchaV3(ctx context.Context, req RecaptchaV3Request) (string, error) {\n\ttaskID, err := c.createTask(ctx, req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn c.waitForResult(ctx, taskID)\n}\n\nfunc (c *Client) createTask(ctx context.Context, req RecaptchaV3Request) (string, error) {\n\trequest := createTaskRequest{\n\t\tClientKey: c.clientKey,\n\t\tTask: task{\n\t\t\tType:       \"RecaptchaV3TaskProxyless\",\n\t\t\tWebsiteURL: req.WebsiteURL,\n\t\t\tWebsiteKey: req.WebsiteKey,\n\t\t\tPageAction: req.PageAction,\n\t\t\tMinScore:   req.MinScore,\n\t\t\tSoftID:     req.SoftID,\n\t\t\tCallback:   req.Callback,\n\t\t},\n\t}\n\n\tjsonData, err := json.Marshal(request)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\thttpReq, err := http.NewRequestWithContext(ctx, \"POST\", c.apiEndpoint+createTaskPath, bytes.NewBuffer(jsonData))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\thttpReq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tresp, err := c.httpClient.Do(httpReq)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar response createTaskResponse\n\tif err := json.Unmarshal(body, &response); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif response.ErrorID != 0 {\n\t\treturn \"\", errors.New(response.ErrorDescription)\n\t}\n\n\treturn response.TaskID, nil\n}\n\nfunc (c *Client) waitForResult(ctx context.Context, taskID string) (string, error) {\n\tticker := time.NewTicker(pollingInterval)\n\tdefer ticker.Stop()\n\n\tfor i := 0; i < maxRetries; i++ {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn \"\", ctx.Err()\n\t\tcase <-ticker.C:\n\t\t\tresult, err := c.getTaskResult(ctx, taskID)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\n\t\t\tif result.Status == \"ready\" {\n\t\t\t\treturn result.Solution.GRecaptchaResponse, nil\n\t\t\t}\n\n\t\t\tif result.ErrorID != 0 {\n\t\t\t\treturn \"\", errors.New(result.ErrorDescription)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\", errors.New(\"timeout waiting for captcha solution\")\n}\n\nfunc (c *Client) getTaskResult(ctx context.Context, taskID string) (*getResultResponse, error) {\n\trequest := getResultRequest{\n\t\tClientKey: c.clientKey,\n\t\tTaskID:    taskID,\n\t}\n\n\tjsonData, err := json.Marshal(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\thttpReq, err := http.NewRequestWithContext(ctx, \"POST\", c.apiEndpoint+getResultPath, bytes.NewBuffer(jsonData))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thttpReq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tresp, err := c.httpClient.Do(httpReq)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response getResultResponse\n\tif err := json.Unmarshal(body, &response); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &response, nil\n}\n"
  }
]