[
  {
    "path": ".dockerignore",
    "content": "*.png\n*.md\nLICENSE\ndocker-compose.yml\nDockerfile\ntests/\n"
  },
  {
    "path": ".github/FUNDING.yml",
    "content": "github: zedeus\nliberapay: zedeus\npatreon: nitter\n"
  },
  {
    "path": ".github/workflows/build-docker.yml",
    "content": "name: Docker\n\non:\n  push:\n    paths-ignore:\n      - \"README.md\"\n    branches:\n      - master\n\njobs:\n  tests:\n    uses: ./.github/workflows/run-tests.yml\n    secrets: inherit\n\n  build-docker-amd64:\n    needs: [tests]\n    runs-on: ubuntu-24.04\n    steps:\n      - uses: actions/checkout@v6\n      - name: Set up Docker Buildx\n        id: buildx\n        uses: docker/setup-buildx-action@v3\n        with:\n          version: latest\n      - name: Login to DockerHub\n        uses: docker/login-action@v3\n        with:\n          username: ${{ secrets.DOCKER_USERNAME }}\n          password: ${{ secrets.DOCKER_PASSWORD }}\n      - name: Build and push AMD64 Docker image\n        uses: docker/build-push-action@v3\n        with:\n          context: .\n          file: ./Dockerfile\n          platforms: linux/amd64\n          push: true\n          tags: zedeus/nitter:latest,zedeus/nitter:${{ github.sha }}\n\n  build-docker-arm64:\n    needs: [tests]\n    runs-on: ubuntu-24.04-arm\n    steps:\n      - uses: actions/checkout@v6\n      - name: Set up Docker Buildx\n        id: buildx\n        uses: docker/setup-buildx-action@v3\n        with:\n          version: latest\n      - name: Login to DockerHub\n        uses: docker/login-action@v3\n        with:\n          username: ${{ secrets.DOCKER_USERNAME }}\n          password: ${{ secrets.DOCKER_PASSWORD }}\n      - name: Build and push ARM64 Docker image\n        uses: docker/build-push-action@v3\n        with:\n          context: .\n          file: ./Dockerfile.arm64\n          platforms: linux/arm64\n          push: true\n          tags: zedeus/nitter:latest-arm64,zedeus/nitter:${{ github.sha }}-arm64\n"
  },
  {
    "path": ".github/workflows/run-tests.yml",
    "content": "name: Tests\n\non:\n  push:\n    paths-ignore:\n      - \"*.md\"\n    branches-ignore:\n      - master\n  workflow_call:\n\n# Ensure that multiple runs on the same branch do not overlap.\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.ref }}\n  cancel-in-progress: true\n\ndefaults:\n  run:\n    shell: bash\n\njobs:\n  build-test:\n    name: Build and test\n    runs-on: ubuntu-24.04\n    strategy:\n      matrix:\n        nim: [\"2.0.x\", \"2.2.x\", \"devel\"]\n    steps:\n      - name: Checkout Code\n        uses: actions/checkout@v6\n\n      - name: Cache Nimble Dependencies\n        id: cache-nimble\n        uses: actions/cache@v5\n        with:\n          path: ~/.nimble\n          key: ${{ matrix.nim }}-nimble-v2-${{ hashFiles('*.nimble') }}\n          restore-keys: |\n            ${{ matrix.nim }}-nimble-v2-\n\n      - name: Setup Nim\n        uses: jiro4989/setup-nim-action@v2\n        with:\n          nim-version: ${{ matrix.nim }}\n          use-nightlies: true\n          repo-token: ${{ secrets.GITHUB_TOKEN }}\n\n      - name: Build Project\n        run: nimble build -Y\n\n      - name: Upload 2.2.x build artifact\n        if: matrix.nim == '2.2.x'\n        uses: actions/upload-artifact@v6\n        with:\n          name: nitter-linux-nim-2.2.x-${{ github.sha }}\n          path: |\n            ./nitter\n          if-no-files-found: error\n\n  integration-test:\n    needs: [build-test]\n    name: Integration test\n    runs-on: ubuntu-24.04\n\n    services:\n      redis:\n        image: redis:7\n        ports:\n          - 6379:6379\n\n    steps:\n      - name: Install runtime deps\n        run: |\n          sudo apt-get install -y --no-install-recommends libsass-dev libpcre3\n\n      - name: Checkout code\n        uses: actions/checkout@v6\n\n      - name: Cache pipx (poetry)\n        uses: actions/cache@v5\n        with:\n          path: |\n            ~/.local/pipx\n            ~/.local/bin\n          key: pipx-poetry-${{ runner.os }}\n\n      - name: Install poetry\n        env:\n          PIPX_HOME: ~/.local/pipx\n          PIPX_BIN_DIR: ~/.local/bin\n        run: command -v poetry >/dev/null 2>&1 || pipx install poetry\n\n      - name: Setup Python (3.14) with Poetry cache\n        uses: actions/setup-python@v6\n        with:\n          python-version: \"3.14\"\n          cache: poetry\n          cache-dependency-path: tests/poetry.lock\n\n      - name: Install Python deps\n        working-directory: tests\n        run: poetry sync\n\n      - name: Cache Nimble Dependencies\n        uses: actions/cache@v5\n        with:\n          path: ~/.nimble\n          key: 2.2.x-nimble-v2-${{ hashFiles('*.nimble') }}\n          restore-keys: |\n            2.2.x-nimble-v2-\n\n      - name: Setup Nim\n        uses: jiro4989/setup-nim-action@v2\n        with:\n          nim-version: 2.2.x\n          use-nightlies: true\n          repo-token: ${{ secrets.GITHUB_TOKEN }}\n\n      - name: Download 2.2.x build artifact\n        uses: actions/download-artifact@v4\n        with:\n          name: nitter-linux-nim-2.2.x-${{ github.sha }}\n          path: .\n\n      - name: Make nitter binary executable\n        run: chmod +x ./nitter\n\n      - name: Prepare Nitter Environment\n        run: |\n          cp nitter.example.conf nitter.conf\n          sed -i 's/enableDebug = false/enableDebug = true/g' nitter.conf\n\n          # Run both Nimble tasks concurrently\n          nim r tools/rendermd.nim &\n          nim r tools/gencss.nim &\n          wait\n\n          echo '${{ secrets.SESSIONS }}' | head -n1\n          echo '${{ secrets.SESSIONS }}' > ./sessions.jsonl\n\n      - name: Run Tests\n        run: |\n          ./nitter &\n          cd tests\n          poetry run pytest -n3 --reruns=3 --rs .\n"
  },
  {
    "path": ".gitignore",
    "content": "nitter\n*.html\n*.db\n/tests/__pycache__\n/tests/geckodriver.log\n/tests/downloaded_files\n/tests/latest_logs\n/tools/gencss\n/tools/rendermd\n/public/css/style.css\n/public/md/*.html\nnitter.conf\nguest_accounts.json*\nsessions.json*\ndump.rdb\n*.bak\n/tools/*.json*\n"
  },
  {
    "path": ".travis.yml",
    "content": "jobs:\n  include:\n    - stage: test\n      if: (NOT type IN (pull_request)) AND (branch = master)\n      dist: bionic\n      language: python\n      python:\n        - 3.6\n      services:\n        - docker\n        - xvfb\n      script:\n        - sudo apt update\n        - sudo apt install --force-yes chromium-chromedriver\n        - wget https://www.dropbox.com/s/ckuoaubd1crrj2k/Linux_x64_737173_chrome-linux.zip -O chrome.zip\n        - unzip chrome.zip\n        - cd chrome-linux\n        - sudo rm /usr/bin/google-chrome\n        - sudo ln -s chrome /usr/bin/google-chrome\n        - cd ..\n        - pip3 install --upgrade pip\n        - pip3 install -U seleniumbase pytest\n        - docker run -d -p 127.0.0.1:8080:8080/tcp $IMAGE_NAME:$TRAVIS_COMMIT\n        - sleep 10\n        - cd tests\n        - pytest --headless -n 8 --reruns 10 --reruns-delay 2\n    - stage: pr\n      if: type IN (pull_request)\n      dist: bionic\n      language: python\n      python:\n        - 3.6\n      services:\n        - docker\n        - xvfb\n      script:\n        - sudo apt update\n        - sudo apt install --force-yes chromium-chromedriver\n        - wget https://www.dropbox.com/s/ckuoaubd1crrj2k/Linux_x64_737173_chrome-linux.zip -O chrome.zip\n        - unzip chrome.zip\n        - cd chrome-linux\n        - sudo rm /usr/bin/google-chrome\n        - sudo ln -s chrome /usr/bin/google-chrome\n        - cd ..\n        - pip3 install --upgrade pip\n        - pip3 install -U seleniumbase pytest\n        - docker build -t $IMAGE_NAME:$TRAVIS_COMMIT .\n        - docker run -d -p 127.0.0.1:8080:8080/tcp $IMAGE_NAME:$TRAVIS_COMMIT\n        - sleep 10\n        - cd tests\n        - pytest --headless -n 8 --reruns 3 --reruns-delay 2\n"
  },
  {
    "path": "Dockerfile",
    "content": "FROM nimlang/nim:2.2.0-alpine-regular as nim\nLABEL maintainer=\"setenforce@protonmail.com\"\n\nRUN apk --no-cache add libsass-dev pcre\n\nWORKDIR /src/nitter\n\nCOPY nitter.nimble .\nRUN nimble install -y --depsOnly\n\nCOPY . .\nRUN nimble build -d:danger -d:lto -d:strip --mm:refc \\\n    && nimble scss \\\n    && nimble md\n\nFROM alpine:latest\nWORKDIR /src/\nRUN apk --no-cache add pcre ca-certificates\nCOPY --from=nim /src/nitter/nitter ./\nCOPY --from=nim /src/nitter/nitter.example.conf ./nitter.conf\nCOPY --from=nim /src/nitter/public ./public\nEXPOSE 8080\nRUN adduser -h /src/ -D -s /bin/sh nitter\nUSER nitter\nCMD ./nitter\n"
  },
  {
    "path": "Dockerfile.arm64",
    "content": "FROM alpine:3.20.6 as nim\nLABEL maintainer=\"setenforce@protonmail.com\"\n\nRUN apk --no-cache add libsass-dev pcre gcc git libc-dev nim nimble\n\nWORKDIR /src/nitter\n\nCOPY nitter.nimble .\nRUN nimble install -y --depsOnly\n\nCOPY . .\nRUN nimble build -d:danger -d:lto -d:strip --mm:refc \\\n    && nimble scss \\\n    && nimble md\n\nFROM alpine:3.20.6\nWORKDIR /src/\nRUN apk --no-cache add pcre ca-certificates openssl\nCOPY --from=nim /src/nitter/nitter ./\nCOPY --from=nim /src/nitter/nitter.example.conf ./nitter.conf\nCOPY --from=nim /src/nitter/public ./public\nEXPOSE 8080\nRUN adduser -h /src/ -D -s /bin/sh nitter\nUSER nitter\nCMD ./nitter\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://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 Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\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,\nour General Public Licenses are 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.\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  Developers that use our General Public Licenses protect your rights\nwith two steps: (1) assert copyright on the software, and (2) offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\n  A secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate.  Many developers of free software are heartened and\nencouraged by the resulting cooperation.  However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\n  The GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community.  It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server.  Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\n  An older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals.  This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.\n\n  Notwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software.  This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\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 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 work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time.  Such new versions\nwill be 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 Affero 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 Affero 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 Affero 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 Affero General Public License as published\n    by 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 Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source.  For example, if your program is a web application, its\ninterface could display a \"Source\" link that leads users to an archive\nof the code.  There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\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 AGPL, see\n<http://www.gnu.org/licenses/>."
  },
  {
    "path": "README.md",
    "content": "# Nitter\n\n[![Test Matrix](https://github.com/zedeus/nitter/workflows/Tests/badge.svg)](https://github.com/zedeus/nitter/actions/workflows/run-tests.yml)\n[![Test Matrix](https://github.com/zedeus/nitter/workflows/Docker/badge.svg)](https://github.com/zedeus/nitter/actions/workflows/build-docker.yml)\n[![License](https://img.shields.io/github/license/zedeus/nitter?style=flat)](#license)\n\n> [!NOTE]\n> Running a Nitter instance now requires real accounts, since Twitter removed the previous methods. \\\n> This does not affect users. \\\n> For instructions on how to obtain session tokens, see [Creating session tokens](https://github.com/zedeus/nitter/wiki/Creating-session-tokens).\n\nA free and open source alternative Twitter front-end focused on privacy and\nperformance. \\\nInspired by the [Invidious](https://github.com/iv-org/invidious) project.\n\n- No JavaScript or ads\n- All requests go through the backend, client never talks to Twitter\n- Prevents Twitter from tracking your IP or JavaScript fingerprint\n- Uses Twitter's unofficial API (no developer account required)\n- Lightweight (for [@nim_lang](https://nitter.net/nim_lang), 60KB vs 784KB from twitter.com)\n- RSS feeds\n- Themes\n- Mobile support (responsive design)\n- AGPLv3 licensed, no proprietary instances permitted\n\n<details>\n<summary>Donations</summary>\nLiberapay: https://liberapay.com/zedeus<br>\nPatreon: https://patreon.com/nitter<br>\nBTC: bc1qpqpzjkcpgluhzf7x9yqe7jfe8gpfm5v08mdr55<br>\nETH: 0x24a0DB59A923B588c7A5EBd0dBDFDD1bCe9c4460<br>\nXMR: 42hKayRoEAw4D6G6t8mQHPJHQcXqofjFuVfavqKeNMNUZfeJLJAcNU19i1bGdDvcdN6romiSscWGWJCczFLe9RFhM3d1zpL<br>\nSOL: ANsyGNXFo6osuFwr1YnUqif2RdoYRhc27WdyQNmmETSW<br>\nZEC: u1vndfqtzyy6qkzhkapxelel7ams38wmfeccu3fdpy2wkuc4erxyjm8ncjhnyg747x6t0kf0faqhh2hxyplgaum08d2wnj4n7cyu9s6zhxkqw2aef4hgd4s6vh5hpqvfken98rg80kgtgn64ff70djy7s8f839z00hwhuzlcggvefhdlyszkvwy3c7yw623vw3rvar6q6evd3xcvveypt\n</details>\n\n## Roadmap\n\n- Embeds\n- Account system with timeline support\n- Archiving tweets/profiles\n- Developer API\n\n## Resources\n\nThe wiki contains\n[a list of instances](https://github.com/zedeus/nitter/wiki/Instances) and\n[browser extensions](https://github.com/zedeus/nitter/wiki/Extensions)\nmaintained by the community.\n\n## Why?\n\nIt's impossible to use Twitter without JavaScript enabled, and as of 2024 you\nneed to sign up. For privacy-minded folks, preventing JavaScript analytics and\nIP-based tracking is important, but apart from using a VPN and uBlock/uMatrix,\nit's impossible. Despite being behind a VPN and using heavy-duty adblockers,\nyou can get accurately tracked with your [browser's\nfingerprint](https://restoreprivacy.com/browser-fingerprinting/), [no\nJavaScript required](https://noscriptfingerprint.com/). This all became\nparticularly important after Twitter [removed the\nability](https://www.eff.org/deeplinks/2020/04/twitter-removes-privacy-option-and-shows-why-we-need-strong-privacy-laws)\nfor users to control whether their data gets sent to advertisers.\n\nUsing an instance of Nitter (hosted on a VPS for example), you can browse\nTwitter without JavaScript while retaining your privacy. In addition to\nrespecting your privacy, Nitter is on average around 15 times lighter than\nTwitter, and in most cases serves pages faster (eg. timelines load 2-4x faster).\n\nIn the future a simple account system will be added that lets you follow Twitter\nusers, allowing you to have a clean chronological timeline without needing a\nTwitter account.\n\n## Screenshot\n\n![nitter](/screenshot.png)\n\n## Installation\n\n### Dependencies\n\n- libpcre\n- libsass\n- redis/valkey\n\nTo compile Nitter you need a Nim installation, see\n[nim-lang.org](https://nim-lang.org/install.html) for details. It is possible\nto install it system-wide or in the user directory you create below.\n\nTo compile the scss files, you need to install `libsass`. On Ubuntu and Debian,\nyou can use `libsass-dev`.\n\nRedis is required for caching and in the future for account info. As of 2024\nRedis is no longer open source, so using the fork Valkey is recommended. It\nshould be available on most distros as `redis` or `redis-server`\n(Ubuntu/Debian), or `valkey`/`valkey-server`. Running it with the default\nconfig is fine, Nitter's default config is set to use the default port and\nlocalhost.\n\nHere's how to create a `nitter` user, clone the repo, and build the project\nalong with the scss and md files.\n\n```bash\n# useradd -m nitter\n# su nitter\n$ git clone https://github.com/zedeus/nitter\n$ cd nitter\n$ nimble build -d:danger --mm:refc\n$ nimble scss\n$ nimble md\n$ cp nitter.example.conf nitter.conf\n```\n\nSet your hostname, port, HMAC key, https (must be correct for cookies), and\nRedis info in `nitter.conf`. To run Redis, either run\n`redis-server --daemonize yes`, or `systemctl enable --now redis` (or\nredis-server depending on the distro). Run Nitter by executing `./nitter` or\nusing the systemd service below. You should run Nitter behind a reverse proxy\nsuch as [Nginx](https://github.com/zedeus/nitter/wiki/Nginx) or\n[Apache](https://github.com/zedeus/nitter/wiki/Apache) for security and\nperformance reasons.\n\n### Docker\n\nPage for the Docker image: https://hub.docker.com/r/zedeus/nitter\n\n#### NOTE: For ARM64 support, please use the separate ARM64 docker image: [`zedeus/nitter:latest-arm64`](https://hub.docker.com/r/zedeus/nitter/tags).\n\nTo run Nitter with Docker, you'll need to install and run Redis separately\nbefore you can run the container. See below for how to also run Redis using\nDocker.\n\nTo build and run Nitter in Docker:\n\n```bash\ndocker build -t nitter:latest .\ndocker run -v $(pwd)/nitter.conf:/src/nitter.conf -d --network host nitter:latest\n```\n\nNote: For ARM64, use this Dockerfile: [`Dockerfile.arm64`](https://github.com/zedeus/nitter/blob/master/Dockerfile.arm64).\n\nA prebuilt Docker image is provided as well:\n\n```bash\ndocker run -v $(pwd)/nitter.conf:/src/nitter.conf -d --network host zedeus/nitter:latest\n```\n\nUsing docker-compose to run both Nitter and Redis as different containers:\nChange `redisHost` from `localhost` to `nitter-redis` in `nitter.conf`, then run:\n\n```bash\ndocker-compose up -d\n```\n\nNote the Docker commands expect a `nitter.conf` file in the directory you run\nthem.\n\n### systemd\n\nTo run Nitter via systemd you can use this service file:\n\n```ini\n[Unit]\nDescription=Nitter (An alternative Twitter front-end)\nAfter=syslog.target\nAfter=network.target\n\n[Service]\nType=simple\n\n# set user and group\nUser=nitter\nGroup=nitter\n\n# configure location\nWorkingDirectory=/home/nitter/nitter\nExecStart=/home/nitter/nitter/nitter\n\nRestart=always\nRestartSec=15\n\n[Install]\nWantedBy=multi-user.target\n```\n\nThen enable and run the service:\n`systemctl enable --now nitter.service`\n\n### Logging\n\nNitter currently prints some errors to stdout, and there is no real logging\nimplemented. If you're running Nitter with systemd, you can check stdout like\nthis: `journalctl -u nitter.service` (add `--follow` to see just the last 15\nlines). If you're running the Docker image, you can do this:\n`docker logs --follow *nitter container id*`\n\n## Contact\n\nFeel free to join our [Matrix channel](https://matrix.to/#/#nitter:matrix.org).\nYou can email me at zedeus@pm.me if you wish to contact me personally.\n"
  },
  {
    "path": "config.nims",
    "content": "--define:ssl\n--define:useStdLib\n--threads:off\n\n# workaround httpbeast file upload bug\n--assertions:off\n\n# disable annoying warnings\nwarning(\"GcUnsafe2\", off)\nwarning(\"HoleEnumConv\", off)\nhint(\"XDeclaredButNotUsed\", off)\nhint(\"XCannotRaiseY\", off)\nhint(\"User\", off)\n"
  },
  {
    "path": "docker-compose.yml",
    "content": "version: \"3\"\n\nservices:\n\n  nitter:\n    image: zedeus/nitter:latest\n    container_name: nitter\n    ports:\n      - \"127.0.0.1:8080:8080\" # Replace with \"8080:8080\" if you don't use a reverse proxy\n    volumes:\n      - ./nitter.conf:/src/nitter.conf:Z,ro\n      - ./sessions.jsonl:/src/sessions.jsonl:Z,ro # Run get_sessions.py to get the credentials\n    depends_on:\n      - nitter-redis\n    restart: unless-stopped\n    healthcheck:\n      test: wget -nv --tries=1 --spider http://127.0.0.1:8080/Jack/status/20 || exit 1\n      interval: 30s\n      timeout: 5s\n      retries: 2\n    user: \"998:998\"\n    read_only: true\n    security_opt:\n      - no-new-privileges:true\n    cap_drop:\n      - ALL\n\n  nitter-redis:\n    image: redis:6-alpine\n    container_name: nitter-redis\n    command: redis-server --save 60 1 --loglevel warning\n    volumes:\n      - nitter-redis:/data\n    restart: unless-stopped\n    healthcheck:\n      test: redis-cli ping\n      interval: 30s\n      timeout: 5s\n      retries: 2\n    user: \"999:1000\"\n    read_only: true\n    security_opt:\n      - no-new-privileges:true\n    cap_drop:\n      - ALL\n\nvolumes:\n  nitter-redis:\n"
  },
  {
    "path": "nitter.example.conf",
    "content": "[Server]\nhostname = \"nitter.net\"      # for generating links, change this to your own domain/ip\ntitle = \"nitter\"\naddress = \"0.0.0.0\"\nport = 8080\nhttps = false                # disable to enable cookies when not using https\nhttpMaxConnections = 100\nstaticDir = \"./public\"\n\n[Cache]\nlistMinutes = 240            # how long to cache list info (not the tweets, so keep it high)\nrssMinutes = 10              # how long to cache rss queries\nredisHost = \"localhost\"      # Change to \"nitter-redis\" if using docker-compose\nredisPort = 6379\nredisPassword = \"\"\nredisConnections = 20        # minimum open connections in pool\nredisMaxConnections = 30\n# new connections are opened when none are available, but if the pool size\n# goes above this, they're closed when released. don't worry about this unless\n# you receive tons of requests per second\n\n[Config]\nhmacKey = \"secretkey\"        # random key for cryptographic signing of video urls\nbase64Media = false          # use base64 encoding for proxied media urls\nenableRSS = true             # master switch, set to false to disable all RSS feeds\nenableRSSUserTweets = true   # /@user/rss\nenableRSSUserReplies = true  # /@user/with_replies/rss\nenableRSSUserMedia = true    # /@user/media/rss\nenableRSSSearch = true       # /search/rss and /@user/search/rss\nenableRSSList = true         # list RSS feeds\nenableDebug = false          # enable request logs and debug endpoints (/.sessions)\nproxy = \"\"                   # http/https url, SOCKS proxies are not supported\nproxyAuth = \"\"\napiProxy = \"\"                # nitter-proxy host, e.g. localhost:7000\ndisableTid = false           # enable this if cookie-based auth is failing\nmaxConcurrentReqs = 2        # max requests at a time per session to avoid race conditions\n\n# Change default preferences here, see src/prefs_impl.nim for a complete list\n[Preferences]\ntheme = \"Nitter\"\nreplaceTwitter = \"nitter.net\"\nreplaceYouTube = \"piped.video\"\nreplaceReddit = \"teddit.net\"\nproxyVideos = true\nhlsPlayback = false\ninfiniteScroll = false\n"
  },
  {
    "path": "nitter.nimble",
    "content": "# Package\n\nversion       = \"0.1.0\"\nauthor        = \"zedeus\"\ndescription   = \"An alternative front-end for Twitter\"\nlicense       = \"AGPL-3.0\"\nsrcDir        = \"src\"\nbin           = @[\"nitter\"]\n\n\n# Dependencies\n\nrequires \"nim >= 2.0.0\"\nrequires \"jester#baca3f\"\nrequires \"karax#5cf360c\"\nrequires \"sass#7dfdd03\"\nrequires \"nimcrypto#a079df9\"\nrequires \"markdown#158efe3\"\nrequires \"packedjson#9e6fbb6\"\nrequires \"supersnappy#6c94198\"\nrequires \"redpool#8b7c1db\"\nrequires \"https://github.com/zedeus/redis#d0a0e6f\"\nrequires \"zippy#ca5989a\"\nrequires \"flatty#e668085\"\nrequires \"jsony#1de1f08\"\nrequires \"oauth#b8c163b\"\n\n# Tasks\n\ntask scss, \"Generate css\":\n  exec \"nim r --hint[Processing]:off tools/gencss\"\n\ntask md, \"Render md\":\n  exec \"nim r --hint[Processing]:off tools/rendermd\"\n"
  },
  {
    "path": "public/browserconfig.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<browserconfig>\n    <msapplication>\n        <tile>\n            <TileColor>#2b5797</TileColor>\n        </tile>\n    </msapplication>\n</browserconfig>\n"
  },
  {
    "path": "public/css/fontello.css",
    "content": "@font-face {\n  font-family: \"fontello\";\n  src: url(\"/fonts/fontello.eot?42791196\");\n  src:\n    url(\"/fonts/fontello.eot?42791196#iefix\") format(\"embedded-opentype\"),\n    url(\"/fonts/fontello.woff2?42791196\") format(\"woff2\"),\n    url(\"/fonts/fontello.woff?42791196\") format(\"woff\"),\n    url(\"/fonts/fontello.ttf?42791196\") format(\"truetype\"),\n    url(\"/fonts/fontello.svg?42791196#fontello\") format(\"svg\");\n  font-weight: normal;\n  font-style: normal;\n}\n\n[class^=\"icon-\"]:before,\n[class*=\" icon-\"]:before {\n  font-family: \"fontello\";\n  font-style: normal;\n  font-weight: normal;\n  speak: never;\n\n  display: inline-block;\n  text-decoration: inherit;\n  width: 1em;\n  margin-right: 0.2em;\n  text-align: center;\n\n  /* For safety - reset parent styles, that can break glyph codes*/\n  font-variant: normal;\n  text-transform: none;\n\n  /* fix buttons height, for twitter bootstrap */\n  line-height: 1em;\n\n  /* Font smoothing. That was taken from TWBS */\n  -webkit-font-smoothing: antialiased;\n  -moz-osx-font-smoothing: grayscale;\n}\n\n.icon-views:before {\n  content: \"\\e800\";\n}\n\n/* '' */\n.icon-heart:before {\n  content: \"\\e801\";\n}\n\n/* '' */\n.icon-quote:before {\n  content: \"\\e802\";\n}\n\n/* '' */\n.icon-comment:before {\n  content: \"\\e803\";\n}\n\n/* '' */\n.icon-group:before {\n  content: \"\\e804\";\n}\n\n/* '' */\n.icon-play:before {\n  content: \"\\e805\";\n}\n\n/* '' */\n.icon-link:before {\n  content: \"\\e806\";\n}\n\n/* '' */\n.icon-calendar:before {\n  content: \"\\e807\";\n}\n\n/* '' */\n.icon-location:before {\n  content: \"\\e808\";\n}\n\n/* '' */\n.icon-picture:before {\n  content: \"\\e809\";\n}\n\n/* '' */\n.icon-lock:before {\n  content: \"\\e80a\";\n}\n\n/* '' */\n.icon-down:before {\n  content: \"\\e80b\";\n}\n\n/* '' */\n.icon-retweet:before {\n  content: \"\\e80c\";\n}\n\n/* '' */\n.icon-search:before {\n  content: \"\\e80d\";\n}\n\n/* '' */\n.icon-pin:before {\n  content: \"\\e80e\";\n}\n\n/* '' */\n.icon-cog:before {\n  content: \"\\e80f\";\n}\n\n/* '' */\n.icon-rss:before {\n  content: \"\\e810\";\n}\n\n/* '' */\n.icon-ok:before {\n  content: \"\\e811\";\n}\n\n/* '' */\n.icon-circle:before {\n  content: \"\\f111\";\n}\n\n/* '' */\n.icon-info:before {\n  content: \"\\f128\";\n}\n\n/* '' */\n.icon-bird:before {\n  content: \"\\f309\";\n}\n\n/* '' */\n"
  },
  {
    "path": "public/css/themes/auto.css",
    "content": "@import \"nitter.css\" (prefers-color-scheme: dark);\n@import \"twitter.css\" (prefers-color-scheme: light);\n"
  },
  {
    "path": "public/css/themes/auto_(twitter).css",
    "content": "@import \"twitter_dark.css\" (prefers-color-scheme: dark);\n@import \"twitter.css\" (prefers-color-scheme: light);\n"
  },
  {
    "path": "public/css/themes/black.css",
    "content": "body {\n    --bg_color: #000000;\n    --fg_color: #FFFFFF;\n    --fg_faded: #FFFFFFD4;\n    --fg_dark: var(--accent);\n    --fg_nav: var(--accent);\n\n    --bg_panel: #0C0C0C;\n    --bg_elements: #000000;\n    --bg_overlays: var(--bg_panel);\n    --bg_hover: #131313;\n\n    --grey: #E2E2E2;\n    --dark_grey: #4E4E4E;\n    --darker_grey: #272727;\n    --darkest_grey: #212121;\n    --border_grey: #7D7D7D;\n\n    --accent: #FF6C60;\n    --accent_light: #FFACA0;\n    --accent_dark: #909090;\n    --accent_border: #FF6C6091;\n\n    --play_button: var(--accent);\n    --play_button_hover: var(--accent_light);\n\n    --more_replies_dots: #A7A7A7;\n    --error_red: #420A05;\n\n    --verified_blue: #1DA1F2;\n    --icon_text: var(--fg_color);\n\n    --tab: var(--fg_color);\n    --tab_selected: var(--accent);\n\n    --profile_stat: var(--fg_color);\n}\n"
  },
  {
    "path": "public/css/themes/dracula.css",
    "content": "body {\n    --bg_color: #282a36;\n    --fg_color: #f8f8f2;\n    --fg_faded: #818eb6;\n    --fg_dark: var(--fg_faded);\n    --fg_nav: var(--accent);\n\n    --bg_panel: #343746;\n    --bg_elements: #292b36;\n    --bg_overlays: #44475a;\n    --bg_hover: #2f323f;\n\n    --grey: var(--fg_faded);\n    --dark_grey: #44475a;\n    --darker_grey: #3d4051;\n    --darkest_grey: #363948;\n    --border_grey: #44475a;\n\n    --accent: #bd93f9;\n    --accent_light: #caa9fa;\n    --accent_dark: var(--accent);\n    --accent_border: #ff79c696;\n\n    --play_button: #ffb86c;\n    --play_button_hover: #ffc689;\n\n    --more_replies_dots: #bd93f9;\n    --error_red: #ff5555;\n\n    --verified_blue: var(--accent);\n    --icon_text: ##F8F8F2;\n\n    --tab: #6272a4;\n    --tab_selected: var(--accent);\n\n    --profile_stat: #919cbf;\n}\n\n.search-bar > form input::placeholder{\n    color: var(--fg_faded);\n}"
  },
  {
    "path": "public/css/themes/mastodon.css",
    "content": "body {\n    --bg_color: #191B22;\n    --fg_color: #FFFFFF;\n    --fg_faded: #F8F8F2CF;\n    --fg_dark: var(--accent);\n    --fg_nav: var(--accent);\n\n    --bg_panel: #282C37;\n    --bg_elements: #22252F;\n    --bg_overlays: var(--bg_panel);\n    --bg_hover: var(--bg_elements);\n\n    --grey: #8595AB;\n    --dark_grey: #393F4F;\n    --darker_grey: #1C1E23;\n    --darkest_grey: #1F2125;\n    --border_grey: #393F4F;\n\n    --accent: #9BAEC8;\n    --accent_light: #CDDEF5;\n    --accent_dark: #748294;\n    --accent_border: var(--accent_dark);\n\n    --play_button: var(--accent);\n    --play_button_hover: var(--accent_light);\n\n    --more_replies_dots: #7F8DA0;\n    --error_red: #420A05;\n\n    --verified_blue: #1DA1F2;\n    --icon_text: var(--fg_color);\n\n    --tab: var(--accent);\n    --tab_selected: #D9E1E8;\n\n    --profile_stat: var(--fg_color);\n}\n"
  },
  {
    "path": "public/css/themes/nitter.css",
    "content": "body {\n    /* uses default values */\n}\n"
  },
  {
    "path": "public/css/themes/pleroma.css",
    "content": "body {\n    --bg_color: #0A1117;\n    --fg_color: #B9B9BA;\n    --fg_faded: #B9B9BAFA;\n    --fg_dark: var(--accent);\n    --fg_nav: var(--accent);\n\n    --bg_panel: #121A24;\n    --bg_elements: #182230;\n    --bg_overlays: var(--bg_elements);\n    --bg_hover: #1B2735;\n\n    --grey: #666A6F;\n    --dark_grey: #42413D;\n    --darker_grey: #293442;\n    --darkest_grey: #202935;\n    --border_grey: #1C2737;\n\n    --accent: #D8A070;\n    --accent_light: #DEB897;\n    --accent_dark: #6D533C;\n    --accent_border: #947050;\n\n    --play_button: var(--accent);\n    --play_button_hover: var(--accent_light);\n\n    --more_replies_dots: #886446;\n    --error_red: #420A05;\n\n    --verified_blue: #1DA1F2;\n    --icon_text: #F8F8F8;\n\n    --tab: var(--fg_color);\n    --tab_selected: var(--accent);\n\n    --profile_stat: var(--fg_color);\n}\n"
  },
  {
    "path": "public/css/themes/twitter.css",
    "content": "body {\n    --bg_color: #E6ECF0;\n    --fg_color: #0F0F0F;\n    --fg_faded: #657786;\n    --fg_dark: var(--fg_faded);\n    --fg_nav: var(--accent);\n\n    --bg_panel: #FFFFFF;\n    --bg_elements: #FDFDFD;\n    --bg_overlays: #FFFFFF;\n    --bg_hover: #F5F8FA;\n\n    --grey: var(--fg_faded);\n    --dark_grey: #D6D6D6;\n    --darker_grey: #CECECE;\n    --darkest_grey: #ECECEC;\n    --border_grey: #E6ECF0;\n\n    --accent: #1DA1F2;\n    --accent_light: #A0EDFF;\n    --accent_dark: var(--accent);\n    --accent_border: #1DA1F296;\n\n    --play_button: #D84D4D;\n    --play_button_hover: #FF6C60;\n\n    --more_replies_dots: #0199F7;\n    --error_red: #FF7266;\n\n    --verified_blue: var(--accent);\n    --icon_text: #F8F8F2;\n\n    --tab: var(--accent);\n    --tab_selected: #000000;\n\n    --profile_stat: var(--fg_dark);\n}\n"
  },
  {
    "path": "public/css/themes/twitter_dark.css",
    "content": "body {\n    --bg_color: #101821;\n    --fg_color: #FFFFFF;\n    --fg_faded: #8899A6;\n    --fg_dark: var(--fg_faded);\n    --fg_nav: var(--accent);\n\n    --bg_panel: #15202B;\n    --bg_elements: var(--bg_panel);\n    --bg_overlays: var(--bg_panel);\n    --bg_hover: #192734;\n\n    --grey: var(--fg_faded);\n    --dark_grey: #38444D;\n    --darker_grey: #2A343C;\n    --darkest_grey:#1B2835;\n    --border_grey: #38444D;\n\n    --accent: #1B95E0;\n    --accent_light: #80CEFF;\n    --accent_dark: #2B608A;\n    --accent_border: #1B95E096;\n\n    --play_button: var(--accent);\n    --play_button_hover: var(--accent_light);\n\n    --more_replies_dots: #39719C;\n    --error_red: #FF7266;\n\n    --verified_blue: var(--accent);\n    --icon_text: var(--fg_color);\n\n    --tab: var(--grey);\n    --tab_selected: var(--accent);\n\n    --profile_stat: var(--fg_color);\n}\n"
  },
  {
    "path": "public/fonts/LICENSE.txt",
    "content": "Font license info\n\n\n## Modern Pictograms\n\n   Copyright (c) 2012 by John Caserta. All rights reserved.\n\n   Author:    John Caserta\n   License:   SIL (http://scripts.sil.org/OFL)\n   Homepage:  http://thedesignoffice.org/project/modern-pictograms/\n\n\n## Entypo\n\n   Copyright (C) 2012 by Daniel Bruce\n\n   Author:    Daniel Bruce\n   License:   SIL (http://scripts.sil.org/OFL)\n   Homepage:  http://www.entypo.com\n\n\n## Iconic\n\n   Copyright (C) 2012 by P.J. Onori\n\n   Author:    P.J. Onori\n   License:   SIL (http://scripts.sil.org/OFL)\n   Homepage:  http://somerandomdude.com/work/iconic/\n\n\n## Font Awesome\n\n   Copyright (C) 2016 by Dave Gandy\n\n   Author:    Dave Gandy\n   License:   SIL ()\n   Homepage:  http://fortawesome.github.com/Font-Awesome/\n\n\n## Elusive\n\n   Copyright (C) 2013 by Aristeides Stathopoulos\n\n   Author:    Aristeides Stathopoulos\n   License:   SIL (http://scripts.sil.org/OFL)\n   Homepage:  http://aristeides.com/\n\n\n"
  },
  {
    "path": "public/js/hlsPlayback.js",
    "content": "// @license http://www.gnu.org/licenses/agpl-3.0.html AGPL-3.0\n// SPDX-License-Identifier: AGPL-3.0-only\nfunction playVideo(overlay) {\n    const video = overlay.parentElement.querySelector('video');\n    const url = video.getAttribute(\"data-url\");\n    video.setAttribute(\"controls\", \"\");\n    overlay.style.display = \"none\";\n\n    if (Hls.isSupported()) {\n        var hls = new Hls({autoStartLoad: false});\n        hls.loadSource(url);\n        hls.attachMedia(video);\n        hls.on(Hls.Events.MANIFEST_PARSED, function () {\n            hls.loadLevel = hls.levels.length - 1;\n            hls.startLoad();\n            video.play();\n        });\n    } else if (video.canPlayType('application/vnd.apple.mpegurl')) {\n        video.src = url;\n        video.addEventListener('canplay', function() {\n            video.play();\n        });\n    }\n}\n// @license-end\n"
  },
  {
    "path": "public/js/infiniteScroll.js",
    "content": "// @license http://www.gnu.org/licenses/agpl-3.0.html AGPL-3.0\n// SPDX-License-Identifier: AGPL-3.0-only\n\nfunction insertBeforeLast(node, elem) {\n  node.insertBefore(elem, node.childNodes[node.childNodes.length - 2]);\n}\n\nfunction getLoadMore(doc) {\n  return doc.querySelector(\".show-more:not(.timeline-item)\");\n}\n\nfunction getHrefs(selector) {\n  return new Set([...document.querySelectorAll(selector)].map(el => el.getAttribute(\"href\")));\n}\n\nfunction getTweetId(item) {\n  const m = item.querySelector(\".tweet-link\")?.getAttribute(\"href\")?.match(/\\/status\\/(\\d+)/);\n  return m ? m[1] : \"\";\n}\n\nfunction isDuplicate(item, hrefs) {\n  return hrefs.has(item.querySelector(\".tweet-link\")?.getAttribute(\"href\"));\n}\n\nconst GAP = 10;\n\nclass Masonry {\n  constructor(container) {\n    this.container = container;\n    this.colHeights = [];\n    this.colCounts = [];\n    this.colCount = 0;\n    this._lastWidth = 0;\n    this._colWidthCache = 0;\n    this._items = [];\n    this._revealTimer = null;\n    this.container.classList.add(\"masonry-active\");\n\n    let resizeTimer;\n    window.addEventListener(\"resize\", () => {\n      clearTimeout(resizeTimer);\n      resizeTimer = setTimeout(() => this._rebuild(), 50);\n    });\n\n    // Re-sync positions whenever images finish loading and items grow taller.\n    // Must be set up before _rebuild() so initial items get observed on first pass.\n    let syncTimer;\n    this._observer = window.ResizeObserver ? new ResizeObserver(() => {\n      clearTimeout(syncTimer);\n      syncTimer = setTimeout(() => this.syncHeights(), 100);\n    }) : null;\n\n    this._rebuild();\n  }\n\n  // Reveal all items and gallery siblings (show-more, top-ref). Idempotent.\n  _revealAll() {\n    clearTimeout(this._revealTimer);\n    for (const item of this._items) item.classList.add(\"masonry-visible\");\n    for (const el of this.container.parentElement.querySelectorAll(\":scope > .show-more, :scope > .top-ref, :scope > .timeline-footer\"))\n      el.classList.add(\"masonry-visible\");\n  }\n\n  // Height-primary, count-as-tiebreaker: handles both tall tweets and unloaded images.\n  _pickCol() {\n    return this.colHeights.reduce((min, h, i) => {\n      const m = this.colHeights[min];\n      return (h < m || (h === m && this.colCounts[i] < this.colCounts[min])) ? i : min;\n    }, 0);\n  }\n\n  // Position items using current column state. Updates colHeights, colCounts, container height.\n  _position(items, heights, colWidth) {\n    for (let i = 0; i < items.length; i++) {\n      const col = this._pickCol();\n      items[i].style.left = `${col * (colWidth + GAP)}px`;\n      items[i].style.top = `${this.colHeights[col]}px`;\n      this.colHeights[col] += heights[i] + GAP;\n      this.colCounts[col]++;\n    }\n    this.container.style.height = `${Math.max(0, ...this.colHeights)}px`;\n  }\n\n  // Full reset and re-place all items.\n  _place(items, heights, n, colWidth) {\n    this.colHeights = new Array(n).fill(0);\n    this.colCounts = new Array(n).fill(0);\n    this.colCount = n;\n    this._position(items, heights, colWidth);\n  }\n\n  _rebuild() {\n    const n = Math.max(1, Math.floor(this.container.clientWidth / 350));\n    const w = this.container.clientWidth;\n    if (n === this.colCount && w === this._lastWidth) return;\n\n    const isFirst = this.colCount === 0;\n\n    if (isFirst) {\n      this._items = [...this.container.querySelectorAll(\".timeline-item\")];\n    }\n\n    // Sort newest-first by tweet ID (snowflake IDs exceed Number precision, compare as strings).\n    this._items.sort((a, b) => {\n      const idA = getTweetId(a), idB = getTweetId(b);\n      if (idA.length !== idB.length) return idB.length - idA.length;\n      return idB < idA ? -1 : idB > idA ? 1 : 0;\n    });\n\n    // Pre-set widths BEFORE reading heights so measurements reflect the new column width.\n    const colWidth = this._colWidthCache = Math.floor((w - GAP * (n - 1)) / n);\n    for (const item of this._items) item.style.width = `${colWidth}px`;\n\n    this._place(this._items, this._items.map(item => item.offsetHeight), n, colWidth);\n    this._lastWidth = w;\n\n    if (isFirst) {\n      if (this._observer) this._items.forEach(item => this._observer.observe(item));\n      // Reveal immediately if all images are cached, else wait for syncHeights.\n      const hasUnloaded = this._items.some(item =>\n        [...item.querySelectorAll(\"img\")].some(img => !img.complete));\n      if (hasUnloaded) {\n        this._revealTimer = setTimeout(() => this._revealAll(), 1000);\n      } else {\n        this._revealAll();\n      }\n    }\n  }\n\n  // Re-read actual heights and re-place all items. Fixes drift after images load.\n  syncHeights() {\n    this._place(this._items, this._items.map(item => item.offsetHeight), this.colCount, this._colWidthCache);\n    this._revealAll();\n  }\n\n  // Batch-add items in three phases to avoid O(N) reflows:\n  //   1. writes: set widths, append all — no reads, no reflows\n  //   2. one read: batch offsetHeight\n  //   3. writes: assign columns, set left/top\n  addAll(newItems) {\n    if (!newItems.length) return;\n    const colWidth = this._colWidthCache;\n\n    for (const item of newItems) {\n      item.style.width = `${colWidth}px`;\n      this.container.appendChild(item);\n    }\n\n    this._position(newItems, newItems.map(item => item.offsetHeight), colWidth);\n    this._items.push(...newItems);\n\n    if (this._observer) newItems.forEach(item => this._observer.observe(item));\n  }\n}\n\ndocument.addEventListener(\"DOMContentLoaded\", function () {\n  const isTweet = location.pathname.includes(\"/status/\");\n  const containerClass = isTweet ? \".replies\" : \".timeline\";\n  const itemClass = containerClass + \" > div:not(.top-ref)\";\n  const html = document.documentElement;\n  const container = document.querySelector(containerClass);\n  const masonryEl = container?.querySelector(\".gallery-masonry\");\n  const masonry = masonryEl ? new Masonry(masonryEl) : null;\n  let loading = false;\n\n  function handleScroll(failed) {\n    if (loading || html.scrollTop + html.clientHeight < html.scrollHeight - 3000) return;\n\n    const loadMore = getLoadMore(document);\n    if (!loadMore) return;\n    loading = true;\n    loadMore.children[0].text = \"Loading...\";\n\n    const url = new URL(loadMore.children[0].href);\n    url.searchParams.append(\"scroll\", \"true\");\n\n    fetch(url)\n      .then(r => {\n        if (r.status > 299) throw new Error(\"error\");\n        return r.text();\n      })\n      .then(responseText => {\n        const doc = new DOMParser().parseFromString(responseText, \"text/html\");\n        loadMore.remove();\n\n        if (masonry) {\n          masonry.syncHeights();\n          const newMasonry = doc.querySelector(\".gallery-masonry\");\n          if (newMasonry) {\n            const knownHrefs = getHrefs(\".gallery-masonry .tweet-link\");\n            masonry.addAll([...newMasonry.querySelectorAll(\".timeline-item\")].filter(item => !isDuplicate(item, knownHrefs)));\n          }\n        } else {\n          const knownHrefs = getHrefs(`${itemClass} .tweet-link`);\n          for (const item of doc.querySelectorAll(itemClass)) {\n            if (item.className === \"timeline-item show-more\" || isDuplicate(item, knownHrefs)) continue;\n            isTweet ? container.appendChild(item) : insertBeforeLast(container, item);\n          }\n        }\n\n        loading = false;\n        const newLoadMore = getLoadMore(doc);\n        if (newLoadMore) {\n          isTweet ? container.appendChild(newLoadMore) : insertBeforeLast(container, newLoadMore);\n          if (masonry) newLoadMore.classList.add(\"masonry-visible\");\n        }\n      })\n      .catch(err => {\n        console.warn(\"Something went wrong.\", err);\n        if (failed > 3) { loadMore.children[0].text = \"Error\"; return; }\n        loading = false;\n        handleScroll((failed || 0) + 1);\n      });\n  }\n\n  window.addEventListener(\"scroll\", () => handleScroll());\n});\n// @license-end\n"
  },
  {
    "path": "public/md/about.md",
    "content": "# About\n\nNitter is a free and open source alternative Twitter front-end focused on\nprivacy and performance. The source is available on GitHub at\n<https://github.com/zedeus/nitter>\n\n- No JavaScript or ads\n- All requests go through the backend, client never talks to Twitter\n- Prevents Twitter from tracking your IP or JavaScript fingerprint\n- Uses Twitter's unofficial API (no developer account required)\n- Lightweight (for [@nim_lang](/nim_lang), 60KB vs 784KB from twitter.com)\n- RSS feeds\n- Themes\n- Mobile support (responsive design)\n- AGPLv3 licensed, no proprietary instances permitted\n\nNitter's GitHub wiki contains\n[instances](https://github.com/zedeus/nitter/wiki/Instances) and\n[browser extensions](https://github.com/zedeus/nitter/wiki/Extensions)\nmaintained by the community.\n\n## Why use Nitter?\n\nIt's impossible to use Twitter without JavaScript enabled, and as of 2024 you\nneed to sign up. For privacy-minded folks, preventing JavaScript analytics and\nIP-based tracking is important, but apart from using a VPN and uBlock/uMatrix,\nit's impossible. Despite being behind a VPN and using heavy-duty adblockers,\nyou can get accurately tracked with your [browser's\nfingerprint](https://restoreprivacy.com/browser-fingerprinting/), [no\nJavaScript required](https://noscriptfingerprint.com/). This all became\nparticularly important after Twitter [removed the\nability](https://www.eff.org/deeplinks/2020/04/twitter-removes-privacy-option-and-shows-why-we-need-strong-privacy-laws)\nfor users to control whether their data gets sent to advertisers.\n\nUsing an instance of Nitter (hosted on a VPS for example), you can browse\nTwitter without JavaScript while retaining your privacy. In addition to\nrespecting your privacy, Nitter is on average around 15 times lighter than\nTwitter, and in most cases serves pages faster (eg. timelines load 2-4x faster).\n\nIn the future a simple account system will be added that lets you follow Twitter\nusers, allowing you to have a clean chronological timeline without needing a\nTwitter account.\n\n## Donating\n\nLiberapay: https://liberapay.com/zedeus \\\nPatreon: https://patreon.com/nitter \\\nBTC: bc1qpqpzjkcpgluhzf7x9yqe7jfe8gpfm5v08mdr55 \\\nETH: 0x24a0DB59A923B588c7A5EBd0dBDFDD1bCe9c4460 \\\nXMR: 42hKayRoEAw4D6G6t8mQHPJHQcXqofjFuVfavqKeNMNUZfeJLJAcNU19i1bGdDvcdN6romiSscWGWJCczFLe9RFhM3d1zpL \\\nSOL: ANsyGNXFo6osuFwr1YnUqif2RdoYRhc27WdyQNmmETSW \\\nZEC: u1vndfqtzyy6qkzhkapxelel7ams38wmfeccu3fdpy2wkuc4erxyjm8ncjhnyg747x6t0kf0faqhh2hxyplgaum08d2wnj4n7cyu9s6zhxkqw2aef4hgd4s6vh5hpqvfken98rg80kgtgn64ff70djy7s8f839z00hwhuzlcggvefhdlyszkvwy3c7yw623vw3rvar6q6evd3xcvveypt\n\n## Contact\n\nFeel free to join our [Matrix channel](https://matrix.to/#/#nitter:matrix.org).\n"
  },
  {
    "path": "public/robots.txt",
    "content": "User-agent: *\nDisallow: /\nCrawl-delay: 1\nUser-agent: Twitterbot\nDisallow:\n"
  },
  {
    "path": "public/site.webmanifest",
    "content": "{\n    \"name\": \"Nitter\",\n    \"short_name\": \"Nitter\",\n    \"icons\": [\n        {\n            \"src\": \"/android-chrome-192x192.png\",\n            \"sizes\": \"192x192\",\n            \"type\": \"image/png\"\n        },\n        {\n            \"src\": \"/android-chrome-384x384.png\",\n            \"sizes\": \"384x384\",\n            \"type\": \"image/png\"\n        },\n        {\n            \"src\": \"/android-chrome-512x512.png\",\n            \"sizes\": \"512x512\",\n            \"type\": \"image/png\"\n        }\n    ],\n    \"theme_color\": \"#333333\",\n    \"background_color\": \"#333333\",\n    \"display\": \"standalone\"\n}\n"
  },
  {
    "path": "src/api.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport asyncdispatch, httpclient, strutils, sequtils, sugar\nimport packedjson\nimport types, query, formatters, consts, apiutils, parser, utils\nimport experimental/parser as newParser\n\n# Helper to generate params object for GraphQL requests\nproc genParams(variables: string; fieldToggles = \"\"): seq[(string, string)] =\n  result.add (\"variables\", variables)\n  result.add (\"features\", gqlFeatures)\n  if fieldToggles.len > 0:\n    result.add (\"fieldToggles\", fieldToggles)\n\nproc apiUrl(endpoint, variables: string; fieldToggles = \"\"): ApiUrl =\n  return ApiUrl(endpoint: endpoint, params: genParams(variables, fieldToggles))\n\nproc apiReq(endpoint, variables: string; fieldToggles = \"\"): ApiReq =\n  let url = apiUrl(endpoint, variables, fieldToggles)\n  return ApiReq(cookie: url, oauth: url)\n\nproc mediaUrl(id, cursor: string; count=20): ApiReq =\n  result = ApiReq(\n    cookie: apiUrl(graphUserMedia, userMediaVars % [id, cursor, $count]),\n    oauth: apiUrl(graphUserMediaV2, restIdVars % [id, cursor, $count])\n  )\n\nproc userTweetsUrl(id: string; cursor: string): ApiReq =\n  result = ApiReq(\n    # cookie: apiUrl(graphUserTweets, userTweetsVars % [id, cursor], userTweetsFieldToggles),\n    oauth: apiUrl(graphUserTweetsV2, restIdVars % [id, cursor, \"20\"])\n  )\n  # might change this in the future pending testing\n  result.cookie = result.oauth\n\nproc userTweetsAndRepliesUrl(id: string; cursor: string): ApiReq =\n  let cookieVars = userTweetsAndRepliesVars % [id, cursor]\n  result = ApiReq(\n    cookie: apiUrl(graphUserTweetsAndReplies, cookieVars, userTweetsFieldToggles),\n    oauth: apiUrl(graphUserTweetsAndRepliesV2, restIdVars % [id, cursor, \"20\"])\n  )\n\nproc tweetDetailUrl(id: string; cursor: string): ApiReq =\n  let cookieVars = tweetDetailVars % [id, cursor]\n  result = ApiReq(\n    # cookie: apiUrl(graphTweetDetail, cookieVars, tweetDetailFieldToggles),\n    cookie: apiUrl(graphTweet, tweetVars % [id, cursor]),\n    oauth: apiUrl(graphTweet, tweetVars % [id, cursor])\n  )\n\nproc userUrl(username: string): ApiReq =\n  let cookieVars = \"\"\"{\"screen_name\":\"$1\",\"withGrokTranslatedBio\":false}\"\"\" % username\n  result = ApiReq(\n    cookie: apiUrl(graphUser, cookieVars, tweetDetailFieldToggles),\n    oauth: apiUrl(graphUserV2, \"\"\"{\"screen_name\": \"$1\"}\"\"\" % username)\n  )\n\nproc getGraphUser*(username: string): Future[User] {.async.} =\n  if username.len == 0: return\n  let js = await fetchRaw(userUrl(username))\n  result = parseGraphUser(js)\n\nproc getGraphUserById*(id: string): Future[User] {.async.} =\n  if id.len == 0 or id.any(c => not c.isDigit): return\n  let\n    url = apiReq(graphUserById, \"\"\"{\"rest_id\": \"$1\"}\"\"\" % id)\n    js = await fetchRaw(url)\n  result = parseGraphUser(js)\n\nproc getGraphUserTweets*(id: string; kind: TimelineKind; after=\"\"): Future[Profile] {.async.} =\n  if id.len == 0: return\n  let\n    cursor = if after.len > 0: \"\\\"cursor\\\":\\\"$1\\\",\" % after else: \"\"\n    url = case kind\n      of TimelineKind.tweets: userTweetsUrl(id, cursor)\n      of TimelineKind.replies: userTweetsAndRepliesUrl(id, cursor)\n      of TimelineKind.media: mediaUrl(id, cursor, 100)\n    js = await fetch(url)\n  result = parseGraphTimeline(js, after)\n\nproc getGraphListTweets*(id: string; after=\"\"): Future[Timeline] {.async.} =\n  if id.len == 0: return\n  let\n    cursor = if after.len > 0: \"\\\"cursor\\\":\\\"$1\\\",\" % after else: \"\"\n    url = apiReq(graphListTweets, restIdVars % [id, cursor, \"20\"])\n    js = await fetch(url)\n  result = parseGraphTimeline(js, after).tweets\n\nproc getGraphListBySlug*(name, list: string): Future[List] {.async.} =\n  let\n    variables = %*{\"screenName\": name, \"listSlug\": list}\n    url = apiReq(graphListBySlug, $variables)\n    js = await fetch(url)\n  result = parseGraphList(js)\n\nproc getGraphList*(id: string): Future[List] {.async.} =\n  let \n    url = apiReq(graphListById, \"\"\"{\"listId\": \"$1\"}\"\"\" % id)\n    js = await fetch(url)\n  result = parseGraphList(js)\n\nproc getGraphListMembers*(list: List; after=\"\"): Future[Result[User]] {.async.} =\n  if list.id.len == 0: return\n  var\n    variables = %*{\n      \"listId\": list.id,\n      \"withBirdwatchPivots\": false,\n      \"withDownvotePerspective\": false,\n      \"withReactionsMetadata\": false,\n      \"withReactionsPerspective\": false\n    }\n  if after.len > 0:\n    variables[\"cursor\"] = % after\n  let \n    url = apiReq(graphListMembers, $variables)\n    js = await fetchRaw(url)\n  result = parseGraphListMembers(js, after)\n\nproc getGraphTweetResult*(id: string): Future[Tweet] {.async.} =\n  if id.len == 0: return\n  let\n    url = apiReq(graphTweetResult, \"\"\"{\"rest_id\": \"$1\"}\"\"\" % id)\n    js = await fetch(url)\n  result = parseGraphTweetResult(js)\n\nproc getGraphTweet(id: string; after=\"\"): Future[Conversation] {.async.} =\n  if id.len == 0: return\n  let\n    cursor = if after.len > 0: \"\\\"cursor\\\":\\\"$1\\\",\" % after else: \"\"\n    js = await fetch(tweetDetailUrl(id, cursor))\n  result = parseGraphConversation(js, id)\n\nproc getReplies*(id, after: string): Future[Result[Chain]] {.async.} =\n  result = (await getGraphTweet(id, after)).replies\n  result.beginning = after.len == 0\n\nproc getTweet*(id: string; after=\"\"): Future[Conversation] {.async.} =\n  result = await getGraphTweet(id)\n  if after.len > 0:\n    result.replies = await getReplies(id, after)\n\nproc getGraphEditHistory*(id: string): Future[EditHistory] {.async.} =\n  if id.len == 0: return\n  let\n    url = apiReq(graphTweetEditHistory, tweetEditHistoryVars % id)\n    js = await fetch(url)\n  result = parseGraphEditHistory(js, id)\n\nproc getGraphTweetSearch*(query: Query; after=\"\"): Future[Timeline] {.async.} =\n  # workaround for #1372\n  let maxId =\n    if not after.startsWith(\"maxid:\"): \"\"\n    else: validateNumber(after[6..^1])\n\n  let q = genQueryParam(query, maxId)\n  if q.len == 0 or q == emptyQuery:\n    return Timeline(query: query, beginning: true)\n\n  var\n    variables = %*{\n      \"rawQuery\": q,\n      \"query_source\": \"typedQuery\",\n      \"count\": 20,\n      \"product\": \"Latest\",\n      \"withDownvotePerspective\": false,\n      \"withReactionsMetadata\": false,\n      \"withReactionsPerspective\": false\n    }\n  if after.len > 0 and maxId.len == 0:\n    variables[\"cursor\"] = % after\n  let\n    url = apiReq(graphSearchTimeline, $variables)\n    js = await fetch(url)\n  result = parseGraphSearch[Tweets](js, after)\n  result.query = query\n\n  # when no more items are available the API just returns the last page in\n  # full. this detects that and clears the page instead.\n  if after.len > 0 and result.bottom.len > 0 and maxId.len == 0 and\n     after[0..<64] == result.bottom[0..<64]:\n    result.content.setLen(0)\n\nproc getGraphUserSearch*(query: Query; after=\"\"): Future[Result[User]] {.async.} =\n  if query.text.len == 0:\n    return Result[User](query: query, beginning: true)\n\n  var\n    variables = %*{\n      \"rawQuery\": query.text,\n      \"query_source\": \"typedQuery\",\n      \"count\": 20,\n      \"product\": \"People\",\n      \"withDownvotePerspective\": false,\n      \"withReactionsMetadata\": false,\n      \"withReactionsPerspective\": false\n    }\n  if after.len > 0:\n    variables[\"cursor\"] = % after\n    result.beginning = false\n\n  let \n    url = apiReq(graphSearchTimeline, $variables)\n    js = await fetch(url)\n  result = parseGraphSearch[User](js, after)\n  result.query = query\n\nproc getPhotoRail*(id: string): Future[PhotoRail] {.async.} =\n  if id.len == 0: return\n  let js = await fetch(mediaUrl(id, \"\", 30))\n  result = parseGraphPhotoRail(js)\n\nproc resolve*(url: string; prefs: Prefs): Future[string] {.async.} =\n  let client = newAsyncHttpClient(maxRedirects=0)\n  try:\n    let resp = await client.request(url, HttpHead)\n    result = resp.headers[\"location\"].replaceUrls(prefs)\n  except:\n    discard\n  finally:\n    client.close()\n"
  },
  {
    "path": "src/apiutils.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport httpclient, asyncdispatch, options, strutils, uri, times, math, tables\nimport jsony, packedjson, zippy, oauth1\nimport types, auth, consts, parserutils, http_pool, tid\nimport experimental/types/common\n\nconst\n  rlRemaining = \"x-rate-limit-remaining\"\n  rlReset = \"x-rate-limit-reset\"\n  rlLimit = \"x-rate-limit-limit\"\n  errorsToSkip = {null, doesntExist, tweetNotFound, timeout, unauthorized, badRequest}\n\nvar \n  pool: HttpPool\n  disableTid: bool\n  apiProxy: string\n\nproc setDisableTid*(disable: bool) =\n  disableTid = disable\n\nproc setApiProxy*(url: string) =\n  apiProxy = \"\"\n  if url.len > 0:\n    apiProxy = url.strip(chars={'/'}) & \"/\"\n    if \"http\" notin apiProxy:\n      apiProxy = \"http://\" & apiProxy\n\nproc toUrl(req: ApiReq; sessionKind: SessionKind): Uri =\n  case sessionKind\n  of oauth:  \n    let o = req.oauth\n    parseUri(\"https://api.x.com/graphql\")   / o.endpoint ? o.params\n  of cookie: \n    let c = req.cookie\n    parseUri(\"https://x.com/i/api/graphql\") / c.endpoint ? c.params\n\nproc getOauthHeader(url, oauthToken, oauthTokenSecret: string): string =\n  let\n    encodedUrl = url.replace(\",\", \"%2C\").replace(\"+\", \"%20\")\n    params = OAuth1Parameters(\n      consumerKey: consumerKey,\n      signatureMethod: \"HMAC-SHA1\",\n      timestamp: $int(round(epochTime())),\n      nonce: \"0\",\n      isIncludeVersionToHeader: true,\n      token: oauthToken\n    )\n    signature = getSignature(HttpGet, encodedUrl, \"\", params, consumerSecret, oauthTokenSecret)\n\n  params.signature = percentEncode(signature)\n\n  return getOauth1RequestHeader(params)[\"authorization\"]\n\nproc getCookieHeader(authToken, ct0: string): string =\n  \"auth_token=\" & authToken & \"; ct0=\" & ct0\n\nproc genHeaders*(session: Session, url: Uri): Future[HttpHeaders] {.async.} =\n  result = newHttpHeaders({\n    \"accept\": \"*/*\",\n    \"accept-encoding\": \"gzip\",\n    \"accept-language\": \"en-US,en;q=0.9\",\n    \"connection\": \"keep-alive\",\n    \"content-type\": \"application/json\",\n    \"origin\": \"https://x.com\",\n    \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36\",\n    \"x-twitter-active-user\": \"yes\",\n    \"x-twitter-client-language\": \"en\",\n    \"priority\": \"u=1, i\"\n  })\n\n  case session.kind\n  of SessionKind.oauth:\n    result[\"authorization\"] = getOauthHeader($url, session.oauthToken, session.oauthSecret)\n  of SessionKind.cookie:\n    result[\"x-twitter-auth-type\"] = \"OAuth2Session\"\n    result[\"x-csrf-token\"] = session.ct0\n    result[\"cookie\"] = getCookieHeader(session.authToken, session.ct0)\n    result[\"sec-ch-ua\"] = \"\"\"\"Google Chrome\";v=\"142\", \"Chromium\";v=\"142\", \"Not A(Brand\";v=\"24\"\"\"\"\n    result[\"sec-ch-ua-mobile\"] = \"?0\"\n    result[\"sec-ch-ua-platform\"] = \"Windows\"\n    result[\"sec-fetch-dest\"] = \"empty\"\n    result[\"sec-fetch-mode\"] = \"cors\"\n    result[\"sec-fetch-site\"] = \"same-site\"\n    if disableTid:\n      result[\"authorization\"] = bearerToken2\n    else:\n      result[\"authorization\"] = bearerToken\n      result[\"x-client-transaction-id\"] = await genTid(url.path)\n\nproc getAndValidateSession*(req: ApiReq): Future[Session] {.async.} =\n  result = await getSession(req)\n  case result.kind\n  of SessionKind.oauth:\n    if result.oauthToken.len == 0:\n      echo \"[sessions] Empty oauth token, session: \", result.pretty\n      raise rateLimitError()\n  of SessionKind.cookie:\n    if result.authToken.len == 0 or result.ct0.len == 0:\n      echo \"[sessions] Empty cookie credentials, session: \", result.pretty\n      raise rateLimitError()\n\ntemplate fetchImpl(result, fetchBody) {.dirty.} =\n  once:\n    pool = HttpPool()\n\n  try:\n    var resp: AsyncResponse\n    pool.use(await genHeaders(session, url)):\n      template getContent =\n        # TODO: this is a temporary simple implementation\n        if apiProxy.len > 0:\n          resp = await c.get(($url).replace(\"https://\", apiProxy))\n        else:\n          resp = await c.get($url)\n        result = await resp.body\n\n      getContent()\n\n      if resp.status == $Http503:\n        badClient = true\n        raise newException(BadClientError, \"Bad client\")\n\n    if resp.headers.hasKey(rlRemaining):\n      let\n        remaining = parseInt(resp.headers[rlRemaining])\n        reset = parseInt(resp.headers[rlReset])\n        limit = parseInt(resp.headers[rlLimit])\n      session.setRateLimit(req, remaining, reset, limit)\n\n    if result.len > 0:\n      if resp.headers.getOrDefault(\"content-encoding\") == \"gzip\":\n        result = uncompress(result, dfGzip)\n\n      if result.startsWith(\"{\\\"errors\"):\n        let errors = result.fromJson(Errors)\n        if errors notin errorsToSkip:\n          echo \"Fetch error, API: \", url.path, \", errors: \", errors\n          if errors in {expiredToken, badToken, locked}:\n            invalidate(session)\n            raise rateLimitError()\n          elif errors in {rateLimited}:\n            # rate limit hit, resets after 24 hours\n            setLimited(session, req)\n            raise rateLimitError()\n      elif result.startsWith(\"429 Too Many Requests\"):\n        echo \"[sessions] 429 error, API: \", url.path, \", session: \", session.pretty\n        raise rateLimitError()\n\n    fetchBody\n\n    if resp.status == $Http400:\n      echo \"ERROR 400, \", url.path, \": \", result\n      raise newException(InternalError, $url)\n  except InternalError as e:\n    raise e\n  except BadClientError as e:\n    raise e\n  except OSError as e:\n    raise e\n  except Exception as e:\n    let s = session.pretty\n    echo \"error: \", e.name, \", msg: \", e.msg, \", session: \", s, \", url: \", url\n    raise rateLimitError()\n  finally:\n    release(session)\n\ntemplate retry(bod) =\n  try:\n    bod\n  except RateLimitError:\n    echo \"[sessions] Rate limited, retrying \", req.cookie.endpoint, \" request...\"\n    bod\n\nproc fetch*(req: ApiReq): Future[JsonNode] {.async.} =\n  retry:\n    var \n      body: string\n      session = await getAndValidateSession(req)\n\n    let url = req.toUrl(session.kind)\n\n    fetchImpl body:\n      if body.startsWith('{') or body.startsWith('['):\n        result = parseJson(body)\n      else:\n        echo resp.status, \": \", body, \" --- url: \", url\n        result = newJNull()\n\n      let error = result.getError\n      if error != null and error notin errorsToSkip:\n        echo \"Fetch error, API: \", url.path, \", error: \", error\n        if error in {expiredToken, badToken, locked}:\n          invalidate(session)\n          raise rateLimitError()\n\nproc fetchRaw*(req: ApiReq): Future[string] {.async.} =\n  retry:\n    var session = await getAndValidateSession(req)\n    let url = req.toUrl(session.kind)\n\n    fetchImpl result:\n      if not (result.startsWith('{') or result.startsWith('[')):\n        echo resp.status, \": \", result, \" --- url: \", url\n        result.setLen(0)\n"
  },
  {
    "path": "src/auth.nim",
    "content": "#SPDX-License-Identifier: AGPL-3.0-only\nimport std/[asyncdispatch, times, json, random, strutils, tables, packedsets, os]\nimport types, consts\nimport experimental/parser/session\n\nconst hourInSeconds = 60 * 60\n\nvar\n  sessionPool: seq[Session]\n  enableLogging = false\n  # max requests at a time per session to avoid race conditions\n  maxConcurrentReqs = 2\n\nproc setMaxConcurrentReqs*(reqs: int) =\n  if reqs > 0:\n    maxConcurrentReqs = reqs\n\ntemplate log(str: varargs[string, `$`]) =\n  echo \"[sessions] \", str.join(\"\")\n\nproc endpoint(req: ApiReq; session: Session): string =\n  case session.kind\n  of oauth: req.oauth.endpoint\n  of cookie: req.cookie.endpoint\n\nproc pretty*(session: Session): string =\n  if session.isNil:\n    return \"<null>\"\n\n  if session.id > 0 and session.username.len > 0:\n    result = $session.id & \" (\" & session.username & \")\"\n  elif session.username.len > 0:\n    result = session.username\n  elif session.id > 0:\n    result = $session.id\n  else:\n    result = \"<unknown>\"\n  result = $session.kind & \" \" & result\n\nproc snowflakeToEpoch(flake: int64): int64 =\n  int64(((flake shr 22) + 1288834974657) div 1000)\n\nproc getSessionPoolHealth*(): JsonNode =\n  let now = epochTime().int\n\n  var\n    totalReqs = 0\n    limited: PackedSet[int64]\n    reqsPerApi: Table[string, int]\n    oldest = now.int64\n    newest = 0'i64\n    average = 0'i64\n\n  for session in sessionPool:\n    let created = snowflakeToEpoch(session.id)\n    if created > newest:\n      newest = created\n    if created < oldest:\n      oldest = created\n    average += created\n\n    if session.limited:\n      limited.incl session.id\n\n    for api in session.apis.keys:\n      let\n        apiStatus = session.apis[api]\n        reqs = apiStatus.limit - apiStatus.remaining\n\n      # no requests made with this session and endpoint since the limit reset\n      if apiStatus.reset < now:\n        continue\n\n      reqsPerApi.mgetOrPut($api, 0).inc reqs\n      totalReqs.inc reqs\n\n  if sessionPool.len > 0:\n    average = average div sessionPool.len\n  else:\n    oldest = 0\n    average = 0\n\n  return %*{\n    \"sessions\": %*{\n      \"total\": sessionPool.len,\n      \"limited\": limited.card,\n      \"oldest\": $fromUnix(oldest),\n      \"newest\": $fromUnix(newest),\n      \"average\": $fromUnix(average)\n    },\n    \"requests\": %*{\n      \"total\": totalReqs,\n      \"apis\": reqsPerApi\n    }\n  }\n\nproc getSessionPoolDebug*(): JsonNode =\n  let now = epochTime().int\n  var list = newJObject()\n\n  for session in sessionPool:\n    let sessionJson = %*{\n      \"apis\": newJObject(),\n      \"pending\": session.pending,\n    }\n\n    if session.limited:\n      sessionJson[\"limited\"] = %true\n\n    for api in session.apis.keys:\n      let\n        apiStatus = session.apis[api]\n        obj = %*{}\n\n      if apiStatus.reset > now.int:\n        obj[\"remaining\"] = %apiStatus.remaining\n        obj[\"reset\"] = %apiStatus.reset\n\n      if \"remaining\" notin obj:\n        continue\n\n      sessionJson{\"apis\", $api} = obj\n      list[$session.id] = sessionJson\n\n  return %list\n\nproc rateLimitError*(): ref RateLimitError =\n  newException(RateLimitError, \"rate limited\")\n\nproc noSessionsError*(): ref NoSessionsError =\n  newException(NoSessionsError, \"no sessions available\")\n\nproc isLimited(session: Session; req: ApiReq): bool =\n  if session.isNil:\n    return true\n\n  let api = req.endpoint(session)\n  if session.limited and api != graphUserTweetsV2:\n    if (epochTime().int - session.limitedAt) > hourInSeconds:\n      session.limited = false\n      log \"resetting limit: \", session.pretty\n      return false\n    else:\n      return true\n\n  if api in session.apis:\n    let limit = session.apis[api]\n    return limit.remaining <= 10 and limit.reset > epochTime().int\n  else:\n    return false\n\nproc isReady(session: Session; req: ApiReq): bool =\n  not (session.isNil or session.pending > maxConcurrentReqs or session.isLimited(req))\n\nproc invalidate*(session: var Session) =\n  if session.isNil: return\n  log \"invalidating: \", session.pretty\n\n  # TODO: This isn't sufficient, but it works for now\n  let idx = sessionPool.find(session)\n  if idx > -1: sessionPool.delete(idx)\n  session = nil\n\nproc release*(session: Session) =\n  if session.isNil: return\n  dec session.pending\n\nproc getSession*(req: ApiReq): Future[Session] {.async.} =\n  for i in 0 ..< sessionPool.len:\n    if result.isReady(req): break\n    result = sessionPool.sample()\n\n  if not result.isNil and result.isReady(req):\n    inc result.pending\n  else:\n    log \"no sessions available for API: \", req.cookie.endpoint\n    raise noSessionsError()\n\nproc setLimited*(session: Session; req: ApiReq) =\n  let api = req.endpoint(session)\n  session.limited = true\n  session.limitedAt = epochTime().int\n  log \"rate limited by api: \", api, \", reqs left: \", session.apis[api].remaining, \", \", session.pretty\n\nproc setRateLimit*(session: Session; req: ApiReq; remaining, reset, limit: int) =\n  # avoid undefined behavior in race conditions\n  let api = req.endpoint(session)\n  if api in session.apis:\n    let rateLimit = session.apis[api]\n    if rateLimit.reset >= reset and rateLimit.remaining < remaining:\n      return\n    if rateLimit.reset == reset and rateLimit.remaining >= remaining:\n      session.apis[api].remaining = remaining\n      return\n\n  session.apis[api] = RateLimit(limit: limit, remaining: remaining, reset: reset)\n\nproc initSessionPool*(cfg: Config; path: string) =\n  enableLogging = cfg.enableDebug\n\n  if path.endsWith(\".json\"):\n    log \"ERROR: .json is not supported, the file must be a valid JSONL file ending in .jsonl\"\n    quit 1\n\n  if not fileExists(path):\n    log \"ERROR: \", path, \" not found. This file is required to authenticate API requests.\"\n    quit 1\n\n  log \"parsing JSONL account sessions file: \", path\n  for line in path.lines:\n    sessionPool.add parseSession(line)\n\n  log \"successfully added \", sessionPool.len, \" valid account sessions\"\n"
  },
  {
    "path": "src/config.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport parsecfg except Config\nimport types, strutils\n\nproc get*[T](config: parseCfg.Config; section, key: string; default: T): T =\n  let val = config.getSectionValue(section, key)\n  if val.len == 0: return default\n\n  when T is int: parseInt(val)\n  elif T is bool: parseBool(val)\n  elif T is string: val\n\nproc getConfig*(path: string): (Config, parseCfg.Config) =\n  var cfg = loadConfig(path)\n\n  let masterRss = cfg.get(\"Config\", \"enableRSS\", true)\n\n  let conf = Config(\n    # Server\n    address: cfg.get(\"Server\", \"address\", \"0.0.0.0\"),\n    port: cfg.get(\"Server\", \"port\", 8080),\n    useHttps: cfg.get(\"Server\", \"https\", true),\n    httpMaxConns: cfg.get(\"Server\", \"httpMaxConnections\", 100),\n    staticDir: cfg.get(\"Server\", \"staticDir\", \"./public\"),\n    title: cfg.get(\"Server\", \"title\", \"Nitter\"),\n    hostname: cfg.get(\"Server\", \"hostname\", \"nitter.net\"),\n\n    # Cache\n    listCacheTime: cfg.get(\"Cache\", \"listMinutes\", 120),\n    rssCacheTime: cfg.get(\"Cache\", \"rssMinutes\", 10),\n\n    redisHost: cfg.get(\"Cache\", \"redisHost\", \"localhost\"),\n    redisPort: cfg.get(\"Cache\", \"redisPort\", 6379),\n    redisConns: cfg.get(\"Cache\", \"redisConnections\", 20),\n    redisMaxConns: cfg.get(\"Cache\", \"redisMaxConnections\", 30),\n    redisPassword: cfg.get(\"Cache\", \"redisPassword\", \"\"),\n\n    # Config\n    hmacKey: cfg.get(\"Config\", \"hmacKey\", \"secretkey\"),\n    base64Media: cfg.get(\"Config\", \"base64Media\", false),\n    minTokens: cfg.get(\"Config\", \"tokenCount\", 10),\n    enableRSSUserTweets: masterRss and cfg.get(\"Config\", \"enableRSSUserTweets\", true),\n    enableRSSUserReplies: masterRss and cfg.get(\"Config\", \"enableRSSUserReplies\", true),\n    enableRSSUserMedia: masterRss and cfg.get(\"Config\", \"enableRSSUserMedia\", true),\n    enableRSSSearch: masterRss and cfg.get(\"Config\", \"enableRSSSearch\", true),\n    enableRSSList: masterRss and cfg.get(\"Config\", \"enableRSSList\", true),\n    enableDebug: cfg.get(\"Config\", \"enableDebug\", false),\n    proxy: cfg.get(\"Config\", \"proxy\", \"\"),\n    proxyAuth: cfg.get(\"Config\", \"proxyAuth\", \"\"),\n    apiProxy: cfg.get(\"Config\", \"apiProxy\", \"\"),\n    disableTid: cfg.get(\"Config\", \"disableTid\", false),\n    maxConcurrentReqs: cfg.get(\"Config\", \"maxConcurrentReqs\", 2)\n  )\n\n  return (conf, cfg)\n"
  },
  {
    "path": "src/consts.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport strutils\n\nconst\n  consumerKey* = \"3nVuSoBZnx6U4vzUxf5w\"\n  consumerSecret* = \"Bcs59EFbbsdF6Sl9Ng71smgStWEGwXXKSjYvPVt7qys\"\n  bearerToken* = \"Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA\"\n  bearerToken2* = \"Bearer AAAAAAAAAAAAAAAAAAAAAFXzAwAAAAAAMHCxpeSDG1gLNLghVe8d74hl6k4%3DRUMF4xAQLsbeBhTSRrCiQpJtxoGWeyHrDb5te2jpGskWDFW82F\"\n\n  graphUser* = \"-oaLodhGbbnzJBACb1kk2Q/UserByScreenName\"\n  graphUserV2* = \"WEoGnYB0EG1yGwamDCF6zg/UserResultByScreenNameQuery\"\n  graphUserById* = \"VN33vKXrPT7p35DgNR27aw/UserResultByIdQuery\"\n  graphUserTweetsV2* = \"6QdSuZ5feXxOadEdXa4XZg/UserWithProfileTweetsQueryV2\"\n  graphUserTweetsAndRepliesV2* = \"BDX77Xzqypdt11-mDfgdpQ/UserWithProfileTweetsAndRepliesQueryV2\"\n  graphUserTweets* = \"oRJs8SLCRNRbQzuZG93_oA/UserTweets\"\n  graphUserTweetsAndReplies* = \"kkaJ0Mf34PZVarrxzLihjg/UserTweetsAndReplies\"\n  graphUserMedia* = \"36oKqyQ7E_9CmtONGjJRsA/UserMedia\"\n  graphUserMediaV2* = \"bp0e_WdXqgNBIwlLukzyYA/MediaTimelineV2\"\n  graphTweet* = \"Y4Erk_-0hObvLpz0Iw3bzA/ConversationTimeline\"\n  graphTweetDetail* = \"YVyS4SfwYW7Uw5qwy0mQCA/TweetDetail\"\n  graphTweetResult* = \"nzme9KiYhfIOrrLrPP_XeQ/TweetResultByIdQuery\"\n  graphTweetEditHistory* = \"upS9teTSG45aljmP9oTuXA/TweetEditHistory\"\n  graphSearchTimeline* = \"bshMIjqDk8LTXTq4w91WKw/SearchTimeline\"\n  graphListById* = \"cIUpT1UjuGgl_oWiY7Snhg/ListByRestId\"\n  graphListBySlug* = \"K6wihoTiTrzNzSF8y1aeKQ/ListBySlug\"\n  graphListMembers* = \"fuVHh5-gFn8zDBBxb8wOMA/ListMembers\"\n  graphListTweets* = \"VQf8_XQynI3WzH6xopOMMQ/ListTimeline\"\n\n  gqlFeatures* = \"\"\"{\n  \"android_ad_formats_media_component_render_overlay_enabled\": false,\n  \"android_graphql_skip_api_media_color_palette\": false,\n  \"android_professional_link_spotlight_display_enabled\": false,\n  \"articles_api_enabled\": false,\n  \"articles_preview_enabled\": true,\n  \"blue_business_profile_image_shape_enabled\": false,\n  \"c9s_tweet_anatomy_moderator_badge_enabled\": true,\n  \"commerce_android_shop_module_enabled\": false,\n  \"communities_web_enable_tweet_community_results_fetch\": true,\n  \"creator_subscriptions_quote_tweet_preview_enabled\": false,\n  \"creator_subscriptions_subscription_count_enabled\": false,\n  \"creator_subscriptions_tweet_preview_api_enabled\": true,\n  \"freedom_of_speech_not_reach_fetch_enabled\": true,\n  \"graphql_is_translatable_rweb_tweet_is_translatable_enabled\": true,\n  \"grok_android_analyze_trend_fetch_enabled\": false,\n  \"grok_translations_community_note_auto_translation_is_enabled\": false,\n  \"grok_translations_community_note_translation_is_enabled\": false,\n  \"grok_translations_post_auto_translation_is_enabled\": false,\n  \"grok_translations_timeline_user_bio_auto_translation_is_enabled\": false,\n  \"hidden_profile_likes_enabled\": false,\n  \"highlights_tweets_tab_ui_enabled\": false,\n  \"immersive_video_status_linkable_timestamps\": false,\n  \"interactive_text_enabled\": false,\n  \"longform_notetweets_consumption_enabled\": true,\n  \"longform_notetweets_inline_media_enabled\": true,\n  \"longform_notetweets_richtext_consumption_enabled\": true,\n  \"longform_notetweets_rich_text_read_enabled\": true,\n  \"mobile_app_spotlight_module_enabled\": false,\n  \"payments_enabled\": false,\n  \"post_ctas_fetch_enabled\": true,\n  \"premium_content_api_read_enabled\": false,\n  \"profile_label_improvements_pcf_label_in_post_enabled\": true,\n  \"profile_label_improvements_pcf_label_in_profile_enabled\": false,\n  \"responsive_web_edit_tweet_api_enabled\": true,\n  \"responsive_web_enhance_cards_enabled\": false,\n  \"responsive_web_graphql_exclude_directive_enabled\": true,\n  \"responsive_web_graphql_skip_user_profile_image_extensions_enabled\": false,\n  \"responsive_web_graphql_timeline_navigation_enabled\": true,\n  \"responsive_web_grok_analysis_button_from_backend\": true,\n  \"responsive_web_grok_analyze_button_fetch_trends_enabled\": false,\n  \"responsive_web_grok_analyze_post_followups_enabled\": true,\n  \"responsive_web_grok_annotations_enabled\": true,\n  \"responsive_web_grok_community_note_auto_translation_is_enabled\": false,\n  \"responsive_web_grok_image_annotation_enabled\": true,\n  \"responsive_web_grok_imagine_annotation_enabled\": true,\n  \"responsive_web_grok_share_attachment_enabled\": true,\n  \"responsive_web_grok_show_grok_translated_post\": false,\n  \"responsive_web_jetfuel_frame\": true,\n  \"responsive_web_media_download_video_enabled\": false,\n  \"responsive_web_profile_redirect_enabled\": false,\n  \"responsive_web_text_conversations_enabled\": false,\n  \"responsive_web_twitter_article_notes_tab_enabled\": false,\n  \"responsive_web_twitter_article_tweet_consumption_enabled\": true,\n  \"responsive_web_twitter_blue_verified_badge_is_enabled\": true,\n  \"rweb_lists_timeline_redesign_enabled\": true,\n  \"rweb_tipjar_consumption_enabled\": true,\n  \"rweb_video_screen_enabled\": false,\n  \"rweb_video_timestamps_enabled\": false,\n  \"spaces_2022_h2_clipping\": true,\n  \"spaces_2022_h2_spaces_communities\": true,\n  \"standardized_nudges_misinfo\": true,\n  \"subscriptions_feature_can_gift_premium\": false,\n  \"subscriptions_verification_info_enabled\": true,\n  \"subscriptions_verification_info_is_identity_verified_enabled\": false,\n  \"subscriptions_verification_info_reason_enabled\": true,\n  \"subscriptions_verification_info_verified_since_enabled\": true,\n  \"super_follow_badge_privacy_enabled\": false,\n  \"super_follow_exclusive_tweet_notifications_enabled\": false,\n  \"super_follow_tweet_api_enabled\": false,\n  \"super_follow_user_api_enabled\": false,\n  \"tweet_awards_web_tipping_enabled\": false,\n  \"tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled\": true,\n  \"tweetypie_unmention_optimization_enabled\": false,\n  \"unified_cards_ad_metadata_container_dynamic_card_content_query_enabled\": false,\n  \"unified_cards_destination_url_params_enabled\": false,\n  \"verified_phone_label_enabled\": false,\n  \"vibe_api_enabled\": false,\n  \"view_counts_everywhere_api_enabled\": true,\n  \"hidden_profile_subscriptions_enabled\": false\n}\"\"\".replace(\" \", \"\").replace(\"\\n\", \"\")\n\n  tweetVars* = \"\"\"{\n  \"postId\": \"$1\",\n  $2\n  \"includeHasBirdwatchNotes\": false,\n  \"includePromotedContent\": false,\n  \"withBirdwatchNotes\": true,\n  \"withVoice\": false,\n  \"withV2Timeline\": true\n}\"\"\".replace(\" \", \"\").replace(\"\\n\", \"\")\n\n  tweetDetailVars* = \"\"\"{\n  \"focalTweetId\": \"$1\",\n  $2\n  \"referrer\": \"profile\",\n  \"with_rux_injections\": false,\n  \"rankingMode\": \"Relevance\",\n  \"includePromotedContent\": true,\n  \"withCommunity\": true,\n  \"withQuickPromoteEligibilityTweetFields\": true,\n  \"withBirdwatchNotes\": true,\n  \"withVoice\": true\n}\"\"\".replace(\" \", \"\").replace(\"\\n\", \"\")\n\n  tweetEditHistoryVars* = \"\"\"{\n  \"tweetId\": \"$1\",\n  \"withQuickPromoteEligibilityTweetFields\": true\n}\"\"\".replace(\" \", \"\").replace(\"\\n\", \"\")\n\n  restIdVars* = \"\"\"{\n  \"rest_id\": \"$1\", $2\n  \"count\": $3\n}\"\"\"\n\n  userMediaVars* = \"\"\"{\n  \"userId\": \"$1\", $2\n  \"count\": $3,\n  \"includePromotedContent\": false,\n  \"withClientEventToken\": false,\n  \"withBirdwatchNotes\": false,\n  \"withVoice\": true\n}\"\"\".replace(\" \", \"\").replace(\"\\n\", \"\")\n\n  userTweetsVars* = \"\"\"{\n  \"userId\": \"$1\", $2\n  \"count\": 20,\n  \"includePromotedContent\": false,\n  \"withQuickPromoteEligibilityTweetFields\": true,\n  \"withVoice\": true\n}\"\"\".replace(\" \", \"\").replace(\"\\n\", \"\")\n\n  userTweetsAndRepliesVars* = \"\"\"{\n  \"userId\": \"$1\", $2\n  \"count\": 20,\n  \"includePromotedContent\": false,\n  \"withCommunity\": true,\n  \"withVoice\": true\n}\"\"\".replace(\" \", \"\").replace(\"\\n\", \"\")\n\n  userFieldToggles = \"\"\"{\"withPayments\":false,\"withAuxiliaryUserLabels\":true}\"\"\"\n  userTweetsFieldToggles* = \"\"\"{\"withArticlePlainText\":false}\"\"\"\n  tweetDetailFieldToggles* = \"\"\"{\"withArticleRichContentState\":true,\"withArticlePlainText\":false,\"withGrokAnalyze\":false,\"withDisallowedReplyControls\":false}\"\"\"\n"
  },
  {
    "path": "src/experimental/parser/graphql.nim",
    "content": "import options, strutils\nimport jsony\nimport user, utils, ../types/[graphuser, graphlistmembers]\nfrom ../../types import User, VerifiedType, Result, Query, QueryKind\n\nproc parseUserResult*(userResult: UserResult): User =\n  result = userResult.legacy\n\n  if result.verifiedType == none and userResult.isBlueVerified:\n    result.verifiedType = blue\n\n  if result.username.len == 0 and userResult.core.screenName.len > 0:\n    result.id = userResult.restId\n    result.username = userResult.core.screenName\n    result.fullname = userResult.core.name\n    result.userPic = userResult.avatar.imageUrl.replace(\"_normal\", \"\")\n\n    if userResult.privacy.isSome:\n      result.protected = userResult.privacy.get.protected\n\n    if userResult.location.isSome:\n      result.location = userResult.location.get.location\n\n    if userResult.core.createdAt.len > 0:\n      result.joinDate = parseTwitterDate(userResult.core.createdAt)\n\n    if userResult.verification.isSome:\n      let v = userResult.verification.get\n      if v.verifiedType != VerifiedType.none:\n        result.verifiedType = v.verifiedType\n\n    if userResult.profileBio.isSome and result.bio.len == 0:\n      result.bio = userResult.profileBio.get.description\n\nproc parseGraphUser*(json: string): User =\n  if json.len == 0 or json[0] != '{':\n    return\n\n  let \n    raw = json.fromJson(GraphUser)\n    userResult = \n      if raw.data.userResult.isSome: raw.data.userResult.get.result\n      elif raw.data.user.isSome: raw.data.user.get.result\n      else: UserResult()\n\n  if userResult.unavailableReason.get(\"\") == \"Suspended\" or\n     userResult.reason.get(\"\") == \"Suspended\":\n    return User(suspended: true)\n\n  result = parseUserResult(userResult)\n\nproc parseGraphListMembers*(json, cursor: string): Result[User] =\n  result = Result[User](\n    beginning: cursor.len == 0,\n    query: Query(kind: userList)\n  )\n\n  let raw = json.fromJson(GraphListMembers)\n  for instruction in raw.data.list.membersTimeline.timeline.instructions:\n    if instruction.kind == \"TimelineAddEntries\":\n      for entry in instruction.entries:\n        case entry.content.entryType\n        of TimelineTimelineItem:\n          let userResult = entry.content.itemContent.userResults.result\n          if userResult.restId.len > 0:\n            result.content.add parseUserResult(userResult)\n        of TimelineTimelineCursor:\n          if entry.content.cursorType == \"Bottom\":\n            result.bottom = entry.content.value\n"
  },
  {
    "path": "src/experimental/parser/session.nim",
    "content": "import std/strutils\nimport jsony\nimport ../types/session\nfrom ../../types import Session, SessionKind\n\nproc parseSession*(raw: string): Session =\n  let session = raw.fromJson(RawSession)\n  let kind = if session.kind == \"\": \"oauth\" else: session.kind\n\n  case kind\n  of \"oauth\":\n    let id = session.oauthToken[0 ..< session.oauthToken.find('-')]\n    result = Session(\n      kind: SessionKind.oauth,\n      id: parseBiggestInt(id),\n      username: session.username,\n      oauthToken: session.oauthToken,\n      oauthSecret: session.oauthTokenSecret\n    )\n  of \"cookie\":\n    let id = if session.id.len > 0: parseBiggestInt(session.id) else: 0\n    result = Session(\n      kind: SessionKind.cookie,\n      id: id,\n      username: session.username,\n      authToken: session.authToken,\n      ct0: session.ct0\n    )\n  else:\n    raise newException(ValueError, \"Unknown session kind: \" & kind)\n"
  },
  {
    "path": "src/experimental/parser/slices.nim",
    "content": "import std/[macros, htmlgen, unicode]\nimport ../types/common\nimport \"..\"/../[formatters, utils]\n\ntype\n  ReplaceSliceKind = enum\n    rkRemove, rkUrl, rkHashtag, rkMention\n\n  ReplaceSlice* = object\n    slice: Slice[int]\n    kind: ReplaceSliceKind\n    url, display: string\n\nproc cmp*(x, y: ReplaceSlice): int = cmp(x.slice.a, y.slice.b)\n\nproc dedupSlices*(s: var seq[ReplaceSlice]) =\n  var\n    len = s.len\n    i = 0\n  while i < len:\n    var j = i + 1\n    while j < len:\n      if s[i].slice.a == s[j].slice.a:\n        s.del j\n        dec len\n      else:\n        inc j\n    inc i\n\nproc extractUrls*(result: var seq[ReplaceSlice]; url: Url;\n                  textLen: int; hideTwitter = false) =\n  let\n    link = url.expandedUrl\n    slice = url.indices[0] ..< url.indices[1]\n\n  if hideTwitter and slice.b.succ >= textLen and link.isTwitterUrl:\n    if slice.a < textLen:\n      result.add ReplaceSlice(kind: rkRemove, slice: slice)\n  else:\n    result.add ReplaceSlice(kind: rkUrl, url: link,\n                            display: link.shortLink, slice: slice)\n\nproc replacedWith*(runes: seq[Rune]; repls: openArray[ReplaceSlice];\n                   textSlice: Slice[int]): string =\n  template extractLowerBound(i: int; idx): int =\n    if i > 0: repls[idx].slice.b.succ else: textSlice.a\n\n  result = newStringOfCap(runes.len)\n\n  for i, rep in repls:\n    result.add $runes[extractLowerBound(i, i - 1) ..< rep.slice.a]\n    case rep.kind\n    of rkHashtag:\n      let\n        name = $runes[rep.slice.a.succ .. rep.slice.b]\n        symbol = $runes[rep.slice.a]\n      result.add a(symbol & name, href = \"/search?f=tweets&q=%23\" & name)\n    of rkMention:\n      result.add a($runes[rep.slice], href = rep.url, title = rep.display)\n    of rkUrl:\n      result.add a(rep.display, href = rep.url)\n    of rkRemove:\n      discard\n\n  let rest = extractLowerBound(repls.len, ^1) ..< textSlice.b\n  if rest.a <= rest.b:\n    result.add $runes[rest]\n"
  },
  {
    "path": "src/experimental/parser/tid.nim",
    "content": "import jsony\nimport ../types/tid\nexport TidPair\n\nproc parseTidPairs*(raw: string): seq[TidPair] =\n  result = raw.fromJson(seq[TidPair])\n  if result.len == 0:\n    raise newException(ValueError, \"Parsing pairs failed: \" & raw)\n"
  },
  {
    "path": "src/experimental/parser/unifiedcard.nim",
    "content": "import std/[options, tables, strutils, strformat, sugar]\nimport jsony\nimport user, ../types/unifiedcard\nimport ../../formatters\nfrom ../../types import Card, CardKind, Video\nfrom ../../utils import twimg, https\n\nproc getImageUrl(entity: MediaEntity): string =\n  entity.mediaUrlHttps.dup(removePrefix(twimg), removePrefix(https))\n\nproc parseDestination(id: string; card: UnifiedCard; result: var Card) =\n  let destination = card.destinationObjects[id].data\n  result.dest = destination.urlData.vanity\n  result.url = destination.urlData.url\n\nproc parseDetails(data: ComponentData; card: UnifiedCard; result: var Card) =\n  data.destination.parseDestination(card, result)\n\n  result.text = data.title\n  if result.text.len == 0:\n    result.text = data.name\n\nproc parseMediaDetails(data: ComponentData; card: UnifiedCard; result: var Card) =\n  data.destination.parseDestination(card, result)\n\n  result.kind = summary\n  result.image = card.mediaEntities[data.mediaId].getImageUrl\n  result.text = data.topicDetail.title\n  result.dest = \"Topic\"\n\nproc parseJobDetails(data: ComponentData; card: UnifiedCard; result: var Card) =\n  data.destination.parseDestination(card, result)\n\n  result.kind = CardKind.jobDetails\n  result.title = data.title\n  result.text = data.shortDescriptionText\n  result.dest = &\"@{data.profileUser.username} · {data.location}\"\n\nproc parseAppDetails(data: ComponentData; card: UnifiedCard; result: var Card) =\n  let app = card.appStoreData[data.appId][0]\n\n  case app.kind\n  of androidApp:\n    result.url = \"http://play.google.com/store/apps/details?id=\" & app.id\n  of iPhoneApp, iPadApp:\n    result.url = \"https://itunes.apple.com/app/id\" & app.id\n\n  result.text = app.title\n  result.dest = app.category\n\nproc parseListDetails(data: ComponentData; result: var Card) =\n  result.dest = &\"List · {data.memberCount} Members\"\n\nproc parseCommunityDetails(data: ComponentData; result: var Card) =\n  result.dest = &\"Community · {data.memberCount} Members\"\n\nproc parseMedia(component: Component; card: UnifiedCard; result: var Card) =\n  let mediaId =\n    if component.kind == swipeableMedia:\n      component.data.mediaList[0].id\n    else:\n      component.data.id\n\n  let rMedia = card.mediaEntities[mediaId]\n  case rMedia.kind:\n  of photo:\n    result.kind = summaryLarge\n    result.image = rMedia.getImageUrl\n  of video:\n    let videoInfo = rMedia.videoInfo.get\n    result.kind = promoVideo\n    result.video = some Video(\n      available: true,\n      thumb: rMedia.getImageUrl,\n      durationMs: videoInfo.durationMillis,\n      variants: videoInfo.variants\n    )\n  of model3d:\n    result.title = \"Unsupported 3D model ad\"\n\nproc parseGrokShare(data: ComponentData; card: UnifiedCard; result: var Card) =\n  result.kind = summaryLarge\n\n  data.destination.parseDestination(card, result)\n  result.dest = \"Answer by Grok\"\n\n  for msg in data.conversationPreview:\n    if msg.sender == \"USER\":\n      result.title = msg.message.shorten(70)\n    elif msg.sender == \"AGENT\":\n      result.text = msg.message.shorten(500)\n\nproc parseUnifiedCard*(json: string): Card =\n  let card = json.fromJson(UnifiedCard)\n\n  for component in card.componentObjects.values:\n    case component.kind\n    of details, communityDetails, twitterListDetails:\n      component.data.parseDetails(card, result)\n    of appStoreDetails:\n      component.data.parseAppDetails(card, result)\n    of mediaWithDetailsHorizontal:\n      component.data.parseMediaDetails(card, result)\n    of media, swipeableMedia:\n      component.parseMedia(card, result)\n    of buttonGroup:\n      discard\n    of grokShare:\n      component.data.parseGrokShare(card, result)\n    of ComponentType.jobDetails:\n      component.data.parseJobDetails(card, result)\n    of ComponentType.hidden:\n      result.kind = CardKind.hidden\n    of ComponentType.unknown:\n      echo \"ERROR: Unknown component type: \", json\n\n    case component.kind\n    of twitterListDetails:\n      component.data.parseListDetails(result)\n    of communityDetails:\n      component.data.parseCommunityDetails(result)\n    else: discard\n"
  },
  {
    "path": "src/experimental/parser/user.nim",
    "content": "import std/[algorithm, unicode, re, strutils, strformat, options, nre]\nimport jsony\nimport utils, slices\nimport ../types/user as userType\nfrom ../../types import Result, User, Error\n\nlet\n  unRegex = re.re\"(^|[^A-z0-9-_./?])@([A-z0-9_]{1,15})\"\n  unReplace = \"$1<a href=\\\"/$2\\\">@$2</a>\"\n\n  htRegex = nre.re\"\"\"(*U)(^|[^\\w-_.?])([#＃$])([\\w_]*+)(?!</a>|\">|#)\"\"\"\n  htReplace = \"$1<a href=\\\"/search?f=tweets&q=%23$3\\\">$2$3</a>\"\n\nproc expandUserEntities(user: var User; raw: RawUser) =\n  let\n    orig = user.bio.toRunes\n    ent = raw.entities\n\n  if ent.url.urls.len > 0:\n    user.website = ent.url.urls[0].expandedUrl\n\n  var replacements = newSeq[ReplaceSlice]()\n\n  for u in ent.description.urls:\n    replacements.extractUrls(u, orig.high)\n\n  replacements.dedupSlices\n  replacements.sort(cmp)\n\n  user.bio = orig.replacedWith(replacements, 0 .. orig.len)\n                 .replacef(unRegex, unReplace)\n                 .replace(htRegex, htReplace)\n\nproc getBanner(user: RawUser): string =\n  if user.profileBannerUrl.len > 0:\n    return user.profileBannerUrl & \"/1500x500\"\n\n  if user.profileLinkColor.len > 0:\n    return '#' & user.profileLinkColor\n\n  if user.profileImageExtensions.isSome:\n    let ext = get(user.profileImageExtensions)\n    if ext.mediaColor.r.ok.palette.len > 0:\n      let color = ext.mediaColor.r.ok.palette[0].rgb\n      return &\"#{color.red:02x}{color.green:02x}{color.blue:02x}\"\n\nproc toUser*(raw: RawUser): User =\n  result = User(\n    id: raw.idStr,\n    username: raw.screenName,\n    fullname: raw.name,\n    location: raw.location,\n    bio: raw.description,\n    following: raw.friendsCount,\n    followers: raw.followersCount,\n    tweets: raw.statusesCount,\n    likes: raw.favouritesCount,\n    media: raw.mediaCount,\n    verifiedType: raw.verifiedType,\n    protected: raw.protected,\n    banner: getBanner(raw),\n    userPic: getImageUrl(raw.profileImageUrlHttps).replace(\"_normal\", \"\")\n  )\n\n  if raw.createdAt.len > 0:\n    result.joinDate = parseTwitterDate(raw.createdAt)\n\n  if raw.pinnedTweetIdsStr.len > 0:\n    result.pinnedTweet = parseBiggestInt(raw.pinnedTweetIdsStr[0])\n\n  result.expandUserEntities(raw)\n\nproc parseHook*(s: string; i: var int; v: var User) =\n  var u: RawUser\n  parseHook(s, i, u)\n  v = toUser u\n"
  },
  {
    "path": "src/experimental/parser/utils.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport std/[sugar, strutils, times]\nimport ../types/common\nimport ../../utils as uutils\n\ntemplate parseTime(time: string; f: static string; flen: int): DateTime =\n  if time.len != flen: return\n  parse(time, f, utc())\n\nproc parseIsoDate*(date: string): DateTime =\n  date.parseTime(\"yyyy-MM-dd\\'T\\'HH:mm:ss\\'Z\\'\", 20)\n\nproc parseTwitterDate*(date: string): DateTime =\n  date.parseTime(\"ddd MMM dd hh:mm:ss \\'+0000\\' yyyy\", 30)\n\nproc getImageUrl*(url: string): string =\n  url.dup(removePrefix(twimg), removePrefix(https))\n\ntemplate handleErrors*(body) =\n  if json.startsWith(\"{\\\"errors\"):\n    for error {.inject.} in json.fromJson(Errors).errors:\n      body\n"
  },
  {
    "path": "src/experimental/parser.nim",
    "content": "import parser/[user, graphql]\nexport user, graphql\n"
  },
  {
    "path": "src/experimental/types/common.nim",
    "content": "from ../../types import Error\n\ntype\n  Url* = object\n    url*: string\n    expandedUrl*: string\n    displayUrl*: string\n    indices*: array[2, int]\n\n  ErrorObj* = object\n    code*: Error\n    message*: string\n\n  Errors* = object\n    errors*: seq[ErrorObj]\n\nproc contains*(codes: set[Error]; errors: Errors): bool =\n  for e in errors.errors:\n    if e.code in codes:\n      return true\n"
  },
  {
    "path": "src/experimental/types/graphlistmembers.nim",
    "content": "import graphuser\n\ntype\n  GraphListMembers* = object\n    data*: tuple[list: List]\n\n  List = object\n    membersTimeline*: tuple[timeline: Timeline]\n\n  Timeline = object\n    instructions*: seq[Instruction]\n\n  Instruction = object\n    kind*: string\n    entries*: seq[tuple[content: Content]]\n\n  ContentEntryType* = enum\n    TimelineTimelineItem\n    TimelineTimelineCursor\n\n  Content = object\n    case entryType*: ContentEntryType\n    of TimelineTimelineItem:\n      itemContent*: tuple[userResults: UserData]\n    of TimelineTimelineCursor:\n      value*: string\n      cursorType*: string\n\nproc renameHook*(v: var Instruction; fieldName: var string) =\n  if fieldName == \"type\":\n    fieldName = \"kind\"\n"
  },
  {
    "path": "src/experimental/types/graphuser.nim",
    "content": "import options, strutils\nfrom ../../types import User, VerifiedType\n\ntype\n  GraphUser* = object\n    data*: tuple[userResult: Option[UserData], user: Option[UserData]]\n\n  UserData* = object\n    result*: UserResult\n\n  UserCore* = object\n    name*: string\n    screenName*: string\n    createdAt*: string\n\n  UserBio* = object\n    description*: string\n\n  UserAvatar* = object\n    imageUrl*: string\n\n  Verification* = object\n    verifiedType*: VerifiedType\n\n  Location* = object\n    location*: string\n\n  Privacy* = object\n    protected*: bool\n\n  UserResult* = object\n    legacy*: User\n    restId*: string\n    isBlueVerified*: bool\n    core*: UserCore\n    avatar*: UserAvatar\n    unavailableReason*: Option[string]\n    reason*: Option[string]\n    privacy*: Option[Privacy]\n    profileBio*: Option[UserBio]\n    verification*: Option[Verification]\n    location*: Option[Location]\n\nproc enumHook*(s: string; v: var VerifiedType) =\n  v = try:\n    parseEnum[VerifiedType](s)\n  except:\n    VerifiedType.none\n"
  },
  {
    "path": "src/experimental/types/session.nim",
    "content": "type\n  RawSession* = object\n    kind*: string\n    id*: string\n    username*: string\n    oauthToken*: string\n    oauthTokenSecret*: string\n    authToken*: string\n    ct0*: string\n"
  },
  {
    "path": "src/experimental/types/tid.nim",
    "content": "type\n  TidPair* = object\n    animationKey*: string\n    verification*: string\n"
  },
  {
    "path": "src/experimental/types/unifiedcard.nim",
    "content": "import std/[options, tables, times]\nimport jsony\nfrom ../../types import VideoType, VideoVariant, User\n\ntype\n  Text* = distinct string\n\n  UnifiedCard* = object\n    componentObjects*: Table[string, Component]\n    destinationObjects*: Table[string, Destination]\n    mediaEntities*: Table[string, MediaEntity]\n    appStoreData*: Table[string, seq[AppStoreData]]\n\n  ComponentType* = enum\n    details\n    media\n    swipeableMedia\n    buttonGroup\n    jobDetails\n    appStoreDetails\n    twitterListDetails\n    communityDetails\n    mediaWithDetailsHorizontal\n    hidden\n    grokShare\n    unknown\n\n  Component* = object\n    kind*: ComponentType\n    data*: ComponentData\n\n  ComponentData* = object\n    id*: string\n    appId*: string\n    mediaId*: string\n    destination*: string\n    location*: string\n    title*: Text\n    subtitle*: Text\n    name*: Text\n    memberCount*: int\n    mediaList*: seq[MediaItem]\n    topicDetail*: tuple[title: Text]\n    profileUser*: User\n    shortDescriptionText*: string\n    conversationPreview*: seq[GrokConversation]\n\n  MediaItem* = object\n    id*: string\n    destination*: string\n\n  Destination* = object\n    kind*: string\n    data*: tuple[urlData: UrlData]\n\n  UrlData* = object\n    url*: string\n    vanity*: string\n\n  MediaType* = enum\n    photo, video, model3d\n\n  MediaEntity* = object\n    kind*: MediaType\n    mediaUrlHttps*: string\n    videoInfo*: Option[VideoInfo]\n\n  VideoInfo* = object\n    durationMillis*: int\n    variants*: seq[VideoVariant]\n\n  AppType* = enum\n    androidApp, iPhoneApp, iPadApp\n\n  AppStoreData* = object\n    kind*: AppType\n    id*: string\n    title*: Text\n    category*: Text\n\n  GrokConversation* = object\n    message*: string\n    sender*: string\n\n  TypeField = Component | Destination | MediaEntity | AppStoreData\n\nconverter fromText*(text: Text): string = string(text)\n\nproc renameHook*(v: var TypeField; fieldName: var string) =\n  if fieldName == \"type\":\n    fieldName = \"kind\"\n\nproc enumHook*(s: string; v: var ComponentType) =\n  v = case s\n      of \"details\": details\n      of \"media\": media\n      of \"swipeable_media\": swipeableMedia\n      of \"button_group\": buttonGroup\n      of \"job_details\": jobDetails\n      of \"app_store_details\": appStoreDetails\n      of \"twitter_list_details\": twitterListDetails\n      of \"community_details\": communityDetails\n      of \"media_with_details_horizontal\": mediaWithDetailsHorizontal\n      of \"commerce_drop_details\": hidden\n      of \"grok_share\": grokShare\n      else: echo \"ERROR: Unknown enum value (ComponentType): \", s; unknown\n\nproc enumHook*(s: string; v: var AppType) =\n  v = case s\n      of \"android_app\": androidApp\n      of \"iphone_app\": iPhoneApp\n      of \"ipad_app\": iPadApp\n      else: echo \"ERROR: Unknown enum value (AppType): \", s; androidApp\n\nproc enumHook*(s: string; v: var MediaType) =\n  v = case s\n      of \"video\": video\n      of \"photo\": photo\n      of \"model3d\": model3d\n      else: echo \"ERROR: Unknown enum value (MediaType): \", s; photo\n\nproc parseHook*(s: string; i: var int; v: var DateTime) =\n  var str: string\n  parseHook(s, i, str)\n  v = parse(str, \"yyyy-MM-dd hh:mm:ss\")\n\nproc parseHook*(s: string; i: var int; v: var Text) =\n  if s[i] == '\"':\n    var str: string\n    parseHook(s, i, str)\n    v = Text(str)\n  else:\n    var t: tuple[content: string]\n    parseHook(s, i, t)\n    v = Text(t.content)\n"
  },
  {
    "path": "src/experimental/types/user.nim",
    "content": "import options\nimport common\nfrom ../../types import VerifiedType\n\ntype\n  RawUser* = object\n    idStr*: string\n    name*: string\n    screenName*: string\n    location*: string\n    description*: string\n    entities*: Entities\n    createdAt*: string\n    followersCount*: int\n    friendsCount*: int\n    favouritesCount*: int\n    statusesCount*: int\n    mediaCount*: int\n    verifiedType*: VerifiedType\n    protected*: bool\n    profileLinkColor*: string\n    profileBannerUrl*: string\n    profileImageUrlHttps*: string\n    profileImageExtensions*: Option[ImageExtensions]\n    pinnedTweetIdsStr*: seq[string]\n\n  Entities* = object\n    url*: Urls\n    description*: Urls\n\n  Urls* = object\n    urls*: seq[Url]\n\n  ImageExtensions = object\n    mediaColor*: tuple[r: Ok]\n\n  Ok = object\n    ok*: Palette\n\n  Palette = object\n    palette*: seq[tuple[rgb: Color]]\n\n  Color* = object\n    red*, green*, blue*: int\n"
  },
  {
    "path": "src/formatters.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport strutils, strformat, times, uri, tables, xmltree, htmlparser, htmlgen, math\nimport std/[enumerate, re]\nimport types, utils, query\n\nconst\n  cards = \"cards.twitter.com/cards\"\n  tco = \"https://t.co\"\n  twitter = parseUri(\"https://x.com\")\n\nlet\n  twRegex = re\"(?<=(?<!\\S)https:\\/\\/|(?<=\\s))(www\\.|mobile\\.)?twitter\\.com\"\n  twLinkRegex = re\"\"\"<a href=\"https:\\/\\/twitter.com([^\"]+)\">twitter\\.com(\\S+)</a>\"\"\"\n  xRegex = re\"(?<=(?<!\\S)https:\\/\\/|(?<=\\s))(www\\.|mobile\\.)?x\\.com\"\n  xLinkRegex = re\"\"\"<a href=\"https:\\/\\/x.com([^\"]+)\">x\\.com(\\S+)</a>\"\"\"\n\n  ytRegex = re(r\"([A-z.]+\\.)?youtu(be\\.com|\\.be)\", {reStudy, reIgnoreCase})\n\n  rdRegex = re\"(?<![.b])((www|np|new|amp|old)\\.)?reddit.com\"\n  rdShortRegex = re\"(?<![.b])redd\\.it\\/\"\n  # Videos cannot be supported uniformly between Teddit and Libreddit,\n  # so v.redd.it links will not be replaced.\n  # Images aren't supported due to errors from Teddit when the image\n  # wasn't first displayed via a post on the Teddit instance.\n\n  wwwRegex = re\"https?://(www[0-9]?\\.)?\"\n  m3u8Regex = re\"\"\"url=\"(.+.m3u8)\"\"\"\"\n  userPicRegex = re\"_(normal|bigger|mini|200x200|400x400)(\\.[A-z]+)$\"\n  extRegex = re\"(\\.[A-z]+)$\"\n  illegalXmlRegex = re\"(*UTF8)[^\\x09\\x0A\\x0D\\x20-\\x{D7FF}\\x{E000}-\\x{FFFD}\\x{10000}-\\x{10FFFF}]\"\n\nproc getUrlPrefix*(cfg: Config): string =\n  if cfg.useHttps: https & cfg.hostname\n  else: \"http://\" & cfg.hostname\n\nproc shorten*(text: string; length=28): string =\n  result = text\n  if result.len > length:\n    result = result[0 ..< length] & \"…\"\n\nproc shortLink*(text: string; length=28): string =\n  result = text.replace(wwwRegex, \"\").shorten(length)\n    \nproc stripHtml*(text: string; shorten=false): string =\n  var html = parseHtml(text)\n  for el in html.findAll(\"a\"):\n    let link = el.attr(\"href\")\n    if \"http\" in link:\n      if el.len == 0: continue\n      el[0].text =\n        if shorten: link.shortLink\n        else: link\n  html.innerText()\n\nproc sanitizeXml*(text: string): string =\n  text.replace(illegalXmlRegex, \"\")\n\nproc replaceUrls*(body: string; prefs: Prefs; absolute=\"\"): string =\n  result = body\n\n  if prefs.replaceYouTube.len > 0 and \"youtu\" in result:\n    let youtubeHost = strip(prefs.replaceYouTube, chars={'/'})\n    result = result.replace(ytRegex, youtubeHost)\n\n  if prefs.replaceTwitter.len > 0:\n    let twitterHost = strip(prefs.replaceTwitter, chars={'/'})\n    if tco in result:\n      result = result.replace(tco, https & twitterHost & \"/t.co\")\n    if \"x.com\" in result:\n      result = result.replace(xRegex, twitterHost)\n      result = result.replacef(xLinkRegex, a(\n        twitterHost & \"$2\", href = https & twitterHost & \"$1\"))\n    if \"twitter.com\" in result:\n      result = result.replace(cards, twitterHost & \"/cards\")\n      result = result.replace(twRegex, twitterHost)\n      result = result.replacef(twLinkRegex, a(\n        twitterHost & \"$2\", href = https & twitterHost & \"$1\"))\n\n  if prefs.replaceReddit.len > 0 and (\"reddit.com\" in result or \"redd.it\" in result):\n    let redditHost = strip(prefs.replaceReddit, chars={'/'})\n    result = result.replace(rdShortRegex, redditHost & \"/comments/\")\n    result = result.replace(rdRegex, redditHost)\n    if redditHost in result and \"/gallery/\" in result:\n      result = result.replace(\"/gallery/\", \"/comments/\")\n\n  if absolute.len > 0 and \"href\" in result:\n    result = result.replace(\"href=\\\"/\", &\"href=\\\"{absolute}/\")\n\nproc getM3u8Url*(content: string): string =\n  var matches: array[1, string]\n  if re.find(content, m3u8Regex, matches) != -1:\n    result = matches[0]\n\nproc proxifyVideo*(manifest: string; proxy: bool): string =\n  var replacements: seq[(string, string)]\n  for line in manifest.splitLines:\n    let url =\n      if line.startsWith(\"#EXT-X-MAP:URI\"): line[16 .. ^2]\n      elif line.startsWith(\"#EXT-X-MEDIA\") and \"URI=\" in line:\n        line[line.find(\"URI=\") + 5 .. -1 + line.find(\"\\\"\", start= 5 + line.find(\"URI=\"))]\n      else: line\n    if url.startsWith('/'):\n      let path = \"https://video.twimg.com\" & url\n      replacements.add (url, if proxy: path.getVidUrl else: path)\n  return manifest.multiReplace(replacements)\n\nproc getUserPic*(userPic: string; style=\"\"): string =\n  userPic.replacef(userPicRegex, \"$2\").replacef(extRegex, style & \"$1\")\n\nproc getUserPic*(user: User; style=\"\"): string =\n  getUserPic(user.userPic, style)\n\nproc getVideoEmbed*(cfg: Config; id: int64): string =\n  &\"{getUrlPrefix(cfg)}/i/videos/{id}\"\n\nproc pageTitle*(user: User): string =\n  &\"{user.fullname} (@{user.username})\"\n\nproc pageTitle*(tweet: Tweet): string =\n  &\"{pageTitle(tweet.user)}: \\\"{stripHtml(tweet.text)}\\\"\"\n\nproc pageDesc*(user: User): string =\n  if user.bio.len > 0:\n    stripHtml(user.bio)\n  else:\n    \"The latest tweets from \" & user.fullname\n\nproc getJoinDate*(user: User): string =\n  user.joinDate.format(\"'Joined' MMMM YYYY\")\n\nproc getJoinDateFull*(user: User): string =\n  user.joinDate.format(\"h:mm tt - d MMM YYYY\")\n\nproc getTime*(tweet: Tweet): string =\n  tweet.time.format(\"MMM d', 'YYYY' · 'h:mm tt' UTC'\")\n\nproc getRfc822Time*(tweet: Tweet): string =\n  tweet.time.format(\"ddd', 'dd MMM yyyy HH:mm:ss 'GMT'\")\n\nproc getShortTime*(tweet: Tweet): string =\n  let now = now()\n  let since = now - tweet.time\n\n  if now.year != tweet.time.year:\n    result = tweet.time.format(\"d MMM yyyy\")\n  elif since.inDays >= 1:\n    result = tweet.time.format(\"MMM d\")\n  elif since.inHours >= 1:\n    result = $since.inHours & \"h\"\n  elif since.inMinutes >= 1:\n    result = $since.inMinutes & \"m\"\n  elif since.inSeconds > 1:\n    result = $since.inSeconds & \"s\"\n  else:\n    result = \"now\"\n\nproc getDuration*(video: Video): string =\n  let \n    ms = video.durationMs\n    sec = int(round(ms / 1000))\n    min = floorDiv(sec, 60)\n    hour = floorDiv(min, 60)\n  if hour > 0:\n    return &\"{hour}:{min mod 60}:{sec mod 60:02}\"\n  else:\n    return &\"{min mod 60}:{sec mod 60:02}\"\n\nproc getLink*(id: int64; username=\"i\"; focus=true): string =\n  var username = username\n  if username.len == 0:\n    username = \"i\"\n  result = &\"/{username}/status/{id}\"\n  if focus: result &= \"#m\"\n\nproc getLink*(tweet: Tweet; focus=true): string =\n  if tweet.id == 0: return\n  var username = tweet.user.username\n  return getLink(tweet.id, username, focus)\n\nproc getTwitterLink*(path: string; params: Table[string, string]): string =\n  var\n    username = params.getOrDefault(\"name\")\n    query = initQuery(params, username)\n    path = path\n\n  if \",\" in username:\n    query.fromUser = username.split(\",\")\n    path = \"/search\"\n\n  if \"/search\" notin path and query.fromUser.len < 2:\n    return $(twitter / path)\n\n  let p = {\n    \"f\": if query.kind == users: \"user\" else: \"live\",\n    \"q\": genQueryParam(query),\n    \"src\": \"typed_query\"\n  }\n\n  result = $(twitter / path ? p)\n  if username.len > 0:\n    result = result.replace(\"/\" & username, \"\")\n\nproc getLocation*(u: User | Tweet): (string, string) =\n  if \"://\" in u.location: return (u.location, \"\")\n  let loc = u.location.split(\":\")\n  let url = if loc.len > 1: \"/search?f=tweets&q=place:\" & loc[1] else: \"\"\n  (loc[0], url)\n\nproc getSuspended*(username: string): string =\n  &\"User \\\"{username}\\\" has been suspended\"\n\nproc titleize*(str: string): string =\n  const\n    lowercase = {'a'..'z'}\n    delims = {' ', '('}\n\n  result = str\n  for i, c in enumerate(str):\n    if c in lowercase and (i == 0 or str[i - 1] in delims):\n      result[i] = c.toUpperAscii\n"
  },
  {
    "path": "src/http_pool.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport httpclient\n\ntype\n  HttpPool* = ref object\n    conns*: seq[AsyncHttpClient]\n\nvar\n  maxConns: int\n  proxy: Proxy\n\nproc setMaxHttpConns*(n: int) =\n  maxConns = n\n\nproc setHttpProxy*(url: string; auth: string) =\n  if url.len > 0:\n    proxy = newProxy(url, auth)\n  else:\n    proxy = nil\n\nproc release*(pool: HttpPool; client: AsyncHttpClient; badClient=false) =\n  if pool.conns.len >= maxConns or badClient:\n    try: client.close()\n    except: discard\n  elif client != nil:\n    pool.conns.insert(client)\n\nproc acquire*(pool: HttpPool; heads: HttpHeaders): AsyncHttpClient =\n  if pool.conns.len == 0:\n    result = newAsyncHttpClient(headers=heads, proxy=proxy)\n  else:\n    result = pool.conns.pop()\n    result.headers = heads\n\ntemplate use*(pool: HttpPool; heads: HttpHeaders; body: untyped): untyped =\n  var\n    c {.inject.} = pool.acquire(heads)\n    badClient {.inject.} = false\n\n  try:\n    body\n  except BadClientError, ProtocolError:\n    # Twitter returned 503 or closed the connection, we need a new client\n    pool.release(c, true)\n    badClient = false\n    c = pool.acquire(heads)\n    body\n  finally:\n    pool.release(c, badClient)\n"
  },
  {
    "path": "src/nitter.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport asyncdispatch, strformat, logging\nfrom net import Port\nfrom htmlgen import a\nfrom os import getEnv\n\nimport jester\n\nimport types, config, prefs, formatters, redis_cache, http_pool, auth, apiutils\nimport views/[general, about]\nimport routes/[\n  preferences, timeline, status, media, search, rss, list, debug,\n  unsupported, embed, resolver, router_utils]\n\nconst instancesUrl = \"https://github.com/zedeus/nitter/wiki/Instances\"\nconst issuesUrl = \"https://github.com/zedeus/nitter/issues\"\n\nlet\n  configPath = getEnv(\"NITTER_CONF_FILE\", \"./nitter.conf\")\n  (cfg, fullCfg) = getConfig(configPath)\n\n  sessionsPath = getEnv(\"NITTER_SESSIONS_FILE\", \"./sessions.jsonl\")\n\ninitSessionPool(cfg, sessionsPath)\n\nif not cfg.enableDebug:\n  # Silence Jester's query warning\n  addHandler(newConsoleLogger())\n  setLogFilter(lvlError)\n\nstdout.write &\"Starting Nitter at {getUrlPrefix(cfg)}\\n\"\nstdout.flushFile\n\nupdateDefaultPrefs(fullCfg)\nsetCacheTimes(cfg)\nsetHmacKey(cfg.hmacKey)\nsetProxyEncoding(cfg.base64Media)\nsetMaxHttpConns(cfg.httpMaxConns)\nsetHttpProxy(cfg.proxy, cfg.proxyAuth)\nsetApiProxy(cfg.apiProxy)\nsetDisableTid(cfg.disableTid)\nsetMaxConcurrentReqs(cfg.maxConcurrentReqs)\ninitAboutPage(cfg.staticDir)\n\nwaitFor initRedisPool(cfg)\nstdout.write &\"Connected to Redis at {cfg.redisHost}:{cfg.redisPort}\\n\"\nstdout.flushFile\n\ncreateUnsupportedRouter(cfg)\ncreateResolverRouter(cfg)\ncreatePrefRouter(cfg)\ncreateTimelineRouter(cfg)\ncreateListRouter(cfg)\ncreateStatusRouter(cfg)\ncreateSearchRouter(cfg)\ncreateMediaRouter(cfg)\ncreateEmbedRouter(cfg)\ncreateRssRouter(cfg)\ncreateDebugRouter(cfg)\n\nsettings:\n  port = Port(cfg.port)\n  staticDir = cfg.staticDir\n  bindAddr = cfg.address\n  reusePort = true\n\nroutes:\n  before:\n    # skip all file URLs\n    cond \".\" notin request.path\n    applyUrlPrefs()\n\n  get \"/\":\n    resp renderMain(renderSearch(), request, cfg, requestPrefs())\n\n  get \"/about\":\n    resp renderMain(renderAbout(), request, cfg, requestPrefs())\n\n  get \"/explore\":\n    redirect(\"/about\")\n\n  get \"/help\":\n    redirect(\"/about\")\n\n  get \"/i/redirect\":\n    let url = decodeUrl(@\"url\")\n    if url.len == 0: resp Http404\n    redirect(replaceUrls(url, requestPrefs()))\n\n  error Http404:\n    resp Http404, showError(\"Page not found\", cfg)\n\n  error InternalError:\n    echo error.exc.name, \": \", error.exc.msg\n    const link = a(\"open a GitHub issue\", href = issuesUrl)\n    resp Http500, showError(\n      &\"An error occurred, please {link} with the URL you tried to visit.\", cfg)\n\n  error BadClientError:\n    echo error.exc.name, \": \", error.exc.msg\n    resp Http500, showError(\"Network error occurred, please try again.\", cfg)\n\n  error RateLimitError:\n    const link = a(\"another instance\", href = instancesUrl)\n    resp Http429, showError(\n      &\"Instance has been rate limited.<br>Use {link} or try again later.\", cfg)\n\n  error NoSessionsError:\n    const link = a(\"another instance\", href = instancesUrl)\n    resp Http429, showError(\n      &\"Instance has no auth tokens, or is fully rate limited.<br>Use {link} or try again later.\", cfg)\n\n  extend rss, \"\"\n  extend status, \"\"\n  extend search, \"\"\n  extend timeline, \"\"\n  extend media, \"\"\n  extend list, \"\"\n  extend preferences, \"\"\n  extend resolver, \"\"\n  extend embed, \"\"\n  extend debug, \"\"\n  extend unsupported, \"\"\n"
  },
  {
    "path": "src/parser.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport strutils, options, times, math, tables\nimport packedjson, packedjson/deserialiser\nimport types, parserutils, utils\nimport experimental/parser/unifiedcard\n\nproc parseGraphTweet(js: JsonNode): Tweet\n\nproc parseCommunityNote(js: JsonNode): string =\n  let subtitle = js{\"subtitle\"}\n  result = subtitle{\"text\"}.getStr\n  with entities, subtitle{\"entities\"}:\n    result = expandBirdwatchEntities(result, entities)\n\nproc parseUser(js: JsonNode; id=\"\"): User =\n  if js.isNull: return\n  result = User(\n    id: if id.len > 0: id else: js{\"id_str\"}.getStr,\n    username: js{\"screen_name\"}.getStr,\n    fullname: js{\"name\"}.getStr,\n    location: js{\"location\"}.getStr,\n    bio: js{\"description\"}.getStr,\n    userPic: js{\"profile_image_url_https\"}.getImageStr.replace(\"_normal\", \"\"),\n    banner: js.getBanner,\n    following: js{\"friends_count\"}.getInt,\n    followers: js{\"followers_count\"}.getInt,\n    tweets: js{\"statuses_count\"}.getInt,\n    likes: js{\"favourites_count\"}.getInt,\n    media: js{\"media_count\"}.getInt,\n    protected: js{\"protected\"}.getBool(js{\"privacy\", \"protected\"}.getBool),\n    joinDate: js{\"created_at\"}.getTime\n  )\n\n  if js{\"is_blue_verified\"}.getBool(false):\n    result.verifiedType = blue\n\n  with verifiedType, js{\"verified_type\"}:\n    result.verifiedType = parseEnum[VerifiedType](verifiedType.getStr)\n\n  result.expandUserEntities(js)\n\nproc parseGraphUser(js: JsonNode): User =\n  var user = js{\"user_result\", \"result\"}\n  if user.isNull:\n    user = ? js{\"user_results\", \"result\"}\n\n  if user.isNull:\n    if js{\"core\"}.notNull and js{\"legacy\"}.notNull:\n      user = js\n    else:\n      return\n\n  result = parseUser(user{\"legacy\"}, user{\"rest_id\"}.getStr)\n\n  if result.verifiedType == none and user{\"is_blue_verified\"}.getBool(false):\n    result.verifiedType = blue\n\n  # fallback to support UserMedia/recent GraphQL updates\n  if result.username.len == 0:\n    result.username = user{\"core\", \"screen_name\"}.getStr\n    result.fullname = user{\"core\", \"name\"}.getStr\n    result.userPic = user{\"avatar\", \"image_url\"}.getImageStr.replace(\"_normal\", \"\")\n\n    if user{\"is_blue_verified\"}.getBool(false):\n      result.verifiedType = blue\n\n    with verifiedType, user{\"verification\", \"verified_type\"}:\n      result.verifiedType = parseEnum[VerifiedType](verifiedType.getStr)\n\nproc parseGraphList*(js: JsonNode): List =\n  if js.isNull: return\n\n  var list = js{\"data\", \"user_by_screen_name\", \"list\"}\n  if list.isNull:\n    list = js{\"data\", \"list\"}\n  if list.isNull:\n    return\n\n  result = List(\n    id: list{\"id_str\"}.getStr,\n    name: list{\"name\"}.getStr,\n    username: list{\"user_results\", \"result\", \"legacy\", \"screen_name\"}.getStr,\n    userId: list{\"user_results\", \"result\", \"rest_id\"}.getStr,\n    description: list{\"description\"}.getStr,\n    members: list{\"member_count\"}.getInt,\n    banner: list{\"custom_banner_media\", \"media_info\", \"original_img_url\"}.getImageStr\n  )\n\nproc parsePoll(js: JsonNode): Poll =\n  let vals = js{\"binding_values\"}\n  # name format is pollNchoice_*\n  for i in '1' .. js{\"name\"}.getStr[4]:\n    let choice = \"choice\" & i\n    result.values.add parseInt(vals{choice & \"_count\"}.getStrVal(\"0\"))\n    result.options.add vals{choice & \"_label\"}.getStrVal\n\n  let time = vals{\"end_datetime_utc\", \"string_value\"}.getDateTime\n  if time > now():\n    let timeLeft = $(time - now())\n    result.status = timeLeft[0 ..< timeLeft.find(\",\")]\n  else:\n    result.status = \"Final results\"\n\n  result.leader = result.values.find(max(result.values))\n  result.votes = result.values.sum\n\nproc parseVideoVariants(variants: JsonNode): seq[VideoVariant] =\n  result = @[]\n  for v in variants:\n    let\n      url = v{\"url\"}.getStr\n      contentType = parseEnum[VideoType](v{\"content_type\"}.getStr(\"video/mp4\"))\n      bitrate = v{\"bit_rate\"}.getInt(v{\"bitrate\"}.getInt(0))\n\n    result.add VideoVariant(\n      contentType: contentType,\n      bitrate: bitrate,\n      url: url,\n      resolution: if contentType == mp4: getMp4Resolution(url) else: 0\n    )\n\nproc parseVideo(js: JsonNode): Video =\n  result = Video(\n    thumb: js{\"media_url_https\"}.getImageStr,\n    available: true,\n    title: js{\"ext_alt_text\"}.getStr,\n    durationMs: js{\"video_info\", \"duration_millis\"}.getInt\n    # playbackType: mp4\n  )\n\n  with status, js{\"ext_media_availability\", \"status\"}:\n    if status.getStr.len > 0 and status.getStr.toLowerAscii != \"available\":\n      result.available = false\n\n  with title, js{\"additional_media_info\", \"title\"}:\n    result.title = title.getStr\n\n  with description, js{\"additional_media_info\", \"description\"}:\n    result.description = description.getStr\n\n  result.variants = parseVideoVariants(js{\"video_info\", \"variants\"})\n\nproc addMedia(media: var MediaEntities; photo: Photo) =\n  media.add Media(kind: photoMedia, photo: photo)\n\nproc addMedia(media: var MediaEntities; video: Video) =\n  media.add Media(kind: videoMedia, video: video)\n\nproc addMedia(media: var MediaEntities; gif: Gif) =\n  media.add Media(kind: gifMedia, gif: gif)\n\nproc parseLegacyMediaEntities(js: JsonNode; result: var Tweet) =\n  with jsMedia, js{\"extended_entities\", \"media\"}:\n    for m in jsMedia:\n      case m.getTypeName:\n      of \"photo\":\n        result.media.addMedia(Photo(\n          url: m{\"media_url_https\"}.getImageStr,\n          altText: m{\"ext_alt_text\"}.getStr\n        ))\n      of \"video\":\n        result.media.addMedia(parseVideo(m))\n        with user, m{\"additional_media_info\", \"source_user\"}:\n          if user{\"id\"}.getInt > 0:\n            result.attribution = some(parseUser(user))\n          else:\n            result.attribution = some(parseGraphUser(user))\n      of \"animated_gif\":\n        result.media.addMedia(Gif(\n          url: m{\"video_info\", \"variants\"}[0]{\"url\"}.getImageStr,\n          thumb: m{\"media_url_https\"}.getImageStr,\n          altText: m{\"ext_alt_text\"}.getStr\n        ))\n      else: discard\n\n      with url, m{\"url\"}:\n        if result.text.endsWith(url.getStr):\n          result.text.removeSuffix(url.getStr)\n          result.text = result.text.strip()\n\nproc parseMediaEntities(js: JsonNode; result: var Tweet) =\n  with mediaEntities, js{\"media_entities\"}:\n    var parsedMedia: MediaEntities\n    for mediaEntity in mediaEntities:\n      with mediaInfo, mediaEntity{\"media_results\", \"result\", \"media_info\"}:\n        case mediaInfo.getTypeName\n        of \"ApiImage\":\n          parsedMedia.addMedia(Photo(\n            url: mediaInfo{\"original_img_url\"}.getImageStr,\n            altText: mediaInfo{\"alt_text\"}.getStr\n          ))\n        of \"ApiVideo\":\n          let status = mediaEntity{\"media_results\", \"result\", \"media_availability_v2\", \"status\"}\n          parsedMedia.addMedia(Video(\n            available: status.getStr == \"Available\",\n            thumb: mediaInfo{\"preview_image\", \"original_img_url\"}.getImageStr,\n            title: mediaInfo{\"alt_text\"}.getStr,\n            durationMs: mediaInfo{\"duration_millis\"}.getInt,\n            variants: parseVideoVariants(mediaInfo{\"variants\"})\n          ))\n        of \"ApiGif\":\n          parsedMedia.addMedia(Gif(\n            url: mediaInfo{\"variants\"}[0]{\"url\"}.getImageStr,\n            thumb: mediaInfo{\"preview_image\", \"original_img_url\"}.getImageStr,\n            altText: mediaInfo{\"alt_text\"}.getStr\n          ))\n        else: discard\n\n    if mediaEntities.len > 0 and parsedMedia.len == mediaEntities.len:\n      result.media = parsedMedia\n\n  # Remove media URLs from text\n  with mediaList, js{\"legacy\", \"entities\", \"media\"}:\n    for url in mediaList:\n      let expandedUrl = url.getExpandedUrl\n      if result.text.endsWith(expandedUrl):\n        result.text.removeSuffix(expandedUrl)\n        result.text = result.text.strip()\n\nproc parsePromoVideo(js: JsonNode): Video =\n  result = Video(\n    thumb: js{\"player_image_large\"}.getImageVal,\n    available: true,\n    durationMs: js{\"content_duration_seconds\"}.getStrVal(\"0\").parseInt * 1000,\n    playbackType: vmap\n  )\n\n  var variant = VideoVariant(\n    contentType: vmap,\n    url: js{\"player_hls_url\"}.getStrVal(js{\"player_stream_url\"}.getStrVal(\n        js{\"amplify_url_vmap\"}.getStrVal()))\n  )\n\n  if \"m3u8\" in variant.url:\n    variant.contentType = m3u8\n    result.playbackType = m3u8\n\n  result.variants.add variant\n\nproc parseBroadcast(js: JsonNode): Card =\n  let image = js{\"broadcast_thumbnail_large\"}.getImageVal\n  result = Card(\n    kind: broadcast,\n    url: js{\"broadcast_url\"}.getStrVal,\n    title: js{\"broadcaster_display_name\"}.getStrVal,\n    text: js{\"broadcast_title\"}.getStrVal,\n    image: image,\n    video: some Video(thumb: image)\n  )\n\nproc parseCard(js: JsonNode; urls: JsonNode): Card =\n  const imageTypes = [\"summary_photo_image\", \"player_image\", \"promo_image\",\n                      \"photo_image_full_size\", \"thumbnail_image\", \"thumbnail\",\n                      \"event_thumbnail\", \"image\"]\n  let\n    vals = ? js{\"binding_values\"}\n    name = js{\"name\"}.getStr\n    kind = parseEnum[CardKind](name[(name.find(\":\") + 1) ..< name.len], unknown)\n\n  if kind == unified:\n    return parseUnifiedCard(vals{\"unified_card\", \"string_value\"}.getStr)\n\n  result = Card(\n    kind: kind,\n    url: vals.getCardUrl(kind),\n    dest: vals.getCardDomain(kind),\n    title: vals.getCardTitle(kind),\n    text: vals{\"description\"}.getStrVal\n  )\n\n  if result.url.len == 0:\n    result.url = js{\"url\"}.getStr\n\n  case kind\n  of promoVideo, promoVideoConvo, appPlayer, videoDirectMessage:\n    result.video = some parsePromoVideo(vals)\n    if kind == appPlayer:\n      result.text = vals{\"app_category\"}.getStrVal(result.text)\n  of broadcast:\n    result = parseBroadcast(vals)\n  of liveEvent:\n    result.text = vals{\"event_title\"}.getStrVal\n  of player:\n    result.url = vals{\"player_url\"}.getStrVal\n    if \"youtube.com\" in result.url:\n      result.url = result.url.replace(\"/embed/\", \"/watch?v=\")\n  of audiospace, unknown:\n    result.title = \"This card type is not supported.\"\n  else: discard\n\n  for typ in imageTypes:\n    with img, vals{typ & \"_large\"}:\n      result.image = img.getImageVal\n      break\n\n  for u in ? urls:\n    if u{\"url\"}.getStr == result.url:\n      result.url = u.getExpandedUrl(result.url)\n      break\n\n  if kind in {videoDirectMessage, imageDirectMessage}:\n    result.url.setLen 0\n\n  if kind in {promoImageConvo, promoImageApp, imageDirectMessage} and\n     result.url.len == 0 or result.url.startsWith(\"card://\"):\n    result.url = getPicUrl(result.image)\n\nproc parseTweet(js: JsonNode; jsCard: JsonNode = newJNull();\n                replyId: int64 = 0): Tweet =\n  if js.isNull: return\n\n  let time =\n    if js{\"created_at\"}.notNull: js{\"created_at\"}.getTime\n    else: js{\"created_at_ms\"}.getTimeFromMs\n\n  result = Tweet(\n    id: js{\"id_str\"}.getId,\n    threadId: js{\"conversation_id_str\"}.getId,\n    replyId: js{\"in_reply_to_status_id_str\"}.getId,\n    text: js{\"full_text\"}.getStr,\n    time: time,\n    hasThread: js{\"self_thread\"}.notNull,\n    available: true,\n    user: User(id: js{\"user_id_str\"}.getStr),\n    stats: TweetStats(\n      replies: js{\"reply_count\"}.getInt,\n      retweets: js{\"retweet_count\"}.getInt,\n      likes: js{\"favorite_count\"}.getInt,\n      views: js{\"views_count\"}.getInt\n    )\n  )\n\n  if result.replyId == 0:\n    result.replyId = replyId\n\n  # fix for pinned threads\n  if result.hasThread and result.threadId == 0:\n    result.threadId = js{\"self_thread\", \"id_str\"}.getId\n\n  if \"retweeted_status\" in js:\n    result.retweet = some Tweet()\n  elif js{\"is_quote_status\"}.getBool:\n    result.quote = some Tweet(id: js{\"quoted_status_id_str\"}.getId)\n\n  # legacy\n  with rt, js{\"retweeted_status_id_str\"}:\n    result.retweet = some Tweet(id: rt.getId)\n    return\n\n  # graphql\n  with rt, js{\"retweeted_status_result\", \"result\"}:\n    # needed due to weird edgecase where the actual tweet data isn't included\n    if \"legacy\" in rt:\n      result.retweet = some parseGraphTweet(rt)\n      return\n\n  with reposts, js{\"repostedStatusResults\"}:\n    with rt, reposts{\"result\"}:\n      if \"legacy\" in rt:\n        result.retweet = some parseGraphTweet(rt)\n        return\n\n  if jsCard.kind != JNull:\n    let name = jsCard{\"name\"}.getStr\n    if \"poll\" in name:\n      if \"image\" in name:\n        result.media.addMedia(Photo(\n          url: jsCard{\"binding_values\", \"image_large\"}.getImageVal\n        ))\n\n      result.poll = some parsePoll(jsCard)\n    elif name == \"amplify\":\n      result.media.addMedia(parsePromoVideo(jsCard{\"binding_values\"}))\n    else:\n      result.card = some parseCard(jsCard, js{\"entities\", \"urls\"})\n\n  result.expandTweetEntities(js)\n  parseLegacyMediaEntities(js, result)\n\n  with jsWithheld, js{\"withheld_in_countries\"}:\n    let withheldInCountries: seq[string] =\n      if jsWithheld.kind != JArray: @[]\n      else: jsWithheld.to(seq[string])\n\n    # XX - Content is withheld in all countries\n    # XY - Content is withheld due to a DMCA request.\n    if js{\"withheld_copyright\"}.getBool or\n       withheldInCountries.len > 0 and (\"XX\" in withheldInCountries or\n                                        \"XY\" in withheldInCountries or\n                                        \"withheld\" in result.text):\n      result.text.removeSuffix(\" Learn more.\")\n      result.available = false\n\nproc parseGraphTweet(js: JsonNode): Tweet =\n  if js.kind == JNull:\n    return Tweet()\n\n  case js.getTypeName:\n  of \"TweetUnavailable\":\n    return Tweet()\n  of \"TweetTombstone\":\n    with text, select(js{\"tombstone\", \"richText\"}, js{\"tombstone\", \"text\"}):\n      return Tweet(text: text.getTombstone)\n    return Tweet()\n  of \"TweetPreviewDisplay\":\n    return Tweet(text: \"You're unable to view this Tweet because it's only available to the Subscribers of the account owner.\")\n  of \"TweetWithVisibilityResults\":\n    return parseGraphTweet(js{\"tweet\"})\n  else:\n    discard\n\n  if not js.hasKey(\"legacy\"):\n    return Tweet()\n\n  var jsCard = select(js{\"card\"}, js{\"tweet_card\"}, js{\"legacy\", \"tweet_card\"})\n  if jsCard.kind != JNull:\n    let legacyCard = jsCard{\"legacy\"}\n    if legacyCard.kind != JNull:\n      let bindingArray = legacyCard{\"binding_values\"}\n      if bindingArray.kind == JArray:\n        var bindingObj: seq[(string, JsonNode)]\n        for item in bindingArray:\n          bindingObj.add((item{\"key\"}.getStr, item{\"value\"}))\n        # Create a new card object with flattened structure\n        jsCard = %*{\n          \"name\": legacyCard{\"name\"},\n          \"url\": legacyCard{\"url\"},\n          \"binding_values\": %bindingObj\n        }\n\n  var replyId = 0\n  with restId, js{\"reply_to_results\", \"rest_id\"}:\n    replyId = restId.getId\n\n  result = parseTweet(js{\"legacy\"}, jsCard, replyId)\n  result.id = js{\"rest_id\"}.getId\n  result.user = parseGraphUser(js{\"core\"})\n\n  if result.reply.len == 0:\n    with replyTo, js{\"reply_to_user_results\", \"result\", \"core\", \"screen_name\"}:\n      result.reply = @[replyTo.getStr]\n\n  with count, js{\"views\", \"count\"}:\n    result.stats.views = count.getStr(\"0\").parseInt\n\n  with noteTweet, js{\"note_tweet\", \"note_tweet_results\", \"result\"}:\n    result.expandNoteTweetEntities(noteTweet)\n\n  parseMediaEntities(js, result)\n\n  with quoted, js{\"quoted_status_result\", \"result\"}:\n    result.quote = some(parseGraphTweet(quoted))\n\n  with quoted, js{\"quotedPostResults\"}:\n    if \"result\" in quoted:\n      result.quote = some(parseGraphTweet(quoted{\"result\"}))\n    else:\n      result.quote = some Tweet(id: js{\"legacy\", \"quoted_status_id_str\"}.getId)\n\n  with ids, js{\"edit_control\", \"edit_control_initial\", \"edit_tweet_ids\"}:\n    for id in ids:\n      result.history.add parseBiggestInt(id.getStr)\n\n  with birdwatch, js{\"birdwatch_pivot\"}:\n    result.note = parseCommunityNote(birdwatch)\n\nproc parseGraphThread(js: JsonNode): tuple[thread: Chain; self: bool] =\n  for t in ? js{\"content\", \"items\"}:\n    let entryId = t.getEntryId\n    if \"tweet-\" in entryId and \"promoted\" notin entryId:\n      let tweet = t.getTweetResult(\"item\")\n      if tweet.notNull:\n        result.thread.content.add parseGraphTweet(tweet)\n\n        let tweetDisplayType = select(\n          t{\"item\", \"content\", \"tweet_display_type\"},\n          t{\"item\", \"itemContent\", \"tweetDisplayType\"}\n        )\n        if tweetDisplayType.getStr == \"SelfThread\":\n          result.self = true\n      else:\n        result.thread.content.add Tweet(id: entryId.getId)\n    elif \"cursor-showmore\" in entryId:\n      let cursor = t{\"item\", \"content\", \"value\"}\n      result.thread.cursor = cursor.getStr\n      result.thread.hasMore = true\n\nproc parseGraphTweetResult*(js: JsonNode): Tweet =\n  with tweet, js{\"data\", \"tweet_result\", \"result\"}:\n    result = parseGraphTweet(tweet)\n\nproc parseGraphConversation*(js: JsonNode; tweetId: string): Conversation =\n  result = Conversation(replies: Result[Chain](beginning: true))\n\n  let instructions = ? select(\n    js{\"data\", \"timelineResponse\", \"instructions\"},\n    js{\"data\", \"timeline_response\", \"instructions\"},\n    js{\"data\", \"threaded_conversation_with_injections_v2\", \"instructions\"}\n  )\n  if instructions.len == 0:\n    return\n\n  for i in instructions:\n    if i.getTypeName == \"TimelineAddEntries\":\n      for e in i{\"entries\"}:\n        let entryId = e.getEntryId\n        if entryId.startsWith(\"tweet-\"):\n          let tweetResult = getTweetResult(e)\n          if tweetResult.notNull:\n            let tweet = parseGraphTweet(tweetResult)\n\n            if not tweet.available:\n              tweet.id = entryId.getId\n\n            if entryId.endsWith(tweetId):\n              result.tweet = tweet\n            else:\n              result.before.content.add tweet\n          elif not entryId.endsWith(tweetId):\n            result.before.content.add Tweet(id: entryId.getId)\n        elif entryId.startsWith(\"conversationthread\"):\n          let (thread, self) = parseGraphThread(e)\n          if self:\n            result.after = thread\n          elif thread.content.len > 0:\n            result.replies.content.add thread\n        elif entryId.startsWith(\"tombstone\"):\n          let\n            content = select(e{\"content\", \"content\"}, e{\"content\", \"itemContent\"})\n            tweet = Tweet(\n              id: entryId.getId,\n              available: false,\n              text: content{\"tombstoneInfo\", \"richText\"}.getTombstone\n            )\n\n          if $tweet.id == tweetId:\n            result.tweet = tweet\n          else:\n            result.before.content.add tweet\n        elif entryId.startsWith(\"cursor-bottom\"):\n          var cursorValue = select(\n            e{\"content\", \"value\"},\n            e{\"content\", \"content\", \"value\"},\n            e{\"content\", \"itemContent\", \"value\"}\n          )\n          result.replies.bottom = cursorValue.getStr\n\nproc parseGraphEditHistory*(js: JsonNode; tweetId: string): EditHistory =\n  let instructions = ? js{\n    \"data\", \"tweet_result_by_rest_id\", \"result\", \n    \"edit_history_timeline\", \"timeline\", \"instructions\"\n  }\n  if instructions.len == 0:\n    return\n\n  for i in instructions:\n    if i.getTypeName == \"TimelineAddEntries\":\n      for e in i{\"entries\"}:\n        let entryId = e.getEntryId\n        if entryId == \"latestTweet\":\n          with item, e{\"content\", \"items\"}[0]:\n            let tweetResult = item.getTweetResult(\"item\")\n            if tweetResult.notNull:\n              result.latest = parseGraphTweet(tweetResult)\n        elif entryId == \"staleTweets\":\n          for item in e{\"content\", \"items\"}:\n            let tweetResult = item.getTweetResult(\"item\")\n            if tweetResult.notNull:\n              result.history.add parseGraphTweet(tweetResult)\n\nproc extractTweetsFromEntry*(e: JsonNode): seq[Tweet] =\n  with tweetResult, getTweetResult(e):\n    var tweet = parseGraphTweet(tweetResult)\n    if not tweet.available:\n      tweet.id = e.getEntryId.getId\n    result.add tweet\n    return\n\n  for item in e{\"content\", \"items\"}:\n    with tweetResult, item.getTweetResult(\"item\"):\n      var tweet = parseGraphTweet(tweetResult)\n      if not tweet.available:\n        tweet.id = item.getEntryId.getId\n      result.add tweet\n\nproc parseGraphTimeline*(js: JsonNode; after=\"\"): Profile =\n  result = Profile(tweets: Timeline(beginning: after.len == 0))\n\n  let instructions = ? select(\n    js{\"data\", \"list\", \"timeline_response\", \"timeline\", \"instructions\"},\n    js{\"data\", \"user\", \"result\", \"timeline\", \"timeline\", \"instructions\"},\n    js{\"data\", \"user_result\", \"result\", \"timeline_response\", \"timeline\", \"instructions\"}\n  )\n  if instructions.len == 0:\n    return\n\n  for i in instructions:\n    if i{\"moduleItems\"}.notNull:\n      for item in i{\"moduleItems\"}:\n        with tweetResult, item.getTweetResult(\"item\"):\n          let tweet = parseGraphTweet(tweetResult)\n          if not tweet.available:\n            tweet.id = item.getEntryId.getId\n          result.tweets.content.add tweet\n      continue\n\n    if i{\"entries\"}.notNull:\n      for e in i{\"entries\"}:\n        let entryId = e.getEntryId\n        if entryId.startsWith(\"tweet\") or entryId.startsWith(\"profile-grid\"):\n          for tweet in extractTweetsFromEntry(e):\n            result.tweets.content.add tweet\n        elif \"-conversation-\" in entryId or entryId.startsWith(\"homeConversation\"):\n          let (thread, self) = parseGraphThread(e)\n          result.tweets.content.add thread.content\n        elif entryId.startsWith(\"cursor-bottom\"):\n          result.tweets.bottom = e{\"content\", \"value\"}.getStr\n\n    if after.len == 0:\n      if i.getTypeName == \"TimelinePinEntry\":\n        let tweets = extractTweetsFromEntry(i{\"entry\"})\n        if tweets.len > 0:\n          var tweet = tweets[0]\n          tweet.pinned = true\n          result.pinned = some tweet\n\nproc parseGraphPhotoRail*(js: JsonNode): PhotoRail =\n  result = @[]\n\n  let instructions = select(\n    js{\"data\", \"user\", \"result\", \"timeline\", \"timeline\", \"instructions\"},\n    js{\"data\", \"user_result\", \"result\", \"timeline_response\", \"timeline\", \"instructions\"}\n  )\n  if instructions.len == 0:\n    return\n\n  for i in instructions:\n    if i{\"moduleItems\"}.notNull:\n      for item in i{\"moduleItems\"}:\n        with tweetResult, item.getTweetResult(\"item\"):\n          let t = parseGraphTweet(tweetResult)\n          if not t.available:\n            t.id = item.getEntryId.getId\n\n          let photo = extractGalleryPhoto(t)\n          if photo.url.len > 0:\n            result.add photo\n\n          if result.len == 16:\n            return\n      continue\n\n    if i.getTypeName != \"TimelineAddEntries\":\n      continue\n\n    for e in i{\"entries\"}:\n      let entryId = e.getEntryId\n      if entryId.startsWith(\"tweet\") or entryId.startsWith(\"profile-grid\"):\n        for t in extractTweetsFromEntry(e):\n          let photo = extractGalleryPhoto(t)\n          if photo.url.len > 0:\n            result.add photo\n\n          if result.len == 16:\n            return\n\nproc parseGraphSearch*[T: User | Tweets](js: JsonNode; after=\"\"): Result[T] =\n  result = Result[T](beginning: after.len == 0)\n\n  let instructions = select(\n    js{\"data\", \"search\", \"timeline_response\", \"timeline\", \"instructions\"},\n    js{\"data\", \"search_by_raw_query\", \"search_timeline\", \"timeline\", \"instructions\"}\n  )\n  if instructions.len == 0:\n    return\n\n  for instruction in instructions:\n    let typ = getTypeName(instruction)\n    if typ == \"TimelineAddEntries\":\n      for e in instruction{\"entries\"}:\n        let entryId = e.getEntryId\n        when T is Tweets:\n          if entryId.startsWith(\"tweet\"):\n            with tweetRes, getTweetResult(e):\n              let tweet = parseGraphTweet(tweetRes)\n              if not tweet.available:\n                tweet.id = entryId.getId\n              result.content.add tweet\n        elif T is User:\n          if entryId.startsWith(\"user\"):\n            with userRes, e{\"content\", \"itemContent\"}:\n              result.content.add parseGraphUser(userRes)\n\n        if entryId.startsWith(\"cursor-bottom\"):\n          result.bottom = e{\"content\", \"value\"}.getStr\n    elif typ == \"TimelineReplaceEntry\":\n      if instruction{\"entry_id_to_replace\"}.getStr.startsWith(\"cursor-bottom\"):\n        result.bottom = instruction{\"entry\", \"content\", \"value\"}.getStr\n"
  },
  {
    "path": "src/parserutils.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport std/[times, macros, htmlgen, options, algorithm, re]\nimport std/strutils except escape\nimport std/unicode except strip\nfrom xmltree import escape\nimport packedjson\nimport types, utils, formatters\n\nconst\n  unicodeOpen = \"\\uFFFA\"\n  unicodeClose = \"\\uFFFB\"\n  xmlOpen = escape(\"<\")\n  xmlClose = escape(\">\")\n\nlet\n  unRegex = re\"(^|[^A-z0-9-_./?])@([A-z0-9_]{1,15})\"\n  unReplace = \"$1<a href=\\\"/$2\\\">@$2</a>\"\n\n  htRegex = re\"(^|[^\\w-_./?])([#$]|＃)([\\w_]+)\"\n  htReplace = \"$1<a href=\\\"/search?f=tweets&q=%23$3\\\">$2$3</a>\"\n\ntype\n  ReplaceSliceKind = enum\n    rkRemove, rkUrl, rkHashtag, rkMention\n\n  ReplaceSlice = object\n    slice: Slice[int]\n    kind: ReplaceSliceKind\n    url, display: string\n\ntemplate isNull*(js: JsonNode): bool = js.kind == JNull\ntemplate notNull*(js: JsonNode): bool = js.kind != JNull\n\ntemplate `?`*(js: JsonNode): untyped =\n  let j = js\n  if j.isNull: return\n  j\n\ntemplate select*(a, b: JsonNode): untyped =\n  if a.notNull: a else: b\n\ntemplate select*(a, b, c: JsonNode): untyped =\n  if a.notNull: a elif b.notNull: b else: c\n\ntemplate with*(ident, value, body): untyped =\n  if true:\n    let ident {.inject.} = value\n    if ident != nil: body\n\ntemplate with*(ident; value: JsonNode; body): untyped =\n  if true:\n    let ident {.inject.} = value\n    if value.notNull: body\n\ntemplate getCursor*(js: JsonNode): string =\n  js{\"content\", \"operation\", \"cursor\", \"value\"}.getStr\n\ntemplate getError*(js: JsonNode): Error =\n  if js.kind != JArray or js.len == 0: null\n  else: Error(js[0]{\"code\"}.getInt)\n\nproc getTweetResult*(js: JsonNode; root=\"content\"): JsonNode =\n  select(\n    js{root, \"content\", \"tweet_results\", \"result\"},\n    js{root, \"itemContent\", \"tweet_results\", \"result\"},\n    js{root, \"content\", \"tweetResult\", \"result\"}\n  )\n\ntemplate getTypeName*(js: JsonNode): string =\n  js{\"__typename\"}.getStr(js{\"type\"}.getStr)\n\ntemplate getEntryId*(e: JsonNode): string =\n  e{\"entryId\"}.getStr(e{\"entry_id\"}.getStr)\n\ntemplate parseTime(time: string; f: static string; flen: int): DateTime =\n  if time.len != flen: return\n  parse(time, f, utc())\n\nproc getDateTime*(js: JsonNode): DateTime =\n  parseTime(js.getStr, \"yyyy-MM-dd\\'T\\'HH:mm:ss\\'Z\\'\", 20)\n\nproc getTime*(js: JsonNode): DateTime =\n  parseTime(js.getStr, \"ddd MMM dd hh:mm:ss \\'+0000\\' yyyy\", 30)\n\nproc getTimeFromMs*(js: JsonNode): DateTime =\n  let ms = js.getInt(0)\n  if ms == 0: return\n  let seconds = ms div 1000\n  return fromUnix(seconds).utc()\n\nproc getId*(id: string): int64 {.inline.} =\n  let start = id.rfind(\"-\")\n  if start < 0:\n    return parseBiggestInt(id)\n  return parseBiggestInt(id[start + 1 ..< id.len])\n\nproc getId*(js: JsonNode): int64 {.inline.} =\n  case js.kind\n  of JString: return js.getStr(\"0\").getId\n  of JInt: return js.getBiggestInt()\n  else: return 0\n\ntemplate getStrVal*(js: JsonNode; default=\"\"): string =\n  js{\"string_value\"}.getStr(default)\n\nproc getImageStr*(js: JsonNode): string =\n  result = js.getStr\n  result.removePrefix(https)\n  result.removePrefix(twimg)\n\ntemplate getImageVal*(js: JsonNode): string =\n  js{\"image_value\", \"url\"}.getImageStr\n\ntemplate getExpandedUrl*(js: JsonNode; fallback=\"\"): string =\n  js{\"expanded_url\"}.getStr(js{\"url\"}.getStr(fallback))\n\nproc getCardUrl*(js: JsonNode; kind: CardKind): string =\n  result = js{\"website_url\"}.getStrVal\n  if kind == promoVideoConvo:\n    result = js{\"thank_you_url\"}.getStrVal(result)\n  if result.startsWith(\"card://\"):\n    result = \"\"\n\nproc getCardDomain*(js: JsonNode; kind: CardKind): string =\n  result = js{\"vanity_url\"}.getStrVal(js{\"domain\"}.getStr)\n  if kind == promoVideoConvo:\n    result = js{\"thank_you_vanity_url\"}.getStrVal(result)\n\nproc getCardTitle*(js: JsonNode; kind: CardKind): string =\n  result = js{\"title\"}.getStrVal\n  if kind == promoVideoConvo:\n    result = js{\"thank_you_text\"}.getStrVal(result)\n  elif kind == liveEvent:\n    result = js{\"event_category\"}.getStrVal\n  elif kind in {videoDirectMessage, imageDirectMessage}:\n    result = js{\"cta1\"}.getStrVal\n\nproc getBanner*(js: JsonNode): string =\n  let url = js{\"profile_banner_url\"}.getImageStr\n  if url.len > 0:\n    return url & \"/1500x500\"\n\n  let color = js{\"profile_link_color\"}.getStr\n  if color.len > 0:\n    return '#' & color\n\n  # use primary color from profile picture color histogram\n  with p, js{\"profile_image_extensions\", \"mediaColor\", \"r\", \"ok\", \"palette\"}:\n    if p.len > 0:\n      let pal = p[0]{\"rgb\"}\n      result = \"#\"\n      result.add toHex(pal{\"red\"}.getInt, 2)\n      result.add toHex(pal{\"green\"}.getInt, 2)\n      result.add toHex(pal{\"blue\"}.getInt, 2)\n      return\n\nproc getTombstone*(js: JsonNode): string =\n  result = js{\"text\"}.getStr\n  result.removeSuffix(\" Learn more\")\n\nproc getMp4Resolution*(url: string): int =\n  # parses the height out of a URL like this one:\n  # https://video.twimg.com/ext_tw_video/<tweet-id>/pu/vid/720x1280/<random>.mp4\n  const vidSep = \"/vid/\"\n  let\n    vidIdx = url.find(vidSep) + vidSep.len\n    resIdx = url.find('x', vidIdx) + 1\n    res = url[resIdx ..< url.find(\"/\", resIdx)]\n\n  try:\n    return parseInt(res)\n  except ValueError:\n    # cannot determine resolution (e.g. m3u8/non-mp4 video)\n    return 0\n\nproc extractSlice(js: JsonNode): Slice[int] =\n  result = js[\"indices\"][0].getInt ..< js[\"indices\"][1].getInt\n\nproc extractUrls(result: var seq[ReplaceSlice]; js: JsonNode;\n                 textLen: int; hideTwitter = false) =\n  let\n    url = js.getExpandedUrl\n    slice = js.extractSlice\n\n  if hideTwitter and slice.b.succ >= textLen and url.isTwitterUrl:\n    if slice.a < textLen:\n      result.add ReplaceSlice(kind: rkRemove, slice: slice)\n  else:\n    result.add ReplaceSlice(kind: rkUrl, url: url,\n                            display: url.shortLink, slice: slice)\n\nproc extractHashtags(result: var seq[ReplaceSlice]; js: JsonNode) =\n  result.add ReplaceSlice(kind: rkHashtag, slice: js.extractSlice)\n\nproc replacedWith(runes: seq[Rune]; repls: openArray[ReplaceSlice];\n                  textSlice: Slice[int]): string =\n  template extractLowerBound(i: int; idx): int =\n    if i > 0: repls[idx].slice.b.succ else: textSlice.a\n\n  result = newStringOfCap(runes.len)\n\n  for i, rep in repls:\n    result.add $runes[extractLowerBound(i, i - 1) ..< rep.slice.a]\n    case rep.kind\n    of rkHashtag:\n      let\n        name = $runes[rep.slice.a.succ .. rep.slice.b]\n        symbol = $runes[rep.slice.a]\n      result.add a(symbol & name, href = \"/search?f=tweets&q=%23\" & name)\n    of rkMention:\n      result.add a($runes[rep.slice], href = rep.url, title = rep.display)\n    of rkUrl:\n      result.add a(rep.display, href = rep.url)\n    of rkRemove:\n      discard\n\n  let rest = extractLowerBound(repls.len, ^1) ..< textSlice.b\n  if rest.a <= rest.b:\n    result.add $runes[rest]\n\nproc deduplicate(s: var seq[ReplaceSlice]) =\n  var\n    len = s.len\n    i = 0\n  while i < len:\n    var j = i + 1\n    while j < len:\n      if s[i].slice.a == s[j].slice.a:\n        s.del j\n        dec len\n      else:\n        inc j\n    inc i\n\nproc cmp(x, y: ReplaceSlice): int = cmp(x.slice.a, y.slice.b)\n\nproc expandUserEntities*(user: var User; js: JsonNode) =\n  let\n    orig = user.bio.toRunes\n    ent = ? js{\"entities\"}\n\n  with urls, ent{\"url\", \"urls\"}:\n    user.website = urls[0].getExpandedUrl\n\n  var replacements = newSeq[ReplaceSlice]()\n\n  with urls, ent{\"description\", \"urls\"}:\n    for u in urls:\n      replacements.extractUrls(u, orig.high)\n\n  replacements.deduplicate\n  replacements.sort(cmp)\n\n  user.bio = orig.replacedWith(replacements, 0 .. orig.len)\n  user.bio = user.bio.replacef(unRegex, unReplace)\n                     .replacef(htRegex, htReplace)\n\nproc expandTextEntities(tweet: Tweet; entities: JsonNode; text: string; textSlice: Slice[int];\n                        replyTo=\"\"; hasRedundantLink=false) =\n  let hasCard = tweet.card.isSome\n\n  var replacements = newSeq[ReplaceSlice]()\n\n  with urls, entities{\"urls\"}:\n    for u in urls:\n      let urlStr = u[\"url\"].getStr\n      if urlStr.len == 0 or urlStr notin text:\n        continue\n\n      replacements.extractUrls(u, textSlice.b, hideTwitter = hasRedundantLink)\n\n      if hasCard and u{\"url\"}.getStr == get(tweet.card).url:\n        get(tweet.card).url = u.getExpandedUrl\n\n  with media, entities{\"media\"}:\n    for m in media:\n      replacements.extractUrls(m, textSlice.b, hideTwitter = true)\n\n  if \"hashtags\" in entities:\n    for hashtag in entities[\"hashtags\"]:\n      replacements.extractHashtags(hashtag)\n\n  if \"symbols\" in entities:\n    for symbol in entities[\"symbols\"]:\n      replacements.extractHashtags(symbol)\n\n  if \"user_mentions\" in entities:\n    for mention in entities[\"user_mentions\"]:\n      let\n        name = mention{\"screen_name\"}.getStr\n        slice = mention.extractSlice\n        idx = tweet.reply.find(name)\n\n      if slice.a >= textSlice.a:\n        replacements.add ReplaceSlice(kind: rkMention, slice: slice,\n          url: \"/\" & name, display: mention[\"name\"].getStr)\n        if idx > -1 and name != replyTo:\n          tweet.reply.delete idx\n      elif idx == -1 and tweet.replyId != 0:\n        tweet.reply.add name\n\n  replacements.deduplicate\n  replacements.sort(cmp)\n\n  tweet.text = text.toRunes.replacedWith(replacements, textSlice).strip(leading=false)\n\nproc expandTweetEntities*(tweet: Tweet; js: JsonNode) =\n  let\n    entities = ? js{\"entities\"}\n    textRange = js{\"display_text_range\"}\n    textSlice = textRange{0}.getInt .. textRange{1}.getInt\n    hasQuote = js{\"is_quote_status\"}.getBool\n    hasJobCard = tweet.card.isSome and get(tweet.card).kind == jobDetails\n\n  var replyTo = \"\"\n  if tweet.replyId != 0:\n    with reply, js{\"in_reply_to_screen_name\"}:\n      replyTo = reply.getStr\n      tweet.reply.add replyTo\n\n  tweet.expandTextEntities(entities, tweet.text, textSlice, replyTo, hasQuote or hasJobCard)\n\nproc expandNoteTweetEntities*(tweet: Tweet; js: JsonNode) =\n  let\n    entities = ? js{\"entity_set\"}\n    text = js{\"text\"}.getStr.multiReplace((\"<\", unicodeOpen), (\">\", unicodeClose))\n    textSlice = 0..text.runeLen\n\n  tweet.expandTextEntities(entities, text, textSlice)\n\n  tweet.text = tweet.text.multiReplace((unicodeOpen, xmlOpen), (unicodeClose, xmlClose))\n\nproc expandBirdwatchEntities*(text: string; entities: JsonNode): string =\n  let runes = text.toRunes\n  var replacements: seq[ReplaceSlice]\n\n  for entity in entities:\n    let\n      fromIdx = entity{\"from_index\"}.getInt\n      toIdx = entity{\"to_index\"}.getInt\n      url = entity{\"ref\", \"url\"}.getStr\n    if url.len > 0:\n      replacements.add ReplaceSlice(\n        kind: rkUrl,\n        slice: fromIdx ..< toIdx,\n        url: url,\n        display: $runes[fromIdx ..< min(toIdx, runes.len)]\n      )\n\n  replacements.sort(cmp)\n  result = runes.replacedWith(replacements, 0 ..< runes.len)\n\nproc extractGalleryPhoto*(t: Tweet): GalleryPhoto =\n  let url =\n    if t.media.len > 0: t.media[0].getThumb\n    elif t.card.isSome: get(t.card).image\n    else: \"\"\n\n  result = GalleryPhoto(url: url, tweetId: $t.id)\n"
  },
  {
    "path": "src/prefs.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport tables, strutils\nimport types, prefs_impl\nfrom config import get\nfrom parsecfg import nil\n\nexport genUpdatePrefs, genResetPrefs, genApplyPrefs\n\nvar defaultPrefs*: Prefs\n\nproc updateDefaultPrefs*(cfg: parsecfg.Config) =\n  genDefaultPrefs()\n\nproc getPrefs*(cookies, params: Table[string, string]): Prefs =\n  result = defaultPrefs\n  genParsePrefs(cookies)\n  genParsePrefs(params)\n\nproc encodePrefs*(prefs: Prefs): string =\n  var encPairs: seq[string]\n  genEncodePrefs(prefs)\n  encPairs.join(\",\")\n"
  },
  {
    "path": "src/prefs_impl.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport macros, tables, strutils, xmltree\n\ntype\n  PrefKind* = enum\n    checkbox, select, input\n\n  Pref* = object\n    name*: string\n    label*: string\n    kind*: PrefKind\n    # checkbox\n    defaultState*: bool\n    # select\n    defaultOption*: string\n    options*: seq[string]\n    # input\n    defaultInput*: string\n    placeholder*: string\n\n  PrefList* = OrderedTable[string, seq[Pref]]\n\nmacro genPrefs*(prefDsl: untyped) =\n  var table = nnkTableConstr.newTree()\n  for category in prefDsl:\n    table.add nnkExprColonExpr.newTree(newLit($category[0]))\n    table[^1].add nnkPrefix.newTree(newIdentNode(\"@\"), nnkBracket.newTree())\n    for pref in category[1]:\n      let\n        name = newLit($pref[0])\n        kind = pref[1]\n        label = pref[3][0]\n        default = pref[2]\n        defaultField =\n          case parseEnum[PrefKind]($kind)\n          of checkbox: ident(\"defaultState\")\n          of select: ident(\"defaultOption\")\n          of input: ident(\"defaultInput\")\n\n      var newPref = quote do:\n        Pref(kind: `kind`, name: `name`, label: `label`, `defaultField`: `default`)\n\n      for node in pref[3]:\n        if node.kind == nnkCall:\n          newPref.add nnkExprColonExpr.newTree(node[0], node[1][0])\n      table[^1][1][1].add newPref\n\n  let name = ident(\"prefList\")\n  result = quote do:\n    const `name`*: PrefList = toOrderedTable(`table`)\n\ngenPrefs:\n  Display:\n    theme(select, \"Nitter\"):\n      \"Theme\"\n\n    infiniteScroll(checkbox, false):\n      \"Infinite scrolling (experimental, requires JavaScript)\"\n\n    stickyProfile(checkbox, true):\n      \"Make profile sidebar stick to top\"\n\n    stickyNav(checkbox, true):\n      \"Keep navbar fixed to top\"\n\n    bidiSupport(checkbox, false):\n      \"Support bidirectional text (makes clicking on tweets harder)\"\n\n    hideTweetStats(checkbox, false):\n      \"Hide tweet stats (replies, retweets, likes)\"\n\n    hideBanner(checkbox, false):\n      \"Hide profile banner\"\n\n    hidePins(checkbox, false):\n      \"Hide pinned tweets\"\n\n    hideReplies(checkbox, false):\n      \"Hide tweet replies\"\n\n    hideCommunityNotes(checkbox, false):\n      \"Hide community notes\"\n\n    squareAvatars(checkbox, false):\n      \"Square profile pictures\"\n\n  Media:\n    mp4Playback(checkbox, true):\n      \"Enable mp4 video playback (only for gifs)\"\n\n    hlsPlayback(checkbox, false):\n      \"Enable HLS video streaming (requires JavaScript)\"\n\n    proxyVideos(checkbox, true):\n      \"Proxy video streaming through the server (might be slow)\"\n\n    muteVideos(checkbox, false):\n      \"Mute videos by default\"\n\n    autoplayGifs(checkbox, true):\n      \"Autoplay gifs\"\n\n    compactGallery(checkbox, false):\n      \"Compact media gallery (no profile info or text)\"\n\n    mediaView(select, \"Timeline\"):\n      \"Default media view\"\n      options: @[\"Timeline\", \"Grid\", \"Gallery\"]\n\n  \"Link replacements (blank to disable)\":\n    replaceTwitter(input, \"\"):\n      \"Twitter -> Nitter\"\n      placeholder: \"Nitter hostname\"\n\n    replaceYouTube(input, \"\"):\n      \"YouTube -> Piped/Invidious\"\n      placeholder: \"Piped hostname\"\n\n    replaceReddit(input, \"\"):\n      \"Reddit -> Teddit/Libreddit\"\n      placeholder: \"Teddit hostname\"\n\niterator allPrefs*(): Pref =\n  for k, v in prefList:\n    for pref in v:\n      yield pref\n\nmacro genDefaultPrefs*(): untyped =\n  result = nnkStmtList.newTree()\n  for pref in allPrefs():\n    let\n      ident = ident(pref.name)\n      name = newLit(pref.name)\n      default =\n        case pref.kind\n        of checkbox: newLit(pref.defaultState)\n        of select: newLit(pref.defaultOption)\n        of input: newLit(pref.defaultInput)\n\n    result.add quote do:\n      defaultPrefs.`ident` = cfg.get(\"Preferences\", `name`, `default`)\n\nmacro genParsePrefs*(prefs): untyped =\n  result = nnkStmtList.newTree()\n  for pref in allPrefs():\n    let\n      name = pref.name\n      ident = ident(pref.name)\n      kind = newLit(pref.kind)\n      options = pref.options\n\n    result.add quote do:\n      if `name` in `prefs`:\n        when `kind` == input or `name` == \"theme\":\n          result.`ident` = `prefs`[`name`]\n        elif `kind` == checkbox:\n          result.`ident` = `prefs`[`name`] == \"on\" or \n                           `prefs`[`name`] == \"true\" or\n                           `prefs`[`name`] == \"1\"\n        else:\n          let value = `prefs`[`name`]\n          if value in `options`: result.`ident` = value\n\nmacro genUpdatePrefs*(): untyped =\n  result = nnkStmtList.newTree()\n  let req = ident(\"request\")\n  for pref in allPrefs():\n    let\n      name = newLit(pref.name)\n      kind = newLit(pref.kind)\n      options = newLit(pref.options)\n      default = nnkDotExpr.newTree(ident(\"defaultPrefs\"), ident(pref.name))\n\n    result.add quote do:\n      let val = @`name`\n      let isDefault =\n        when `kind` == input or `name` == \"theme\":\n          if `default`.len != val.len: false\n          else: val == `default`\n        elif `kind` == checkbox:\n          (val == \"on\") == `default`\n        else:\n          val notin `options` or val == `default`\n\n      if isDefault:\n        savePref(`name`, \"\", `req`, expire=true)\n      else:\n        savePref(`name`, val, `req`)\n\nmacro genResetPrefs*(): untyped =\n  result = nnkStmtList.newTree()\n  let req = ident(\"request\")\n  for pref in allPrefs():\n    let name = newLit(pref.name)\n    result.add quote do:\n      savePref(`name`, \"\", `req`, expire=true)\n\nmacro genEncodePrefs*(prefs): untyped =\n  result = nnkStmtList.newTree()\n  for pref in allPrefs():\n    let\n      name = newLit(pref.name)\n      ident = ident(pref.name)\n      kind = newLit(pref.kind)\n      defaultIdent = nnkDotExpr.newTree(ident(\"defaultPrefs\"), ident(pref.name))\n\n    result.add quote do:\n      when `kind` == checkbox:\n        if `prefs`.`ident` != `defaultIdent`:\n          if `prefs`.`ident`:\n            encPairs.add `name` & \"=on\"\n          else:\n            encPairs.add `name` & \"=\"\n      else:\n        if `prefs`.`ident` != `defaultIdent`:\n          encPairs.add `name` & \"=\" & `prefs`.`ident`\n\nmacro genApplyPrefs*(params, req): untyped =\n  result = nnkStmtList.newTree()\n  for pref in allPrefs():\n    let name = newLit(pref.name)\n    result.add quote do:\n      if `name` in `params`:\n        savePref(`name`, `params`[`name`], `req`)\n      else:\n        savePref(`name`, \"\", `req`, expire=true)\n\nmacro genPrefsType*(): untyped =\n  let name = nnkPostfix.newTree(ident(\"*\"), ident(\"Prefs\"))\n  result = quote do:\n    type `name` = object\n      discard\n\n  for pref in allPrefs():\n    result[0][2][2].add nnkIdentDefs.newTree(\n      nnkPostfix.newTree(ident(\"*\"), ident(pref.name)),\n      (case pref.kind\n       of checkbox: ident(\"bool\")\n       of input, select: ident(\"string\")),\n      newEmptyNode())\n"
  },
  {
    "path": "src/query.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport strutils, strformat, sequtils, tables, uri\n\nimport types, utils\n\nconst\n  validFilters* = @[\n    \"media\", \"images\", \"twimg\", \"videos\",\n    \"native_video\", \"consumer_video\", \"spaces\",\n    \"links\", \"news\", \"quote\", \"mentions\",\n    \"replies\", \"retweets\", \"nativeretweets\"\n  ]\n\n  emptyQuery* = \"include:nativeretweets\"\n\ntemplate `@`(param: string): untyped =\n  if param in pms: pms[param]\n  else: \"\"\n\nproc initQuery*(pms: Table[string, string]; name=\"\"): Query =\n  result = Query(\n    kind: parseEnum[QueryKind](@\"f\", tweets),\n    view: @\"view\",\n    text: @\"q\",\n    filters: validFilters.filterIt(\"f-\" & it in pms),\n    excludes: validFilters.filterIt(\"e-\" & it in pms),\n    since: @\"since\",\n    until: @\"until\",\n    minLikes: validateNumber(@\"min_faves\")\n  )\n\n  if name.len > 0:\n    result.fromUser = name.split(\",\")\n\nproc getMediaQuery*(name: string): Query =\n  Query(\n    kind: media,\n    filters: @[\"twimg\", \"native_video\"],\n    fromUser: @[name],\n    sep: \"OR\"\n  )\n\nproc getReplyQuery*(name: string): Query =\n  Query(\n    kind: replies,\n    fromUser: @[name]\n  )\n\nproc genQueryParam*(query: Query; maxId=\"\"): string =\n  var\n    filters: seq[string]\n    param: string\n\n  if query.kind == users:\n    return query.text\n\n  for i, user in query.fromUser:\n    if i == 0:\n      param = \"(\"\n\n    param &= &\"from:{user}\"\n    if i < query.fromUser.high:\n      param &= \" OR \"\n    else:\n      param &= \")\"\n\n  if query.fromUser.len > 0 and query.kind in {posts, media}:\n    param &= \" (filter:self_threads OR -filter:replies)\"\n\n  if \"nativeretweets\" notin query.excludes:\n    param &= \" include:nativeretweets\"\n\n  for f in query.filters:\n    filters.add \"filter:\" & f\n  for e in query.excludes:\n    if e == \"nativeretweets\": continue\n    filters.add \"-filter:\" & e\n  for i in query.includes:\n    filters.add \"include:\" & i\n\n  if filters.len > 0:\n    result = strip(param & \" (\" & filters.join(&\" {query.sep} \") & \")\")\n  else:\n    result = strip(param)\n\n  if query.since.len > 0:\n    result &= \" since:\" & query.since\n  if query.until.len > 0 and maxId.len == 0:\n    result &= \" until:\" & query.until\n  if query.minLikes.len > 0:\n    result &= \" min_faves:\" & query.minLikes\n  if query.text.len > 0:\n    if result.len > 0:\n      result &= \" \" & query.text\n    else:\n      result = query.text\n\n  if result.len > 0 and maxId.len > 0:\n    result &= \" max_id:\" & maxId\n\nproc genQueryUrl*(query: Query): string =\n  var params: seq[string]\n\n  if query.view.len > 0:\n    params.add \"view=\" & encodeUrl(query.view)\n\n  if query.kind in {tweets, users}:\n    params.add &\"f={query.kind}\"\n    if query.text.len > 0:\n      params.add \"q=\" & encodeUrl(query.text)\n    for f in query.filters:\n      params.add &\"f-{f}=on\"\n    for e in query.excludes:\n      params.add &\"e-{e}=on\"\n    for i in query.includes.filterIt(it != \"nativeretweets\"):\n      params.add &\"i-{i}=on\"\n\n    if query.since.len > 0:\n      params.add \"since=\" & query.since\n    if query.until.len > 0:\n      params.add \"until=\" & query.until\n    if query.minLikes.len > 0:\n      params.add \"min_faves=\" & query.minLikes\n\n  if params.len > 0:\n    result &= params.join(\"&\")\n"
  },
  {
    "path": "src/redis_cache.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport asyncdispatch, times, strformat, strutils, tables, hashes\nimport redis, redpool, flatty, supersnappy\n\nimport types, api\n\nconst\n  redisNil = \"\\0\\0\"\n  baseCacheTime = 60 * 60\n\nvar\n  pool: RedisPool\n  rssCacheTime: int\n  listCacheTime*: int\n\ntemplate dawait(future) =\n  discard await future\n\n# flatty can't serialize DateTime, so we need to define this\nproc toFlatty*(s: var string, x: DateTime) =\n  s.toFlatty(x.toTime().toUnix())\n\nproc fromFlatty*(s: string, i: var int, x: var DateTime) =\n  var unix: int64\n  s.fromFlatty(i, unix)\n  x = fromUnix(unix).utc()\n\nproc setCacheTimes*(cfg: Config) =\n  rssCacheTime = cfg.rssCacheTime * 60\n  listCacheTime = cfg.listCacheTime * 60\n\nproc migrate*(key, match: string) {.async.} =\n  pool.withAcquire(r):\n    let hasKey = await r.get(key)\n    if hasKey == redisNil:\n      let list = await r.scan(newCursor(0), match, 100000)\n      r.startPipelining()\n      for item in list:\n        dawait r.del(item)\n      await r.setk(key, \"true\")\n      dawait r.flushPipeline()\n\nproc initRedisPool*(cfg: Config) {.async.} =\n  try:\n    pool = await newRedisPool(cfg.redisConns, cfg.redisMaxConns,\n                              host=cfg.redisHost, port=cfg.redisPort,\n                              password=cfg.redisPassword)\n\n    await migrate(\"flatty\", \"*:*\")\n    await migrate(\"snappyRss\", \"rss:*\")\n    await migrate(\"userBuckets\", \"p:*\")\n    await migrate(\"profileDates\", \"p:*\")\n    await migrate(\"profileStats\", \"p:*\")\n    await migrate(\"userType\", \"p:*\")\n    await migrate(\"verifiedType\", \"p:*\")\n\n    pool.withAcquire(r):\n      # optimize memory usage for user ID buckets\n      await r.configSet(\"hash-max-ziplist-entries\", \"1000\")\n\n  except OSError:\n    stdout.write \"Failed to connect to Redis.\\n\"\n    stdout.flushFile\n    quit(1)\n\ntemplate uidKey(name: string): string = \"pid:\" & $(hash(name) div 1_000_000)\ntemplate userKey(name: string): string = \"p:\" & name\ntemplate listKey(l: List): string = \"l:\" & l.id\ntemplate tweetKey(id: int64): string = \"t:\" & $id\n\nproc get(query: string): Future[string] {.async.} =\n  pool.withAcquire(r):\n    result = await r.get(query)\n\nproc setEx(key: string; time: int; data: string) {.async.} =\n  pool.withAcquire(r):\n    dawait r.setEx(key, time, data)\n\nproc cacheUserId(username, id: string) {.async.} =\n  if username.len == 0 or id.len == 0: return\n  let name = toLower(username)\n  pool.withAcquire(r):\n    dawait r.hSet(name.uidKey, name, id)\n\nproc cache*(data: List) {.async.} =\n  await setEx(data.listKey, listCacheTime, compress(toFlatty(data)))\n\nproc cache*(data: PhotoRail; name: string) {.async.} =\n  await setEx(\"pr2:\" & toLower(name), baseCacheTime * 2, compress(toFlatty(data)))\n\nproc cache*(data: User) {.async.} =\n  if data.username.len == 0: return\n  let name = toLower(data.username)\n  await cacheUserId(name, data.id)\n  pool.withAcquire(r):\n    dawait r.setEx(name.userKey, baseCacheTime, compress(toFlatty(data)))\n\nproc cache*(data: Tweet) {.async.} =\n  if data.isNil or data.id == 0: return\n  pool.withAcquire(r):\n    dawait r.setEx(data.id.tweetKey, baseCacheTime, compress(toFlatty(data)))\n\nproc cacheRss*(query: string; rss: Rss) {.async.} =\n  let key = \"rss:\" & query\n  pool.withAcquire(r):\n    dawait r.hSet(key, \"min\", rss.cursor)\n    if rss.cursor != \"suspended\":\n      dawait r.hSet(key, \"rss\", compress(rss.feed))\n    dawait r.expire(key, rssCacheTime)\n\ntemplate deserialize(data, T) =\n  try:\n    result = fromFlatty(uncompress(data), T)\n  except:\n    echo \"Decompression failed($#): '$#'\" % [astToStr(T), data]\n\nproc getUserId*(username: string): Future[string] {.async.} =\n  let name = toLower(username)\n  pool.withAcquire(r):\n    result = await r.hGet(name.uidKey, name)\n    if result == redisNil:\n      let user = await getGraphUser(username)\n      if user.suspended:\n        return \"suspended\"\n      else:\n        await all(cacheUserId(name, user.id), cache(user))\n        return user.id\n\nproc getCachedUser*(username: string; fetch=true): Future[User] {.async.} =\n  let prof = await get(\"p:\" & toLower(username))\n  if prof != redisNil:\n    prof.deserialize(User)\n  elif fetch:\n    result = await getGraphUser(username)\n    await cache(result)\n\nproc getCachedUsername*(userId: string): Future[string] {.async.} =\n  let\n    key = \"i:\" & userId\n    username = await get(key)\n\n  if username != redisNil:\n    result = username\n  else:\n    let user = await getGraphUserById(userId)\n    result = user.username\n    await setEx(key, baseCacheTime, result)\n    if result.len > 0 and user.id.len > 0:\n      await all(cacheUserId(result, user.id), cache(user))\n\n# proc getCachedTweet*(id: int64): Future[Tweet] {.async.} =\n#   if id == 0: return\n#   let tweet = await get(id.tweetKey)\n#   if tweet != redisNil:\n#     tweet.deserialize(Tweet)\n#   else:\n#     result = await getGraphTweetResult($id)\n#     if not result.isNil:\n#       await cache(result)\n\nproc getCachedPhotoRail*(id: string): Future[PhotoRail] {.async.} =\n  if id.len == 0: return\n  let rail = await get(\"pr2:\" & toLower(id))\n  if rail != redisNil:\n    rail.deserialize(PhotoRail)\n  else:\n    result = await getPhotoRail(id)\n    await cache(result, id)\n\nproc getCachedList*(username=\"\"; slug=\"\"; id=\"\"): Future[List] {.async.} =\n  let list = if id.len == 0: redisNil\n             else: await get(\"l:\" & id)\n\n  if list != redisNil:\n    list.deserialize(List)\n  else:\n    if id.len > 0:\n      result = await getGraphList(id)\n    else:\n      result = await getGraphListBySlug(username, slug)\n    await cache(result)\n\nproc getCachedRss*(key: string): Future[Rss] {.async.} =\n  let k = \"rss:\" & key\n  pool.withAcquire(r):\n    result.cursor = await r.hGet(k, \"min\")\n    if result.cursor.len > 2:\n      if result.cursor != \"suspended\":\n        let feed = await r.hGet(k, \"rss\")\n        if feed.len > 0 and feed != redisNil:\n          try: result.feed = uncompress feed\n          except: echo \"Decompressing RSS failed: \", feed\n    else:\n      result.cursor.setLen 0\n"
  },
  {
    "path": "src/routes/debug.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport jester\nimport router_utils\nimport \"..\"/[auth, types]\n\nproc createDebugRouter*(cfg: Config) =\n  router debug:\n    get \"/.health\":\n      respJson getSessionPoolHealth()\n\n    get \"/.sessions\":\n      cond cfg.enableDebug\n      respJson getSessionPoolDebug()\n"
  },
  {
    "path": "src/routes/embed.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport asyncdispatch, strutils, strformat, options\nimport jester, karax/vdom\nimport \"..\"/[types, api]\nimport ../views/[embed, tweet, general]\nimport router_utils\n\nexport api, embed, vdom, tweet, general, router_utils\n\nproc createEmbedRouter*(cfg: Config) =\n  router embed:\n    get \"/i/videos/tweet/@id\":\n      let tweet = await getGraphTweetResult(@\"id\")\n      if tweet == nil or not tweet.hasVideos:\n        resp Http404\n\n      resp renderVideoEmbed(tweet, cfg, request)\n\n    get \"/@user/status/@id/embed\":\n      let\n        tweet = await getGraphTweetResult(@\"id\")\n        prefs = requestPrefs()\n        path = getPath()\n\n      if tweet == nil:\n        resp Http404\n\n      resp renderTweetEmbed(tweet, path, prefs, cfg, request)\n\n    get \"/embed/Tweet.html\":\n      let id = @\"id\"\n\n      if id.len > 0:\n        redirect(&\"/i/status/{id}/embed\")\n      else:\n        resp Http404\n"
  },
  {
    "path": "src/routes/list.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport strutils, strformat, uri\n\nimport jester\n\nimport router_utils\nimport \"..\"/[types, redis_cache, api]\nimport ../views/[general, timeline, list]\n\ntemplate respList*(list, timeline, title, vnode: typed) =\n  if list.id.len == 0 or list.name.len == 0:\n    resp Http404, showError(&\"\"\"List \"{@\"id\"}\" not found\"\"\", cfg)\n\n  let\n    html = renderList(vnode, timeline.query, list)\n    rss = if cfg.enableRSSList: &\"\"\"/i/lists/{@\"id\"}/rss\"\"\" else: \"\"\n\n  resp renderMain(html, request, cfg, prefs, titleText=title, rss=rss, banner=list.banner)\n\nproc title*(list: List): string =\n  &\"@{list.username}/{list.name}\"\n\nproc createListRouter*(cfg: Config) =\n  router list:\n    get \"/@name/lists/@slug/?\":\n      cond '.' notin @\"name\"\n      cond @\"name\" != \"i\"\n      cond @\"slug\" != \"memberships\"\n      let\n        slug = decodeUrl(@\"slug\")\n        list = await getCachedList(@\"name\", slug)\n      if list.id.len == 0:\n        resp Http404, showError(&\"\"\"List \"{@\"slug\"}\" not found\"\"\", cfg)\n      redirect(&\"/i/lists/{list.id}\")\n\n    get \"/i/lists/@id/?\":\n      cond '.' notin @\"id\"\n      let\n        prefs = requestPrefs()\n        list = await getCachedList(id=(@\"id\"))\n        timeline = await getGraphListTweets(list.id, getCursor())\n        vnode = renderTimelineTweets(timeline, prefs, request.path)\n      respList(list, timeline, list.title, vnode)\n\n    get \"/i/lists/@id/members\":\n      cond '.' notin @\"id\"\n      let\n        prefs = requestPrefs()\n        list = await getCachedList(id=(@\"id\"))\n        members = await getGraphListMembers(list, getCursor())\n      respList(list, members, list.title, renderTimelineUsers(members, prefs, request.path))\n"
  },
  {
    "path": "src/routes/media.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport uri, strutils, httpclient, os, hashes, base64, re\nimport asynchttpserver, asyncstreams, asyncfile, asyncnet\n\nimport jester\n\nimport router_utils\nimport \"..\"/[types, formatters, utils]\n\nexport asynchttpserver, asyncstreams, asyncfile, asyncnet\nexport httpclient, os, strutils, asyncstreams, base64, re\n\nconst\n  m3u8Mime* = \"application/vnd.apple.mpegurl\"\n  maxAge* = \"max-age=604800\"\n\nproc safeFetch*(url: string): Future[string] {.async.} =\n  let client = newAsyncHttpClient()\n  try: result = await client.getContent(url)\n  except: discard\n  finally: client.close()\n\ntemplate respond*(req: asynchttpserver.Request; headers) =\n  var msg = \"HTTP/1.1 200 OK\\c\\L\"\n  for k, v in headers:\n    msg.add(k & \": \" & v & \"\\c\\L\")\n\n  msg.add \"\\c\\L\"\n  yield req.client.send(msg)\n\nproc proxyMedia*(req: jester.Request; url: string): Future[HttpCode] {.async.} =\n  result = Http200\n  let\n    request = req.getNativeReq()\n    client = newAsyncHttpClient()\n\n  try:\n    let res = await client.get(url)\n    if res.status != \"200 OK\":\n      if res.status != \"404 Not Found\":\n        echo \"[media] Proxying failed, status: $1, url: $2\" % [res.status, url]\n      return Http404\n\n    let hashed = $hash(url)\n    if request.headers.getOrDefault(\"If-None-Match\") == hashed:\n      return Http304\n\n    let contentLength =\n      if res.headers.hasKey(\"content-length\"):\n        res.headers[\"content-length\", 0]\n      else:\n        \"\"\n\n    let headers = newHttpHeaders({\n      \"content-type\": res.headers[\"content-type\", 0],\n      \"content-length\": contentLength,\n      \"cache-control\": maxAge,\n      \"etag\": hashed\n    })\n\n    respond(request, headers)\n\n    var (hasValue, data) = (true, \"\")\n    while hasValue:\n      (hasValue, data) = await res.bodyStream.read()\n      if hasValue:\n        await request.client.send(data)\n    data.setLen 0\n  except HttpRequestError, ProtocolError, OSError:\n    echo \"[media] Proxying exception, error: $1, url: $2\" % [getCurrentExceptionMsg(), url]\n    result = Http404\n  finally:\n    client.close()\n\ntemplate check*(code): untyped =\n  if code != Http200:\n    resp code\n  else:\n    enableRawMode()\n    break route\n\nproc decoded*(req: jester.Request; index: int): string =\n  let\n    based = req.matches[0].len > 1\n    encoded = req.matches[index]\n  if based: decode(encoded)\n  else: decodeUrl(encoded)\n\nproc createMediaRouter*(cfg: Config) =\n  router media:\n    get \"/pic/?\":\n      resp Http404\n\n    get re\"^\\/pic\\/orig\\/(enc)?\\/?(.+)\":\n      var url = decoded(request, 1)\n      cond \"/amplify_video/\" notin url\n\n      if \"twimg.com\" notin url:\n        url.insert(twimg)\n      if not url.startsWith(https):\n        url.insert(https)\n      url.add(\"?name=orig\")\n\n      let uri = parseUri(url)\n      cond isTwitterUrl(uri) == true\n\n      let code = await proxyMedia(request, url)\n      check code\n\n    get re\"^\\/pic\\/(enc)?\\/?(.+)\":\n      var url = decoded(request, 1)\n      cond \"/amplify_video/\" notin url\n\n      if \"twimg.com\" notin url:\n        url.insert(twimg)\n      if not url.startsWith(https):\n        url.insert(https)\n\n      let uri = parseUri(url)\n      cond isTwitterUrl(uri) == true\n\n      let code = await proxyMedia(request, url)\n      check code\n\n    get re\"^\\/video\\/(enc)?\\/?(.+)\\/(.+)$\":\n      let url = decoded(request, 2)\n      cond \"http\" in url\n\n      if getHmac(url) != request.matches[1]:\n        resp Http403, showError(\"Failed to verify signature\", cfg)\n\n      if \".mp4\" in url or \".ts\" in url or \".m4s\" in url:\n        let code = await proxyMedia(request, url)\n        check code\n\n      var content: string\n      if \".vmap\" in url:\n        let m3u8 = getM3u8Url(await safeFetch(url))\n        if m3u8.len > 0:\n          content = await safeFetch(url)\n        else:\n          resp Http404\n\n      if \".m3u8\" in url:\n        let vid = await safeFetch(url)\n        content = proxifyVideo(vid, requestPrefs().proxyVideos)\n\n      resp content, m3u8Mime\n"
  },
  {
    "path": "src/routes/preferences.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport strutils, uri, os, algorithm\n\nimport jester\n\nimport router_utils\nimport \"..\"/[types, formatters]\nimport ../views/[general, preferences]\n\nexport preferences\n\nproc findThemes*(dir: string): seq[string] =\n  for kind, path in walkDir(dir / \"css\" / \"themes\"):\n    let theme = path.splitFile.name\n    result.add theme.replace(\"_\", \" \").titleize\n  sort(result)\n\nproc createPrefRouter*(cfg: Config) =\n  router preferences:\n    get \"/settings\":\n      let\n        prefs = requestPrefs()\n        prefsCode = encodePrefs(prefs)\n        prefsUrl = getUrlPrefix(cfg) & \"/?prefs=\" & prefsCode\n        html = renderPreferences(prefs, refPath(), findThemes(cfg.staticDir), prefsUrl)\n      resp renderMain(html, request, cfg, prefs, \"Preferences\")\n\n    get \"/settings/@i?\":\n      redirect(\"/settings\")\n\n    post \"/saveprefs\":\n      genUpdatePrefs()\n      redirect(refPath())\n\n    post \"/resetprefs\":\n      genResetPrefs()\n      redirect(\"/settings?referer=\" & encodeUrl(refPath()))\n\n    post \"/enablehls\":\n      savePref(\"hlsPlayback\", \"on\", request)\n      redirect(refPath())\n\n"
  },
  {
    "path": "src/routes/resolver.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport strutils\n\nimport jester\n\nimport router_utils\nimport \"..\"/[types, api]\nimport ../views/general\n\ntemplate respResolved*(url, kind: string): untyped =\n  let u = url\n  if u.len == 0:\n    resp showError(\"Invalid $1 link\" % kind, cfg)\n  else:\n    redirect(u)\n\nproc createResolverRouter*(cfg: Config) =\n  router resolver:\n    get \"/cards/@card/@id\":\n      let url = \"https://cards.twitter.com/cards/$1/$2\" % [@\"card\", @\"id\"]\n      respResolved(await resolve(url, requestPrefs()), \"card\")\n\n    get \"/t.co/@url\":\n      let url = \"https://t.co/\" & @\"url\"\n      respResolved(await resolve(url, requestPrefs()), \"t.co\")\n"
  },
  {
    "path": "src/routes/router_utils.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport strutils, sequtils, uri, tables, json\nfrom jester import Request, cookies\n\nimport ../views/general\nimport \"..\"/[utils, prefs, types]\nexport utils, prefs, types, uri\n\ntemplate savePref*(pref, value: string; req: Request; expire=false) =\n  if not expire or pref in cookies(req):\n    setCookie(pref, value, daysForward(when expire: -10 else: 360),\n              httpOnly=true, secure=cfg.useHttps, sameSite=None, path=\"/\")\n\ntemplate requestPrefs*(): untyped {.dirty.} =\n  getPrefs(cookies(request), params(request))\n\ntemplate showError*(error: string; cfg: Config): string =\n  renderMain(renderError(error), request, cfg, requestPrefs(), \"Error\")\n\ntemplate getPath*(): untyped {.dirty.} =\n  $(parseUri(request.path) ? filterParams(request.params))\n\ntemplate refPath*(): untyped {.dirty.} =\n  if @\"referer\".len > 0: @\"referer\" else: \"/\"\n\ntemplate getCursor*(): string =\n  let cursor = @\"cursor\"\n  decodeUrl(if cursor.len > 0: cursor else: @\"max_position\", false)\n\ntemplate getCursor*(req: Request): string =\n  let cursor = req.params.getOrDefault(\"cursor\")\n  decodeUrl(if cursor.len > 0: cursor\n            else: req.params.getOrDefault(\"max_position\"), false)\n\nproc getNames*(name: string): seq[string] =\n  name.strip(chars={'/'}).split(\",\").filterIt(it.len > 0)\n\ntemplate applyUrlPrefs*() {.dirty.} =\n  if @\"prefs\".len > 0:\n    var prefParams = initTable[string, string]()\n    for pair in @\"prefs\".split(','):\n      let kv = pair.split('=', maxsplit=1)\n      if kv.len == 2:\n        prefParams[kv[0]] = kv[1]\n      elif kv.len == 1 and kv[0].len > 0:\n        prefParams[kv[0]] = \"\"\n    genApplyPrefs(prefParams, request)\n\n    # Rebuild URL without prefs param\n    var params: seq[(string, string)]\n    for k, v in request.params:\n      if k != \"prefs\":\n        params.add (k, v)\n\n    if params.len > 0:\n      let cleanUrl = request.getNativeReq.url ? params\n      redirect($cleanUrl)\n    else:\n      redirect(request.path)\n\ntemplate respJson*(node: JsonNode) =\n  resp $node, \"application/json\"\n"
  },
  {
    "path": "src/routes/rss.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport asyncdispatch, tables, times, hashes, uri\n\nimport jester\n\nimport router_utils, timeline\nimport ../query\n\ninclude \"../views/rss.nimf\"\n\nexport times, hashes\n\nproc redisKey*(page, name, cursor: string): string =\n  result = page & \":\" & name\n  if cursor.len > 0:\n    result &= \":\" & cursor\n\nproc timelineRss*(req: Request; cfg: Config; query: Query; prefs: Prefs): Future[Rss] {.async.} =\n  var profile: Profile\n  let\n    name = req.params.getOrDefault(\"name\")\n    after = getCursor(req)\n    names = getNames(name)\n\n  if names.len == 1:\n    profile = await fetchProfile(after, query, skipRail=true)\n  else:\n    var q = query\n    q.fromUser = names\n    profile.tweets = await getGraphTweetSearch(q, after)\n    # this is kinda dumb\n    profile.user = User(\n      username: name,\n      fullname: names.join(\" | \"),\n      userpic: \"https://abs.twimg.com/sticky/default_profile_images/default_profile.png\"\n    )\n\n  if profile.user.suspended:\n    return Rss(feed: profile.user.username, cursor: \"suspended\")\n\n  if profile.user.fullname.len > 0:\n    let rss = renderTimelineRss(profile, cfg, prefs, multi=(names.len > 1))\n    return Rss(feed: rss, cursor: profile.tweets.bottom)\n\ntemplate respRss*(rss, page) =\n  if rss.cursor.len == 0:\n    let info = case page\n               of \"User\": \" \\\"\" & @\"name\" & \"\\\" \"\n               of \"List\": \" \\\"\" & @\"id\" & \"\\\" \"\n               else: \" \"\n\n    resp Http404, showError(page & info & \"not found\", cfg)\n  elif rss.cursor.len == 9 and rss.cursor == \"suspended\":\n    resp Http404, showError(getSuspended(@\"name\"), cfg)\n\n  let headers = {\"Content-Type\": \"application/rss+xml; charset=utf-8\",\n                 \"Min-Id\": rss.cursor}\n  resp Http200, headers, rss.feed\n\nproc createRssRouter*(cfg: Config) =\n  router rss:\n    get \"/search/rss\":\n      if not cfg.enableRSSSearch:\n        resp Http403, showError(\"RSS feed is disabled\", cfg)\n      if @\"q\".len > 200:\n        resp Http400, showError(\"Search input too long.\", cfg)\n\n      let\n        prefs = requestPrefs()\n        query = initQuery(params(request))\n      if query.kind != tweets:\n        resp Http400, showError(\"Only Tweet searches are allowed for RSS feeds.\", cfg)\n\n      let\n        cursor = getCursor()\n        key = redisKey(\"search\", $hash(genQueryUrl(query)), cursor)\n\n      var rss = await getCachedRss(key)\n      if rss.cursor.len > 0:\n        respRss(rss, \"Search\")\n\n      let tweets = await getGraphTweetSearch(query, cursor)\n      rss.cursor = tweets.bottom\n      rss.feed = renderSearchRss(tweets.content, query.text, genQueryUrl(query), cfg, prefs)\n\n      await cacheRss(key, rss)\n      respRss(rss, \"Search\")\n\n    get \"/@name/rss\":\n      cond '.' notin @\"name\"\n      if not cfg.enableRSSUserTweets:\n        resp Http403, showError(\"RSS feed is disabled\", cfg)\n      let\n        prefs = requestPrefs()\n        name = @\"name\"\n        key = redisKey(\"twitter\", name, getCursor())\n\n      var rss = await getCachedRss(key)\n      if rss.cursor.len > 0:\n        respRss(rss, \"User\")\n\n      rss = await timelineRss(request, cfg, Query(fromUser: @[name]), prefs)\n\n      await cacheRss(key, rss)\n      respRss(rss, \"User\")\n\n    get \"/@name/@tab/rss\":\n      cond '.' notin @\"name\"\n      cond @\"tab\" in [\"with_replies\", \"media\", \"search\"]\n      let rssEnabled = case @\"tab\"\n        of \"with_replies\": cfg.enableRSSUserReplies\n        of \"media\": cfg.enableRSSUserMedia\n        of \"search\": cfg.enableRSSSearch\n        else: false\n      if not rssEnabled:\n        resp Http403, showError(\"RSS feed is disabled\", cfg)\n      let\n        prefs = requestPrefs()\n        name = @\"name\"\n        tab = @\"tab\"\n        query =\n          case tab\n          of \"with_replies\": getReplyQuery(name)\n          of \"media\": getMediaQuery(name)\n          of \"search\": initQuery(params(request), name=name)\n          else: Query(fromUser: @[name])\n\n      let searchKey = if tab != \"search\": \"\"\n                      else: \":\" & $hash(genQueryUrl(query))\n\n      let key = redisKey(tab, name & searchKey, getCursor())\n\n      var rss = await getCachedRss(key)\n      if rss.cursor.len > 0:\n        respRss(rss, \"User\")\n\n      rss = await timelineRss(request, cfg, query, prefs)\n\n      await cacheRss(key, rss)\n      respRss(rss, \"User\")\n\n    get \"/@name/lists/@slug/rss\":\n      cond @\"name\" != \"i\"\n      if not cfg.enableRSSList:\n        resp Http403, showError(\"RSS feed is disabled\", cfg)\n      let\n        slug = decodeUrl(@\"slug\")\n        list = await getCachedList(@\"name\", slug)\n        cursor = getCursor()\n\n      if list.id.len == 0:\n        resp Http404, showError(\"List \\\"\" & @\"slug\" & \"\\\" not found\", cfg)\n\n      let url = \"/i/lists/\" & list.id & \"/rss\"\n      if cursor.len > 0:\n        redirect(url & \"?cursor=\" & encodeUrl(cursor, false))\n      else:\n        redirect(url)\n\n    get \"/i/lists/@id/rss\":\n      if not cfg.enableRSSList:\n        resp Http403, showError(\"RSS feed is disabled\", cfg)\n      let\n        prefs = requestPrefs()\n        id = @\"id\"\n        cursor = getCursor()\n        key = redisKey(\"lists\", id, cursor)\n\n      var rss = await getCachedRss(key)\n      if rss.cursor.len > 0:\n        respRss(rss, \"List\")\n\n      let\n        list = await getCachedList(id=id)\n        timeline = await getGraphListTweets(list.id, cursor)\n      rss.cursor = timeline.bottom\n      rss.feed = renderListRss(timeline.content, list, cfg, prefs)\n\n      await cacheRss(key, rss)\n      respRss(rss, \"List\")\n"
  },
  {
    "path": "src/routes/search.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport strutils, uri\n\nimport jester\n\nimport router_utils\nimport \"..\"/[query, types, api, formatters]\nimport ../views/[general, search]\n\ninclude \"../views/opensearch.nimf\"\n\nexport search\n\nproc createSearchRouter*(cfg: Config) =\n  router search:\n    get \"/search/?\":\n      let q = @\"q\"\n      if q.len > 500:\n        resp Http400, showError(\"Search input too long.\", cfg)\n\n      let\n        prefs = requestPrefs()\n        query = initQuery(params(request))\n        title = \"Search\" & (if q.len > 0: \" (\" & q & \")\" else: \"\")\n\n      case query.kind\n      of users:\n        if \",\" in q:\n          redirect(\"/\" & q)\n        var users: Result[User]\n        try:\n          users = await getGraphUserSearch(query, getCursor())\n        except InternalError:\n          users = Result[User](beginning: true, query: query)\n        resp renderMain(renderUserSearch(users, prefs), request, cfg, prefs, title)\n      of tweets:\n        let\n          tweets = await getGraphTweetSearch(query, getCursor())\n          rss = if cfg.enableRSSSearch: \"/search/rss?\" & genQueryUrl(query) else: \"\"\n        resp renderMain(renderTweetSearch(tweets, prefs, getPath()),\n                        request, cfg, prefs, title, rss=rss)\n      else:\n        resp Http404, showError(\"Invalid search\", cfg)\n\n    get \"/hashtag/@hash\":\n      redirect(\"/search?f=tweets&q=\" & encodeUrl(\"#\" & @\"hash\"))\n\n    get \"/opensearch\":\n      let url = getUrlPrefix(cfg) & \"/search?f=tweets&q=\"\n      resp Http200, {\"Content-Type\": \"application/opensearchdescription+xml\"},\n                     generateOpenSearchXML(cfg.title, cfg.hostname, url)\n"
  },
  {
    "path": "src/routes/status.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport asyncdispatch, strutils, sequtils, uri, options, sugar\n\nimport jester, karax/vdom\n\nimport router_utils\nimport \"..\"/[types, formatters, api]\nimport ../views/[general, status]\n\nexport uri, sequtils, options, sugar\nexport router_utils\nexport api, formatters\nexport status\n\nproc createStatusRouter*(cfg: Config) =\n  router status:\n    get \"/@name/status/@id/?\":\n      cond '.' notin @\"name\"\n      let id = @\"id\"\n\n      if id.len > 19 or id.any(c => not c.isDigit):\n        resp Http404, showError(\"Invalid tweet ID\", cfg)\n\n      let prefs = requestPrefs()\n\n      # used for the infinite scroll feature\n      if @\"scroll\".len > 0:\n        let replies = await getReplies(id, getCursor())\n        if replies.content.len == 0:\n          resp Http204\n        resp $renderReplies(replies, prefs, getPath())\n\n      let conv = await getTweet(id, getCursor())\n\n      if conv == nil or conv.tweet == nil or conv.tweet.id == 0:\n        var error = \"Tweet not found\"\n        if conv != nil and conv.tweet != nil and conv.tweet.tombstone.len > 0:\n          error = conv.tweet.tombstone\n        resp Http404, showError(error, cfg)\n\n      let\n        title = pageTitle(conv.tweet)\n        ogTitle = pageTitle(conv.tweet.user)\n        desc = conv.tweet.text\n\n      var\n        images = conv.tweet.getPhotos.mapIt(it.url)\n        video = \"\"\n\n      let\n        firstMediaKind = if conv.tweet.media.len > 0: conv.tweet.media[0].kind\n                         else: photoMedia\n\n      if firstMediaKind == videoMedia:\n        images = @[conv.tweet.media[0].getThumb]\n        video = getVideoEmbed(cfg, conv.tweet.id)\n      elif firstMediaKind == gifMedia:\n        images = @[conv.tweet.media[0].getThumb]\n        video = getPicUrl(conv.tweet.media[0].gif.url)\n      elif conv.tweet.card.isSome():\n        let card = conv.tweet.card.get()\n        if card.image.len > 0:\n          images = @[card.image]\n        elif card.video.isSome():\n          images = @[card.video.get().thumb]\n\n      let html = renderConversation(conv, prefs, getPath() & \"#m\")\n      resp renderMain(html, request, cfg, prefs, title, desc, ogTitle,\n                      images=images, video=video)\n\n    get \"/@name/status/@id/history/?\":\n      cond '.' notin @\"name\"\n      let id = @\"id\"\n\n      if id.len > 19 or id.any(c => not c.isDigit):\n        resp Http404, showError(\"Invalid tweet ID\", cfg)\n\n      let edits = await getGraphEditHistory(id)\n      if edits.latest == nil or edits.latest.id == 0:\n        resp Http404, showError(\"Tweet history not found\", cfg)\n\n      let\n        prefs = requestPrefs()\n        title = \"History for \" & pageTitle(edits.latest)\n        ogTitle = \"Edit History for \" & pageTitle(edits.latest.user)\n        desc = edits.latest.text\n\n      let html = renderEditHistory(edits, prefs, getPath())\n      resp renderMain(html, request, cfg, prefs, title, desc, ogTitle)\n\n    get \"/@name/@s/@id/@m/?@i?\":\n      cond @\"s\" in [\"status\", \"statuses\"]\n      cond @\"m\" in [\"video\", \"photo\"]\n      redirect(\"/$1/status/$2\" % [@\"name\", @\"id\"])\n\n    get \"/@name/statuses/@id/?\":\n      redirect(\"/$1/status/$2\" % [@\"name\", @\"id\"])\n\n    get \"/i/web/status/@id\":\n      redirect(\"/i/status/\" & @\"id\")\n\n    get \"/@name/thread/@id/?\":\n      redirect(\"/$1/status/$2\" % [@\"name\", @\"id\"])\n"
  },
  {
    "path": "src/routes/timeline.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport asyncdispatch, strutils, sequtils, uri, options, times\nimport jester, karax/vdom\n\nimport router_utils\nimport \"..\"/[types, redis_cache, formatters, query, api]\nimport ../views/[general, profile, timeline, status, search]\n\nexport vdom\nexport uri, sequtils\nexport router_utils\nexport redis_cache, formatters, query, api\nexport profile, timeline, status\n\nproc getQuery*(request: Request; tab, name: string; prefs: Prefs): Query =\n  let view = request.params.getOrDefault(\"view\")\n  case tab\n  of \"with_replies\":\n    result = getReplyQuery(name)\n  of \"media\":\n    result = getMediaQuery(name)\n    result.view =\n      if view in [\"timeline\", \"grid\", \"gallery\"]: view\n      else: prefs.mediaView.toLowerAscii\n  of \"search\":\n    result = initQuery(params(request), name=name)\n  else:\n    result = Query(fromUser: @[name])\n\ntemplate skipIf[T](cond: bool; default; body: Future[T]): Future[T] =\n  if cond:\n    let fut = newFuture[T]()\n    fut.complete(default)\n    fut\n  else:\n    body\n\nproc fetchProfile*(after: string; query: Query; skipRail=false): Future[Profile] {.async.} =\n  let\n    name = query.fromUser[0]\n    userId = await getUserId(name)\n\n  if userId.len == 0:\n    return Profile(user: User(username: name))\n  elif userId == \"suspended\":\n    return Profile(user: User(username: name, suspended: true))\n\n  # temporary fix to prevent errors from people browsing\n  # timelines during/immediately after deployment\n  var after = after\n  if query.kind in {posts, replies} and after.startsWith(\"scroll\"):\n    after.setLen 0\n\n  let\n    rail =\n      skipIf(skipRail or query.kind == media, @[]):\n        getCachedPhotoRail(userId)\n\n    user = getCachedUser(name)\n\n  result =\n    case query.kind\n    of posts: await getGraphUserTweets(userId, TimelineKind.tweets, after)\n    of replies: await getGraphUserTweets(userId, TimelineKind.replies, after)\n    of media: await getGraphUserTweets(userId, TimelineKind.media, after)\n    else: Profile(tweets: await getGraphTweetSearch(query, after))\n\n  result.user = await user\n  result.photoRail = await rail\n\n  result.tweets.query = query\n\nproc showTimeline*(request: Request; query: Query; cfg: Config; prefs: Prefs;\n                   rss, after: string): Future[string] {.async.} =\n  if query.fromUser.len != 1:\n    let\n      timeline = await getGraphTweetSearch(query, after)\n      html = renderTweetSearch(timeline, prefs, getPath())\n    return renderMain(html, request, cfg, prefs, \"Multi\", rss=rss)\n\n  var profile = await fetchProfile(after, query)\n  template u: untyped = profile.user\n\n  if u.suspended:\n    return showError(getSuspended(u.username), cfg)\n\n  if profile.user.id.len == 0: return\n\n  let pHtml = renderProfile(profile, prefs, getPath())\n  result = renderMain(pHtml, request, cfg, prefs, pageTitle(u), pageDesc(u),\n                      rss=rss, images = @[u.getUserPic(\"_400x400\")],\n                      banner=u.banner)\n\ntemplate respTimeline*(timeline: typed) =\n  let t = timeline\n  if t.len == 0:\n    resp Http404, showError(\"User \\\"\" & @\"name\" & \"\\\" not found\", cfg)\n  resp t\n\ntemplate respUserId*() =\n  cond @\"user_id\".len > 0\n  let username = await getCachedUsername(@\"user_id\")\n  if username.len > 0:\n    redirect(\"/\" & username)\n  else:\n    resp Http404, showError(\"User not found\", cfg)\n\nproc createTimelineRouter*(cfg: Config) =\n  router timeline:\n    get \"/i/user/@user_id\":\n      respUserId()\n\n    get \"/intent/user\":\n      respUserId()\n\n    get \"/intent/follow/?\":\n      let username = request.params.getOrDefault(\"screen_name\")\n      if username.len == 0:\n        resp Http400, showError(\"Missing screen_name parameter\", cfg)\n      redirect(\"/\" & username)\n\n    get \"/@name/?@tab?/?\":\n      cond '.' notin @\"name\"\n      cond @\"name\" notin [\"pic\", \"gif\", \"video\", \"search\", \"settings\", \"login\", \"intent\", \"i\"]\n      cond @\"name\".allCharsInSet({'a'..'z', 'A'..'Z', '0'..'9', '_', ','})\n      cond @\"tab\" in [\"with_replies\", \"media\", \"search\", \"\"]\n      let\n        prefs = requestPrefs()\n        after = getCursor()\n        names = getNames(@\"name\")\n\n      var query = request.getQuery(@\"tab\", @\"name\", prefs)\n      if names.len != 1:\n        query.fromUser = names\n\n      # used for the infinite scroll feature\n      if @\"scroll\".len > 0:\n        if query.fromUser.len != 1:\n          var timeline = await getGraphTweetSearch(query, after)\n          if timeline.content.len == 0: \n            resp Http204\n          timeline.beginning = true\n          resp $renderTweetSearch(timeline, prefs, getPath())\n        else:\n          var profile = await fetchProfile(after, query, skipRail=true)\n          if profile.tweets.content.len == 0: resp Http404\n          profile.tweets.beginning = true\n          resp $renderTimelineTweets(profile.tweets, prefs, getPath())\n\n      let rssEnabled =\n        if @\"tab\".len == 0: cfg.enableRSSUserTweets\n        elif @\"tab\" == \"with_replies\": cfg.enableRSSUserReplies\n        elif @\"tab\" == \"media\": cfg.enableRSSUserMedia\n        elif @\"tab\" == \"search\": cfg.enableRSSSearch\n        else: false\n\n      let rss =\n        if not rssEnabled: \n          \"\"\n        elif @\"tab\".len == 0:\n          \"/$1/rss\" % @\"name\"\n        elif @\"tab\" == \"search\":\n          \"/$1/search/rss?$2\" % [@\"name\", genQueryUrl(query)]\n        else:\n          \"/$1/$2/rss\" % [@\"name\", @\"tab\"]\n\n      respTimeline(await showTimeline(request, query, cfg, prefs, rss, after))\n"
  },
  {
    "path": "src/routes/unsupported.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport jester\n\nimport router_utils\nimport ../types\nimport ../views/[general, feature]\n\nexport feature\n\nproc createUnsupportedRouter*(cfg: Config) =\n  router unsupported:\n    template feature {.dirty.} =\n      resp renderMain(renderFeature(), request, cfg, requestPrefs())\n\n    get \"/about/feature\": feature()\n    get \"/login/?@i?\": feature()\n    get \"/@name/lists/?\": feature()\n\n    get \"/intent/?@i?\": \n      cond @\"i\" notin [\"user\", \"follow\"]\n      feature()\n\n    get \"/i/@i?/?@j?\":\n      cond @\"i\" notin [\"status\", \"lists\" , \"user\"]\n      feature()\n"
  },
  {
    "path": "src/sass/general.scss",
    "content": "@import \"_variables\";\n@import \"_mixins\";\n\n.panel-container {\n  margin: auto;\n  font-size: 130%;\n}\n\n.error-panel {\n  @include center-panel(var(--error_red));\n  text-align: center;\n}\n\n.search-bar > form {\n  @include center-panel(var(--darkest_grey));\n\n  button {\n    background: var(--bg_elements);\n    color: var(--fg_color);\n    border: 0;\n    border-radius: 3px;\n    cursor: pointer;\n    font-weight: bold;\n    width: 30px;\n    height: 30px;\n    padding: 0px 5px 1px 8px;\n  }\n\n  input {\n    font-size: 16px;\n    width: 100%;\n    background: var(--bg_elements);\n    color: var(--fg_color);\n    border: 0;\n    border-radius: 4px;\n    padding: 4px;\n    margin-right: 8px;\n    height: unset;\n  }\n}\n"
  },
  {
    "path": "src/sass/include/_mixins.css",
    "content": "@import '_variables';\n\n@mixin panel($width, $max-width) {\n    max-width: $max-width;\n    margin: 0 auto;\n    float: none;\n    border-radius: 0;\n    position: relative;\n    width: $width;\n}\n\n@mixin play-button {\n    position: absolute;\n    width: 100%;\n    height: 100%;\n    top: 0;\n    left: 0;\n    z-index: 1;\n\n    &:hover {\n        .overlay-circle {\n            border-color: var(--play_button_hover);\n        }\n\n        .overlay-triangle {\n            border-color: transparent transparent transparent var(--play_button_hover);\n        }\n    }\n}\n\n@mixin breakable {\n    overflow: hidden;\n    overflow-wrap: break-word;\n}\n\n@mixin ellipsis {\n    overflow: hidden;\n    text-overflow: ellipsis;\n    white-space: nowrap;\n}\n\n@mixin center-panel($bg) {\n    padding: 12px;\n    border-radius: 4px;\n    display: flex;\n    background: $bg;\n    box-shadow: 0 0 15px $shadow_dark;\n    margin: auto;\n    margin-top: -50px;\n}\n\n@mixin input-colors {\n    &:hover {\n        border-color: var(--accent);\n    }\n\n    &:active {\n        border-color: var(--accent_light);\n    }\n}\n\n@mixin search-resize($width, $rows) {\n    @media(max-width: $width) {\n        .search-toggles {\n            grid-template-columns: repeat($rows, auto);\n        }\n\n        #search-panel-toggle:checked ~ .search-panel {\n            max-height: 380px !important;\n        }\n    }\n}\n\n@mixin create-toggle($elem, $height) {\n    ##{$elem}-toggle {\n        display: none;\n\n        &:checked ~ .#{$elem} {\n            max-height: $height;\n        }\n\n        &:checked ~ label .icon-down:before {\n            transform: rotate(180deg) translateY(-1px);\n        }\n    }\n}\n"
  },
  {
    "path": "src/sass/include/_variables.scss",
    "content": "// colors\n$bg_color: #0f0f0f;\n$fg_color: #f8f8f2;\n$fg_faded: #f8f8f2cf;\n$fg_dark: #ff6c60;\n$fg_nav: #ff6c60;\n\n$bg_panel: #161616;\n$bg_elements: #121212;\n$bg_overlays: #1f1f1f;\n$bg_hover: #1a1a1a;\n\n$grey: #888889;\n$dark_grey: #404040;\n$darker_grey: #282828;\n$darkest_grey: #222222;\n$border_grey: #3e3e35;\n\n$accent: #ff6c60;\n$accent_light: #ffaca0;\n$accent_dark: #8a3731;\n$accent_border: #ff6c6091;\n\n$play_button: #d8574d;\n$play_button_hover: #ff6c60;\n\n$more_replies_dots: #ad433b;\n$error_red: #420a05;\n\n$verified_blue: #1da1f2;\n$verified_business: #fac82b;\n$verified_government: #c1b6a4;\n$icon_text: $fg_color;\n\n$tab: $fg_color;\n$tab_selected: $accent;\n\n$shadow: rgba(0, 0, 0, 0.6);\n$shadow_dark: rgba(0, 0, 0, 0.2);\n\n//fonts\n$font_0: sans-serif;\n$font_1: fontello;\n"
  },
  {
    "path": "src/sass/index.scss",
    "content": "@import \"_variables\";\n\n@import \"tweet/_base\";\n@import \"profile/_base\";\n@import \"general\";\n@import \"navbar\";\n@import \"inputs\";\n@import \"timeline\";\n@import \"search\";\n\nbody {\n  // colors\n  --bg_color: #{$bg_color};\n  --fg_color: #{$fg_color};\n  --fg_faded: #{$fg_faded};\n  --fg_dark: #{$fg_dark};\n  --fg_nav: #{$fg_nav};\n\n  --bg_panel: #{$bg_panel};\n  --bg_elements: #{$bg_elements};\n  --bg_overlays: #{$bg_overlays};\n  --bg_hover: #{$bg_hover};\n\n  --grey: #{$grey};\n  --dark_grey: #{$dark_grey};\n  --darker_grey: #{$darker_grey};\n  --darkest_grey: #{$darkest_grey};\n  --border_grey: #{$border_grey};\n\n  --accent: #{$accent};\n  --accent_light: #{$accent_light};\n  --accent_dark: #{$accent_dark};\n  --accent_border: #{$accent_border};\n\n  --play_button: #{$play_button};\n  --play_button_hover: #{$play_button_hover};\n\n  --more_replies_dots: #{$more_replies_dots};\n  --error_red: #{$error_red};\n\n  --verified_blue: #{$verified_blue};\n  --verified_business: #{$verified_business};\n  --verified_government: #{$verified_government};\n  --icon_text: #{$icon_text};\n\n  --tab: #{$fg_color};\n  --tab_selected: #{$accent};\n\n  --profile_stat: #{$fg_color};\n\n  background-color: var(--bg_color);\n  color: var(--fg_color);\n  font-family: $font_0, $font_1;\n  font-size: 15px;\n  line-height: 1.3;\n  margin: 0;\n}\n\n* {\n  outline: unset;\n  margin: 0;\n  text-decoration: none;\n}\n\nimg {\n  dynamic-range-limit: standard;\n}\n\nh1 {\n  display: inline;\n}\n\nh2,\nh3 {\n  font-weight: normal;\n}\n\np {\n  margin: 14px 0;\n}\n\na {\n  color: var(--accent);\n\n  &:hover {\n    text-decoration: underline;\n  }\n}\n\nfieldset {\n  border: 0;\n  padding: 0;\n  margin-top: -0.6em;\n}\n\nlegend {\n  width: 100%;\n  padding: 0.6em 0 0.3em 0;\n  border: 0;\n  font-size: 16px;\n  font-weight: 600;\n  border-bottom: 1px solid var(--border_grey);\n  margin-bottom: 8px;\n}\n\n.preferences {\n  .note {\n    border-top: 1px solid var(--border_grey);\n    border-bottom: 1px solid var(--border_grey);\n    padding: 6px 0 8px 0;\n    margin-bottom: 8px;\n    margin-top: 16px;\n  }\n\n  .bookmark-note {\n    margin: 0;\n    margin-bottom: 10px;\n  }\n}\n\nul {\n  padding-left: 1.3em;\n}\n\n.container {\n  display: flex;\n  flex-wrap: wrap;\n  box-sizing: border-box;\n  margin: auto;\n  min-height: 100vh;\n}\n\nbody.fixed-nav .container {\n  padding-top: 50px;\n}\n\n.icon-container {\n  display: inline;\n}\n\n.overlay-panel {\n  max-width: 600px;\n  width: 100%;\n  margin: 0 auto;\n  margin-top: 10px;\n  background-color: var(--bg_overlays);\n  padding: 10px 15px;\n  align-self: start;\n\n  ul {\n    margin-bottom: 14px;\n  }\n\n  p {\n    word-break: break-word;\n  }\n}\n\n.verified-icon {\n  display: inline-block;\n  width: 14px;\n  height: 14px;\n  margin-left: 2px;\n\n  .verified-icon-circle {\n    position: absolute;\n    font-size: 15px;\n  }\n\n  .verified-icon-check {\n    position: absolute;\n    font-size: 9px;\n    margin: 5px 3px;\n  }\n\n  &.blue {\n    .verified-icon-circle {\n      color: var(--verified_blue);\n    }\n\n    .verified-icon-check {\n      color: var(--icon_text);\n    }\n  }\n\n  &.business {\n    .verified-icon-circle {\n      color: var(--verified_business);\n    }\n\n    .verified-icon-check {\n      color: var(--bg_panel);\n    }\n  }\n\n  &.government {\n    .verified-icon-circle {\n      color: var(--verified_government);\n    }\n\n    .verified-icon-check {\n      color: var(--bg_panel);\n    }\n  }\n}\n\n@media (max-width: 600px) {\n  .preferences-container {\n    max-width: 95vw;\n  }\n\n  .nav-item,\n  .nav-item .icon-container {\n    font-size: 16px;\n  }\n}\n"
  },
  {
    "path": "src/sass/inputs.scss",
    "content": "@import \"_variables\";\n@import \"_mixins\";\n\nbutton {\n  @include input-colors;\n  background-color: var(--bg_elements);\n  color: var(--fg_color);\n  border: 1px solid var(--accent_border);\n  padding: 3px 6px;\n  font-size: 14px;\n  cursor: pointer;\n  float: right;\n}\n\ninput[type=\"text\"],\ninput[type=\"date\"],\ninput[type=\"number\"],\nselect {\n  @include input-colors;\n  background-color: var(--bg_elements);\n  padding: 1px 4px;\n  color: var(--fg_color);\n  border: 1px solid var(--accent_border);\n  border-radius: 0;\n  font-size: 14px;\n}\n\ninput[type=\"number\"] {\n  -moz-appearance: textfield;\n}\n\ninput[type=\"text\"],\ninput[type=\"number\"] {\n  height: 16px;\n}\n\nselect {\n  height: 20px;\n  padding: 0 2px;\n  line-height: 1;\n}\n\ninput[type=\"date\"]::-webkit-inner-spin-button {\n  display: none;\n}\n\ninput[type=\"number\"] {\n  -moz-appearance: textfield;\n}\n\ninput[type=\"number\"]::-webkit-inner-spin-button,\ninput[type=\"number\"]::-webkit-outer-spin-button {\n  display: none;\n  -webkit-appearance: none;\n  margin: 0;\n}\n\ninput[type=\"date\"]::-webkit-clear-button {\n  margin-left: 17px;\n  filter: grayscale(100%);\n  filter: hue-rotate(120deg);\n}\n\ninput::-webkit-calendar-picker-indicator {\n  opacity: 0;\n}\n\ninput::-webkit-datetime-edit-day-field:focus,\ninput::-webkit-datetime-edit-month-field:focus,\ninput::-webkit-datetime-edit-year-field:focus {\n  background-color: var(--accent);\n  color: var(--fg_color);\n  outline: none;\n}\n\n.date-range {\n  .date-input {\n    display: inline-block;\n    position: relative;\n  }\n\n  .icon-container {\n    pointer-events: none;\n    position: absolute;\n    top: 2px;\n    right: 5px;\n  }\n\n  .search-title {\n    margin: 0 2px;\n  }\n}\n\n.icon-button button {\n  color: var(--accent);\n  text-decoration: none;\n  background: none;\n  border: none;\n  float: none;\n  padding: unset;\n  padding-left: 4px;\n\n  &:hover {\n    color: var(--accent_light);\n  }\n}\n\n.checkbox {\n  position: absolute;\n  top: 1px;\n  right: 0;\n  height: 17px;\n  width: 17px;\n  background-color: var(--bg_elements);\n  border: 1px solid var(--accent_border);\n\n  &:after {\n    content: \"\";\n    position: absolute;\n    display: none;\n  }\n}\n\n.checkbox-container {\n  display: block;\n  position: relative;\n  margin-bottom: 5px;\n  cursor: pointer;\n  user-select: none;\n  padding-right: 22px;\n\n  input {\n    position: absolute;\n    opacity: 0;\n    cursor: pointer;\n    height: 0;\n    width: 0;\n\n    &:checked ~ .checkbox:after {\n      display: block;\n    }\n  }\n\n  &:hover input ~ .checkbox {\n    border-color: var(--accent);\n  }\n\n  &:active input ~ .checkbox {\n    border-color: var(--accent_light);\n  }\n\n  .checkbox:after {\n    left: 2px;\n    bottom: 0;\n    font-size: 13px;\n    font-family: $font_1;\n    content: \"\\e811\";\n  }\n}\n\n.pref-group {\n  display: inline;\n}\n\n.preferences {\n  button {\n    margin: 6px 0 3px 0;\n  }\n\n  label {\n    padding-right: 150px;\n  }\n\n  select {\n    position: absolute;\n    top: 0;\n    right: 0;\n    display: block;\n    -moz-appearance: none;\n    -webkit-appearance: none;\n    appearance: none;\n    min-width: 100px;\n  }\n\n  input[type=\"text\"],\n  input[type=\"number\"] {\n    position: absolute;\n    right: 0;\n    max-width: 140px;\n  }\n\n  .pref-group {\n    display: block;\n  }\n\n  .pref-input {\n    position: relative;\n    margin-bottom: 6px;\n  }\n\n  .pref-reset {\n    float: left;\n  }\n\n  .prefs-code {\n    background-color: var(--bg_elements);\n    border: 1px solid var(--accent_border);\n    color: var(--fg_color);\n    font-size: 13px;\n    padding: 6px 8px;\n    margin: 4px 0;\n    word-break: break-all;\n    white-space: pre-wrap;\n    user-select: all;\n  }\n}\n"
  },
  {
    "path": "src/sass/navbar.scss",
    "content": "@import \"_variables\";\n\nnav {\n  display: flex;\n  align-items: center;\n  background-color: var(--bg_overlays);\n  box-shadow: 0 0 4px $shadow;\n  padding: 0;\n  width: 100%;\n  height: 50px;\n  z-index: 1000;\n  font-size: 16px;\n\n  a,\n  .icon-button button {\n    color: var(--fg_nav);\n  }\n\n  body.fixed-nav & {\n    position: fixed;\n  }\n}\n\n.inner-nav {\n  margin: auto;\n  box-sizing: border-box;\n  padding: 0 10px;\n  display: flex;\n  align-items: center;\n  flex-basis: 920px;\n  height: 50px;\n}\n\n.site-name {\n  font-size: 15px;\n  font-weight: 600;\n  line-height: 1;\n\n  &:hover {\n    color: var(--accent_light);\n    text-decoration: unset;\n  }\n}\n\n.site-logo {\n  display: block;\n  width: 35px;\n  height: 35px;\n}\n\n.nav-item {\n  display: flex;\n  flex: 1;\n  line-height: 50px;\n  height: 50px;\n  overflow: hidden;\n  flex-wrap: wrap;\n  align-items: center;\n\n  &.right {\n    text-align: right;\n    justify-content: flex-end;\n  }\n\n  &.right a:hover {\n    color: var(--accent_light);\n    text-decoration: unset;\n  }\n}\n\n.lp {\n  height: 14px;\n  display: inline-block;\n  position: relative;\n  top: 2px;\n  fill: var(--fg_nav);\n\n  &:hover {\n    fill: var(--accent_light);\n  }\n}\n\n.icon-info {\n  margin: 0 -3px;\n}\n\n.icon-cog {\n  font-size: 15px;\n  padding-left: 0 !important;\n}\n"
  },
  {
    "path": "src/sass/profile/_base.scss",
    "content": "@import \"_variables\";\n@import \"_mixins\";\n\n@import \"card\";\n@import \"photo-rail\";\n\n.profile-tabs {\n  @include panel(auto, 900px);\n\n  .timeline-container {\n    float: right;\n    width: 68% !important;\n    max-width: unset;\n  }\n}\n\n.profile-banner {\n  margin-bottom: 4px;\n  background-color: var(--bg_panel);\n\n  a {\n    display: block;\n    position: relative;\n    padding: 33.34% 0 0 0;\n  }\n\n  img {\n    max-width: 100%;\n    position: absolute;\n    top: 0;\n  }\n}\n\n.profile-tab {\n  padding: 0 4px 0 0;\n  box-sizing: border-box;\n  display: inline-block;\n  font-size: 14px;\n  text-align: left;\n  vertical-align: top;\n  max-width: 32%;\n  top: 0;\n\n  body.fixed-nav & {\n    top: 50px;\n  }\n}\n\n.profile-result {\n  min-height: 54px;\n\n  .username {\n    margin: 0 !important;\n  }\n\n  .tweet-header {\n    margin-bottom: unset;\n  }\n}\n\n.profile-tabs.media-only {\n  max-width: none;\n  width: 100%;\n\n  .timeline-container {\n    float: none;\n    width: 100% !important;\n    max-width: none;\n    padding: 0 10px;\n    box-sizing: border-box;\n  }\n\n  .timeline-container > .tab {\n    max-width: 900px;\n    margin-left: auto;\n    margin-right: auto;\n  }\n}\n\n@media (max-width: 700px) {\n  .profile-tabs {\n    width: 100vw;\n    max-width: 600px;\n\n    .timeline-container {\n      width: 100% !important;\n\n      .tab-item wide {\n        flex-grow: 1.4;\n      }\n    }\n  }\n\n  .profile-tabs.media-only {\n    width: 100%;\n    max-width: none;\n\n    .timeline-container {\n      width: 100vw !important;\n      padding: 0;\n    }\n  }\n\n  .profile-tab {\n    width: 100%;\n    max-width: unset;\n    position: initial !important;\n    padding: 0;\n  }\n}\n\n@media (min-height: 900px) {\n  .profile-tab.sticky {\n    position: sticky;\n  }\n}\n"
  },
  {
    "path": "src/sass/profile/card.scss",
    "content": "@import '_variables';\n@import '_mixins';\n\n.profile-card {\n    flex-wrap: wrap;\n    background: var(--bg_panel);\n    padding: 12px;\n    display: flex;\n}\n\n.profile-card-info {\n    @include breakable;\n    width: 100%;\n}\n\n.profile-card-tabs-name {\n    @include breakable;\n    max-width: 100%;\n}\n\n.profile-card-username {\n    @include breakable;\n    color: var(--fg_color);\n    font-size: 14px;\n    display: block;\n}\n\n.profile-card-fullname {\n    @include breakable;\n    color: var(--fg_color);\n    font-size: 16px;\n    font-weight: bold;\n    text-shadow: none;\n    max-width: 100%;\n}\n\n.profile-card-avatar {\n    display: inline-block;\n    position: relative;\n    width: 100%;\n    margin-right: 4px;\n    margin-bottom: 6px;\n\n    &:after {\n        content: '';\n        display: block;\n        margin-top: 100%;\n    }\n\n    img {\n        box-sizing: border-box;\n        position: absolute;\n        width: 100%;\n        height: 100%;\n        border: 4px solid var(--darker_grey);\n        background: var(--bg_panel);\n    }\n}\n\n.profile-card-extra {\n    display: contents;\n    flex: 100%;\n    margin-top: 7px;\n\n    .profile-bio {\n        @include breakable;\n        width: 100%;\n        margin: 4px -6px 6px 0;\n        white-space: pre-wrap;\n\n        p {\n            margin: 0;\n        }\n    }\n\n    .profile-joindate, .profile-location, .profile-website {\n        color: var(--fg_faded);\n        margin: 1px 0;\n        width: 100%;\n    }\n}\n\n.profile-card-extra-links {\n    margin-top: 8px;\n    font-size: 14px;\n    width: 100%;\n}\n\n.profile-statlist {\n    display: flex;\n    flex-wrap: wrap;\n    padding: 0;\n    width: 100%;\n    justify-content: space-between;\n\n    li {\n        display: table-cell;\n        text-align: center;\n    }\n}\n\n.profile-stat-header {\n    font-weight: bold;\n    color: var(--profile_stat);\n}\n\n.profile-stat-num {\n    display: block;\n    color: var(--profile_stat);\n}\n\n@media(max-width: 700px) {\n    .profile-card-info {\n        display: flex;\n    }\n\n    .profile-card-tabs-name {\n        flex-shrink: 100;\n    }\n\n    .profile-card-avatar {\n        width: 80px;\n        height: 80px;\n\n        img {\n            border-width: 2px;\n            width: unset;\n        }\n    }\n}\n"
  },
  {
    "path": "src/sass/profile/photo-rail.scss",
    "content": "@import '_variables';\n\n.photo-rail {\n    &-card {\n        float: left;\n        background: var(--bg_panel);\n        border-radius: 0 0 4px 4px;\n        width: 100%;\n        margin: 5px 0;\n    }\n\n    &-header {\n        padding: 5px 12px 0;\n    }\n\n    &-header-mobile {\n        display: none;\n        box-sizing: border-box;\n        padding: 5px 12px 0;\n        width: 100%;\n        float: unset;\n        color: var(--accent);\n        justify-content: space-between;\n    }\n\n    &-grid {\n        display: grid;\n        grid-template-columns: repeat(4, 1fr);\n        grid-gap: 3px 3px;\n        padding: 5px 12px 12px;\n\n        a {\n            position: relative;\n            border-radius: 5px;\n            background-color: var(--darker_grey);\n\n            &:before {\n                content: \"\";\n                display: block;\n                padding-top: 100%;\n            }\n        }\n\n        img {\n            height: 100%;\n            width: 100%;\n            border-radius: 4px;\n            object-fit: cover;\n            position: absolute;\n            top: 0;\n            left: 0;\n            bottom: 0;\n            right: 0;\n        }\n    }\n}\n\n@include create-toggle(photo-rail-grid, 640px);\n#photo-rail-grid-toggle:checked ~ .photo-rail-grid {\n    padding-bottom: 12px;\n}\n\n@media(max-width: 700px) {\n    .photo-rail-header {\n        display: none;\n    }\n\n    .photo-rail-header-mobile {\n        display: flex;\n    }\n\n    .photo-rail-grid {\n        max-height: 0;\n        padding-bottom: 0;\n        overflow: hidden;\n        transition: max-height 0.4s;\n    }\n\n    .photo-rail-grid {\n        grid-template-columns: repeat(6, 1fr);\n    }\n\n    #photo-rail-grid-toggle:checked ~ .photo-rail-grid {\n        max-height: 300px;\n    }\n}\n\n@media(max-width: 450px) {\n    .photo-rail-grid {\n        grid-template-columns: repeat(4, 1fr);\n    }\n\n    #photo-rail-grid-toggle:checked ~ .photo-rail-grid {\n        max-height: 450px;\n    }\n}\n"
  },
  {
    "path": "src/sass/search.scss",
    "content": "@import \"_variables\";\n@import \"_mixins\";\n\n.search-title {\n  font-weight: bold;\n  display: inline-block;\n  margin-top: 4px;\n}\n\n.search-field {\n  display: flex;\n  flex-wrap: wrap;\n\n  button {\n    margin: 0 2px 0 0;\n    padding: 0px 1px 1px 4px;\n    height: 23px;\n    display: flex;\n    align-items: center;\n  }\n\n  .pref-input {\n    margin: 0 4px 0 0;\n    flex-grow: 1;\n    height: 23px;\n  }\n\n  input[type=\"text\"],\n  input[type=\"number\"] {\n    height: calc(100% - 4px);\n    width: calc(100% - 8px);\n  }\n\n  > label {\n    display: inline;\n    background-color: var(--bg_elements);\n    color: var(--fg_color);\n    border: 1px solid var(--accent_border);\n    padding: 1px 1px 2px 4px;\n    font-size: 14px;\n    cursor: pointer;\n    margin-bottom: 2px;\n\n    @include input-colors;\n  }\n\n  @include create-toggle(search-panel, 380px);\n}\n\n.search-panel {\n  width: 100%;\n  max-height: 0;\n  overflow: hidden;\n  transition: max-height 0.4s;\n\n  flex-grow: 1;\n  font-weight: initial;\n  text-align: left;\n\n  .checkbox-container {\n    display: inline;\n    padding-right: unset;\n    margin-bottom: 5px;\n    margin-left: 23px;\n  }\n\n  .checkbox {\n    right: unset;\n    left: -22px;\n    line-height: 1.6em;\n  }\n\n  .checkbox-container .checkbox:after {\n    top: -4px;\n  }\n}\n\n.search-row {\n  display: flex;\n  flex-wrap: wrap;\n  line-height: unset;\n\n  > div {\n    flex-grow: 1;\n    flex-shrink: 1;\n  }\n\n  input {\n    height: 21px;\n  }\n\n  .pref-input {\n    display: block;\n    padding-bottom: 5px;\n\n    input {\n      height: 21px;\n      margin-top: 1px;\n    }\n  }\n}\n\n.search-toggles {\n  flex-grow: 1;\n  display: grid;\n  grid-template-columns: repeat(5, auto);\n  grid-column-gap: 10px;\n}\n\n.profile-tabs {\n  @include search-resize(820px, 5);\n  @include search-resize(715px, 4);\n  @include search-resize(700px, 5);\n  @include search-resize(485px, 4);\n  @include search-resize(410px, 3);\n}\n\n@include search-resize(700px, 5);\n@include search-resize(485px, 4);\n@include search-resize(410px, 3);\n"
  },
  {
    "path": "src/sass/timeline.scss",
    "content": "@import \"_variables\";\n\n.timeline-container {\n  @include panel(100%, 600px);\n}\n\n.timeline > div:not(:first-child) {\n  border-top: 1px solid var(--border_grey);\n}\n\n.timeline-header {\n  width: 100%;\n  background-color: var(--bg_panel);\n  text-align: center;\n  padding: 8px;\n  display: block;\n  font-weight: bold;\n  margin-bottom: 4px;\n  box-sizing: border-box;\n\n  button {\n    float: unset;\n  }\n}\n\n.timeline-banner img {\n  width: 100%;\n}\n\n.timeline-description {\n  font-weight: normal;\n}\n\n.tab {\n  align-items: center;\n  display: flex;\n  flex-wrap: wrap;\n  list-style: none;\n  margin: 0 0 4px 0;\n  background-color: var(--bg_panel);\n  padding: 0;\n}\n\n.tab-item {\n  flex: 1 1 0;\n  text-align: center;\n  margin-top: 0;\n\n  a {\n    border-bottom: 0.1rem solid transparent;\n    color: var(--tab);\n    display: block;\n    padding: 8px 0;\n    text-decoration: none;\n    font-weight: bold;\n\n    &:hover {\n      text-decoration: none;\n    }\n\n    &.active {\n      border-bottom-color: var(--tab_selected);\n      color: var(--tab_selected);\n    }\n  }\n\n  &.active a {\n    border-bottom-color: var(--tab_selected);\n    color: var(--tab_selected);\n  }\n\n  &.wide {\n    flex-grow: 1.2;\n    flex-basis: 50px;\n  }\n}\n\n.timeline-footer {\n  background-color: var(--bg_panel);\n  padding: 6px 0;\n}\n\n.timeline-protected {\n  text-align: center;\n\n  p {\n    margin: 8px 0;\n  }\n\n  h2 {\n    color: var(--accent);\n    font-size: 20px;\n    font-weight: 600;\n  }\n}\n\n.timeline-none {\n  color: var(--accent);\n  font-size: 20px;\n  font-weight: 600;\n  text-align: center;\n}\n\n.timeline-end {\n  background-color: var(--bg_panel);\n  color: var(--accent);\n  font-size: 16px;\n  font-weight: 600;\n  text-align: center;\n}\n\n.show-more {\n  background-color: var(--bg_panel);\n  text-align: center;\n  padding: 0.75em 0;\n  display: block !important;\n\n  a {\n    background-color: var(--darkest_grey);\n    display: inline-block;\n    height: 2em;\n    padding: 0 2em;\n    line-height: 2em;\n\n    &:hover {\n      background-color: var(--darker_grey);\n    }\n  }\n}\n\n.top-ref {\n  background-color: var(--bg_color);\n  border-top: none !important;\n\n  .icon-down {\n    font-size: 20px;\n    display: flex;\n    justify-content: center;\n    text-decoration: none;\n\n    &:hover {\n      color: var(--accent_light);\n    }\n\n    &::before {\n      transform: rotate(180deg) translateY(-1px);\n    }\n  }\n}\n\n.timeline-item {\n  overflow-wrap: break-word;\n  border-left-width: 0;\n  min-width: 0;\n  padding: 0.75em;\n  display: flex;\n  position: relative;\n  background-color: var(--bg_panel);\n}\n\n.timeline.media-grid-view,\n.timeline.media-gallery-view {\n  > div:not(:first-child) {\n    border-top: none;\n  }\n\n  .timeline-item::before {\n    display: none;\n  }\n}\n\n.timeline.media-grid-view,\n.timeline.media-gallery-view .gallery-masonry.compact {\n  .tweet-header,\n  .replying-to,\n  .retweet-header,\n  .pinned,\n  .tweet-stats,\n  .attribution,\n  .poll,\n  .quote,\n  .community-note,\n  .media-tag-block,\n  .tweet-content,\n  .card-content {\n    display: none;\n  }\n\n  .card {\n    margin: unset;\n\n    .card-container {\n      border: unset;\n      border-radius: unset;\n\n      .card-image-container {\n        width: 100%;\n        min-height: 100%;\n      }\n\n      .card-content-container {\n        display: none;\n      }\n    }\n  }\n}\n\n.timeline.media-grid-view {\n  display: grid;\n  gap: 4px;\n  grid-template-columns: repeat(3, minmax(0, 1fr));\n\n  > div:not(:first-child) {\n    margin-top: 0;\n  }\n\n  .timeline-item {\n    padding: 0;\n  }\n\n  .tweet-link {\n    z-index: 1000;\n\n    &:hover {\n      background-color: unset;\n    }\n  }\n\n  > .show-more,\n  > .top-ref,\n  > .timeline-footer,\n  > .timeline-header {\n    grid-column: 1 / -1;\n  }\n\n  .tweet-body {\n    height: 100%;\n    margin-left: 0;\n    padding: 0;\n    position: relative;\n    aspect-ratio: 1/1;\n  }\n\n  .gallery-row + .gallery-row {\n    margin-top: 0.25em !important;\n  }\n\n  .attachments {\n    background-color: var(--darkest_grey);\n    border-radius: 0;\n    margin: 0;\n    max-height: none;\n  }\n\n  .attachments,\n  .gallery-row,\n  .still-image {\n    height: 100%;\n    width: 100%;\n  }\n\n  .still-image img,\n  .attachment > video,\n  .attachment > img {\n    object-fit: cover;\n    height: 100%;\n    width: 100%;\n  }\n\n  .attachment {\n    display: flex;\n    align-items: center;\n  }\n\n  .gallery-video {\n    height: 100%;\n  }\n\n  .media-gif {\n    display: flex;\n  }\n\n  .timeline-item:hover {\n    opacity: 0.85;\n  }\n\n  .alt-text {\n    display: none;\n  }\n}\n\n.timeline.media-gallery-view {\n  .gallery-masonry {\n    margin: 10px 0;\n    column-gap: 10px;\n    column-width: 350px;\n\n    &.masonry-active {\n      column-width: unset;\n      column-gap: unset;\n      position: relative;\n\n      .timeline-item {\n        animation: none;\n        position: absolute;\n        box-sizing: border-box;\n        margin-bottom: 0;\n      }\n    }\n\n    &.compact {\n      .tweet-body {\n        padding: 0;\n\n        > .attachments {\n          margin: 0;\n        }\n      }\n\n      .card-image-container img {\n        max-height: unset;\n      }\n    }\n  }\n\n  @keyframes masonry-init {\n    to {\n      opacity: 1;\n      pointer-events: auto;\n    }\n  }\n\n  // Start hidden. CSS animation reveals after a delay as a no-JS fallback.\n  // With JS, masonry-active cancels the animation and masonry-visible reveals.\n  .gallery-masonry .timeline-item,\n  > .show-more,\n  > .top-ref,\n  > .timeline-footer {\n    opacity: 0;\n    pointer-events: none;\n    animation: masonry-init 0.2s 0.3s forwards;\n  }\n\n  .gallery-masonry.masonry-active .timeline-item.masonry-visible,\n  > .show-more.masonry-visible,\n  > .top-ref.masonry-visible,\n  > .timeline-footer.masonry-visible {\n    opacity: 1;\n    pointer-events: auto;\n    transition: opacity 0.15s ease;\n    animation: none;\n  }\n\n  .timeline-item {\n    margin-bottom: 10px;\n    break-inside: avoid;\n    flex-direction: column;\n    padding: 0;\n  }\n\n  > .show-more,\n  > .top-ref,\n  > .timeline-footer,\n  > .timeline-header {\n    margin-left: auto;\n    margin-right: auto;\n    max-width: 900px;\n  }\n\n  > .show-more {\n    padding: 0;\n    margin-top: 8px;\n    background-color: unset;\n  }\n\n  .tweet-content {\n    margin: 3px 0;\n  }\n\n  .tweet-body {\n    display: flex;\n    flex-direction: column;\n    height: 100%;\n    margin-left: 0;\n    padding: 10px;\n\n    > .attachments {\n      align-self: stretch;\n      border-radius: 0;\n      margin: -10px -10px 10px;\n      max-height: none;\n      order: -1;\n      width: auto;\n      background-color: var(--bg_elements);\n\n      .gallery-row {\n        max-height: none;\n        max-width: none;\n        align-items: center;\n      }\n\n      .still-image img,\n      .attachment > video,\n      .attachment > img {\n        max-height: none;\n        width: 100%;\n      }\n\n      .attachment:last-child {\n        max-height: none;\n      }\n\n      .card-container {\n        border: unset;\n        border-radius: unset;\n      }\n    }\n\n    .tweet-stat {\n      padding-top: unset;\n    }\n\n    .quote {\n      margin-bottom: 5px;\n      margin-top: 5px;\n    }\n\n    .replying-to {\n      margin: 0;\n    }\n  }\n\n  .tweet-header {\n    align-items: flex-start;\n    display: flex;\n    gap: 0.75em;\n    margin-bottom: 0;\n\n    .tweet-avatar {\n      img {\n        float: none;\n        height: 42px;\n        margin: 0;\n        width: 42px;\n      }\n    }\n\n    .tweet-name-row {\n      flex: 1;\n    }\n\n    .fullname-and-username {\n      flex-wrap: wrap;\n    }\n\n    .fullname {\n      max-width: calc(100% - 18px);\n    }\n\n    .verified-icon {\n      margin-left: 4px;\n      margin-top: 1px;\n    }\n\n    .username {\n      display: block;\n      flex-basis: 100%;\n      margin-left: 0;\n    }\n  }\n}\n\n@media (max-width: 900px) {\n  .timeline.media-grid-view {\n    grid-template-columns: repeat(2, minmax(0, 1fr));\n  }\n}\n\n@media (max-width: 520px) {\n  .timeline.media-grid-view {\n    grid-template-columns: 1fr;\n  }\n\n  .timeline.media-gallery-view {\n    padding: 8px 0;\n\n    .gallery-masonry {\n      columns: 1;\n      column-gap: 0;\n\n      &.masonry-active {\n        columns: unset;\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "src/sass/tweet/_base.scss",
    "content": "@import \"_variables\";\n@import \"_mixins\";\n@import \"thread\";\n@import \"media\";\n@import \"video\";\n@import \"embed\";\n@import \"card\";\n@import \"poll\";\n@import \"quote\";\n\n.tweet-body {\n  flex: 1;\n  min-width: 0;\n  margin-left: 58px;\n  pointer-events: none;\n  z-index: 1;\n}\n\n.tweet-content {\n  line-height: 1.3em;\n  pointer-events: all;\n  display: inline;\n}\n\n.tweet-bidi {\n  display: block !important;\n}\n\n.tweet-header {\n  padding: 0;\n  vertical-align: bottom;\n  flex-basis: 100%;\n  margin-bottom: 0.2em;\n\n  a {\n    display: inline-block;\n    word-break: break-all;\n    max-width: 100%;\n    pointer-events: all;\n  }\n}\n\n.tweet-name-row {\n  padding: 0;\n  display: flex;\n  justify-content: space-between;\n}\n\n.fullname-and-username {\n  display: flex;\n  min-width: 0;\n}\n\n.fullname {\n  @include ellipsis;\n  flex-shrink: 2;\n  max-width: 80%;\n  font-size: 14px;\n  font-weight: 700;\n  color: var(--fg_color);\n}\n\n.username {\n  @include ellipsis;\n  min-width: 1.6em;\n  margin-left: 0.4em;\n  word-wrap: normal;\n}\n\n.tweet-date {\n  display: flex;\n  flex-shrink: 0;\n  margin-left: 4px;\n}\n\n.tweet-date a,\n.username,\n.show-more a {\n  color: var(--fg_dark);\n}\n\n.tweet-published {\n  margin-top: 10px;\n  margin-bottom: 3px;\n  color: var(--grey);\n  pointer-events: all;\n}\n\n.tweet-avatar {\n  display: contents !important;\n\n  img {\n    float: left;\n    margin-top: 3px;\n    margin-left: -58px;\n    width: 48px;\n    height: 48px;\n  }\n}\n\n.avatar {\n  &.round {\n    border-radius: 50%;\n    user-select: none;\n    -webkit-user-select: none;\n  }\n\n  &.mini {\n    position: unset;\n    margin-right: 5px;\n    margin-top: -1px;\n    width: 20px;\n    height: 20px;\n  }\n}\n\n.tweet-embed {\n  display: flex;\n  flex-direction: column;\n  justify-content: center;\n  height: 100%;\n  background-color: var(--bg_panel);\n\n  .tweet-content {\n    font-size: 18px;\n  }\n\n  .tweet-body {\n    display: flex;\n    flex-direction: column;\n    max-height: calc(100vh - 0.75em * 2);\n  }\n\n  .card-image img {\n    height: auto;\n  }\n\n  .avatar {\n    position: absolute;\n  }\n}\n\n.attribution {\n  display: flex;\n  pointer-events: all;\n  margin: 5px 0;\n\n  strong {\n    color: var(--fg_color);\n  }\n}\n\n.media-tag-block {\n  padding-top: 5px;\n  pointer-events: all;\n  color: var(--fg_faded);\n\n  .icon-container {\n    padding-right: 2px;\n  }\n\n  .media-tag,\n  .icon-container {\n    color: var(--fg_faded);\n  }\n}\n\n.timeline-container .media-tag-block {\n  font-size: 13px;\n}\n\n.tweet-geo {\n  color: var(--fg_faded);\n}\n\n.replying-to {\n  color: var(--fg_faded);\n  margin: -2px 0 4px;\n\n  a {\n    pointer-events: all;\n  }\n}\n\n.retweet-header,\n.pinned,\n.tweet-stats {\n  align-content: center;\n  color: var(--grey);\n  display: flex;\n  flex-shrink: 0;\n  flex-wrap: wrap;\n  font-size: 14px;\n  font-weight: 600;\n  line-height: 22px;\n\n  span {\n    @include ellipsis;\n  }\n}\n\n.retweet-header {\n  margin-top: -5px !important;\n}\n\n.tweet-stats {\n  margin-bottom: -3px;\n  user-select: none;\n  -webkit-user-select: none;\n}\n\n.tweet-stat {\n  padding-top: 5px;\n  min-width: 1em;\n  margin-right: 0.8em;\n}\n\n.show-thread {\n  display: block;\n  pointer-events: all;\n  padding-top: 2px;\n}\n\n.unavailable-box {\n  width: 100%;\n  height: 100%;\n  padding: 12px;\n  border: solid 1px var(--dark_grey);\n  box-sizing: border-box;\n  border-radius: 10px;\n  background-color: var(--bg_color);\n  z-index: 2;\n}\n\n.tweet-link {\n  height: 100%;\n  width: 100%;\n  left: 0;\n  top: 0;\n  position: absolute;\n  user-select: none;\n  -webkit-user-select: none;\n\n  &:hover {\n    background-color: var(--bg_hover);\n  }\n}\n\n.latest-post-version {\n  border-bottom: 1px solid var(--dark_grey);\n  border-top: 1px solid var(--dark_grey);\n  padding: 01ch 0px;\n  margin: 1ch 0px;\n  color: var(--grey);\n\n  a {\n    pointer-events: all;\n  }\n}\n\n.community-note {\n  background-color: var(--bg_elements);\n  margin-top: 10px;\n  border: solid 1px var(--dark_grey);\n  border-radius: 10px;\n  overflow: hidden;\n  pointer-events: all;\n\n  &:hover {\n    background-color: var(--bg_panel);\n    border-color: var(--grey);\n  }\n}\n\n.community-note-header {\n  background-color: var(--bg_hover);\n  font-weight: 700;\n  padding: 8px 10px;\n  padding-top: 6px;\n  display: flex;\n  align-items: center;\n  gap: 2px;\n\n  .icon-container {\n    flex-shrink: 0;\n    color: var(--accent);\n  }\n}\n\n.community-note-text {\n  white-space: pre-line;\n  padding: 10px 10px;\n  padding-top: 6px;\n}\n"
  },
  {
    "path": "src/sass/tweet/card.scss",
    "content": "@import \"_variables\";\n@import \"_mixins\";\n\n.card {\n  margin: 5px 0;\n  pointer-events: all;\n  max-height: unset;\n}\n\n.card-container {\n  border: solid 1px var(--dark_grey);\n  border-radius: 10px;\n  background-color: var(--bg_elements);\n  overflow: hidden;\n  color: inherit;\n  display: flex;\n  flex-direction: row;\n  text-decoration: none !important;\n\n  &:hover {\n    border-color: var(--grey);\n  }\n\n  .attachments {\n    margin: 0;\n    border-radius: 0;\n  }\n}\n\n.card-content {\n  padding: 0.5em;\n}\n\n.card-title {\n  @include ellipsis;\n  white-space: unset;\n  font-weight: bold;\n  font-size: 1.1em;\n}\n\n.card-description {\n  margin: 0.3em 0;\n  white-space: pre-wrap;\n}\n\n.card-destination {\n  @include ellipsis;\n  color: var(--grey);\n  display: block;\n}\n\n.card-content-container {\n  color: unset;\n  overflow: auto;\n\n  &:hover {\n    text-decoration: none;\n  }\n}\n\n.card-image-container {\n  width: 98px;\n  flex-shrink: 0;\n  position: relative;\n  overflow: hidden;\n\n  &:before {\n    content: \"\";\n    display: block;\n    padding-top: 100%;\n  }\n}\n\n.card-image {\n  position: absolute;\n  top: 0;\n  left: 0;\n  bottom: 0;\n  right: 0;\n  background-color: var(--bg_overlays);\n\n  img {\n    width: 100%;\n    height: 100%;\n    max-height: 400px;\n    display: block;\n    object-fit: cover;\n  }\n}\n\n.card-overlay {\n  @include play-button;\n  opacity: 0.8;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n}\n\n.large {\n  .card-container {\n    display: block;\n  }\n\n  .card-image-container {\n    width: unset;\n\n    &:before {\n      display: none;\n    }\n  }\n\n  .card-image {\n    position: unset;\n    border-style: solid;\n    border-color: var(--dark_grey);\n    border-width: 0;\n    border-bottom-width: 1px;\n  }\n}\n"
  },
  {
    "path": "src/sass/tweet/embed.scss",
    "content": "@import \"_variables\";\n@import \"_mixins\";\n\n.embed-video {\n  .gallery-video {\n    width: 100%;\n    height: 100%;\n    position: absolute;\n    background-color: black;\n    top: 0%;\n    left: 0%;\n  }\n\n  .gallery-video > .attachment {\n    max-height: unset;\n  }\n}\n"
  },
  {
    "path": "src/sass/tweet/media.scss",
    "content": "@import \"_variables\";\n\n.gallery-row {\n  display: flex;\n  flex-direction: row;\n  flex-wrap: nowrap;\n  overflow: hidden;\n  flex-grow: 1;\n  max-height: 379.5px;\n  max-width: 533px;\n  pointer-events: all;\n\n  &.mixed-row {\n    .attachment {\n      min-width: 0;\n      min-height: 0;\n      flex: 1 1 0;\n      max-height: 379.5px;\n      display: flex;\n      align-items: center;\n      justify-content: center;\n      background-color: #101010;\n    }\n\n    .still-image,\n    .still-image img,\n    .attachment > video,\n    .attachment > img {\n      width: 100%;\n      height: 100%;\n      max-width: none;\n      max-height: none;\n    }\n\n    .still-image {\n      display: flex;\n      align-self: stretch;\n    }\n\n    .still-image img {\n      flex-basis: auto;\n      flex-grow: 0;\n      object-fit: cover;\n    }\n\n    .attachment > video,\n    .attachment > img {\n      object-fit: cover;\n    }\n\n    .attachment > video {\n      object-fit: contain;\n    }\n  }\n}\n\n.attachments {\n  margin-top: 0.35em;\n  display: flex;\n  flex-direction: row;\n  width: 100%;\n  max-height: 600px;\n  border-radius: 7px;\n  overflow: hidden;\n  flex-flow: column;\n  background-color: var(--bg_color);\n  align-items: center;\n  pointer-events: all;\n}\n\n.attachment {\n  position: relative;\n  line-height: 0;\n  overflow: hidden;\n  margin: 0 0.25em 0 0;\n  flex-grow: 1;\n  box-sizing: border-box;\n  min-width: 2em;\n\n  &:last-child {\n    margin: 0;\n    max-height: 530px;\n  }\n}\n\n.media-gif {\n  display: table;\n  background-color: unset;\n  width: unset;\n  max-height: unset;\n}\n\n.media-gif video {\n  max-height: 530px;\n  background-color: #101010;\n}\n\n.still-image {\n  max-height: 379.5px;\n  max-width: 533px;\n\n  img {\n    object-fit: cover;\n    max-width: 100%;\n    max-height: 379.5px;\n    flex-basis: 300px;\n    flex-grow: 1;\n  }\n}\n\n.alt-text {\n  margin: 0px;\n  padding: 11px 7px;\n  box-sizing: border-box;\n  position: absolute;\n  bottom: 10px;\n  left: 10px;\n  width: 2.98em;\n  max-height: 25px;\n  white-space: pre;\n  overflow: hidden;\n  border-radius: 10px;\n  color: var(--fg_color);\n  font-size: 12px;\n  font-weight: bold;\n  background: rgba(0, 0, 0, 0.5);\n  backdrop-filter: blur(12px);\n}\n\n.alt-text:hover {\n  padding: 7px;\n  width: Min(230px, calc(100% - 10px * 2));\n  max-height: calc(100% - 10px);\n  line-height: 1.2em;\n  white-space: pre-wrap;\n  transition-duration: 0.4s;\n  transition-property: max-height;\n}\n\n.overlay-circle {\n  border-radius: 50%;\n  background-color: var(--dark_grey);\n  width: 40px;\n  height: 40px;\n  align-items: center;\n  display: flex;\n  border-width: 5px;\n  border-color: var(--play_button);\n  border-style: solid;\n}\n\n.overlay-triangle {\n  width: 0;\n  height: 0;\n  border-style: solid;\n  border-width: 12px 0 12px 17px;\n  border-color: transparent transparent transparent var(--play_button);\n  margin-left: 14px;\n}\n\n.media-body {\n  flex: 1;\n  padding: 0;\n  white-space: pre-wrap;\n}\n"
  },
  {
    "path": "src/sass/tweet/poll.scss",
    "content": "@import \"_variables\";\n\n.poll-meter {\n  overflow: hidden;\n  position: relative;\n  margin: 6px 0;\n  height: 26px;\n  background: var(--bg_color);\n  border-radius: 5px;\n  display: flex;\n  align-items: center;\n}\n\n.poll-choice-bar {\n  height: 100%;\n  position: absolute;\n  background: var(--dark_grey);\n}\n\n.poll-choice-value {\n  position: relative;\n  font-weight: bold;\n  margin-left: 5px;\n  margin-right: 6px;\n  min-width: 30px;\n  text-align: right;\n  pointer-events: all;\n}\n\n.poll-choice-option {\n  position: relative;\n  pointer-events: all;\n}\n\n.poll-info {\n  color: var(--grey);\n  pointer-events: all;\n}\n\n.leader .poll-choice-bar {\n  background: var(--accent_dark);\n}\n"
  },
  {
    "path": "src/sass/tweet/quote.scss",
    "content": "@import \"_variables\";\n\n.quote {\n  margin-top: 10px;\n  border: solid 1px var(--dark_grey);\n  border-radius: 10px;\n  background-color: var(--bg_elements);\n  overflow: hidden;\n  pointer-events: all;\n  position: relative;\n  width: 100%;\n\n  &:hover {\n    border-color: var(--grey);\n  }\n\n  &.unavailable:hover {\n    border-color: var(--dark_grey);\n  }\n\n  .tweet-name-row {\n    padding: 8px 10px 6px 10px;\n  }\n\n  .quote-text {\n    overflow: hidden;\n    white-space: pre-wrap;\n    word-wrap: break-word;\n    padding: 10px;\n    padding-top: 0;\n  }\n\n  .show-thread {\n    padding: 0px 10px 6px 10px;\n    margin-top: -6px;\n  }\n\n  .quote-latest {\n    padding: 0px 10px 6px 10px;\n    color: var(--grey);\n  }\n\n  .replying-to {\n    padding: 0px 10px;\n    padding-bottom: 4px;\n    margin: unset;\n  }\n\n  .community-note {\n    background-color: var(--bg_panel);\n    border: unset;\n    border-top: solid 1px var(--dark_grey);\n    border-radius: unset;\n    margin-top: 0;\n\n    &:hover {\n      border-top-color: var(--grey);\n    }\n\n    .community-note-header {\n      background-color: var(--bg_panel);\n      padding-bottom: 0;\n    }\n  }\n}\n\n.unavailable-quote {\n  padding: 12px;\n  display: block;\n}\n\n.quote-link {\n  width: 100%;\n  height: 100%;\n  left: 0;\n  top: 0;\n  position: absolute;\n}\n\n.quote-media-container {\n  max-height: 300px;\n  display: flex;\n\n  .card {\n    margin: unset;\n  }\n\n  .attachments {\n    border-radius: 0;\n  }\n\n  .media-gif {\n    width: 100%;\n    display: flex;\n    justify-content: center;\n  }\n\n  .media-gif > .attachment {\n    display: flex;\n    justify-content: center;\n    background-color: var(--bg_color);\n\n    video {\n      height: unset;\n      width: unset;\n      max-height: 100%;\n      max-width: 100%;\n    }\n  }\n\n  .gallery-row .attachment,\n  .gallery-row .attachment > video,\n  .gallery-row .attachment > img {\n    max-height: 300px;\n  }\n\n  .still-image img {\n    max-height: 250px;\n  }\n}\n"
  },
  {
    "path": "src/sass/tweet/thread.scss",
    "content": "@import \"_variables\";\n@import \"_mixins\";\n\n.conversation,\n.edit-history {\n  @include panel(100%, 600px);\n\n  .show-more {\n    margin-bottom: 10px;\n  }\n}\n\n.main-thread,\n.latest-edit {\n  margin-bottom: 20px;\n}\n\n.reply {\n  margin-bottom: 10px;\n}\n\n.main-tweet,\n.replies,\n.edit-history > div {\n  body.fixed-nav & {\n    padding-top: 50px;\n    margin-top: -50px;\n  }\n}\n\n.edit-history-header {\n  padding: 10px;\n  margin-bottom: 5px;\n  font-size: 16px;\n  font-weight: bold;\n  background-color: var(--bg_panel);\n}\n\n.tweet-edit {\n  margin-bottom: 5px;\n}\n\n.main-tweet .tweet-content {\n  font-size: 18px;\n}\n\n@media (max-width: 600px) {\n  .main-tweet .tweet-content {\n    font-size: 16px;\n  }\n}\n\n.thread-line {\n  .timeline-item::before,\n  &.timeline-item::before {\n    background: var(--accent_dark);\n    content: \"\";\n    position: relative;\n    min-width: 3px;\n    width: 3px;\n    left: 26px;\n    border-radius: 2px;\n    margin-left: -3px;\n    margin-bottom: 37px;\n    top: 56px;\n    z-index: 1;\n    pointer-events: none;\n  }\n\n  .with-header:not(:first-child)::after {\n    background: var(--accent_dark);\n    content: \"\";\n    position: relative;\n    float: left;\n    min-width: 3px;\n    width: 3px;\n    right: calc(100% - 26px);\n    border-radius: 2px;\n    margin-left: -3px;\n    margin-bottom: 37px;\n    bottom: 10px;\n    height: 30px;\n    z-index: 1;\n    pointer-events: none;\n  }\n\n  .unavailable::before {\n    top: 48px;\n    margin-bottom: 28px;\n  }\n\n  .more-replies::before {\n    content: \"...\";\n    background: unset;\n    color: var(--more_replies_dots);\n    font-weight: bold;\n    font-size: 20px;\n    line-height: 0.25em;\n    left: 1.2em;\n    width: 5px;\n    top: 2px;\n    margin-bottom: 0;\n    margin-left: -2.5px;\n  }\n\n  .earlier-replies {\n    padding-bottom: 0;\n    margin-bottom: -5px;\n  }\n}\n\n.timeline-item.thread-last::before {\n  background: unset;\n  min-width: unset;\n  width: 0;\n  margin: 0;\n}\n\n.more-replies {\n  padding-top: 0.3em !important;\n}\n\n.more-replies-text {\n  @include ellipsis;\n  display: block;\n  margin-left: 58px;\n  padding: 7px 0;\n}\n\n.timeline-item.thread.more-replies-thread {\n  padding: 0 0.75em;\n\n  &::before {\n    top: 40px;\n    margin-bottom: 31px;\n  }\n\n  .more-replies {\n    display: flex;\n    padding-top: unset !important;\n    margin-top: 8px;\n\n    &::before {\n      display: inline-block;\n      position: relative;\n      top: -1px;\n      line-height: 0.4em;\n    }\n\n    .more-replies-text {\n      display: inline;\n    }\n  }\n}\n"
  },
  {
    "path": "src/sass/tweet/video.scss",
    "content": "@import \"_variables\";\n@import \"_mixins\";\n\nvideo {\n  height: 100%;\n  width: 100%;\n}\n\n.gallery-video {\n  display: flex;\n  overflow: hidden;\n  \n  &.card-container {\n    flex-direction: column;\n    width: 100%;\n  }\n\n  > .attachment {\n    min-height: 80px;\n    min-width: 200px;\n    max-height: 530px;\n    margin: 0;\n\n    img {\n      max-height: 100%;\n      max-width: 100%;\n    }\n  }\n}\n\n.video-overlay {\n  @include play-button;\n  background-color: $shadow;\n\n  p {\n    position: relative;\n    z-index: 0;\n    text-align: center;\n    top: calc(50% - 20px);\n    font-size: 20px;\n    line-height: 1.3;\n    margin: 0 20px;\n  }\n\n  .overlay-circle {\n    position: relative;\n    z-index: 0;\n    top: calc(50% - 20px);\n    margin: 0 auto;\n    width: 40px;\n    height: 40px;\n  }\n\n  .overlay-duration {\n    position: absolute;\n    bottom: 8px;\n    left: 8px;\n    background-color: #0000007a;\n    line-height: 1em;\n    padding: 4px 6px 4px 6px;\n    border-radius: 5px;\n    font-weight: bold;\n  }\n\n  form {\n    width: 100%;\n    height: 100%;\n    align-items: center;\n    justify-content: center;\n    display: flex;\n  }\n\n  button {\n    padding: 5px 8px;\n    font-size: 16px;\n  }\n}\n"
  },
  {
    "path": "src/tid.nim",
    "content": "import std/[asyncdispatch, base64, httpclient, random, strutils, sequtils, times]\nimport nimcrypto\nimport experimental/parser/tid\n\nrandomize()\n\nconst defaultKeyword = \"obfiowerehiring\";\nconst pairsUrl =\n  \"https://raw.githubusercontent.com/fa0311/x-client-transaction-id-pair-dict/refs/heads/main/pair.json\";\n\nvar\n  cachedPairs: seq[TidPair] = @[]\n  lastCached = 0\n  # refresh every hour\n  ttlSec = 60 * 60\n\nproc getPair(): Future[TidPair] {.async.} =\n  if cachedPairs.len == 0 or int(epochTime()) - lastCached > ttlSec:\n    lastCached = int(epochTime())\n\n    let client = newAsyncHttpClient()\n    defer: client.close()\n\n    let resp = await client.get(pairsUrl)\n    if resp.status == $Http200:\n      cachedPairs = parseTidPairs(await resp.body)\n\n  return sample(cachedPairs)\n\nproc encodeSha256(text: string): array[32, byte] =\n  let\n    data = cast[ptr byte](addr text[0])\n    dataLen = uint(len(text))\n    digest = sha256.digest(data, dataLen)\n  return digest.data\n\nproc encodeBase64[T](data: T): string =\n  return encode(data).replace(\"=\", \"\")\n\nproc decodeBase64(data: string): seq[byte] =\n  return cast[seq[byte]](decode(data))\n\nproc genTid*(path: string): Future[string] {.async.} =\n  let \n    pair = await getPair()\n\n    timeNow = int(epochTime() - 1682924400)\n    timeNowBytes = @[\n      byte(timeNow and 0xff),\n      byte((timeNow shr 8) and 0xff),\n      byte((timeNow shr 16) and 0xff),\n      byte((timeNow shr 24) and 0xff)\n    ]\n\n    data = \"GET!\" & path & \"!\" & $timeNow & defaultKeyword & pair.animationKey\n    hashBytes = encodeSha256(data)\n    keyBytes = decodeBase64(pair.verification)\n    bytesArr = keyBytes & timeNowBytes & hashBytes[0 ..< 16] & @[3'u8]\n    randomNum = byte(rand(256))\n    tid = @[randomNum] & bytesArr.mapIt(it xor randomNum)\n\n  return encodeBase64(tid)\n"
  },
  {
    "path": "src/types.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport times, sequtils, options, tables\nimport prefs_impl\n\ngenPrefsType()\n\ntype\n  RateLimitError* = object of CatchableError\n  NoSessionsError* = object of CatchableError\n  InternalError* = object of CatchableError\n  BadClientError* = object of CatchableError\n\n  TimelineKind* {.pure.} = enum\n    tweets, replies, media\n\n  ApiUrl* = object\n    endpoint*: string\n    params*: seq[(string, string)]\n\n  ApiReq* = object\n    oauth*: ApiUrl\n    cookie*: ApiUrl\n\n  RateLimit* = object\n    limit*: int\n    remaining*: int\n    reset*: int\n\n  SessionKind* = enum\n    oauth\n    cookie\n\n  Session* = ref object\n    id*: int64\n    username*: string\n    pending*: int\n    limited*: bool\n    limitedAt*: int\n    apis*: Table[string, RateLimit]\n    case kind*: SessionKind\n    of oauth:\n      oauthToken*: string\n      oauthSecret*: string\n    of cookie:\n      authToken*: string\n      ct0*: string\n\n  Error* = enum\n    null = 0\n    noUserMatches = 17\n    protectedUser = 22\n    missingParams = 25\n    timeout = 29\n    couldntAuth = 32\n    doesntExist = 34\n    unauthorized = 37\n    invalidParam = 47\n    userNotFound = 50\n    suspended = 63\n    rateLimited = 88\n    expiredToken = 89\n    listIdOrSlug = 112\n    tweetNotFound = 144\n    tweetNotAuthorized = 179\n    forbidden = 200\n    badRequest = 214\n    badToken = 239\n    locked = 326\n    noCsrf = 353\n    tweetUnavailable = 421\n    tweetCensored = 422\n\n  VerifiedType* = enum\n    none = \"None\"\n    blue = \"Blue\"\n    business = \"Business\"\n    government = \"Government\"\n\n  User* = object\n    id*: string\n    username*: string\n    fullname*: string\n    location*: string\n    website*: string\n    bio*: string\n    userPic*: string\n    banner*: string\n    pinnedTweet*: int64\n    following*: int\n    followers*: int\n    tweets*: int\n    likes*: int\n    media*: int\n    verifiedType*: VerifiedType\n    protected*: bool\n    suspended*: bool\n    joinDate*: DateTime\n\n  VideoType* = enum\n    m3u8 = \"application/x-mpegURL\"\n    mp4 = \"video/mp4\"\n    vmap = \"video/vmap\"\n\n  VideoVariant* = object\n    contentType*: VideoType\n    url*: string\n    bitrate*: int\n    resolution*: int\n\n  Video* = object\n    durationMs*: int\n    url*: string\n    thumb*: string\n    available*: bool\n    reason*: string\n    title*: string\n    description*: string\n    playbackType*: VideoType\n    variants*: seq[VideoVariant]\n\n  QueryKind* = enum\n    posts, replies, media, users, tweets, userList\n\n  Query* = object\n    kind*: QueryKind\n    view*: string\n    text*: string\n    filters*: seq[string]\n    includes*: seq[string]\n    excludes*: seq[string]\n    fromUser*: seq[string]\n    since*: string\n    until*: string\n    minLikes*: string\n    sep*: string\n\n  Gif* = object\n    url*: string\n    thumb*: string\n    altText*: string\n\n  Photo* = object\n    url*: string\n    altText*: string\n\n  MediaKind* = enum\n    photoMedia\n    videoMedia\n    gifMedia\n\n  Media* = object\n    case kind*: MediaKind\n    of photoMedia:\n      photo*: Photo\n    of videoMedia:\n      video*: Video\n    of gifMedia:\n      gif*: Gif\n\n  MediaEntities* = seq[Media]\n\n  GalleryPhoto* = object\n    url*: string\n    tweetId*: string\n    color*: string\n\n  PhotoRail* = seq[GalleryPhoto]\n\n  Poll* = object\n    options*: seq[string]\n    values*: seq[int]\n    votes*: int\n    leader*: int\n    status*: string\n\n  CardKind* = enum\n    amplify = \"amplify\"\n    app = \"app\"\n    appPlayer = \"appplayer\"\n    player = \"player\"\n    summary = \"summary\"\n    summaryLarge = \"summary_large_image\"\n    promoWebsite = \"promo_website\"\n    promoVideo = \"promo_video_website\"\n    promoVideoConvo = \"promo_video_convo\"\n    promoImageConvo = \"promo_image_convo\"\n    promoImageApp = \"promo_image_app\"\n    storeLink = \"direct_store_link_app\"\n    liveEvent = \"live_event\"\n    broadcast = \"broadcast\"\n    periscope = \"periscope_broadcast\"\n    unified = \"unified_card\"\n    moment = \"moment\"\n    messageMe = \"message_me\"\n    videoDirectMessage = \"video_direct_message\"\n    imageDirectMessage = \"image_direct_message\"\n    audiospace = \"audiospace\"\n    newsletterPublication = \"newsletter_publication\"\n    jobDetails = \"job_details\"\n    hidden\n    unknown\n\n  Card* = object\n    kind*: CardKind\n    url*: string\n    title*: string\n    dest*: string\n    text*: string\n    image*: string\n    video*: Option[Video]\n\n  TweetStats* = object\n    replies*: int\n    retweets*: int\n    likes*: int\n    views*: int\n\n  Tweet* = ref object\n    id*: int64\n    threadId*: int64\n    replyId*: int64\n    user*: User\n    text*: string\n    time*: DateTime\n    reply*: seq[string]\n    pinned*: bool\n    hasThread*: bool\n    available*: bool\n    tombstone*: string\n    location*: string\n    # Unused, needed for backwards compat\n    source*: string\n    stats*: TweetStats\n    retweet*: Option[Tweet]\n    attribution*: Option[User]\n    mediaTags*: seq[User]\n    quote*: Option[Tweet]\n    card*: Option[Card]\n    poll*: Option[Poll]\n    media*: MediaEntities\n    history*: seq[int64]\n    note*: string\n\n  Tweets* = seq[Tweet]\n\n  Result*[T] = object\n    content*: seq[T]\n    top*, bottom*: string\n    beginning*: bool\n    query*: Query\n\n  Chain* = object\n    content*: Tweets\n    hasMore*: bool\n    cursor*: string\n\n  Conversation* = ref object\n    tweet*: Tweet\n    before*: Chain\n    after*: Chain\n    replies*: Result[Chain]\n\n  EditHistory* = object\n    latest*: Tweet\n    history*: Tweets\n\n  Timeline* = Result[Tweets]\n\n  Profile* = object\n    user*: User\n    photoRail*: PhotoRail\n    pinned*: Option[Tweet]\n    tweets*: Timeline\n\n  List* = object\n    id*: string\n    name*: string\n    userId*: string\n    username*: string\n    description*: string\n    members*: int\n    banner*: string\n\n  GlobalObjects* = ref object\n    tweets*: Table[string, Tweet]\n    users*: Table[string, User]\n\n  Config* = ref object\n    address*: string\n    port*: int\n    useHttps*: bool\n    httpMaxConns*: int\n    title*: string\n    hostname*: string\n    staticDir*: string\n\n    hmacKey*: string\n    base64Media*: bool\n    minTokens*: int\n    enableRSSUserTweets*: bool\n    enableRSSUserReplies*: bool\n    enableRSSUserMedia*: bool\n    enableRSSSearch*: bool\n    enableRSSList*: bool\n    enableDebug*: bool\n    proxy*: string\n    proxyAuth*: string\n    apiProxy*: string\n    disableTid*: bool\n    maxConcurrentReqs*: int\n\n    rssCacheTime*: int\n    listCacheTime*: int\n\n    redisHost*: string\n    redisPort*: int\n    redisConns*: int\n    redisMaxConns*: int\n    redisPassword*: string\n\n  Rss* = object\n    feed*, cursor*: string\n\nproc contains*(thread: Chain; tweet: Tweet): bool =\n  thread.content.anyIt(it.id == tweet.id)\n\nproc add*(timeline: var seq[Tweets]; tweet: Tweet) =\n  timeline.add @[tweet]\n\nproc getPhotos*(tweet: Tweet): seq[Photo] =\n  tweet.media.filterIt(it.kind == photoMedia).mapIt(it.photo)\n\nproc getVideos*(tweet: Tweet): seq[Video] =\n  tweet.media.filterIt(it.kind == videoMedia).mapIt(it.video)\n\nproc hasPhotos*(tweet: Tweet): bool =\n  tweet.media.anyIt(it.kind == photoMedia)\n\nproc hasVideos*(tweet: Tweet): bool =\n  tweet.media.anyIt(it.kind == videoMedia)\n\nproc hasGifs*(tweet: Tweet): bool =\n  tweet.media.anyIt(it.kind == gifMedia)\n\nproc getThumb*(media: Media): string =\n  case media.kind\n  of photoMedia: media.photo.url\n  of videoMedia: media.video.thumb\n  of gifMedia: media.gif.thumb\n"
  },
  {
    "path": "src/utils.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport sequtils, strutils, strformat, uri, tables, base64\nimport nimcrypto\n\nvar\n  hmacKey: string\n  base64Media = false\n\nconst\n  https* = \"https://\"\n  twimg* = \"pbs.twimg.com/\"\n  nitterParams* = [\"name\", \"tab\", \"id\", \"list\", \"referer\", \"scroll\", \"prefs\"]\n  twitterDomains = @[\n    \"twitter.com\",\n    \"pic.twitter.com\",\n    \"twimg.com\",\n    \"abs.twimg.com\",\n    \"pbs.twimg.com\",\n    \"video.twimg.com\",\n    \"x.com\"\n  ]\n\nproc setHmacKey*(key: string) =\n  hmacKey = key\n\nproc setProxyEncoding*(state: bool) =\n  base64Media = state\n\nproc getHmac*(data: string): string =\n  ($hmac(sha256, hmacKey, data))[0 .. 12]\n\nproc getVidUrl*(link: string): string =\n  if link.len == 0: return\n  let sig = getHmac(link)\n  if base64Media:\n    &\"/video/enc/{sig}/{encode(link, safe=true)}\"\n  else:\n    &\"/video/{sig}/{encodeUrl(link)}\"\n\nproc getPicUrl*(link: string): string =\n  if base64Media:\n    &\"/pic/enc/{encode(link, safe=true)}\"\n  else:\n    &\"/pic/{encodeUrl(link)}\"\n\nproc getOrigPicUrl*(link: string): string =\n  if base64Media:\n    &\"/pic/orig/enc/{encode(link, safe=true)}\"\n  else:\n    &\"/pic/orig/{encodeUrl(link)}\"\n\nproc filterParams*(params: Table): seq[(string, string)] =\n  for p in params.pairs():\n    if p[1].len > 0 and p[0] notin nitterParams:\n      result.add p\n\nproc isTwitterUrl*(uri: Uri): bool =\n  uri.hostname in twitterDomains\n\nproc isTwitterUrl*(url: string): bool =\n  isTwitterUrl(parseUri(url))\n\nproc validateNumber*(value: string): string =\n  if value.anyIt(not it.isDigit):\n    return \"\"\n  return value\n"
  },
  {
    "path": "src/views/about.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport os, strformat\nimport karax/[karaxdsl, vdom]\n\nconst\n  date = staticExec(\"git show -s --format=\\\"%cd\\\" --date=format:\\\"%Y.%m.%d\\\"\")\n  hash = staticExec(\"git show -s --format=\\\"%h\\\"\")\n  link = \"https://github.com/zedeus/nitter/commit/\" & hash\n  version = &\"{date}-{hash}\"\n\nvar aboutHtml: string\n\nproc initAboutPage*(dir: string) =\n  try:\n    aboutHtml = readFile(dir/\"md/about.html\")\n  except IOError:\n    stderr.write (dir/\"md/about.html\") & \" not found, please run `nimble md`\\n\"\n    aboutHtml = \"<h1>About page is missing</h1><br><br>\"\n\nproc renderAbout*(): VNode =\n  buildHtml(tdiv(class=\"overlay-panel\")):\n    verbatim aboutHtml\n    h2: text \"Instance info\"\n    p:\n      text \"Version \"\n      a(href=link): text version\n"
  },
  {
    "path": "src/views/embed.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport options\nimport karax/[karaxdsl, vdom]\nfrom jester import Request\n\nimport \"..\"/[types, formatters]\nimport general, tweet\n\nconst doctype = \"<!DOCTYPE html>\\n\"\n\nproc renderVideoEmbed*(tweet: Tweet; cfg: Config; req: Request): string =\n  let \n    video = tweet.getVideos()[0]\n    thumb = video.thumb\n    vidUrl = getVideoEmbed(cfg, tweet.id)\n    prefs = Prefs(hlsPlayback: true, mp4Playback: true)\n\n  let node = buildHtml(html(lang=\"en\")):\n    renderHead(prefs, cfg, req, video=vidUrl, images=(@[thumb]))\n\n    body:\n      tdiv(class=\"embed-video\"):\n        renderVideo(video, prefs, \"\")\n\n  result = doctype & $node\n"
  },
  {
    "path": "src/views/feature.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport karax/[karaxdsl, vdom]\n\nproc renderFeature*(): VNode =\n  buildHtml(tdiv(class=\"overlay-panel\")):\n    h1: text \"Unsupported feature\"\n    p:\n      text \"Nitter doesn't support this feature yet, but it might in the future. \"\n      text \"You can check for an issue and open one if needed here: \"\n      a(href=\"https://github.com/zedeus/nitter/issues\"):\n        text \"https://github.com/zedeus/nitter/issues\"\n    p:\n      text \"To find out more about the Nitter project, see the \"\n      a(href=\"/about\"): text \"About page\"\n"
  },
  {
    "path": "src/views/general.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport uri, strutils, strformat\nimport karax/[karaxdsl, vdom]\n\nimport renderutils\nimport ../utils, ../types, ../prefs, ../formatters\n\nimport jester\n\nconst\n  doctype = \"<!DOCTYPE html>\\n\"\n  lp = readFile(\"public/lp.svg\")\n\nproc toTheme(theme: string): string =\n  theme.toLowerAscii.replace(\" \", \"_\")\n\nproc renderNavbar(cfg: Config; req: Request; rss, canonical: string): VNode =\n  var path = req.params.getOrDefault(\"referer\")\n  if path.len == 0:\n    path = $(parseUri(req.path) ? filterParams(req.params))\n    if \"/status/\" in path: path.add \"#m\"\n\n  buildHtml(nav):\n    tdiv(class=\"inner-nav\"):\n      tdiv(class=\"nav-item\"):\n        a(class=\"site-name\", href=\"/\"): text cfg.title\n\n      a(href=\"/\"): img(class=\"site-logo\", src=\"/logo.png\", alt=\"Logo\")\n\n      tdiv(class=\"nav-item right\"):\n        icon \"search\", title=\"Search\", href=\"/search\"\n        if rss.len > 0:\n          icon \"rss\", title=\"RSS Feed\", href=rss\n        icon \"bird\", title=\"Open in X\", href=canonical\n        a(href=\"https://liberapay.com/zedeus\"): verbatim lp\n        icon \"info\", title=\"About\", href=\"/about\"\n        icon \"cog\", title=\"Preferences\", href=(\"/settings?referer=\" & encodeUrl(path))\n\nproc renderHead*(prefs: Prefs; cfg: Config; req: Request; titleText=\"\"; desc=\"\";\n                 video=\"\"; images: seq[string] = @[]; banner=\"\"; ogTitle=\"\";\n                 rss=\"\"; alternate=\"\"): VNode =\n  let theme = prefs.theme.toTheme\n    \n  let ogType =\n    if video.len > 0: \"video\"\n    elif rss.len > 0: \"object\"\n    elif images.len > 0: \"photo\"\n    else: \"article\"\n\n  let opensearchUrl = getUrlPrefix(cfg) & \"/opensearch\"\n\n  buildHtml(head):\n    link(rel=\"stylesheet\", type=\"text/css\", href=\"/css/style.css?v=30\")\n    link(rel=\"stylesheet\", type=\"text/css\", href=\"/css/fontello.css?v=4\")\n\n    if theme.len > 0:\n      link(rel=\"stylesheet\", type=\"text/css\", href=(&\"/css/themes/{theme}.css\"))\n\n    link(rel=\"apple-touch-icon\", sizes=\"180x180\", href=\"/apple-touch-icon.png\")\n    link(rel=\"icon\", type=\"image/png\", sizes=\"32x32\", href=\"/favicon-32x32.png\")\n    link(rel=\"icon\", type=\"image/png\", sizes=\"16x16\", href=\"/favicon-16x16.png\")\n    link(rel=\"manifest\", href=\"/site.webmanifest\")\n    link(rel=\"mask-icon\", href=\"/safari-pinned-tab.svg\", color=\"#ff6c60\")\n    link(rel=\"search\", type=\"application/opensearchdescription+xml\", title=cfg.title,\n                            href=opensearchUrl)\n\n    if alternate.len > 0:\n      link(rel=\"alternate\", href=alternate, title=\"View on X\")\n\n    if rss.len > 0:\n      link(rel=\"alternate\", type=\"application/rss+xml\", href=rss, title=\"RSS feed\")\n\n    if prefs.hlsPlayback:\n      script(src=\"/js/hls.min.js\", `defer`=\"\")\n      script(src=\"/js/hlsPlayback.js\", `defer`=\"\")\n\n    if prefs.infiniteScroll:\n      script(src=\"/js/infiniteScroll.js\", `defer`=\"\")\n\n    title:\n      if titleText.len > 0:\n        text titleText & \" | \" & cfg.title\n      else:\n        text cfg.title\n\n    meta(name=\"viewport\", content=\"width=device-width, initial-scale=1.0\")\n    meta(name=\"theme-color\", content=\"#1F1F1F\")\n    meta(property=\"og:type\", content=ogType)\n    meta(property=\"og:title\", content=(if ogTitle.len > 0: ogTitle else: titleText))\n    meta(property=\"og:description\", content=stripHtml(desc))\n    meta(property=\"og:site_name\", content=\"Nitter\")\n    meta(property=\"og:locale\", content=\"en_US\")\n\n    if banner.len > 0 and not banner.startsWith('#'):\n      let bannerUrl = getPicUrl(banner)\n      link(rel=\"preload\", type=\"image/png\", href=bannerUrl, `as`=\"image\")\n\n    for url in images:\n      let preloadUrl = if \"400x400\" in url: getPicUrl(url)\n                       else: getSmallPic(url)\n      link(rel=\"preload\", type=\"image/png\", href=preloadUrl, `as`=\"image\")\n\n      let image = getUrlPrefix(cfg) & getPicUrl(url)\n      meta(property=\"og:image\", content=image)\n      meta(property=\"twitter:image:src\", content=image)\n\n      if rss.len > 0:\n        meta(property=\"twitter:card\", content=\"summary\")\n      else:\n        meta(property=\"twitter:card\", content=\"summary_large_image\")\n\n    if video.len > 0:\n      meta(property=\"og:video:url\", content=video)\n      meta(property=\"og:video:secure_url\", content=video)\n      meta(property=\"og:video:type\", content=\"text/html\")\n\n    # this is last so images are also preloaded\n    # if this is done earlier, Chrome only preloads one image for some reason\n    link(rel=\"preload\", type=\"font/woff2\", `as`=\"font\",\n         href=\"/fonts/fontello.woff2?61663884\", crossorigin=\"anonymous\")\n\nproc renderMain*(body: VNode; req: Request; cfg: Config; prefs=defaultPrefs;\n                 titleText=\"\"; desc=\"\"; ogTitle=\"\"; rss=\"\"; video=\"\";\n                 images: seq[string] = @[]; banner=\"\"): string =\n\n  let twitterLink = getTwitterLink(req.path, req.params)\n\n  let node = buildHtml(html(lang=\"en\")):\n    renderHead(prefs, cfg, req, titleText, desc, video, images, banner, ogTitle,\n               rss, twitterLink)\n\n    let bodyClass = if prefs.stickyNav: \"fixed-nav\" else: \"\"\n    body(class=bodyClass):\n      renderNavbar(cfg, req, rss, twitterLink)\n\n      tdiv(class=\"container\"):\n        body\n\n  result = doctype & $node\n\nproc renderError*(error: string): VNode =\n  buildHtml(tdiv(class=\"panel-container\")):\n    tdiv(class=\"error-panel\"):\n      span: verbatim error\n"
  },
  {
    "path": "src/views/list.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport strformat\nimport karax/[karaxdsl, vdom]\n\nimport renderutils\nimport \"..\"/[types, utils]\n\nproc renderListTabs*(query: Query; path: string): VNode =\n  buildHtml(ul(class=\"tab\")):\n    li(class=query.getTabClass(posts)):\n      a(href=(path)): text \"Tweets\"\n    li(class=query.getTabClass(userList)):\n      a(href=(path & \"/members\")): text \"Members\"\n\nproc renderList*(body: VNode; query: Query; list: List): VNode =\n  buildHtml(tdiv(class=\"timeline-container\")):\n    if list.banner.len > 0:\n      tdiv(class=\"timeline-banner\"):\n        a(href=getPicUrl(list.banner), target=\"_blank\"):\n          genImg(list.banner)\n\n    tdiv(class=\"timeline-header\"):\n      text &\"\\\"{list.name}\\\" by @{list.username}\"\n\n      tdiv(class=\"timeline-description\"):\n        text list.description\n\n    renderListTabs(query, &\"/i/lists/{list.id}\")\n    body\n"
  },
  {
    "path": "src/views/opensearch.nimf",
    "content": "#? stdtmpl(subsChar = '$', metaChar = '#')\n## SPDX-License-Identifier: AGPL-3.0-only\n#proc generateOpenSearchXML*(name, hostname, url: string): string =\n#  result = \"\"\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<OpenSearchDescription xmlns=\"http://a9.com/-/spec/opensearch/1.1/\"\n                       xmlns:moz=\"http://www.mozilla.org/2006/browser/search/\">\n  <ShortName>${name}</ShortName>\n  <Description>Twitter search via ${hostname}</Description>\n  <InputEncoding>UTF-8</InputEncoding>\n  <Url type=\"text/html\" template=\"${url}{searchTerms}\" />\n</OpenSearchDescription>\n#end proc\n"
  },
  {
    "path": "src/views/preferences.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport tables, macros, strutils\nimport karax/[karaxdsl, vdom]\n\nimport renderutils\nimport ../types, ../prefs_impl\n\nmacro renderPrefs*(): untyped =\n  result = nnkCall.newTree(\n    ident(\"buildHtml\"), ident(\"tdiv\"), nnkStmtList.newTree())\n\n  for header, options in prefList:\n    result[2].add nnkCall.newTree(\n      ident(\"legend\"),\n      nnkStmtList.newTree(\n        nnkCommand.newTree(ident(\"text\"), newLit(header))))\n\n    for pref in options:\n      let procName = ident(\"gen\" & capitalizeAscii($pref.kind))\n      let state = nnkDotExpr.newTree(ident(\"prefs\"), ident(pref.name))\n      var stmt = nnkStmtList.newTree(\n        nnkCall.newTree(procName, newLit(pref.name), newLit(pref.label), state))\n\n      case pref.kind\n      of checkbox: discard\n      of input: stmt[0].add newLit(pref.placeholder)\n      of select:\n        if pref.name == \"theme\":\n          stmt[0].add ident(\"themes\")\n        else:\n          stmt[0].add newLit(pref.options)\n\n      result[2].add stmt\n\nproc renderPreferences*(prefs: Prefs; path: string; themes: seq[string];\n                        prefsUrl: string): VNode =\n  buildHtml(tdiv(class=\"overlay-panel\")):\n    fieldset(class=\"preferences\"):\n      form(`method`=\"post\", action=\"/saveprefs\", autocomplete=\"off\"):\n        refererField path\n\n        renderPrefs()\n\n        legend: text \"Bookmark\"\n        p(class=\"bookmark-note\"):\n          text \"Save this URL to restore your preferences (?prefs works on all pages)\"\n        pre(class=\"prefs-code\"):\n          text prefsUrl\n        p(class=\"bookmark-note\"):\n          verbatim \"You can override preferences with query parameters (e.g. <code>?hlsPlayback=on</code>). These overrides aren't saved to cookies, and links won't retain the parameters. Intended for configuring RSS feeds and other cookieless environments. Hover over a preference to see its name.\"\n\n        h4(class=\"note\"):\n          text \"Preferences are stored client-side using cookies without any personal information.\"\n\n        button(`type`=\"submit\", class=\"pref-submit\"):\n          text \"Save preferences\"\n\n      buttonReferer \"/resetprefs\", \"Reset preferences\", path, class=\"pref-reset\"\n"
  },
  {
    "path": "src/views/profile.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport strutils, strformat\nimport karax/[karaxdsl, vdom, vstyles]\n\nimport renderutils, search\nimport \"..\"/[types, utils, formatters]\n\nproc renderStat(num: int; class: string; text=\"\"): VNode =\n  let t = if text.len > 0: text else: class\n  buildHtml(li(class=class)):\n    span(class=\"profile-stat-header\"): text capitalizeAscii(t)\n    span(class=\"profile-stat-num\"):\n      text insertSep($num, ',')\n\nproc renderUserCard*(user: User; prefs: Prefs): VNode =\n  buildHtml(tdiv(class=\"profile-card\")):\n    tdiv(class=\"profile-card-info\"):\n      let\n        url = getPicUrl(user.getUserPic())\n        size =\n          if prefs.autoplayGifs and user.userPic.endsWith(\"gif\"): \"\"\n          else: \"_400x400\"\n\n      a(class=\"profile-card-avatar\", href=url, target=\"_blank\"):\n        genImg(user.getUserPic(size))\n\n      tdiv(class=\"profile-card-tabs-name\"):\n        linkUser(user, class=\"profile-card-fullname\")\n        verifiedIcon(user)\n        linkUser(user, class=\"profile-card-username\")\n\n    tdiv(class=\"profile-card-extra\"):\n      if user.bio.len > 0:\n        tdiv(class=\"profile-bio\"):\n          p(dir=\"auto\"):\n            verbatim replaceUrls(user.bio, prefs)\n\n      if user.location.len > 0:\n        tdiv(class=\"profile-location\"):\n          span: icon \"location\"\n          let (place, url) = getLocation(user)\n          if url.len > 1:\n            a(href=url): text place\n          elif \"://\" in place:\n            a(href=place): text place\n          else:\n            span: text place\n\n      if user.website.len > 0:\n        tdiv(class=\"profile-website\"):\n          span:\n            let url = replaceUrls(user.website, prefs)\n            icon \"link\"\n            a(href=url): text url.shortLink\n\n      tdiv(class=\"profile-joindate\"):\n        span(title=getJoinDateFull(user)):\n          icon \"calendar\", getJoinDate(user)\n\n      tdiv(class=\"profile-card-extra-links\"):\n        ul(class=\"profile-statlist\"):\n          renderStat(user.tweets, \"posts\", text=\"Tweets\")\n          renderStat(user.following, \"following\")\n          renderStat(user.followers, \"followers\")\n          renderStat(user.likes, \"likes\")\n\nproc renderPhotoRail(profile: Profile): VNode =\n  let count = insertSep($profile.user.media, ',')\n  buildHtml(tdiv(class=\"photo-rail-card\")):\n    tdiv(class=\"photo-rail-header\"):\n      a(href=(&\"/{profile.user.username}/media\")):\n        icon \"picture\", count & \" Photos and videos\"\n\n    input(id=\"photo-rail-grid-toggle\", `type`=\"checkbox\")\n    label(`for`=\"photo-rail-grid-toggle\", class=\"photo-rail-header-mobile\"):\n      icon \"picture\", count & \" Photos and videos\"\n      icon \"down\"\n\n    tdiv(class=\"photo-rail-grid\"):\n      for i, photo in profile.photoRail:\n        if i == 16: break\n        let photoSuffix =\n          if \"format\" in photo.url or \"placeholder\" in photo.url: \"\"\n          else: \":thumb\"\n        a(href=(&\"/{profile.user.username}/status/{photo.tweetId}#m\")):\n          genImg(photo.url & photoSuffix)\n\nproc renderBanner(banner: string): VNode =\n  buildHtml():\n    if banner.len == 0:\n      a()\n    elif banner.startsWith('#'):\n      a(style={backgroundColor: banner})\n    else:\n      a(href=getPicUrl(banner), target=\"_blank\"): genImg(banner)\n\nproc renderProtected(username: string): VNode =\n  buildHtml(tdiv(class=\"timeline-container\")):\n    tdiv(class=\"timeline-header timeline-protected\"):\n      h2: text \"This account's tweets are protected.\"\n      p: text &\"Only confirmed followers have access to @{username}'s tweets.\"\n\nproc renderProfile*(profile: var Profile; prefs: Prefs; path: string): VNode =\n  profile.tweets.query.fromUser = @[profile.user.username]\n  let\n    isGalleryView = profile.tweets.query.kind == media and\n      profile.tweets.query.view == \"gallery\"\n    viewClass = if isGalleryView: \" media-only\" else: \"\"\n\n  buildHtml(tdiv(class=(\"profile-tabs\" & viewClass))):\n    if not isGalleryView and not prefs.hideBanner:\n      tdiv(class=\"profile-banner\"):\n        renderBanner(profile.user.banner)\n\n    if not isGalleryView:\n      let sticky = if prefs.stickyProfile: \" sticky\" else: \"\"\n      tdiv(class=(\"profile-tab\" & sticky)):\n        renderUserCard(profile.user, prefs)\n        if profile.photoRail.len > 0:\n          renderPhotoRail(profile)\n\n    if profile.user.protected:\n      renderProtected(profile.user.username)\n    else:\n      renderTweetSearch(profile.tweets, prefs, path, profile.pinned)\n"
  },
  {
    "path": "src/views/renderutils.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport strutils, strformat\nimport karax/[karaxdsl, vdom, vstyles]\nimport \"..\"/[types, utils]\n\nconst smallWebp* = \"?name=small&format=webp\"\n\nproc getSmallPic*(url: string): string =\n  result = url\n  if \"?\" notin url and not url.endsWith(\"placeholder.png\"):\n    result &= smallWebp\n  result = getPicUrl(result)\n\nproc icon*(icon: string; text=\"\"; title=\"\"; class=\"\"; href=\"\"): VNode =\n  var c = \"icon-\" & icon\n  if class.len > 0: c = &\"{c} {class}\"\n  buildHtml(tdiv(class=\"icon-container\")):\n    if href.len > 0:\n      a(class=c, title=title, href=href)\n    else:\n      span(class=c, title=title)\n\n    if text.len > 0:\n      text \" \" & text\n\ntemplate verifiedIcon*(user: User): untyped {.dirty.} =\n  if user.verifiedType != VerifiedType.none:\n    let lower = ($user.verifiedType).toLowerAscii()\n    buildHtml(tdiv(class=(&\"verified-icon {lower}\"))):\n      icon \"circle\", class=\"verified-icon-circle\", title=(&\"Verified {lower} account\")\n      icon \"ok\", class=\"verified-icon-check\", title=(&\"Verified {lower} account\")\n  else:\n    text \"\"\n\nproc linkUser*(user: User, class=\"\"): VNode =\n  let\n    isName = \"username\" notin class\n    href = \"/\" & user.username\n    nameText = if isName: user.fullname\n               else: \"@\" & user.username\n\n  buildHtml(a(href=href, class=class, title=nameText)):\n    text nameText\n    if isName:\n      if user.protected:\n        text \" \"\n        icon \"lock\", title=\"Protected account\"\n\nproc linkText*(text: string; class=\"\"): VNode =\n  let url = if \"http\" notin text: https & text else: text\n  buildHtml():\n    a(href=url, class=class): text text\n\nproc hiddenField*(name, value: string): VNode =\n  buildHtml():\n    input(name=name, style={display: \"none\"}, value=value)\n\nproc refererField*(path: string): VNode =\n  hiddenField(\"referer\", path)\n\nproc buttonReferer*(action, text, path: string; class=\"\"; `method`=\"post\"): VNode =\n  buildHtml(form(`method`=`method`, action=action, class=class)):\n    refererField path\n    button(`type`=\"submit\"):\n      text text\n\nproc genCheckbox*(pref, label: string; state: bool): VNode =\n  buildHtml(label(class=\"pref-group checkbox-container\", title=pref)):\n    text label\n    input(name=pref, `type`=\"checkbox\", checked=state)\n    span(class=\"checkbox\")\n\nproc genInput*(pref, label, state, placeholder: string; class=\"\"; autofocus=true): VNode =\n  let p = placeholder\n  buildHtml(tdiv(class=(\"pref-group pref-input \" & class), title=pref)):\n    if label.len > 0:\n      label(`for`=pref): text label\n    input(name=pref, `type`=\"text\", placeholder=p, value=state, autofocus=(autofocus and state.len == 0))\n\nproc genSelect*(pref, label, state: string; options: seq[string]): VNode =\n  buildHtml(tdiv(class=\"pref-group pref-input\", title=pref)):\n    label(`for`=pref): text label\n    select(name=pref):\n      for opt in options:\n        option(value=opt, selected=(opt == state)):\n          text opt\n\nproc genDate*(pref, state: string): VNode =\n  buildHtml(span(class=\"date-input\")):\n    input(name=pref, `type`=\"date\", value=state)\n    icon \"calendar\"\n\nproc genNumberInput*(pref, label, state, placeholder: string; class=\"\"; autofocus=true; min=\"0\"): VNode =\n  let p = placeholder\n  buildHtml(tdiv(class=(\"pref-group pref-input \" & class))):\n    if label.len > 0:\n      label(`for`=pref): text label\n    input(name=pref, `type`=\"number\", placeholder=p, value=state, autofocus=(autofocus and state.len == 0), min=min, step=\"1\")\n\nproc genImg*(url: string; class=\"\"; alt=\"\"): VNode =\n  buildHtml():\n    img(src=getPicUrl(url), class=class, alt=alt, loading=\"lazy\")\n\nproc getTabClass*(query: Query; tab: QueryKind): string =\n  if query.kind == tab: \"tab-item active\"\n  else: \"tab-item\"\n\nproc getAvatarClass*(prefs: Prefs): string =\n  if prefs.squareAvatars: \"avatar\"\n  else: \"avatar round\"\n"
  },
  {
    "path": "src/views/rss.nimf",
    "content": "#? stdtmpl(subsChar = '$', metaChar = '#')\n## SPDX-License-Identifier: AGPL-3.0-only\n#import strutils, sequtils, xmltree, strformat, options, unicode\n#import ../types, ../utils, ../formatters, ../prefs\n## Snowflake ID cutoff for RSS GUID format transition\n## Corresponds to approximately December 14, 2025 UTC\n#const guidCutoff = 2000000000000000000'i64\n#\n#proc getTitle(tweet: Tweet; retweet: string): string =\n#var prefix = \"\"\n#if tweet.pinned: prefix = \"Pinned: \"\n#elif retweet.len > 0: prefix = &\"RT by @{retweet}: \"\n#elif tweet.reply.len > 0: prefix = &\"R to @{tweet.reply[0]}: \"\n#end if\n#var text = stripHtml(tweet.text)\n##if unicode.runeLen(text) > 32:\n##  text = unicode.runeSubStr(text, 0, 32) & \"...\"\n##end if\n#text = xmltree.escape(text)\n#if text.len > 0:\n#  result = prefix & text\n#  return\n#end if\n#if tweet.media.len > 0:\n#  result = prefix\n#  let firstKind = tweet.media[0].kind\n#  if tweet.media.anyIt(it.kind != firstKind):\n#    result &= \"Media\"\n#  else:\n#    case firstKind\n#    of photoMedia: result &= \"Image\"\n#    of videoMedia: result &= \"Video\"\n#    of gifMedia:   result &= \"Gif\"\n#    end case\n#  end if\n#end if\n#end proc\n#\n#proc getDescription(desc: string; cfg: Config): string =\nTwitter feed for: ${desc}. Generated by ${getUrlPrefix(cfg)}\n#end proc\n#\n#proc renderRssMedia(media: Media; tweet: Tweet; urlPrefix: string): string =\n#case media.kind\n#of photoMedia:\n#  let photo = media.photo\n<img src=\"${urlPrefix}${getPicUrl(photo.url)}\" style=\"max-width:250px;\" />\n#of videoMedia:\n#  let video = media.video\n<a href=\"${urlPrefix}${tweet.getLink}\">\n<br>Video<br>\n  <img src=\"${urlPrefix}${getPicUrl(video.thumb)}\" style=\"max-width:250px;\" />\n</a>\n#of gifMedia:\n#  let gif = media.gif\n#  let thumb = &\"{urlPrefix}{getPicUrl(gif.thumb)}\"\n#  let url = &\"{urlPrefix}{getPicUrl(gif.url)}\"\n<video poster=\"${thumb}\" autoplay muted loop style=\"max-width:250px;\">\n  <source src=\"${url}\" type=\"video/mp4\"></video>\n#end case\n#end proc\n#\n#proc getTweetsWithPinned(profile: Profile): seq[Tweets] =\n#result = profile.tweets.content\n#if profile.pinned.isSome and result.len > 0:\n#  let pinnedTweet = profile.pinned.get\n#  var inserted = false\n#  for threadIdx in 0 ..< result.len:\n#    if not inserted:\n#      for tweetIdx in 0 ..< result[threadIdx].len:\n#        if result[threadIdx][tweetIdx].id < pinnedTweet.id:\n#          result[threadIdx].insert(pinnedTweet, tweetIdx)\n#          inserted = true\n#        end if\n#      end for\n#    end if\n#  end for\n#end if\n#end proc\n#\n#proc renderRssTweet(tweet: Tweet; cfg: Config; prefs: Prefs): string =\n#let tweet = tweet.retweet.get(tweet)\n#let urlPrefix = getUrlPrefix(cfg)\n#let text = replaceUrls(tweet.text, prefs, absolute=urlPrefix)\n<p>${text.replace(\"\\n\", \"<br>\\n\")}</p>\n#if tweet.media.len > 0:\n#  for media in tweet.media:\n${renderRssMedia(media, tweet, urlPrefix)}\n#  end for\n#elif tweet.card.isSome:\n#  let card = tweet.card.get()\n#  if card.image.len > 0:\n<img src=\"${urlPrefix}${getPicUrl(card.image)}\" style=\"max-width:250px;\" />\n#  end if\n#end if\n#if tweet.note.len > 0 and not prefs.hideCommunityNotes:\n<p><b>Community note:</b> ${replaceUrls(tweet.note, prefs, absolute=urlPrefix)}</p>\n#end if\n#if tweet.quote.isSome and get(tweet.quote).available:\n#  let quoteTweet = get(tweet.quote)\n#  let quoteLink = urlPrefix & getLink(quoteTweet)\n<hr/>\n<blockquote>\n<b>${quoteTweet.user.fullname} (@${quoteTweet.user.username})</b>\n<p>\n${renderRssTweet(quoteTweet, cfg, prefs)}\n</p>\n<footer>\n— <cite><a href=\"${quoteLink}\">${quoteLink}</a>\n</footer>\n</blockquote>\n#end if\n#end proc\n#\n#proc renderRssTweets(tweets: seq[Tweets]; cfg: Config; prefs: Prefs; userId=\"\"): string =\n#let urlPrefix = getUrlPrefix(cfg)\n#var links: seq[string]\n#for thread in tweets:\n#  for tweet in thread:\n#    if userId.len > 0 and tweet.user.id != userId: continue\n#    end if\n#\n#    let retweet = if tweet.retweet.isSome: tweet.user.username else: \"\"\n#    let tweet = if retweet.len > 0: tweet.retweet.get else: tweet\n#    let link = getLink(tweet)\n#    if link in links: continue\n#    end if\n#    links.add link\n#    let useGlobalGuid = tweet.id >= guidCutoff\n      <item>\n        <title>${getTitle(tweet, retweet)}</title>\n        <dc:creator>@${tweet.user.username}</dc:creator>\n        <description><![CDATA[${renderRssTweet(tweet, cfg, prefs).strip(chars={'\\n'})}]]></description>\n        <pubDate>${getRfc822Time(tweet)}</pubDate>\n#if useGlobalGuid:\n        <guid isPermaLink=\"false\">${tweet.id}</guid>\n#else:\n        <guid>${urlPrefix & link}</guid>\n#end if\n        <link>${urlPrefix & link}</link>\n      </item>\n#  end for\n#end for\n#end proc\n#\n#proc renderTimelineRss*(profile: Profile; cfg: Config; prefs: Prefs; multi=false): string =\n#let urlPrefix = getUrlPrefix(cfg)\n#result = \"\"\n#let handle = (if multi: \"\" else: \"@\") & profile.user.username\n#var title = profile.user.fullname\n#if not multi: title &= \" / \" & handle\n#end if\n#title = xmltree.escape(title).sanitizeXml\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<rss xmlns:atom=\"http://www.w3.org/2005/Atom\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" version=\"2.0\">\n  <channel>\n    <atom:link href=\"${urlPrefix}/${profile.user.username}/rss\" rel=\"self\" type=\"application/rss+xml\" />\n    <title>${title}</title>\n    <link>${urlPrefix}/${profile.user.username}</link>\n    <description>${getDescription(handle, cfg)}</description>\n    <language>en-us</language>\n    <ttl>40</ttl>\n    <image>\n      <title>${title}</title>\n      <link>${urlPrefix}/${profile.user.username}</link>\n      <url>${urlPrefix}${getPicUrl(profile.user.getUserPic(style=\"_400x400\"))}</url>\n      <width>128</width>\n      <height>128</height>\n    </image>\n#let tweetsList = getTweetsWithPinned(profile)\n#if tweetsList.len > 0:\n${renderRssTweets(tweetsList, cfg, prefs, userId=profile.user.id)}\n#end if\n  </channel>\n</rss>\n#end proc\n#\n#proc renderListRss*(tweets: seq[Tweets]; list: List; cfg: Config; prefs: Prefs): string =\n#let link = &\"{getUrlPrefix(cfg)}/i/lists/{list.id}\"\n#result = \"\"\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<rss xmlns:atom=\"http://www.w3.org/2005/Atom\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" version=\"2.0\">\n  <channel>\n    <atom:link href=\"${link}\" rel=\"self\" type=\"application/rss+xml\" />\n    <title>${xmltree.escape(list.name)} / @${list.username}</title>\n    <link>${link}</link>\n    <description>${getDescription(&\"{list.name} by @{list.username}\", cfg)}</description>\n    <language>en-us</language>\n    <ttl>40</ttl>\n${renderRssTweets(tweets, cfg, prefs)}\n </channel>\n</rss>\n#end proc\n#\n#proc renderSearchRss*(tweets: seq[Tweets]; name, param: string; cfg: Config; prefs: Prefs): string =\n#let link = &\"{getUrlPrefix(cfg)}/search\"\n#let escName = xmltree.escape(name)\n#result = \"\"\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<rss xmlns:atom=\"http://www.w3.org/2005/Atom\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" version=\"2.0\">\n  <channel>\n    <atom:link href=\"${link}\" rel=\"self\" type=\"application/rss+xml\" />\n    <title>Search results for \"${escName}\"</title>\n    <link>${link}</link>\n    <description>${getDescription(&\"Search \\\"{escName}\\\"\", cfg)}</description>\n    <language>en-us</language>\n    <ttl>40</ttl>\n${renderRssTweets(tweets, cfg, prefs)}\n  </channel>\n</rss>\n#end proc\n"
  },
  {
    "path": "src/views/search.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport strutils, strformat, sequtils, unicode, tables, options\nimport karax/[karaxdsl, vdom]\n\nimport renderutils, timeline\nimport \"..\"/[types, query]\n\nconst toggles = {\n  \"nativeretweets\": \"Retweets\",\n  \"media\": \"Media\",\n  \"videos\": \"Videos\",\n  \"news\": \"News\",\n  \"native_video\": \"Native videos\",\n  \"replies\": \"Replies\",\n  \"links\": \"Links\",\n  \"images\": \"Images\",\n  \"quote\": \"Quotes\",\n  \"spaces\": \"Spaces\"\n}.toOrderedTable\n\nproc renderSearch*(): VNode =\n  buildHtml(tdiv(class=\"panel-container\")):\n    tdiv(class=\"search-bar\"):\n      form(`method`=\"get\", action=\"/search\", autocomplete=\"off\"):\n        hiddenField(\"f\", \"tweets\")\n        input(`type`=\"text\", name=\"q\", autofocus=\"\",\n              placeholder=\"Search...\", dir=\"auto\")\n        button(`type`=\"submit\"): icon \"search\"\n\nproc renderProfileTabs*(query: Query; username: string): VNode =\n  let link = \"/\" & username\n  buildHtml(ul(class=\"tab\")):\n    li(class=query.getTabClass(posts)):\n      a(href=link): text \"Tweets\"\n    li(class=(query.getTabClass(replies) & \" wide\")):\n      a(href=(link & \"/with_replies\")): text \"Tweets & Replies\"\n    li(class=query.getTabClass(media)):\n      a(href=(link & \"/media\")): text \"Media\"\n    li(class=query.getTabClass(tweets)):\n      a(href=(link & \"/search\")): text \"Search\"\n\nproc renderMediaViewTabs*(query: Query; username: string): VNode =\n  let currentView = if query.view.len > 0: query.view else: \"timeline\"\n  let base = \"/\" & username & \"/media?view=\"\n  func cls(view: string): string =\n    if currentView == view: \"tab-item active\" else: \"tab-item\"\n  buildHtml(ul(class=\"tab media-view-tabs\")):\n    li(class=cls(\"timeline\")):\n      a(href=(base & \"timeline\")): text \"Timeline\"\n    li(class=cls(\"grid\")):\n      a(href=(base & \"grid\")): text \"Grid\"\n    li(class=cls(\"gallery\")):\n      a(href=(base & \"gallery\")): text \"Gallery\"\n\nproc renderSearchTabs*(query: Query): VNode =\n  var q = query\n  buildHtml(ul(class=\"tab\")):\n    li(class=query.getTabClass(tweets)):\n      q.kind = tweets\n      a(href=(\"?\" & genQueryUrl(q))): text \"Tweets\"\n    li(class=query.getTabClass(users)):\n      q.kind = users\n      a(href=(\"?\" & genQueryUrl(q))): text \"Users\"\n\nproc isPanelOpen(q: Query): bool =\n  q.fromUser.len == 0 and (q.filters.len > 0 or q.excludes.len > 0 or\n  @[q.minLikes, q.until, q.since].anyIt(it.len > 0))\n\nproc renderSearchPanel*(query: Query): VNode =\n  let user = query.fromUser.join(\",\")\n  let action = if user.len > 0: &\"/{user}/search\" else: \"/search\"\n  buildHtml(form(`method`=\"get\", action=action,\n                 class=\"search-field\", autocomplete=\"off\")):\n    hiddenField(\"f\", \"tweets\")\n    genInput(\"q\", \"\", query.text, \"Enter search...\", class=\"pref-inline\")\n    button(`type`=\"submit\"): icon \"search\"\n\n    input(id=\"search-panel-toggle\", `type`=\"checkbox\", checked=isPanelOpen(query))\n    label(`for`=\"search-panel-toggle\"): icon \"down\"\n\n    tdiv(class=\"search-panel\"):\n      for f in @[\"filter\", \"exclude\"]:\n        span(class=\"search-title\"): text capitalize(f)\n        tdiv(class=\"search-toggles\"):\n          for k, v in toggles:\n            let state =\n              if f == \"filter\": k in query.filters\n              else: k in query.excludes\n            genCheckbox(&\"{f[0]}-{k}\", v, state)\n\n      tdiv(class=\"search-row\"):\n        tdiv:\n          span(class=\"search-title\"): text \"Time range\"\n          tdiv(class=\"date-range\"):\n            genDate(\"since\", query.since)\n            span(class=\"search-title\"): text \"-\"\n            genDate(\"until\", query.until)\n        tdiv:\n          span(class=\"search-title\"): text \"Minimum likes\"\n          genNumberInput(\"min_faves\", \"\", query.minLikes, \"Number...\", autofocus=false)\n\nproc renderTweetSearch*(results: Timeline; prefs: Prefs; path: string;\n                        pinned=none(Tweet)): VNode =\n  let query = results.query\n  buildHtml(tdiv(class=\"timeline-container\")):\n    if query.fromUser.len > 1:\n      tdiv(class=\"timeline-header\"):\n        text query.fromUser.join(\" | \")\n\n    if query.fromUser.len > 0:\n      if query.kind != media or query.view != \"gallery\":\n        renderProfileTabs(query, query.fromUser.join(\",\"))\n      if query.kind == media and query.fromUser.len == 1:\n        renderMediaViewTabs(query, query.fromUser[0])\n\n    if query.fromUser.len == 0 or query.kind == tweets:\n      tdiv(class=\"timeline-header\"):\n        renderSearchPanel(query)\n\n    if query.fromUser.len == 0:\n      renderSearchTabs(query)\n\n    renderTimelineTweets(results, prefs, path, pinned)\n\nproc renderUserSearch*(results: Result[User]; prefs: Prefs): VNode =\n  buildHtml(tdiv(class=\"timeline-container\")):\n    tdiv(class=\"timeline-header\"):\n      form(`method`=\"get\", action=\"/search\", class=\"search-field\", autocomplete=\"off\"):\n        hiddenField(\"f\", \"users\")\n        genInput(\"q\", \"\", results.query.text, \"Enter username...\", class=\"pref-inline\")\n        button(`type`=\"submit\"): icon \"search\"\n\n    renderSearchTabs(results.query)\n    renderTimelineUsers(results, prefs)\n"
  },
  {
    "path": "src/views/status.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport karax/[karaxdsl, vdom]\n\nimport \"..\"/[types, formatters]\nimport tweet, timeline\n\nproc renderEarlier(thread: Chain): VNode =\n  buildHtml(tdiv(class=\"timeline-item more-replies earlier-replies\")):\n    a(class=\"more-replies-text\", href=getLink(thread.content[0])):\n      text \"earlier replies\"\n\nproc renderMoreReplies(thread: Chain): VNode =\n  let link = getLink(thread.content[^1])\n  buildHtml(tdiv(class=\"timeline-item more-replies\")):\n    if thread.content[^1].available:\n      a(class=\"more-replies-text\", href=link):\n        text \"more replies\"\n    else:\n      a(class=\"more-replies-text\"):\n        text \"more replies\"\n\nproc renderReplyThread(thread: Chain; prefs: Prefs; path: string): VNode =\n  buildHtml(tdiv(class=\"reply thread thread-line\")):\n    for i, tweet in thread.content:\n      let last = (i == thread.content.high and not thread.hasMore)\n      renderTweet(tweet, prefs, path, index=i, last=last)\n\n    if thread.hasMore:\n      renderMoreReplies(thread)\n\nproc renderReplies*(replies: Result[Chain]; prefs: Prefs; path: string; tweet: Tweet = nil): VNode =\n  buildHtml(tdiv(class=\"replies\", id=\"r\")):\n    var hasReplies = false\n    var replyCount = 0\n    for thread in replies.content:\n      if thread.content.len == 0: continue\n      hasReplies = true\n      replyCount += thread.content.len\n      renderReplyThread(thread, prefs, path)\n\n    if hasReplies and replies.bottom.len > 0:\n      if tweet == nil or not replies.beginning or replyCount < tweet.stats.replies:\n        renderMore(Query(), replies.bottom, focus=\"#r\")\n\nproc renderConversation*(conv: Conversation; prefs: Prefs; path: string): VNode =\n  let hasAfter = conv.after.content.len > 0\n  let threadId = conv.tweet.threadId\n  buildHtml(tdiv(class=\"conversation\")):\n    tdiv(class=\"main-thread\"):\n      if conv.before.content.len > 0:\n        tdiv(class=\"before-tweet thread-line\"):\n          let first = conv.before.content[0]\n          if threadId != first.id and (first.replyId > 0 or not first.available):\n            renderEarlier(conv.before)\n          for i, tweet in conv.before.content:\n            renderTweet(tweet, prefs, path, index=i)\n\n      tdiv(class=\"main-tweet\", id=\"m\"):\n        let afterClass = if hasAfter: \"thread thread-line\" else: \"\"\n        renderTweet(conv.tweet, prefs, path, class=afterClass, mainTweet=true)\n\n      if hasAfter:\n        tdiv(class=\"after-tweet thread-line\"):\n          let\n            total = conv.after.content.high\n            hasMore = conv.after.hasMore\n          for i, tweet in conv.after.content:\n            renderTweet(tweet, prefs, path, index=i,\n                        last=(i == total and not hasMore), afterTweet=true)\n\n          if hasMore:\n            renderMoreReplies(conv.after)\n\n    if not prefs.hideReplies:\n      if not conv.replies.beginning:\n        renderNewer(Query(), getLink(conv.tweet), focus=\"#r\")\n      if conv.replies.content.len > 0 or conv.replies.bottom.len > 0:\n        renderReplies(conv.replies, prefs, path, conv.tweet)\n\n    renderToTop(focus=\"#m\")\n\nproc renderEditHistory*(edits: EditHistory; prefs: Prefs; path: string): VNode =\n  buildHtml(tdiv(class=\"edit-history\")):\n    tdiv(class=\"latest-edit\"):\n      tdiv(class=\"edit-history-header\"): \n        text \"Latest post\"\n      renderTweet(edits.latest, prefs, path)\n\n    tdiv(class=\"previous-edits\"):\n      tdiv(class=\"edit-history-header\"): \n        text \"Version history\"\n      for tweet in edits.history:\n        tdiv(class=\"tweet-edit\"):\n          renderTweet(tweet, prefs, path)\n"
  },
  {
    "path": "src/views/timeline.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport strutils, strformat, algorithm, uri, options\nimport karax/[karaxdsl, vdom]\n\nimport \"..\"/[types, query, formatters]\nimport tweet, renderutils\n\nproc timelineViewClass(query: Query): string =\n  if query.kind != media:\n    return \"timeline\"\n\n  case query.view\n  of \"grid\": \"timeline media-grid-view\"\n  of \"gallery\": \"timeline media-gallery-view\"\n  else: \"timeline\"\n\nproc getQuery(query: Query): string =\n  if query.kind != posts:\n    result = genQueryUrl(query)\n  if result.len > 0:\n    result &= \"&\"\n\nproc getSearchMaxId(results: Timeline; path: string): string =\n  if results.query.kind != tweets or results.content.len == 0 or\n     results.query.until.len == 0:\n    return\n\n  let lastThread = results.content[^1]\n  if lastThread.len == 0 or lastThread[^1].id == 0:\n    return\n\n  # 2000000 is the minimum decrement to guarantee no result overlap\n  var maxId = lastThread[^1].id - 2_000_000'i64\n  if maxId <= 0:\n    maxId = lastThread[^1].id - 1\n\n  if maxId > 0:\n    return \"maxid:\" & $maxId\n\nproc renderToTop*(focus=\"#\"): VNode =\n  buildHtml(tdiv(class=\"top-ref\")):\n    icon \"down\", href=focus\n\nproc renderNewer*(query: Query; path: string; focus=\"\"): VNode =\n  let\n    q = genQueryUrl(query)\n    url = if q.len > 0: \"?\" & q else: \"\"\n    p = if focus.len > 0: path.replace(\"#m\", focus) else: path\n  buildHtml(tdiv(class=\"timeline-item show-more\")):\n    a(href=(p & url)):\n      text \"Load newest\"\n\nproc renderMore*(query: Query; cursor: string; focus=\"\"): VNode =\n  buildHtml(tdiv(class=\"show-more\")):\n    a(href=(&\"?{getQuery(query)}cursor={encodeUrl(cursor, usePlus=false)}{focus}\")):\n      text \"Load more\"\n\nproc renderNoMore(): VNode =\n  buildHtml(tdiv(class=\"timeline-footer\")):\n    h2(class=\"timeline-end\"):\n      text \"No more items\"\n\nproc renderNoneFound(): VNode =\n  buildHtml(tdiv(class=\"timeline-header\")):\n    h2(class=\"timeline-none\"):\n      text \"No items found\"\n\nproc renderThread(thread: Tweets; prefs: Prefs; path: string): VNode =\n  buildHtml(tdiv(class=\"thread-line\")):\n    let sortedThread = thread.sortedByIt(it.id)\n    for i, tweet in sortedThread:\n      # thread has a gap, display \"more replies\" link\n      if i > 0 and tweet.replyId != sortedThread[i - 1].id:\n        tdiv(class=\"timeline-item thread more-replies-thread\"):\n          tdiv(class=\"more-replies\"):\n            a(class=\"more-replies-text\", href=getLink(tweet)):\n              text \"more replies\"\n\n      let show = i == thread.high and sortedThread[0].id != tweet.threadId\n      let header = if tweet.pinned or tweet.retweet.isSome: \"with-header \" else: \"\"\n      renderTweet(tweet, prefs, path, class=(header & \"thread\"),\n                  index=i, last=(i == thread.high))\n\nproc renderUser(user: User; prefs: Prefs): VNode =\n  buildHtml(tdiv(class=\"timeline-item\", data-username=user.username)):\n    a(class=\"tweet-link\", href=(\"/\" & user.username))\n    tdiv(class=\"tweet-body profile-result\"):\n      tdiv(class=\"tweet-header\"):\n        a(class=\"tweet-avatar\", href=(\"/\" & user.username)):\n          genImg(user.getUserPic(\"_bigger\"), class=prefs.getAvatarClass)\n\n        tdiv(class=\"tweet-name-row\"):\n          tdiv(class=\"fullname-and-username\"):\n            linkUser(user, class=\"fullname\")\n            verifiedIcon(user)\n        linkUser(user, class=\"username\")\n\n      tdiv(class=\"tweet-content media-body\", dir=\"auto\"):\n        verbatim replaceUrls(user.bio, prefs)\n\nproc renderTimelineUsers*(results: Result[User]; prefs: Prefs; path=\"\"): VNode =\n  buildHtml(tdiv(class=\"timeline\")):\n    if not results.beginning:\n      renderNewer(results.query, path)\n\n    if results.content.len > 0:\n      for user in results.content:\n        renderUser(user, prefs)\n      if results.bottom.len > 0:\n        renderMore(results.query, results.bottom)\n      renderToTop()\n    elif results.beginning:\n      renderNoneFound()\n    else:\n      renderNoMore()\n\nproc filterThreads(threads: seq[Tweets]; prefs: Prefs): seq[Tweets] =\n  var retweets: seq[int64]\n  for thread in threads:\n    if thread.len == 1:\n      let tweet = thread[0]\n      let retweetId = if tweet.retweet.isSome: get(tweet.retweet).id else: 0\n      if retweetId in retweets or tweet.id in retweets or\n         tweet.pinned and prefs.hidePins:\n        continue\n      if retweetId != 0 and tweet.retweet.isSome:\n        retweets &= retweetId\n    result.add(thread)\n\nproc renderTimelineTweets*(results: Timeline; prefs: Prefs; path: string;\n                           pinned=none(Tweet)): VNode =\n  buildHtml(tdiv(class=results.query.timelineViewClass)):\n    if not results.beginning:\n      renderNewer(results.query, parseUri(path).path)\n\n    if not prefs.hidePins and pinned.isSome:\n      let tweet = get pinned\n      renderTweet(tweet, prefs, path)\n\n    if results.content.len == 0:\n      if not results.beginning:\n        renderNoMore()\n      else:\n        renderNoneFound()\n    else:\n      let filtered = filterThreads(results.content, prefs)\n\n      if results.query.view == \"gallery\":\n        tdiv(class=if prefs.compactGallery: \"gallery-masonry compact\" else: \"gallery-masonry\"):\n          for thread in filtered:\n            if thread.len == 1: renderTweet(thread[0], prefs, path)\n            else: renderThread(thread, prefs, path)\n      else:\n        for thread in filtered:\n          if thread.len == 1: renderTweet(thread[0], prefs, path)\n          else: renderThread(thread, prefs, path)\n\n      var cursor = getSearchMaxId(results, path)\n      if cursor.len > 0:\n        renderMore(results.query, cursor)\n      elif results.bottom.len > 0:\n        renderMore(results.query, results.bottom)\n      renderToTop()\n"
  },
  {
    "path": "src/views/tweet.nim",
    "content": "# SPDX-License-Identifier: AGPL-3.0-only\nimport strutils, sequtils, strformat, options, algorithm\nimport karax/[karaxdsl, vdom, vstyles]\nfrom jester import Request\n\nimport renderutils\nimport \"..\"/[types, utils, formatters]\nimport general\n\nconst doctype = \"<!DOCTYPE html>\\n\"\n\nproc renderMiniAvatar(user: User; prefs: Prefs): VNode =\n  genImg(user.getUserPic(\"_mini\"), class=(prefs.getAvatarClass & \" mini\"))\n\nproc renderHeader(tweet: Tweet; retweet: string; pinned: bool; prefs: Prefs): VNode =\n  buildHtml(tdiv):\n    if pinned:\n      tdiv(class=\"pinned\"):\n        span: icon \"pin\", \"Pinned Tweet\"\n    elif retweet.len > 0:\n      tdiv(class=\"retweet-header\"):\n        span: icon \"retweet\", retweet & \" retweeted\"\n\n    tdiv(class=\"tweet-header\"):\n      a(class=\"tweet-avatar\", href=(\"/\" & tweet.user.username)):\n        var size = \"_bigger\"\n        if not prefs.autoplayGifs and tweet.user.userPic.endsWith(\"gif\"):\n          size = \"_400x400\"\n        genImg(tweet.user.getUserPic(size), class=prefs.getAvatarClass)\n\n      tdiv(class=\"tweet-name-row\"):\n        tdiv(class=\"fullname-and-username\"):\n          linkUser(tweet.user, class=\"fullname\")\n          verifiedIcon(tweet.user)\n          linkUser(tweet.user, class=\"username\")\n\n        span(class=\"tweet-date\"):\n          a(href=getLink(tweet), title=tweet.getTime):\n            text tweet.getShortTime\n\nproc renderAltText(altText: string): VNode =\n  buildHtml(p(class=\"alt-text\")):\n    text \"ALT  \" & altText\n\nproc renderPhotoAttachment(photo: Photo): VNode =\n  buildHtml(tdiv(class=\"attachment\")):\n    let\n      named = \"name=\" in photo.url\n      small = if named: photo.url else: photo.url & smallWebp\n    a(href=getOrigPicUrl(photo.url), class=\"still-image\", target=\"_blank\"):\n      genImg(small, alt=photo.altText)\n    if photo.altText.len > 0:\n      renderAltText(photo.altText)\n\nproc isPlaybackEnabled(prefs: Prefs; playbackType: VideoType): bool =\n  case playbackType\n  of mp4: prefs.mp4Playback\n  of m3u8, vmap: prefs.hlsPlayback\n\nproc hasMp4Url(video: Video): bool =\n  video.variants.anyIt(it.contentType == mp4)\n\nproc renderVideoDisabled(playbackType: VideoType; path=\"\"): VNode =\n  buildHtml(tdiv(class=\"video-overlay\")):\n    case playbackType\n    of mp4:\n      p: text \"mp4 playback disabled in preferences\"\n    of m3u8, vmap:\n      buttonReferer \"/enablehls\", \"Enable hls playback\", path\n\nproc renderVideoUnavailable(video: Video): VNode =\n  buildHtml(tdiv(class=\"video-overlay\")):\n    case video.reason\n    of \"dmcaed\":\n      p: text \"This media has been disabled in response to a report by the copyright owner\"\n    else:\n      p: text \"This media is unavailable\"\n\nproc renderVideoAttachment(videoData: Video; prefs: Prefs; path=\"\"): VNode =\n  let\n    playbackType = if not prefs.proxyVideos and videoData.hasMp4Url: mp4\n                   else: videoData.playbackType\n    thumb = getSmallPic(videoData.thumb)\n\n  buildHtml(tdiv(class=\"attachment\")):\n    if not videoData.available:\n      img(src=thumb, loading=\"lazy\")\n      renderVideoUnavailable(videoData)\n    elif not prefs.isPlaybackEnabled(playbackType):\n      img(src=thumb, loading=\"lazy\")\n      renderVideoDisabled(playbackType, path)\n    else:\n      let\n        vars = videoData.variants.filterIt(it.contentType == playbackType)\n        vidUrl = vars.sortedByIt(it.resolution)[^1].url\n        source = if prefs.proxyVideos: getVidUrl(vidUrl)\n                 else: vidUrl\n      case playbackType\n      of mp4:\n        video(poster=thumb, controls=\"\", muted=prefs.muteVideos):\n          source(src=source, `type`=\"video/mp4\")\n      of m3u8, vmap:\n        video(poster=thumb, data-url=source, data-autoload=\"false\", muted=prefs.muteVideos)\n        verbatim \"<div class=\\\"video-overlay\\\" onclick=\\\"playVideo(this)\\\">\"\n        tdiv(class=\"overlay-circle\"): span(class=\"overlay-triangle\")\n        tdiv(class=\"overlay-duration\"): text getDuration(videoData)\n        verbatim \"</div>\"\n\nproc renderVideo*(video: Video; prefs: Prefs; path: string): VNode =\n  let hasCardContent = video.description.len > 0 or video.title.len > 0\n\n  buildHtml(tdiv(class=\"attachments card\")):\n    tdiv(class=(\"gallery-video\" & (if hasCardContent: \" card-container\" else: \"\"))):\n      renderVideoAttachment(video, prefs, path)\n      if hasCardContent:\n        tdiv(class=\"card-content\"):\n          h2(class=\"card-title\"): text video.title\n          if video.description.len > 0:\n            p(class=\"card-description\"): text video.description\n\nproc renderGifAttachment(gif: Gif; prefs: Prefs): VNode =\n  let thumb = getSmallPic(gif.thumb)\n\n  buildHtml(tdiv(class=\"attachment\")):\n    if not prefs.mp4Playback:\n      img(src=thumb, loading=\"lazy\")\n      renderVideoDisabled(mp4)\n    elif prefs.autoplayGifs:\n      video(class=\"gif\", poster=thumb, autoplay=\"\", muted=\"\", loop=\"\"):\n        source(src=getPicUrl(gif.url), `type`=\"video/mp4\")\n    else:\n      video(class=\"gif\", poster=thumb, controls=\"\", muted=\"\", loop=\"\"):\n        source(src=getPicUrl(gif.url), `type`=\"video/mp4\")\n    if gif.altText.len > 0:\n      renderAltText(gif.altText)\n\nproc renderGif(gif: Gif; prefs: Prefs): VNode =\n  buildHtml(tdiv(class=\"attachments media-gif\")):\n    renderGifAttachment(gif, prefs)\n\nproc renderMedia(media: seq[Media]; prefs: Prefs; path: string): VNode =\n  if media.len == 0:\n    return nil\n\n  if media.len == 1:\n    let item = media[0]\n    if item.kind == videoMedia:\n      return renderVideo(item.video, prefs, path)\n    if item.kind == gifMedia:\n      return renderGif(item.gif, prefs)\n\n  let\n    groups = if media.len < 3: @[media]\n             else: media.distribute(2)\n\n  buildHtml(tdiv(class=\"attachments\")):\n    for i, mediaGroup in groups:\n      let margin = if i > 0: \".25em\" else: \"\"\n      let rowClass = \"gallery-row\" &\n                     (if mediaGroup.allIt(it.kind == photoMedia): \"\" else: \" mixed-row\")\n      tdiv(class=rowClass, style={marginTop: margin}):\n        for mediaItem in mediaGroup:\n          case mediaItem.kind\n          of photoMedia:\n            renderPhotoAttachment(mediaItem.photo)\n          of videoMedia:\n            renderVideoAttachment(mediaItem.video, prefs, path)\n          of gifMedia:\n            renderGifAttachment(mediaItem.gif, prefs)\n\nproc renderPoll(poll: Poll): VNode =\n  buildHtml(tdiv(class=\"poll\")):\n    for i in 0 ..< poll.options.len:\n      let\n        leader = if poll.leader == i: \" leader\" else: \"\"\n        val = poll.values[i]\n        perc = if val > 0: val / poll.votes * 100 else: 0\n        percStr = (&\"{perc:>3.0f}\").strip(chars={'.'}) & '%'\n      tdiv(class=(\"poll-meter\" & leader)):\n        span(class=\"poll-choice-bar\", style={width: percStr})\n        span(class=\"poll-choice-value\"): text percStr\n        span(class=\"poll-choice-option\"): text poll.options[i]\n    span(class=\"poll-info\"):\n      text &\"{insertSep($poll.votes, ',')} votes • {poll.status}\"\n\nproc renderCardImage(card: Card): VNode =\n  buildHtml(tdiv(class=\"card-image-container\")):\n    tdiv(class=\"card-image\"):\n      genImg(card.image)\n      if card.kind == player:\n        tdiv(class=\"card-overlay\"):\n          tdiv(class=\"overlay-circle\"):\n            span(class=\"overlay-triangle\")\n\nproc renderCardContent(card: Card): VNode =\n  buildHtml(tdiv(class=\"card-content\")):\n    h2(class=\"card-title\"): text card.title\n    if card.text.len > 0:\n      p(class=\"card-description\"): text card.text\n    if card.dest.len > 0:\n      span(class=\"card-destination\"): text card.dest\n\nproc renderCard(card: Card; prefs: Prefs; path: string): VNode =\n  const smallCards = {app, player, summary, storeLink}\n  let large = if card.kind notin smallCards: \" large\" else: \"\"\n  let url = replaceUrls(card.url, prefs)\n\n  buildHtml(tdiv(class=(\"card\" & large))):\n    if card.video.isSome:\n      tdiv(class=\"card-container\"):\n        renderVideo(get(card.video), prefs, path)\n        a(class=\"card-content-container\", href=url):\n          renderCardContent(card)\n    else:\n      a(class=\"card-container\", href=url):\n        if card.image.len > 0:\n          renderCardImage(card)\n        tdiv(class=\"card-content-container\"):\n          renderCardContent(card)\n\nfunc formatStat(stat: int): string =\n  if stat > 0: insertSep($stat, ',')\n  else: \"\"\n\nproc renderStats(stats: TweetStats): VNode =\n  buildHtml(tdiv(class=\"tweet-stats\")):\n    span(class=\"tweet-stat\"): icon \"comment\", formatStat(stats.replies)\n    span(class=\"tweet-stat\"): icon \"retweet\", formatStat(stats.retweets)\n    span(class=\"tweet-stat\"): icon \"heart\", formatStat(stats.likes)\n    span(class=\"tweet-stat\"): icon \"views\", formatStat(stats.views)\n\nproc renderReply(tweet: Tweet): VNode =\n  buildHtml(tdiv(class=\"replying-to\")):\n    text \"Replying to \"\n    for i, u in tweet.reply:\n      if i > 0: text \" \"\n      a(href=(\"/\" & u)): text \"@\" & u\n\nproc renderAttribution(user: User; prefs: Prefs): VNode =\n  buildHtml(a(class=\"attribution\", href=(\"/\" & user.username))):\n    renderMiniAvatar(user, prefs)\n    strong: text user.fullname\n    verifiedIcon(user)\n\nproc renderMediaTags(tags: seq[User]): VNode =\n  buildHtml(tdiv(class=\"media-tag-block\")):\n    icon \"user\"\n    for i, p in tags:\n      a(class=\"media-tag\", href=(\"/\" & p.username), title=p.username):\n        text p.fullname\n      if i < tags.high:\n        text \", \"\n\nproc renderLatestPost(username: string; id: int64): VNode =\n  buildHtml(tdiv(class=\"latest-post-version\")):\n    text \"There's a new version of this post. \"\n    a(href=getLink(id, username)):\n      text \"See the latest post\"\n\nproc renderQuoteMedia(quote: Tweet; prefs: Prefs; path: string): VNode =\n  buildHtml(tdiv(class=\"quote-media-container\")):\n    renderMedia(quote.media, prefs, path)\n\nproc renderCommunityNote(note: string; prefs: Prefs): VNode =\n  buildHtml(tdiv(class=\"community-note\")):\n    tdiv(class=\"community-note-header\"):\n      icon \"group\"\n      span: text \"Community note\"\n    tdiv(class=\"community-note-text\", dir=\"auto\"):\n      verbatim replaceUrls(note, prefs)\n\nproc renderQuote(quote: Tweet; prefs: Prefs; path: string): VNode =\n  if not quote.available:\n    return buildHtml(tdiv(class=\"quote unavailable\")):\n      a(class=\"unavailable-quote\", href=getLink(quote, focus=false)):\n        if quote.tombstone.len > 0:\n          text quote.tombstone\n        elif quote.text.len > 0:\n          text quote.text\n        else:\n          text \"This tweet is unavailable\"\n\n  buildHtml(tdiv(class=\"quote quote-big\")):\n    a(class=\"quote-link\", href=getLink(quote))\n\n    tdiv(class=\"tweet-name-row\"):\n      tdiv(class=\"fullname-and-username\"):\n        renderMiniAvatar(quote.user, prefs)\n        linkUser(quote.user, class=\"fullname\")\n        verifiedIcon(quote.user)\n        linkUser(quote.user, class=\"username\")\n\n      span(class=\"tweet-date\"):\n        a(href=getLink(quote), title=quote.getTime):\n          text quote.getShortTime\n\n    if quote.reply.len > 0:\n      renderReply(quote)\n\n    if quote.text.len > 0:\n      tdiv(class=\"quote-text\", dir=\"auto\"):\n        verbatim replaceUrls(quote.text, prefs)\n\n    if quote.media.len > 0:\n      renderQuoteMedia(quote, prefs, path)\n\n    if quote.note.len > 0 and not prefs.hideCommunityNotes:\n      renderCommunityNote(quote.note, prefs)\n\n    if quote.hasThread:\n      a(class=\"show-thread\", href=getLink(quote)):\n        text \"Show this thread\"\n\n    if quote.history.len > 0 and quote.id != max(quote.history):\n      tdiv(class=\"quote-latest\"):\n        text \"There's a new version of this post\"\n\nproc renderLocation*(tweet: Tweet): string =\n  let (place, url) = tweet.getLocation()\n  if place.len == 0: return\n  let node = buildHtml(span(class=\"tweet-geo\")):\n    text \" – at \"\n    if url.len > 1:\n      a(href=url): text place\n    else:\n      text place\n  return $node\n\nproc renderTweet*(tweet: Tweet; prefs: Prefs; path: string; class=\"\"; index=0;\n                  last=false; mainTweet=false; afterTweet=false): VNode =\n  var divClass = class\n  if index == -1 or last:\n    divClass = \"thread-last \" & class\n\n  if not tweet.available:\n    return buildHtml(tdiv(class=divClass & \"unavailable timeline-item\", data-username=tweet.user.username)):\n      a(class=\"unavailable-box\", href=getLink(tweet)):\n        if tweet.tombstone.len > 0:\n          text tweet.tombstone\n        elif tweet.text.len > 0:\n          text tweet.text\n        else:\n          text \"This tweet is unavailable\"\n\n      if tweet.quote.isSome:\n        renderQuote(tweet.quote.get(), prefs, path)\n\n  let\n    fullTweet = tweet\n    pinned = tweet.pinned\n\n  var retweet: string\n  var tweet = fullTweet\n  if tweet.retweet.isSome:\n    tweet = tweet.retweet.get\n    retweet = fullTweet.user.fullname\n\n  buildHtml(tdiv(class=(\"timeline-item \" & divClass), data-username=tweet.user.username)):\n    if not mainTweet:\n      a(class=\"tweet-link\", href=getLink(tweet))\n\n    tdiv(class=\"tweet-body\"):\n      renderHeader(tweet, retweet, pinned, prefs)\n\n      if not afterTweet and index == 0 and tweet.reply.len > 0 and\n         (tweet.reply.len > 1 or tweet.reply[0] != tweet.user.username or pinned):\n        renderReply(tweet)\n\n      var tweetClass = \"tweet-content media-body\"\n      if prefs.bidiSupport:\n        tweetClass &= \" tweet-bidi\"\n\n      tdiv(class=tweetClass, dir=\"auto\"):\n        verbatim replaceUrls(tweet.text, prefs) & renderLocation(tweet)\n\n      if tweet.attribution.isSome:\n        renderAttribution(tweet.attribution.get(), prefs)\n\n      if tweet.card.isSome and tweet.card.get().kind != hidden:\n        renderCard(tweet.card.get(), prefs, path)\n\n      if tweet.media.len > 0:\n        renderMedia(tweet.media, prefs, path)\n\n      if tweet.poll.isSome:\n        renderPoll(tweet.poll.get())\n\n      if tweet.quote.isSome:\n        renderQuote(tweet.quote.get(), prefs, path)\n\n      if tweet.note.len > 0 and not prefs.hideCommunityNotes:\n        renderCommunityNote(tweet.note, prefs)\n\n      let\n        hasEdits = tweet.history.len > 1\n        isLatest = hasEdits and tweet.id == max(tweet.history)\n\n      if mainTweet:\n        p(class=\"tweet-published\"): \n          if hasEdits and isLatest:\n            a(href=(getLink(tweet, focus=false) & \"/history\")):\n              text &\"Last edited {getTime(tweet)}\"\n          else:\n            text &\"{getTime(tweet)}\"\n\n        if hasEdits and not isLatest:\n          renderLatestPost(tweet.user.username, max(tweet.history))\n\n      if tweet.mediaTags.len > 0:\n        renderMediaTags(tweet.mediaTags)\n\n      if not prefs.hideTweetStats:\n        renderStats(tweet.stats)\n\nproc renderTweetEmbed*(tweet: Tweet; path: string; prefs: Prefs; cfg: Config; req: Request): string =\n  let node = buildHtml(html(lang=\"en\")):\n    renderHead(prefs, cfg, req)\n\n    body:\n      tdiv(class=\"tweet-embed\"):\n        renderTweet(tweet, prefs, path, mainTweet=true)\n\n  result = doctype & $node\n"
  },
  {
    "path": "tests/base.py",
    "content": "from seleniumbase import BaseCase\n\n\nclass Card(object):\n    def __init__(self, tweet=''):\n        card = tweet + '.card '\n        self.link = card + 'a'\n        self.title = card + '.card-title'\n        self.description = card + '.card-description'\n        self.destination = card + '.card-destination'\n        self.image = card + '.card-image'\n\n\nclass Quote(object):\n    def __init__(self, tweet=''):\n        quote = tweet + '.quote '\n        namerow = quote + '.fullname-and-username '\n        self.link = quote + '.quote-link'\n        self.fullname = namerow + '.fullname'\n        self.username = namerow + '.username'\n        self.text = quote + '.quote-text'\n        self.media = quote + '.quote-media-container'\n        self.unavailable = quote + '.quote.unavailable'\n\n\nclass Tweet(object):\n    def __init__(self, tweet=''):\n        namerow = tweet + '.tweet-header '\n        self.fullname = namerow + '.fullname'\n        self.username = namerow + '.username'\n        self.date = namerow + '.tweet-date'\n        self.text = tweet + '.tweet-content.media-body'\n        self.retweet = tweet + '.retweet-header'\n        self.reply = tweet + '.replying-to'\n\n\nclass Profile(object):\n    fullname = '.profile-card-fullname'\n    username = '.profile-card-username'\n    protected = '.icon-lock'\n    verified = '.verified-icon'\n    banner = '.profile-banner'\n    bio = '.profile-bio'\n    location = '.profile-location'\n    website = '.profile-website'\n    joinDate = '.profile-joindate'\n    mediaCount = '.photo-rail-header'\n\n\nclass Timeline(object):\n    newest = 'div[class=\"timeline-item show-more\"]'\n    older = 'div[class=\"show-more\"]'\n    end = '.timeline-end'\n    none = '.timeline-none'\n    protected = '.timeline-protected'\n    photo_rail = '.photo-rail-grid'\n    media_view_tabs = '.media-view-tabs'\n    media_view_timeline = '.media-view-tabs a[href$=\"media?view=timeline\"]'\n    media_view_grid = '.media-view-tabs a[href$=\"media?view=grid\"]'\n    media_view_gallery = '.media-view-tabs a[href$=\"media?view=gallery\"]'\n    media_view_active = '.media-view-tabs .tab-item.active a'\n    grid_view = '.timeline.media-grid-view'\n    gallery_view = '.timeline.media-gallery-view'\n\n\nclass Conversation(object):\n    main = '.main-tweet'\n    before = '.before-tweet'\n    after = '.after-tweet'\n    replies = '.replies'\n    thread = '.reply'\n    tweet = '.timeline-item'\n    tweet_text = '.tweet-content'\n\n\nclass Poll(object):\n    votes = '.poll-info'\n    choice = '.poll-meter'\n    value = 'poll-choice-value'\n    option = 'poll-choice-option'\n    leader = 'leader'\n\n\nclass Media(object):\n    container = '.attachments'\n    row = '.gallery-row'\n    image = '.still-image'\n    video = '.gallery-video'\n    gif = '.media-gif'\n\n\nclass BaseTestCase(BaseCase):\n    def setUp(self):\n        super(BaseTestCase, self).setUp()\n\n    def tearDown(self):\n        super(BaseTestCase, self).tearDown()\n\n    def open_nitter(self, page=''):\n        self.open(f'http://localhost:8080/{page}')\n\n    def search_username(self, username):\n        self.open_nitter()\n        self.update_text('.search-bar input[type=text]', username)\n        self.submit('.search-bar form')\n\n\ndef get_timeline_tweet(num=1):\n    return Tweet(f'.timeline > div:nth-child({num}) ')\n"
  },
  {
    "path": "tests/poetry.toml",
    "content": "[virtualenvs]\nin-project = true\n"
  },
  {
    "path": "tests/pyproject.toml",
    "content": "[tool.poetry]\nname = \"nitter-tests\"\nversion = \"0.0.0\"\npackage-mode = false\n\n[tool.poetry.dependencies]\npython = \"^3.14\"\nseleniumbase = \"4.46.5\"\n"
  },
  {
    "path": "tests/requirements.txt",
    "content": "seleniumbase==4.46.5\n"
  },
  {
    "path": "tests/test_card.py",
    "content": "from base import BaseTestCase, Card, Conversation\nfrom parameterized import parameterized\n\n\ncard = [\n    ['nim_lang/status/1136652293510717440',\n     'Version 0.20.0 released',\n     'We are very proud to announce Nim version 0.20. This is a massive release, both literally and figuratively. It contains more than 1,000 commits and it marks our release candidate for version 1.0!',\n     'nim-lang.org', True],\n\n    ['voidtarget/status/1094632512926605312',\n     'Basic OBS Studio plugin, written in nim, supporting C++ (C fine too)',\n     'Basic OBS Studio plugin, written in nim, supporting C++ (C fine too) - obsplugin.nim',\n     'gist.github.com', True]\n]\n\nno_thumb = [\n    ['FluentAI/status/1116417904831029248',\n     'LinkedIn',\n     'This link will take you to a page that’s not on LinkedIn',\n     'lnkd.in'],\n\n    ['Thom_Wolf/status/1122466524860702729',\n     'GitHub - facebookresearch/fairseq: Facebook AI Research Sequence-to-Sequence Toolkit written in',\n     '',\n     'github.com'],\n\n    ['brent_p/status/1088857328680488961',\n     'GitHub - brentp/hts-nim: nim wrapper for htslib for parsing genomics data files',\n     '',\n     'github.com'],\n\n    ['voidtarget/status/1133028231672582145',\n     'sinkingsugar/nimqt-example',\n     'A sample of a Qt app written using mostly nim. Contribute to sinkingsugar/nimqt-example development by creating an account on GitHub.',\n     'github.com']\n]\n\nplayable = [\n    ['nim_lang/status/1118234460904919042',\n     'Nim development blog 2019-03',\n     'Arne (aka Krux02)* debugging: * improved nim-gdb, $ works, framefilter * alias for --debugger:native: -g* bugs: * forwarding of .pure. * sizeof union* fe...',\n     'youtube.com'],\n\n    ['nim_lang/status/1121090879823986688',\n     'Nim - First natively compiled language w/ hot code-reloading at...',\n     '#nim #c++ #ACCUConfNim is a statically typed systems and applications programming language which offers perhaps some of the most powerful metaprogramming cap...',\n     'youtube.com']\n]\n\nclass CardTest(BaseTestCase):\n    @parameterized.expand(card)\n    def test_card(self, tweet, title, description, destination, large):\n        self.open_nitter(tweet)\n        c = Card(Conversation.main + \" \")\n        self.assert_text(title, c.title)\n        self.assert_text(destination, c.destination)\n        self.assertIn('/pic/', self.get_image_url(c.image + ' img'))\n        if len(description) > 0:\n            self.assert_text(description, c.description)\n        if large:\n            self.assert_element_visible('.card.large')\n        else:\n            self.assert_element_not_visible('.card.large')\n\n    @parameterized.expand(no_thumb)\n    def test_card_no_thumb(self, tweet, title, description, destination):\n        self.open_nitter(tweet)\n        c = Card(Conversation.main + \" \")\n        self.assert_text(title, c.title)\n        self.assert_text(destination, c.destination)\n        if len(description) > 0:\n            self.assert_text(description, c.description)\n\n    @parameterized.expand(playable)\n    def test_card_playable(self, tweet, title, description, destination):\n        self.open_nitter(tweet)\n        c = Card(Conversation.main + \" \")\n        self.assert_text(title, c.title)\n        self.assert_text(destination, c.destination)\n        self.assertIn('/pic/', self.get_image_url(c.image + ' img'))\n        self.assert_element_visible('.card-overlay')\n        if len(description) > 0:\n            self.assert_text(description, c.description)\n"
  },
  {
    "path": "tests/test_profile.py",
    "content": "from base import BaseTestCase, Profile\nfrom parameterized import parameterized\n\nprofiles = [\n        ['mobile_test', 'Test account',\n         'Test Account. test test Testing username with @mobile_test_2 and a #hashtag',\n         'San Francisco, CA', 'example.com/foobar', 'Joined October 2009', '97'],\n        ['mobile_test_2', 'mobile test 2', '', '', '', 'Joined January 2011', '13']\n]\n\nverified = [['jack'], ['elonmusk']]\n\nprotected = [\n    ['mobile_test_7', 'mobile test 7', ''],\n    ['Poop', 'Randy', 'Social media fanatic.']\n]\n\ninvalid = [['thisprofiledoesntexist']]\n\nmalformed = [\n    ['${userId}'],\n    ['$%7BuserId%7D'],  # URL encoded version\n    ['%'],  # Percent sign is invalid\n    ['user@name'],\n    ['user.name'],\n    ['user-name'],\n    ['user$name'],\n    ['user{name}'],\n    ['user name'],  # space\n]\n\nbanner_image = [\n    ['mobile_test', 'profile_banners%2F82135242%2F1384108037%2F1500x500']\n]\n\n\nclass ProfileTest(BaseTestCase):\n    @parameterized.expand(profiles)\n    def test_data(self, username, fullname, bio, location, website, joinDate, mediaCount):\n        self.open_nitter(username)\n        self.assert_exact_text(fullname, Profile.fullname)\n        self.assert_exact_text(f'@{username}', Profile.username)\n\n        tests = [\n            (bio, Profile.bio),\n            (location, Profile.location),\n            (website, Profile.website),\n            (joinDate, Profile.joinDate),\n            (mediaCount + \" Photos and videos\", Profile.mediaCount)\n        ]\n\n        for text, selector in tests:\n            if len(text) > 0:\n                self.assert_exact_text(text, selector)\n            else:\n                self.assert_element_absent(selector)\n\n    @parameterized.expand(verified)\n    def test_verified(self, username):\n        self.open_nitter(username)\n        self.assert_element_visible(Profile.verified)\n\n    @parameterized.expand(protected)\n    def test_protected(self, username, fullname, bio):\n        self.open_nitter(username)\n        self.assert_element_visible(Profile.protected)\n        self.assert_exact_text(fullname, Profile.fullname)\n        self.assert_exact_text(f'@{username}', Profile.username)\n\n        if len(bio) > 0:\n            self.assert_text(bio, Profile.bio)\n        else:\n            self.assert_element_absent(Profile.bio)\n\n    @parameterized.expand(invalid)\n    def test_invalid_username(self, username):\n        self.open_nitter(username)\n        self.assert_text(f'User \"{username}\" not found')\n\n    @parameterized.expand(malformed)\n    def test_malformed_username(self, username):\n        \"\"\"Test that malformed usernames (with invalid characters) return 404\"\"\"\n        self.open_nitter(username)\n        # Malformed usernames should return 404 page not found, not try to fetch from Twitter\n        self.assert_text('Page not found')\n\n    def test_suspended(self):\n        self.open_nitter('suspendme')\n        self.assert_text('User \"suspendme\" has been suspended')\n\n    @parameterized.expand(banner_image)\n    def test_banner_image(self, username, url):\n        self.open_nitter(username)\n        banner = self.find_element(Profile.banner + ' img')\n        self.assertIn(url, banner.get_attribute('src'))\n"
  },
  {
    "path": "tests/test_quote.py",
    "content": "from base import BaseTestCase, Quote, Conversation\nfrom parameterized import parameterized\n\ntext = [\n    ['nim_lang/status/1491461266849808397#m',\n     'Nim', '@nim_lang',\n     \"\"\"What's better than Nim 1.6.0?\n\nNim 1.6.2 :)\n\nnim-lang.org/blog/2021/12/17…\"\"\"]\n]\n\nimage = [\n    ['elonmusk/status/1138827760107790336', 'D83h6Y8UIAE2Wlz'],\n    ['SpaceX/status/1067155053461426176', 'Ds9EYfxXoAAPNmx']\n]\n\ngif = [\n    ['SpaceX/status/747497521593737216', 'Cl-R5yFWkAA_-3X'],\n    ['nim_lang/status/1068099315074248704', 'DtJSqP9WoAAKdRC']\n]\n\nvideo = [\n    ['bkuensting/status/1067316003200217088', 'IyCaQlzF0q8u9vBd']\n]\n\n\nclass QuoteTest(BaseTestCase):\n    @parameterized.expand(text)\n    def test_text(self, tweet, fullname, username, text):\n        self.open_nitter(tweet)\n        quote = Quote(Conversation.main + \" \")\n        self.assert_text(fullname, quote.fullname)\n        self.assert_text(username, quote.username)\n        self.assert_text(text, quote.text)\n\n    @parameterized.expand(image)\n    def test_image(self, tweet, url):\n        self.open_nitter(tweet)\n        quote = Quote(Conversation.main + \" \")\n        self.assert_element_visible(quote.media)\n        self.assertIn(url, self.get_image_url(quote.media + ' img'))\n\n    @parameterized.expand(gif)\n    def test_gif(self, tweet, url):\n        self.open_nitter(tweet)\n        quote = Quote(Conversation.main + \" \")\n        self.assert_element_visible(quote.media)\n        self.assertIn(url, self.get_attribute(quote.media + ' source', 'src'))\n\n    @parameterized.expand(video)\n    def test_video(self, tweet, url):\n        self.open_nitter(tweet)\n        quote = Quote(Conversation.main + \" \")\n        self.assert_element_visible(quote.media)\n        self.assertIn(url, self.get_image_url(quote.media + ' img'))\n"
  },
  {
    "path": "tests/test_search.py",
    "content": "from base import BaseTestCase\nfrom parameterized import parameterized\n\n\n#class SearchTest(BaseTestCase):\n    #@parameterized.expand([['@mobile_test'], ['@mobile_test_2']])\n    #def test_username_search(self, username):\n        #self.search_username(username)\n        #self.assert_text(f'{username}')\n"
  },
  {
    "path": "tests/test_thread.py",
    "content": "from base import BaseTestCase, Conversation\nfrom parameterized import parameterized\n\nthread = [\n    ['octonion/status/975253897697611777', [], 'Based', ['Crystal', 'Julia'], [\n        ['For', 'Then', 'Okay,', 'Python', 'Speed', 'Java', 'Coding', 'I', 'You'],\n        ['yeah,']\n    ]],\n\n    ['octonion/status/975254452625002496', ['Based'], 'Crystal', ['Julia'], []],\n\n    ['octonion/status/975256058384887808', ['Based', 'Crystal'], 'Julia', [], []],\n\n    ['gauravssnl/status/975364889039417344',\n     ['Based', 'For', 'Then', 'Okay,', 'Python'], 'Speed', [], [\n         ['Java', 'Coding', 'I', 'You'], ['JAVA!']\n     ]],\n\n    ['d0m96/status/1141811379407425537', [], 'I\\'m',\n     ['The', 'The', 'Today', 'Some', 'If', 'There', 'Above'],\n     [['Thank', 'Also,']]],\n\n    ['gmpreussner/status/999766552546299904', [], 'A', [],\n     [['I', 'Especially'], ['I']]]\n]\n\n\nclass ThreadTest(BaseTestCase):\n    def find_tweets(self, selector):\n        return self.find_elements(f\"{selector} {Conversation.tweet_text}\")\n\n    def compare_first_word(self, tweets, selector):\n        if len(tweets) > 0:\n            self.assert_element_visible(selector)\n            for i, tweet in enumerate(self.find_tweets(selector)):\n                text = tweet.text.split(\" \")[0]\n                self.assert_equal(tweets[i], text)\n\n    @parameterized.expand(thread)\n    def test_thread(self, tweet, before, main, after, replies):\n        self.open_nitter(tweet)\n        self.assert_element_visible(Conversation.main)\n\n        self.assert_text(main, Conversation.main)\n        self.assert_text(main, Conversation.main)\n\n        self.compare_first_word(before, Conversation.before)\n        self.compare_first_word(after, Conversation.after)\n\n        for i, reply in enumerate(self.find_elements(Conversation.thread)):\n            selector = Conversation.replies + f\" > div:nth-child({i + 1})\"\n            self.compare_first_word(replies[i], selector)\n"
  },
  {
    "path": "tests/test_timeline.py",
    "content": "from base import BaseTestCase, Timeline\nfrom parameterized import parameterized\n\nnormal = [['jack'], ['elonmusk']]\n\nafter = [['jack', '1681686036294803456'],\n         ['elonmusk', '1681686036294803456']]\n\nno_more = [['mobile_test_8?cursor=DAABCgABF4YVAqN___kKAAICNn_4msIQAAgAAwAAAAIAAA']]\n\nempty = [['emptyuser'], ['mobile_test_10']]\n\nprotected = [['mobile_test_7'], ['Empty_user']]\n\nphoto_rail = [['mobile_test', ['Bo0nDsYIYAIjqVn', 'BoQbwJAIUAA0QCY', 'BoQbRQxIIAA3FWD', 'Bn8Qh8iIIAABXrG']]]\n\n\nclass TweetTest(BaseTestCase):\n    @parameterized.expand(normal)\n    def test_timeline(self, username):\n        self.open_nitter(username)\n        self.assert_element_present(Timeline.older)\n        self.assert_element_absent(Timeline.newest)\n        self.assert_element_absent(Timeline.end)\n        self.assert_element_absent(Timeline.none)\n\n    @parameterized.expand(after)\n    def test_after(self, username, cursor):\n        self.open_nitter(f'{username}?cursor={cursor}')\n        self.assert_element_present(Timeline.newest)\n        self.assert_element_present(Timeline.older)\n        self.assert_element_absent(Timeline.end)\n        self.assert_element_absent(Timeline.none)\n\n    @parameterized.expand(no_more)\n    def test_no_more(self, username):\n        self.open_nitter(username)\n        self.assert_text('No more items', Timeline.end)\n        self.assert_element_present(Timeline.newest)\n        self.assert_element_absent(Timeline.older)\n\n    @parameterized.expand(empty)\n    def test_empty(self, username):\n        self.open_nitter(username)\n        self.assert_text('No items found', Timeline.none)\n        self.assert_element_absent(Timeline.newest)\n        self.assert_element_absent(Timeline.older)\n        self.assert_element_absent(Timeline.end)\n\n    @parameterized.expand(protected)\n    def test_protected(self, username):\n        self.open_nitter(username)\n        self.assert_text('This account\\'s tweets are protected.', Timeline.protected)\n        self.assert_element_absent(Timeline.newest)\n        self.assert_element_absent(Timeline.older)\n        self.assert_element_absent(Timeline.end)\n\n    def test_media_view_tabs(self):\n        self.open_nitter('mobile_test/media')\n        self.assert_element_present(Timeline.media_view_tabs)\n        self.assert_text('Timeline', Timeline.media_view_timeline)\n        self.assert_text('Grid', Timeline.media_view_grid)\n        self.assert_text('Gallery', Timeline.media_view_gallery)\n        self.assert_text('Timeline', Timeline.media_view_active)\n\n    def test_media_view_grid_tab(self):\n        self.open_nitter('mobile_test/media?view=grid')\n        self.assert_element_present(Timeline.grid_view)\n        self.assert_text('Grid', Timeline.media_view_active)\n\n    def test_media_view_gallery_tab(self):\n        self.open_nitter('mobile_test/media?view=gallery')\n        self.assert_element_present(Timeline.gallery_view)\n        self.assert_text('Gallery', Timeline.media_view_active)\n\n    def test_media_view_tabs_not_on_posts(self):\n        self.open_nitter('mobile_test')\n        self.assert_element_absent(Timeline.media_view_tabs)\n\n    #@parameterized.expand(photo_rail)\n    #def test_photo_rail(self, username, images):\n        #self.open_nitter(username)\n        #self.assert_element_visible(Timeline.photo_rail)\n        #for i, url in enumerate(images):\n            #img = self.get_attribute(Timeline.photo_rail + f' a:nth-child({i + 1}) img', 'src')\n            #self.assertIn(url, img)\n"
  },
  {
    "path": "tests/test_tweet.py",
    "content": "from base import BaseTestCase, Tweet, Conversation, get_timeline_tweet\nfrom parameterized import parameterized\n\n# image = tweet + 'div.attachments.media-body > div > div > a > div > img'\n# self.assert_true(self.get_image_url(image).split('/')[0] == 'http')\n\ntimeline = [\n    [1, 'Test account', 'mobile_test', '10 Aug 2016', '763483571793174528',\n     '.'],\n\n    [3, 'Test account', 'mobile_test', '3 Mar 2016', '705522133443571712',\n     'LIVE on #Periscope pscp.tv/w/aadiTzF6dkVOTXZSbX…'],\n\n    [6, 'mobile test 2', 'mobile_test_2', '1 Oct 2014', '517449200045277184',\n     'Testing. One two three four. Test.']\n]\n\nstatus = [\n    [20, 'jack', 'jack', '21 Mar 2006', 'just setting up my twttr'],\n    [134849778302464000, 'The Twoffice', 'TheTwoffice', '11 Nov 2011', 'test'],\n    [105685475985080322, 'The Twoffice', 'TheTwoffice', '22 Aug 2011', 'regular tweet'],\n    [572593440719912960, 'Test account', 'mobile_test', '3 Mar 2015', 'testing test']\n]\n\ninvalid = [\n    ['mobile_test/status/120938109238'],\n    ['TheTwoffice/status/8931928312']\n]\n\nmultiline = [\n    [1718660434457239868, 'WebDesignMuseum',\n     \"\"\"\nHappy 32nd Birthday HTML tags! \n\nOn October 29, 1991, the internet pioneer, Tim Berners-Lee, published a document entitled HTML Tags. \n\nThe document contained a description of the first 18 HTML tags: <title>, <nextid>, <a>, <isindex>, <plaintext>, <listing>, <p>, <h1>…<h6>, <address>, <hp1>, <hp2>…, <dl>, <dt>, <dd>, <ul>, <li>,<menu> and <dir>. The design of the first version of HTML language was influenced by the SGML universal markup language.\n\n#WebDesignHistory\"\"\"]\n]\n\nlink = [\n    ['nim_lang/status/1110499584852353024', [\n        'nim-lang.org/araq/ownedrefs.…',\n        'news.ycombinator.com/item?id…',\n        'teddit.net/r/programming…'\n    ]],\n    ['nim_lang/status/1125887775151140864', [\n        'en.wikipedia.org/wiki/Nim_(p…'\n    ]],\n    ['hiankun_taioan/status/1086916335215341570', [\n        '(hackernoon.com/interview-wit…)'\n    ]],\n    ['archillinks/status/1146302618223951873', [\n        'flickr.com/photos/87101284@N…',\n        'hisafoto.tumblr.com/post/176…'\n    ]],\n    ['archillinks/status/1146292551936335873', [\n        'flickr.com/photos/michaelrye…',\n        'furtho.tumblr.com/post/16618…'\n    ]]\n]\n\nusername = [\n    ['Bountysource/status/1094803522053320705', ['nim_lang']],\n    ['leereilly/status/1058464250098704385', ['godotengine', 'unity3d', 'nim_lang']]\n]\n\nemoji = [\n    ['Tesla/status/1134850442511257600', '🌈❤️🧡💛💚💙💜']\n]\n\nretweet = [\n    [7, 'mobile_test_2', 'mobile test 2', 'Test account', '@mobile_test', '1234'],\n    [3, 'mobile_test_8', 'mobile test 8', 'jack', '@jack', 'twttr']\n]\n\n\nclass TweetTest(BaseTestCase):\n    @parameterized.expand(timeline)\n    def test_timeline(self, index, fullname, username, date, tid, text):\n        self.open_nitter(username)\n        tweet = get_timeline_tweet(index)\n        self.assert_exact_text(fullname, tweet.fullname)\n        self.assert_exact_text('@' + username, tweet.username)\n        self.assert_exact_text(date, tweet.date)\n        self.assert_text(text, tweet.text)\n        permalink = self.find_element(tweet.date + ' a')\n        self.assertIn(tid, permalink.get_attribute('href'))\n\n    @parameterized.expand(status)\n    def test_status(self, tid, fullname, username, date, text):\n        tweet = Tweet()\n        self.open_nitter(f'{username}/status/{tid}')\n        self.assert_exact_text(fullname, tweet.fullname)\n        self.assert_exact_text('@' + username, tweet.username)\n        self.assert_exact_text(date, tweet.date)\n        self.assert_text(text, tweet.text)\n\n    @parameterized.expand(multiline)\n    def test_multiline_formatting(self, tid, username, text):\n        self.open_nitter(f'{username}/status/{tid}')\n        self.assert_text(text.strip('\\n'), Conversation.main)\n\n    @parameterized.expand(emoji)\n    def test_emoji(self, tweet, text):\n        self.open_nitter(tweet)\n        self.assert_text(text, Conversation.main)\n\n    @parameterized.expand(link)\n    def test_link(self, tweet, links):\n        self.open_nitter(tweet)\n        for link in links:\n            self.assert_text(link, Conversation.main)\n\n    @parameterized.expand(username)\n    def test_username(self, tweet, usernames):\n        self.open_nitter(tweet)\n        for un in usernames:\n            link = self.find_link_text(f'@{un}')\n            self.assertIn(f'/{un}', link.get_property('href'))\n\n    @parameterized.expand(retweet)\n    def test_retweet(self, index, url, retweet_by, fullname, username, text):\n        self.open_nitter(url)\n        tweet = get_timeline_tweet(index)\n        self.assert_text(f'{retweet_by} retweeted', tweet.retweet)\n        self.assert_text(text, tweet.text)\n        self.assert_exact_text(fullname, tweet.fullname)\n        self.assert_exact_text(username, tweet.username)\n\n    @parameterized.expand(invalid)\n    def test_invalid_id(self, tweet):\n        self.open_nitter(tweet)\n        self.assert_text('Tweet not found', '.error-panel')\n\n    #@parameterized.expand(reply)\n    #def test_thread(self, tweet, num):\n        #self.open_nitter(tweet)\n        #thread = self.find_element(f'.timeline > div:nth-child({num})')\n        #self.assertIn(thread.get_attribute('class'), 'thread-line')\n"
  },
  {
    "path": "tests/test_tweet_media.py",
    "content": "from base import BaseTestCase, Poll, Media\nfrom parameterized import parameterized\nfrom selenium.webdriver.common.by import By\n\npoll = [\n    ['nim_lang/status/1064219801499955200', 'Style insensitivity', '91', 1, [\n        ('47%', 'Yay'), ('53%', 'Nay')\n    ]],\n\n    ['polls/status/1031986180622049281', 'What Tree Is Coolest?', '3,322', 1, [\n        ('30%', 'Oak'), ('42%', 'Bonsai'), ('5%', 'Hemlock'), ('23%', 'Apple')\n    ]]\n]\n\nimage = [\n    ['mobile_test/status/519364660823207936', 'BzUnaDFCUAAmrjs'],\n    #['mobile_test_2/status/324619691039543297', 'BIFH45vCUAAQecj']\n]\n\ngif = [\n    ['elonmusk/status/1141367104702038016', 'D9bzUqoUcAAfUgf'],\n    ['Proj_Borealis/status/1136595194621677568', 'D8X_PJAXUAAavPT']\n]\n\nvideo_m3u8 = [\n    ['d0m96/status/1078373829917974528', '9q1-v9w8-ft3awgD.jpg'],\n    ['SpaceX/status/1138474014152712192', 'ocJJj2uu4n1kyD2Y.jpg']\n]\n\ngallery = [\n    # ['mobile_test/status/451108446603980803', [\n    #     ['BkKovdrCUAAEz79', 'BkKovdcCEAAfoBO']\n    # ]],\n\n    # ['mobile_test/status/471539824713691137', [\n    #     ['Bos--KNIQAAA7Li', 'Bos--FAIAAAWpah'],\n    #     ['Bos--IqIQAAav23']\n    # ]],\n\n    ['mobile_test/status/469530783384743936', [\n        ['BoQbwJAIUAA0QCY', 'BoQbwN1IMAAuTiP'],\n        ['BoQbwarIAAAlaE-', 'BoQbwh_IEAA27ef']\n    ]]\n]\n\n\nclass MediaTest(BaseTestCase):\n    @parameterized.expand(poll)\n    def test_poll(self, tweet, text, votes, leader, choices):\n        self.open_nitter(tweet)\n        self.assert_text(text, '.main-tweet')\n        self.assert_text(votes, Poll.votes)\n\n        poll_choices = self.find_elements(Poll.choice)\n        for i, (v, o) in enumerate(choices):\n            choice = poll_choices[i]\n            value = choice.find_element(By.CLASS_NAME, Poll.value)\n            option = choice.find_element(By.CLASS_NAME, Poll.option)\n            choice_class = choice.get_attribute('class')\n\n            self.assert_equal(v, value.text)\n            self.assert_equal(o, option.text)\n\n            if i == leader:\n                self.assertIn(Poll.leader, choice_class)\n            else:\n                self.assertNotIn(Poll.leader, choice_class)\n\n    @parameterized.expand(image)\n    def test_image(self, tweet, url):\n        self.open_nitter(tweet)\n        self.assert_element_visible(Media.container)\n        self.assert_element_visible(Media.image)\n\n        image_url = self.get_image_url(Media.image + ' img')\n        self.assertIn(url, image_url)\n\n    @parameterized.expand(gif)\n    def test_gif(self, tweet, gif_id):\n        self.open_nitter(tweet)\n        self.assert_element_visible(Media.container)\n        self.assert_element_visible(Media.gif)\n\n        url = self.get_attribute('source', 'src')\n        thumb = self.get_attribute('video', 'poster')\n        self.assertIn(gif_id + '.mp4', url)\n        self.assertIn(gif_id + '.jpg', thumb)\n\n    @parameterized.expand(video_m3u8)\n    def test_video_m3u8(self, tweet, thumb):\n        # no url because video playback isn't supported yet\n        self.open_nitter(tweet)\n        self.assert_element_visible(Media.container)\n        self.assert_element_visible(Media.video)\n\n        video_thumb = self.get_attribute(Media.video + ' img', 'src')\n        self.assertIn(thumb, video_thumb)\n\n    @parameterized.expand(gallery)\n    def test_gallery(self, tweet, rows):\n        self.open_nitter(tweet)\n        self.assert_element_visible(Media.container)\n        self.assert_element_visible(Media.row)\n        self.assert_element_visible(Media.image)\n\n        gallery_rows = self.find_elements(Media.row)\n        self.assert_equal(len(rows), len(gallery_rows))\n\n        for i, row in enumerate(gallery_rows):\n            images = row.find_elements(By.CSS_SELECTOR, 'img')\n            self.assert_equal(len(rows[i]), len(images))\n            for j, image in enumerate(images):\n                self.assertIn(rows[i][j], image.get_attribute('src'))\n"
  },
  {
    "path": "tools/create_session_browser.py",
    "content": "#!/usr/bin/env python3\n\"\"\"\nRequirements:\n  pip install -r tools/requirements.txt\n\nUsage:\n  python3 tools/create_session_browser.py <username> <password> [totp_seed] [--append sessions.jsonl] [--headless]\n\nExamples:\n  # Output to terminal\n  python3 tools/create_session_browser.py myusername mypassword TOTP_SECRET\n\n  # Append to sessions.jsonl\n  python3 tools/create_session_browser.py myusername mypassword TOTP_SECRET --append sessions.jsonl\n\n  # Headless mode (may increase detection risk)\n  python3 tools/create_session_browser.py myusername mypassword TOTP_SECRET --headless\n\nOutput:\n  {\"kind\": \"cookie\", \"username\": \"...\", \"id\": \"...\", \"auth_token\": \"...\", \"ct0\": \"...\"}\n\"\"\"\n\nimport asyncio\nimport json\nimport os\nimport sys\n\nimport nodriver as uc\nimport pyotp\n\n\nasync def login_and_get_cookies(username, password, totp_seed=None, headless=False):\n    \"\"\"Authenticate with X.com and extract session cookies\"\"\"\n    # Note: headless mode may increase detection risk from bot-detection systems\n    browser = await uc.start(headless=headless)\n    tab = await browser.get(\"https://x.com/i/flow/login\")\n\n    try:\n        # Enter username\n        print(f\"[*] Entering username {username}...\", file=sys.stderr)\n\n        retry = 0\n        while retry < 5:\n            username_input = await tab.find(\n                'input[autocomplete=\"username\"]', timeout=10\n            )\n\n            pos = await username_input.get_position()\n            await tab.mouse_move(pos.x, pos.y, steps=50, flash=True)\n            await asyncio.sleep(0.1)\n\n            await username_input.click()\n            await asyncio.sleep(0.5)\n            await username_input.send_keys(username)\n            await asyncio.sleep(0.2)\n            await username_input.send_keys(\"\\n\")\n            await asyncio.sleep(2)\n\n            page_content = await tab.get_content()\n            if \"Could not log you in\" in page_content:\n                retry += 1\n                wait = retry * 10\n                print(f\"Retrying in {wait} seconds...\")\n                await asyncio.sleep(wait)\n            else:\n                break\n\n        # Enter password\n        print(\"[*] Entering password...\", file=sys.stderr)\n        pretry = 0\n        while pretry < 5:\n            password_input = await tab.find(\n                'input[autocomplete=\"current-password\"]', timeout=15\n            )\n            await password_input.click()\n            await asyncio.sleep(0.5)\n            await password_input.send_keys(password)\n            await asyncio.sleep(0.2)\n            await password_input.send_keys(\"\\n\")\n            await asyncio.sleep(2)\n\n            page_content = await tab.get_content()\n            if \"Could not log you in\" in page_content:\n                pretry += 1\n                wait = pretry * 10\n                print(f\"Retrying in {wait} seconds...\")\n                await asyncio.sleep(wait)\n            else:\n                break\n\n        # Handle 2FA if needed\n        page_content = await tab.get_content()\n        if \"verification code\" in page_content or \"Enter code\" in page_content:\n            if not totp_seed:\n                raise Exception(\"2FA required but no TOTP seed provided\")\n\n            print(\"[*] 2FA detected, entering code...\", file=sys.stderr)\n            totp_code = pyotp.TOTP(totp_seed).now()\n            code_input = await tab.select('input[type=\"text\"]')\n            await code_input.send_keys(totp_code + \"\\n\")\n            await asyncio.sleep(3)\n\n        # Get cookies\n        print(\"[*] Retrieving cookies...\", file=sys.stderr)\n        for _ in range(20):  # 20 second timeout\n            cookies = await browser.cookies.get_all()\n            cookies_dict = {cookie.name: cookie.value for cookie in cookies}\n\n            if \"auth_token\" in cookies_dict and \"ct0\" in cookies_dict:\n                # Extract ID from twid cookie (may be URL-encoded)\n                user_id = None\n                if \"twid\" in cookies_dict:\n                    twid = cookies_dict[\"twid\"]\n                    # Try to extract the ID from twid (format: u%3D<id> or u=<id>)\n                    if \"u%3D\" in twid:\n                        user_id = twid.split(\"u%3D\")[1].split(\"&\")[0].strip('\"')\n                    elif \"u=\" in twid:\n                        user_id = twid.split(\"u=\")[1].split(\"&\")[0].strip('\"')\n\n                cookies_dict[\"username\"] = username\n                if user_id:\n                    cookies_dict[\"id\"] = user_id\n\n                return cookies_dict\n\n            await asyncio.sleep(1)\n\n        raise Exception(\"Timeout waiting for cookies\")\n\n    finally:\n        browser.stop()\n\n\nasync def main():\n    if len(sys.argv) < 3:\n        print(\n            \"Usage: python3 create_session_browser.py username password [totp_seed] [--append file.jsonl] [--headless]\"\n        )\n        sys.exit(1)\n\n    username = sys.argv[1]\n    password = sys.argv[2]\n    totp_seed = None\n    append_file = None\n    headless = False\n\n    # Parse optional arguments\n    i = 3\n    while i < len(sys.argv):\n        arg = sys.argv[i]\n        if arg == \"--append\":\n            if i + 1 < len(sys.argv):\n                append_file = sys.argv[i + 1]\n                i += 2  # Skip '--append' and filename\n            else:\n                print(\"[!] Error: --append requires a filename\", file=sys.stderr)\n                sys.exit(1)\n        elif arg == \"--headless\":\n            headless = True\n            i += 1\n        elif not arg.startswith(\"--\"):\n            if totp_seed is None:\n                totp_seed = arg\n            i += 1\n        else:\n            # Unkown args\n            print(f\"[!] Warning: Unknown argument: {arg}\", file=sys.stderr)\n            i += 1\n\n    try:\n        cookies = await login_and_get_cookies(username, password, totp_seed, headless)\n        session = {\n            \"kind\": \"cookie\",\n            \"username\": cookies[\"username\"],\n            \"id\": cookies.get(\"id\"),\n            \"auth_token\": cookies[\"auth_token\"],\n            \"ct0\": cookies[\"ct0\"],\n        }\n        output = json.dumps(session)\n\n        if append_file:\n            with open(append_file, \"a\") as f:\n                f.write(output + \"\\n\")\n            print(f\"✓ Session appended to {append_file}\", file=sys.stderr)\n        else:\n            print(output)\n\n        os._exit(0)\n\n    except Exception as error:\n        print(f\"[!] Error: {error}\", file=sys.stderr)\n        sys.exit(1)\n\n\nif __name__ == \"__main__\":\n    asyncio.run(main())\n"
  },
  {
    "path": "tools/create_session_curl.py",
    "content": "#!/usr/bin/env python3\n\"\"\"\nRequirements:\n  pip install curl_cffi pyotp\n\nUsage:\n  python3 tools/create_session_curl.py <username> <password> [totp_seed] [--append sessions.jsonl]\n\nExamples:\n  # Output to terminal\n  python3 tools/create_session_curl.py myusername mypassword TOTP_SECRET\n\n  # Append to sessions.jsonl\n  python3 tools/create_session_curl.py myusername mypassword TOTP_SECRET --append sessions.jsonl\n\nOutput:\n  {\"kind\": \"cookie\", \"username\": \"...\", \"id\": \"...\", \"auth_token\": \"...\", \"ct0\": \"...\"}\n\"\"\"\n\nimport sys\nimport json\nimport pyotp\nfrom curl_cffi import requests\n\nBEARER_TOKEN = \"AAAAAAAAAAAAAAAAAAAAAFQODgEAAAAAVHTp76lzh3rFzcHbmHVvQxYYpTw%3DckAlMINMjmCwxUcaXbAN4XqJVdgMJaHqNOFgPMK0zN1qLqLQCF\"\nBASE_URL = \"https://api.x.com/1.1/onboarding/task.json\"\nGUEST_ACTIVATE_URL = \"https://api.x.com/1.1/guest/activate.json\"\n\n# Subtask versions required by API\nSUBTASK_VERSIONS = {\n    \"action_list\": 2, \"alert_dialog\": 1, \"app_download_cta\": 1,\n    \"check_logged_in_account\": 2, \"choice_selection\": 3,\n    \"contacts_live_sync_permission_prompt\": 0, \"cta\": 7, \"email_verification\": 2,\n    \"end_flow\": 1, \"enter_date\": 1, \"enter_email\": 2, \"enter_password\": 5,\n    \"enter_phone\": 2, \"enter_recaptcha\": 1, \"enter_text\": 5, \"generic_urt\": 3,\n    \"in_app_notification\": 1, \"interest_picker\": 3, \"js_instrumentation\": 1,\n    \"menu_dialog\": 1, \"notifications_permission_prompt\": 2, \"open_account\": 2,\n    \"open_home_timeline\": 1, \"open_link\": 1, \"phone_verification\": 4,\n    \"privacy_options\": 1, \"security_key\": 3, \"select_avatar\": 4,\n    \"select_banner\": 2, \"settings_list\": 7, \"show_code\": 1, \"sign_up\": 2,\n    \"sign_up_review\": 4, \"tweet_selection_urt\": 1, \"update_users\": 1,\n    \"upload_media\": 1, \"user_recommendations_list\": 4,\n    \"user_recommendations_urt\": 1, \"wait_spinner\": 3, \"web_modal\": 1\n}\n\n\ndef get_base_headers(guest_token=None):\n    \"\"\"Build base headers for API requests.\"\"\"\n    headers = {\n        \"Authorization\": f\"Bearer {BEARER_TOKEN}\",\n        \"Content-Type\": \"application/json\",\n        \"Accept\": \"*/*\",\n        \"Accept-Language\": \"en-US\",\n        \"X-Twitter-Client-Language\": \"en-US\",\n        \"Origin\": \"https://x.com\",\n        \"Referer\": \"https://x.com/\",\n    }\n    if guest_token:\n        headers[\"X-Guest-Token\"] = guest_token\n    return headers\n\n\ndef get_cookies_dict(session):\n    \"\"\"Extract cookies from session.\"\"\"\n    return session.cookies.get_dict() if hasattr(session.cookies, 'get_dict') else dict(session.cookies)\n\n\ndef make_request(session, headers, flow_token, subtask_data, print_msg):\n    \"\"\"Generic request handler for flow steps.\"\"\"\n    print(f\"[*] {print_msg}...\", file=sys.stderr)\n\n    payload = {\n        \"flow_token\": flow_token,\n        \"subtask_inputs\": [subtask_data] if isinstance(subtask_data, dict) else subtask_data\n    }\n\n    response = session.post(BASE_URL, json=payload, headers=headers)\n    response.raise_for_status()\n\n    data = response.json()\n    new_flow_token = data.get('flow_token')\n    if not new_flow_token:\n        raise Exception(f\"Failed to get flow token: {print_msg}\")\n\n    return new_flow_token, data\n\n\ndef get_guest_token(session):\n    \"\"\"Get guest token for unauthenticated requests.\"\"\"\n    print(\"[*] Getting guest token...\", file=sys.stderr)\n    response = session.post(GUEST_ACTIVATE_URL, headers={\"Authorization\": f\"Bearer {BEARER_TOKEN}\"})\n    response.raise_for_status()\n\n    guest_token = response.json().get('guest_token')\n    if not guest_token:\n        raise Exception(\"Failed to obtain guest token\")\n\n    print(f\"[*] Got guest token: {guest_token}\", file=sys.stderr)\n    return guest_token\n\n\ndef init_flow(session, guest_token):\n    \"\"\"Initialize the login flow.\"\"\"\n    print(\"[*] Initializing login flow...\", file=sys.stderr)\n\n    headers = get_base_headers(guest_token)\n    payload = {\n        \"input_flow_data\": {\n            \"flow_context\": {\n                \"debug_overrides\": {},\n                \"start_location\": {\"location\": \"manual_link\"}\n            },\n            \"subtask_versions\": SUBTASK_VERSIONS\n        }\n    }\n\n    response = session.post(f\"{BASE_URL}?flow_name=login\", json=payload, headers=headers)\n    response.raise_for_status()\n\n    flow_token = response.json().get('flow_token')\n    if not flow_token:\n        raise Exception(\"Failed to get initial flow token\")\n\n    print(\"[*] Got initial flow token\", file=sys.stderr)\n    return flow_token, headers\n\n\ndef submit_username(session, flow_token, headers, guest_token, username):\n    \"\"\"Submit username.\"\"\"\n    headers = headers.copy()\n    headers[\"X-Guest-Token\"] = guest_token\n\n    subtask = {\n        \"subtask_id\": \"LoginEnterUserIdentifierSSO\",\n        \"settings_list\": {\n            \"setting_responses\": [{\n                \"key\": \"user_identifier\",\n                \"response_data\": {\"text_data\": {\"result\": username}}\n            }],\n            \"link\": \"next_link\"\n        }\n    }\n\n    flow_token, data = make_request(session, headers, flow_token, subtask, \"Submitting username\")\n\n    # Check for denial (suspicious activity)\n    if data.get('subtasks') and 'cta' in data['subtasks'][0]:\n        error_msg = data['subtasks'][0]['cta'].get('primary_text', {}).get('text')\n        if error_msg:\n            raise Exception(f\"Login denied: {error_msg}\")\n\n    return flow_token\n\n\ndef submit_password(session, flow_token, headers, guest_token, password):\n    \"\"\"Submit password and detect if 2FA is needed.\"\"\"\n    headers = headers.copy()\n    headers[\"X-Guest-Token\"] = guest_token\n\n    subtask = {\n        \"subtask_id\": \"LoginEnterPassword\",\n        \"enter_password\": {\"password\": password, \"link\": \"next_link\"}\n    }\n\n    flow_token, data = make_request(session, headers, flow_token, subtask, \"Submitting password\")\n\n    needs_2fa = any(s.get('subtask_id') == 'LoginTwoFactorAuthChallenge' for s in data.get('subtasks', []))\n    if needs_2fa:\n        print(\"[*] 2FA required\", file=sys.stderr)\n\n    return flow_token, needs_2fa\n\n\ndef submit_2fa(session, flow_token, headers, guest_token, totp_seed):\n    \"\"\"Submit 2FA code.\"\"\"\n    if not totp_seed:\n        raise Exception(\"2FA required but no TOTP seed provided\")\n\n    code = pyotp.TOTP(totp_seed).now()\n    print(\"[*] Generating 2FA code...\", file=sys.stderr)\n\n    headers = headers.copy()\n    headers[\"X-Guest-Token\"] = guest_token\n\n    subtask = {\n        \"subtask_id\": \"LoginTwoFactorAuthChallenge\",\n        \"enter_text\": {\"text\": code, \"link\": \"next_link\"}\n    }\n\n    flow_token, _ = make_request(session, headers, flow_token, subtask, \"Submitting 2FA code\")\n    return flow_token\n\n\ndef submit_js_instrumentation(session, flow_token, headers, guest_token):\n    \"\"\"Submit JS instrumentation response.\"\"\"\n    headers = headers.copy()\n    headers[\"X-Guest-Token\"] = guest_token\n\n    subtask = {\n        \"subtask_id\": \"LoginJsInstrumentationSubtask\",\n        \"js_instrumentation\": {\n            \"response\": '{\"rf\":{\"a4fc506d24bb4843c48a1966940c2796bf4fb7617a2d515ad3297b7df6b459b6\":121,\"bff66e16f1d7ea28c04653dc32479cf416a9c8b67c80cb8ad533b2a44fee82a3\":-1,\"ac4008077a7e6ca03210159dbe2134dea72a616f03832178314bb9931645e4f7\":-22,\"c3a8a81a9b2706c6fec42c771da65a9597c537b8e4d9b39e8e58de9fe31ff239\":-12},\"s\":\"ZHYaDA9iXRxOl2J3AZ9cc23iJx-Fg5E82KIBA_fgeZFugZGYzRtf8Bl3EUeeYgsK30gLFD2jTQx9fAMsnYCw0j8ahEy4Pb5siM5zD6n7YgOeWmFFaXoTwaGY4H0o-jQnZi5yWZRAnFi4lVuCVouNz_xd2BO2sobCO7QuyOsOxQn2CWx7bjD8vPAzT5BS1mICqUWyjZDjLnRZJU6cSQG5YFIHEPBa8Kj-v1JFgkdAfAMIdVvP7C80HWoOqYivQR7IBuOAI4xCeLQEdxlGeT-JYStlP9dcU5St7jI6ExyMeQnRicOcxXLXsan8i5Joautk2M8dAJFByzBaG4wtrPhQ3QAAAZEi-_t7\"}',\n            \"link\": \"next_link\"\n        }\n    }\n\n    flow_token, _ = make_request(session, headers, flow_token, subtask, \"Submitting JS instrumentation\")\n    return flow_token\n\n\ndef complete_flow(session, flow_token, headers):\n    \"\"\"Complete the login flow.\"\"\"\n    cookies = get_cookies_dict(session)\n\n    headers = headers.copy()\n    headers[\"X-Twitter-Auth-Type\"] = \"OAuth2Session\"\n    if cookies.get('ct0'):\n        headers[\"X-Csrf-Token\"] = cookies['ct0']\n\n    subtask = {\n        \"subtask_id\": \"AccountDuplicationCheck\",\n        \"check_logged_in_account\": {\"link\": \"AccountDuplicationCheck_false\"}\n    }\n\n    make_request(session, headers, flow_token, subtask, \"Completing login flow\")\n\n\ndef extract_user_id(cookies_dict):\n    \"\"\"Extract user ID from twid cookie.\"\"\"\n    twid = cookies_dict.get('twid', '').strip('\"')\n\n    for prefix in ['u=', 'u%3D']:\n        if prefix in twid:\n            return twid.split(prefix)[1].split('&')[0].strip('\"')\n\n    return None\n\n\ndef login_and_get_cookies(username, password, totp_seed=None):\n    \"\"\"Authenticate with X.com and extract session cookies.\"\"\"\n    session = requests.Session(impersonate=\"chrome\")\n\n    try:\n        guest_token = get_guest_token(session)\n        flow_token, headers = init_flow(session, guest_token)\n        flow_token = submit_js_instrumentation(session, flow_token, headers, guest_token)\n        flow_token = submit_username(session, flow_token, headers, guest_token, username)\n        flow_token, needs_2fa = submit_password(session, flow_token, headers, guest_token, password)\n\n        if needs_2fa:\n            flow_token = submit_2fa(session, flow_token, headers, guest_token, totp_seed)\n\n        complete_flow(session, flow_token, headers)\n\n        cookies_dict = get_cookies_dict(session)\n        cookies_dict['username'] = username\n\n        user_id = extract_user_id(cookies_dict)\n        if user_id:\n            cookies_dict['id'] = user_id\n\n        print(\"[*] Successfully authenticated\", file=sys.stderr)\n        return cookies_dict\n\n    finally:\n        session.close()\n\n\ndef main():\n    if len(sys.argv) < 3:\n        print('Usage: python3 create_session_curl.py username password [totp_seed] [--append sessions.jsonl]', file=sys.stderr)\n        sys.exit(1)\n\n    username = sys.argv[1]\n    password = sys.argv[2]\n    totp_seed = None\n    append_file = None\n\n    # Parse optional arguments\n    i = 3\n    while i < len(sys.argv):\n        arg = sys.argv[i]\n        if arg == '--append':\n            if i + 1 < len(sys.argv):\n                append_file = sys.argv[i + 1]\n                i += 2\n            else:\n                print('[!] Error: --append requires a filename', file=sys.stderr)\n                sys.exit(1)\n        elif not arg.startswith('--'):\n            if totp_seed is None:\n                totp_seed = arg\n            i += 1\n        else:\n            print(f'[!] Warning: Unknown argument: {arg}', file=sys.stderr)\n            i += 1\n\n    try:\n        cookies = login_and_get_cookies(username, password, totp_seed)\n\n        session = {\n            'kind': 'cookie',\n            'username': cookies['username'],\n            'id': cookies.get('id'),\n            'auth_token': cookies['auth_token'],\n            'ct0': cookies['ct0']\n        }\n\n        output = json.dumps(session)\n\n        if append_file:\n            with open(append_file, 'a') as f:\n                f.write(output + '\\n')\n            print(f'✓ Session appended to {append_file}', file=sys.stderr)\n        else:\n            print(output)\n\n        sys.exit(0)\n\n    except Exception as error:\n        print(f'[!] Error: {error}', file=sys.stderr)\n        import traceback\n        traceback.print_exc(file=sys.stderr)\n        sys.exit(1)\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "tools/create_sessions_browser.py",
    "content": "#!/usr/bin/env python3\n\"\"\"\nRequirements:\n  pip install -r tools/requirements.txt\n\nUsage:\n  python3 tools/create_sessions_browser.py <accounts_file> [--append sessions.jsonl] [--headless] [--delay]\n\nExamples:\n  # Output to terminal\n  python3 tools/create_sessions_browser.py <accounts_file>\n\n  # Append to sessions.jsonl\n  python3 tools/create_sessions_browser.py <accounts_file> --append sessions.jsonl\n\n  # Add 5 second delay between sessions (default: 1)\n  python3 tools/create_sessions_browser.py <accounts_file> --delay 5\n\n  # Headless mode (may increase detection risk)\n  python3 tools/create_sessions_browser.py <accounts_file> --headless\n\nInput (accounts_file):\n  [{\"username\": \"user\", \"password\": \"pass\", \"totp\": \"totp_code\"}, {...}, ...]\n\nOutput:\n  {\"kind\": \"cookie\", \"username\": \"...\", \"id\": \"...\", \"auth_token\": \"...\", \"ct0\": \"...\"}\n  {\"kind\": \"cookie\", \"username\": \"...\", \"id\": \"...\", \"auth_token\": \"...\", \"ct0\": \"...\"}\n  ...\n\"\"\"\n\nimport asyncio\nimport json\nimport sys\nfrom time import sleep\n\nimport nodriver as uc\nimport pyotp\n\n\nasync def login_and_get_cookies(account, headless=False):\n    \"\"\"Authenticate with X.com and extract session cookies\"\"\"\n    # Note: headless mode may increase detection risk from bot-detection systems\n    browser = await uc.start(headless=headless)\n    tab = await browser.get(\"https://x.com/i/flow/login\")\n\n    username = account[\"username\"]\n    password = account[\"password\"]\n    totp_seed = account[\"totp\"]\n\n    try:\n        # Enter username\n        print(f\"[*] Entering username {username}...\", file=sys.stderr)\n\n        retry = 0\n        while retry < 5:\n            username_input = await tab.find(\n                'input[autocomplete=\"username\"]', timeout=10\n            )\n\n            pos = await username_input.get_position()\n            await tab.mouse_move(pos.x, pos.y, steps=50, flash=True)\n            await asyncio.sleep(0.1)\n\n            await username_input.click()\n            await asyncio.sleep(0.5)\n            await username_input.send_keys(username)\n            await asyncio.sleep(0.2)\n            await username_input.send_keys(\"\\n\")\n            await asyncio.sleep(2)\n\n            page_content = await tab.get_content()\n            if \"Could not log you in\" in page_content:\n                retry += 1\n                wait = retry * 10\n                print(f\"Retrying in {wait} seconds...\")\n                await asyncio.sleep(wait)\n            else:\n                break\n\n        # Enter password\n        print(\"[*] Entering password...\", file=sys.stderr)\n        pretry = 0\n        while pretry < 5:\n            password_input = await tab.find(\n                'input[autocomplete=\"current-password\"]', timeout=15\n            )\n            await password_input.click()\n            await asyncio.sleep(0.5)\n            await password_input.send_keys(password)\n            await asyncio.sleep(0.2)\n            await password_input.send_keys(\"\\n\")\n            await asyncio.sleep(2)\n\n            page_content = await tab.get_content()\n            if \"Could not log you in\" in page_content:\n                pretry += 1\n                wait = pretry * 10\n                print(f\"Retrying in {wait} seconds...\")\n                await asyncio.sleep(wait)\n            else:\n                break\n\n        # Handle 2FA if needed\n        page_content = await tab.get_content()\n        if \"verification code\" in page_content or \"Enter code\" in page_content:\n            if not totp_seed:\n                raise Exception(\"2FA required but no TOTP seed provided\")\n\n            print(\"[*] 2FA detected, entering code...\", file=sys.stderr)\n            totp_code = pyotp.TOTP(totp_seed).now()\n            code_input = await tab.select('input[type=\"text\"]')\n            await code_input.send_keys(totp_code + \"\\n\")\n            await asyncio.sleep(3)\n\n        # Get cookies\n        print(\"[*] Retrieving cookies...\", file=sys.stderr)\n        for _ in range(20):  # 20 second timeout\n            cookies = await browser.cookies.get_all()\n            cookies_dict = {cookie.name: cookie.value for cookie in cookies}\n\n            if \"auth_token\" in cookies_dict and \"ct0\" in cookies_dict:\n                # Extract ID from twid cookie (may be URL-encoded)\n                user_id = None\n                if \"twid\" in cookies_dict:\n                    twid = cookies_dict[\"twid\"]\n                    # Try to extract the ID from twid (format: u%3D<id> or u=<id>)\n                    if \"u%3D\" in twid:\n                        user_id = twid.split(\"u%3D\")[1].split(\"&\")[0].strip('\"')\n                    elif \"u=\" in twid:\n                        user_id = twid.split(\"u=\")[1].split(\"&\")[0].strip('\"')\n\n                cookies_dict[\"username\"] = username\n                if user_id:\n                    cookies_dict[\"id\"] = user_id\n\n                return cookies_dict\n\n            await asyncio.sleep(1)\n\n        raise Exception(\"Timeout waiting for cookies\")\n\n    finally:\n        browser.stop()\n\n\nasync def main():\n    if len(sys.argv) < 2:\n        print(\n            \"Usage: python3 create_sessions_browser.py <accounts_file> [--append sessions.jsonl] [--headless]\"\n        )\n        sys.exit(1)\n\n    input = sys.argv[1]\n    append_file = None\n    headless = False\n    delay = 1\n\n    # Parse optional arguments\n    i = 2\n    while i < len(sys.argv):\n        arg = sys.argv[i]\n        if arg == \"--append\":\n            if i + 1 < len(sys.argv):\n                append_file = sys.argv[i + 1]\n                i += 2  # Skip '--append' and filename\n            else:\n                print(\"[!] Error: --append requires a filename\", file=sys.stderr)\n                sys.exit(1)\n        elif arg == \"--headless\":\n            headless = True\n            i += 1\n        elif arg == \"--delay\":\n            delay = int(sys.argv[i + 1])\n            i += 2\n        else:\n            # Unkown args\n            print(f\"[!] Warning: Unknown argument: {arg}\", file=sys.stderr)\n            i += 1\n\n    accounts = []\n    with open(input) as f:\n        accounts = json.load(f)\n\n    if len(accounts) == 0:\n        print(\"no accounts in file\")\n        sys.exit(0)\n\n    sessions = 0\n    for acc in accounts:\n        sessions += 1\n        try:\n            cookies = await login_and_get_cookies(acc, headless)\n            session = {\n                \"kind\": \"cookie\",\n                \"username\": cookies[\"username\"],\n                \"id\": cookies.get(\"id\"),\n                \"auth_token\": cookies[\"auth_token\"],\n                \"ct0\": cookies[\"ct0\"],\n            }\n\n            if append_file:\n                with open(append_file, \"a\") as f:\n                    f.write(json.dumps(session) + \"\\n\")\n            else:\n                print(json.dumps(session))\n\n            print(f\"Progress: {sessions} / {len(accounts)}\")\n            if sessions < len(accounts):\n                print(\"Waiting\", delay, \"seconds\")\n                sleep(delay)\n        except Exception as error:\n            print(\n                f\"[!] Error getting session for {acc[\"username\"]}, skipping: {error}\",\n                file=sys.stderr,\n            )\n\n\nif __name__ == \"__main__\":\n    asyncio.run(main())\n"
  },
  {
    "path": "tools/gencss.nim",
    "content": "import sass\n\ncompileFile(\"src/sass/index.scss\",\n            outputPath = \"public/css/style.css\",\n            includePaths = @[\"src/sass/include\"])\n\necho \"Compiled to public/css/style.css\"\n"
  },
  {
    "path": "tools/get_session.py",
    "content": "#!/usr/bin/env python3\nimport requests\nimport json\nimport sys\nimport pyotp\nimport cloudscraper\n\n# NOTE: pyotp, requests and cloudscraper are dependencies\n# > pip install pyotp requests cloudscraper\n\nTW_CONSUMER_KEY = '3nVuSoBZnx6U4vzUxf5w'\nTW_CONSUMER_SECRET = 'Bcs59EFbbsdF6Sl9Ng71smgStWEGwXXKSjYvPVt7qys'\n\ndef auth(username, password, otp_secret):\n    bearer_token_req = requests.post(\"https://api.twitter.com/oauth2/token\",\n        auth=(TW_CONSUMER_KEY, TW_CONSUMER_SECRET),\n        headers={\"Content-Type\": \"application/x-www-form-urlencoded\"},\n        data='grant_type=client_credentials'\n    ).json()\n    bearer_token = ' '.join(str(x) for x in bearer_token_req.values())\n\n    guest_token = requests.post(\n        \"https://api.twitter.com/1.1/guest/activate.json\",\n        headers={\n            'Authorization': bearer_token,\n             \"User-Agent\": \"TwitterAndroid/10.21.0-release.0 (310210000-r-0) ONEPLUS+A3010/9\"\n        }\n    ).json().get('guest_token')\n\n    if not guest_token:\n        print(\"Failed to obtain guest token.\")\n        sys.exit(1)\n\n    twitter_header = {\n        'Authorization': bearer_token,\n        \"Content-Type\": \"application/json\",\n        \"User-Agent\": \"TwitterAndroid/10.21.0-release.0 (310210000-r-0) ONEPLUS+A3010/9 (OnePlus;ONEPLUS+A3010;OnePlus;OnePlus3;0;;1;2016)\",\n        \"X-Twitter-API-Version\": '5',\n        \"X-Twitter-Client\": \"TwitterAndroid\",\n        \"X-Twitter-Client-Version\": \"10.21.0-release.0\",\n        \"OS-Version\": \"28\",\n        \"System-User-Agent\": \"Dalvik/2.1.0 (Linux; U; Android 9; ONEPLUS A3010 Build/PKQ1.181203.001)\",\n        \"X-Twitter-Active-User\": \"yes\",\n        \"X-Guest-Token\": guest_token,\n        \"X-Twitter-Client-DeviceID\": \"\"\n    }\n\n    scraper = cloudscraper.create_scraper()\n    scraper.headers = twitter_header\n\n    task1 = scraper.post(\n        'https://api.twitter.com/1.1/onboarding/task.json',\n        params={\n            'flow_name': 'login',\n            'api_version': '1',\n            'known_device_token': '',\n            'sim_country_code': 'us'\n        },\n        json={\n            \"flow_token\": None,\n            \"input_flow_data\": {\n                \"country_code\": None,\n                \"flow_context\": {\n                    \"referrer_context\": {\n                        \"referral_details\": \"utm_source=google-play&utm_medium=organic\",\n                        \"referrer_url\": \"\"\n                    },\n                    \"start_location\": {\n                        \"location\": \"deeplink\"\n                    }\n                },\n                \"requested_variant\": None,\n                \"target_user_id\": 0\n            }\n        }\n    )\n\n    scraper.headers['att'] = task1.headers.get('att')\n\n    task2 = scraper.post(\n        'https://api.twitter.com/1.1/onboarding/task.json',\n        json={\n            \"flow_token\": task1.json().get('flow_token'),\n            \"subtask_inputs\": [{\n                \"enter_text\": {\n                    \"suggestion_id\": None,\n                    \"text\": username,\n                    \"link\": \"next_link\"\n                },\n                \"subtask_id\": \"LoginEnterUserIdentifier\"\n            }]\n        }\n    )\n\n    task3 = scraper.post(\n        'https://api.twitter.com/1.1/onboarding/task.json',\n        json={\n            \"flow_token\": task2.json().get('flow_token'),\n            \"subtask_inputs\": [{\n                \"enter_password\": {\n                    \"password\": password,\n                    \"link\": \"next_link\"\n                },\n                \"subtask_id\": \"LoginEnterPassword\"\n            }],\n        }\n    )\n\n    for t3_subtask in task3.json().get('subtasks', []):\n        if \"open_account\" in t3_subtask:\n            return t3_subtask[\"open_account\"]\n        elif \"enter_text\" in t3_subtask:\n            response_text = t3_subtask[\"enter_text\"][\"hint_text\"]\n            totp = pyotp.TOTP(otp_secret)\n            generated_code = totp.now()\n            task4resp = scraper.post(\n                \"https://api.twitter.com/1.1/onboarding/task.json\",\n                json={\n                    \"flow_token\": task3.json().get(\"flow_token\"),\n                    \"subtask_inputs\": [\n                        {\n                            \"enter_text\": {\n                                \"suggestion_id\": None,\n                                \"text\": generated_code,\n                                \"link\": \"next_link\",\n                            },\n                            \"subtask_id\": \"LoginTwoFactorAuthChallenge\",\n                        }\n                    ],\n                }\n            )\n            task4 = task4resp.json()\n            for t4_subtask in task4.get(\"subtasks\", []):\n                if \"open_account\" in t4_subtask:\n                    return t4_subtask[\"open_account\"]\n\n    return None\n\nif __name__ == \"__main__\":\n    if len(sys.argv) != 5:\n        print(\"Usage: python3 get_session.py <username> <password> <2fa secret> <path>\")\n        sys.exit(1)\n\n    username = sys.argv[1]\n    password = sys.argv[2]\n    otp_secret = sys.argv[3]\n    path = sys.argv[4]\n\n    result = auth(username, password, otp_secret)\n    if result is None:\n        print(\"Authentication failed.\")\n        sys.exit(1)\n\n    session_entry = {\n        \"oauth_token\": result.get(\"oauth_token\"),\n        \"oauth_token_secret\": result.get(\"oauth_token_secret\")\n    }\n\n    try:\n        with open(path, \"a\") as f:\n            f.write(json.dumps(session_entry) + \"\\n\")\n        print(\"Authentication successful. Session appended to\", path)\n    except Exception as e:\n        print(f\"Failed to write session information: {e}\")\n        sys.exit(1)\n"
  },
  {
    "path": "tools/rendermd.nim",
    "content": "import std/[os, strutils]\nimport markdown\n\nfor file in walkFiles(\"public/md/*.md\"):\n  let\n    html = markdown(readFile(file))\n    output = file.replace(\".md\", \".html\")\n\n  output.writeFile(html)\n  echo \"Rendered \", output\n"
  },
  {
    "path": "tools/requirements.txt",
    "content": "nodriver>=0.48.0\npyotp\ncurl_cffi\n"
  }
]