master 7830652957e8 cached
34 files
108.0 KB
27.2k tokens
125 symbols
1 requests
Download .txt
Repository: krypton-byte/tiktok-downloader
Branch: master
Commit: 7830652957e8
Files: 34
Total size: 108.0 KB

Directory structure:
gitextract_la14e1v6/

├── .deepsource.toml
├── .github/
│   └── workflows/
│       ├── python-publish.yml
│       └── unittest.yml
├── .gitignore
├── MANIFEST
├── MANIFEST.in
├── Procfile
├── README.md
├── app.json
├── license
├── pyproject.toml
├── requirements.txt
├── resetup.py
├── setup.py
└── tiktok_downloader/
    ├── Except.py
    ├── __init__.py
    ├── __main__.py
    ├── decoder.js
    ├── decoder.py
    ├── mdown.py
    ├── scrapper.py
    ├── scrapper_v2.py
    ├── server.py
    ├── snaptik.py
    ├── ssstik.py
    ├── static/
    │   └── script.js
    ├── templates/
    │   └── index.html
    ├── test.py
    ├── tikdown.py
    ├── tikmate.py
    ├── tiktok_async.py
    ├── tikwm.py
    ├── ttdownloader.py
    └── utils.py

================================================
FILE CONTENTS
================================================

================================================
FILE: .deepsource.toml
================================================
version = 1

[[analyzers]]
name = "python"
enabled = true

  [analyzers.meta]
  runtime_version = "3.x.x"

[[analyzers]]
name = "javascript"
enabled = true

================================================
FILE: .github/workflows/python-publish.yml
================================================
name: Upload to PyPi

on:
  release:
    types:
      - published

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@master
    - name: Set up Python 3.9
      uses: actions/setup-python@v1
      with:
        python-version: '3.x'
    - name: Test
      run: |
        rm -rf build dist *.egg-info
        python resetup.py --version="${{ github.ref }}"
    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        pip install setuptools wheel twine
    - name: Build and publish ${{ github.ref }}
      env:
        TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }}
        TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }}
      run: |
        ls tiktok_downloader/*
        python setup.py build sdist
        twine upload dist/*


================================================
FILE: .github/workflows/unittest.yml
================================================
# This workflow will upload a Python Package using Twine when a release is created
# For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries

name: Unittest

on:
  push:
    branches:
    - master

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    - name: Set up Python
      uses: actions/setup-python@v2
      with:
        python-version: '3.x'
    - name: Install Library && OpenSSL
      run: |
        sudo apt-get install --only-upgrade openssl -y
        python -m pip install --upgrade pip
        python -m pip install flake8 aiohttp
        python setup.py install --user
    - name: Testing
      run: |
        python -m tiktok_downloader.test
    - name: PEP8
      run: |
        flake8 tiktok_downloader


================================================
FILE: .gitignore
================================================
dist
build
.mypy_cache
*.egg-info
env/
__pycache__*
cookie.txt

================================================
FILE: MANIFEST
================================================
# file GENERATED by distutils, do NOT edit
setup.py
tiktok_downloader/Except.py
tiktok_downloader/__init__.py
tiktok_downloader/keeptiktok.py
tiktok_downloader/scrapper.py
tiktok_downloader/utils.py


================================================
FILE: MANIFEST.in
================================================
include README.md
include tiktok_downloader/static/*
include tiktok_downloader/templates/*
recursive-include templates static

================================================
FILE: Procfile
================================================
web: python -m tiktok_downloader --server --host=0.0.0.0 --port=${PORT}

================================================
FILE: README.md
================================================
<p align="center">
<img src="tiktok_downloader/static/tiktok.svg"><br>
<img src="https://img.shields.io/badge/AUTHOR-KRYPTON--BYTE-brightgreen">
</p>
<center>
    
[![Unittest](https://github.com/krypton-byte/tiktok-downloader/actions/workflows/unittest.yml/badge.svg)](https://github.com/krypton-byte/tiktok-downloader/actions/workflows/unittest.yml)
[![Upload to PyPi](https://github.com/krypton-byte/tiktok-downloader/actions/workflows/python-publish.yml/badge.svg?branch=0.1.7&event=release)](https://github.com/krypton-byte/tiktok-downloader/actions/workflows/python-publish.yml)
[![Downloads](https://static.pepy.tech/personalized-badge/tiktok-downloader?period=total&units=none&left_color=black&right_color=orange&left_text=Downloads)](https://pepy.tech/project/tiktok-downloader)
[![viitor](https://visitor-badge.glitch.me/badge?page_id=krypton-byte.tiktok-downloader)]()

</center>

# install

```bash
> python3 -m pip install tiktok_downloader
> python3 -m pip install git+https://github.com/krypton-byte/tiktok-downloader
```

# Library
<details>
<summary>Tikmate</summary>

```python
>>> from tiktok_downloader import Tikmate
>>> d=Tikmate("url")
[<[type: "video" watermark: False]>, <[type: "video" watermark: False]>]
>>> d[0].download('video.mp4')
```

</details>

<details>
<summary>Snaptik</summary>

```python
>>> from tiktok_downloader import snaptik
>>> d=snaptik('https://vt.tiktok.com/xxxxxx/')
>>> d
[<[type: "video" watermark: False]>]
>>> d[0].download('video.mp4')
```
</details>

<details>
<summary>Musically Down</summary>

```python
>>> from tiktok_downloader import mdown
>>> d=mdown('https://vt.tiktok.com/xxxxxx/')
>>> d
[<[type: "video" watermark: False]>]
>>> d[0].download('video.mp4')
```
</details>

<details>
<summary>Tikdown</summary>

```python
>>> from tiktok_downloader import tikdown
>>> d=tikdown('https://vt.tiktok.com/xxxxxx/')
>>> d
[<[type: "video" watermark: False]>]
>>> d[0].download('video.mp4')
```
</details>

<details>
<summary>TTDownloader</summary>

```python
>>> from tiktok_downloader import ttdownloader
>>> d=ttdownloader('https://vt.tiktok.com/xxxxxx/')
>>> d
[<[type: "video" watermark: False]>]
>>> d[0].download('video.mp4')
```
</details>

<details>
<summary>Tikwm</summary>

```python
>>> from tiktok_downloader import tikwm
>>> d=tikwm('https://vt.tiktok.com/xxxxxx/')
>>> d
[<[type: "video" watermark: False]>]
>>> d[0].download('video.mp4')
```
</details>

<details>
<summary>Tiktok</summary>

```python
>>> from tiktok_downloader import VideoInfo
>>> d=VideoInfo.service('https://vt.tiktok.com/xxxxxx/')
>>> d
[<[type: "video" watermark: False]>]
>>> d[0].download('video.mp4')
```
</details>

<details>
<summary>Get Info</summary>

```python
>>> from tiktok_downloader import VideoInfo
>>> VideoInfo.get_info('https://vt.tiktok.com/xxxxxx/')
```
</details>

# Command line

```
usage: python3 -m tiktok_downloader [-h] [--snaptik | --ssstik | --tikmate | --mdown | --ttdownloader | --tikwm | --tikdown | --tiktok] [--host HOST] [--debug] [--port PORT] (--server | --url URL) [--info] [--json | --save SAVE]

Tiktok Downloader [CLI]

options:
  -h, --help      show this help message and exit

List Of Services:
  --snaptik
  --ssstik
  --tikmate
  --mdown
  --ttdownloader
  --tikdown
  --tikwm
  --tiktok

Web Configuration:
  --host HOST     Set host to run this web
  --debug         Set flask mode to debug
  --port PORT     Set port

Mode:
  --server        Run as web application
  --url URL       Video URL

Optional:
  --info          Print info video like author, id & etc

Output Type:
  --json          Print result to json format
  --save SAVE     Write the result to file
```
## Example CLI

<details>
<summary>Download</summary>

```bash
$ python3 -m tiktok_downloader --url https://vt.tiktok.com/lorem --snaptik --save tiktok.mp4
```

</details>

<details>
<summary>Json</summary>

```bash
$ python3 -m tiktok_downloader --url https://vt.tiktok.com/lorem --snaptik --json
```

</details>

<details><summary>Run as web</summary>

```bash
$ python3 -m tiktok_downloader --host=0.0.0.0 --port=8000 --server
 * Serving Flask app 'tiktok_downloader.server' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
</details>

## Deploy Heroku
[![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy?template=https://github.com/krypton-byte/tiktok-downloader/tree/master)
## Preview
<img src="image/web.png">

## Request API using curl & wget

```bash
$ wget -O result.mp4 $(curl -sG http://127.0.0.1:8000/snaptik -d url=https://vm.tiktok.com/xxxxxxxx/|jq .[0].url -r)
```
## you can direct Download using browser or curl
```
http://127.0.0.1:8000/snaptik?url=https://vm.tiktok.com/xxxxxxxx/&type=embed
```
### Endpoint 
| Name                                                 | Endpoint      | Status|
|------------------------------------------------------|---------------|--------|
| <a href="https://snaptik.app">Snaptik</a>            | /snaptik      | ✓
| <a href="https://tikmate.online">Tikmate</a>         | /tikmate      |✓
| <a href="https://musicaldown.com/">MusicalDown       | /mdown        |✓
| <a href="https://ssstik.io">ssstik</a>               | /ssstik       | ✓
| <a href="https://ttdownloader.com/">ttdownloader</a> | /ttdownloader | ✓
| <a href="https://www.tikwm.com/">tikwm</a>           | /tikwm        | ✓
| <a href="https://tikdown.org/">tikdown</a>           | /tikdown      | x
| <a href="https://tiktok.com/">tiktok</a>             | /tiktok       | ✓
# Donasi
<p align="center"><img src="https://svgur.com/i/Vtt.svg">

</p>
<ul><li><a href="https://saweria.co/kryptonbyte">Saweria</a><li><a href="https://wa.me/6283172366463">Whatsapp</a></li><li><a href="https://trakteer.id/krypton-byte-z8vbo">Trakteer</a></li></ul>


================================================
FILE: app.json
================================================
{
    "name":"Tiktok Downloader",
    "description":" Without Watermark Lightweight & No Ads (Open Source)",
    "stack":"heroku-20",
    "repository":"https://github.com/krypton-byte/titok-downloader",
    "keywords":[
        "tiktok-downloader",
        "python",
        "without",
        "nowm",
        "lightweigth"
    ]
}

================================================
FILE: license
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.


================================================
FILE: pyproject.toml
================================================
[tool.poetry]
name = "tiktok-downloader"
version = "0.1.0"
description = "tiktok downloader"
authors = ["krypton-byte <rosid6434@gmail.com>"]
license = "GPL-3.0"
readme = "README.md"

[tool.poetry.dependencies]
python = "^3.11"
bs4 = "^0.0.1"
flask = "^3.0.0"
cloudscraper = "^1.2.71"
requests = "^2.31.0"
tqdm = "^4.66.1"
rich = "^13.7.0"
httpx = "^0.25.2"
aiohttp = "^3.9.1"
moviepy = "^1.0.3"
js2py = "^0.74"


[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"


================================================
FILE: requirements.txt
================================================
bs4
flask
cloudscraper
requests
tqdm
rich
httpx
aiohttp
moviepy
pyjsparser

================================================
FILE: resetup.py
================================================
import argparse
import re
arg = argparse.ArgumentParser()
arg.add_argument('--version', type=str)
args = arg.parse_args()
if args.version:
    new = open('setup.py').read().replace(
        '0.1.6',
        re.search(r'\/?([0-9][0-9A-Za-z\.]+)', args.version).group(1)
    )
    with open('setup.py', 'w') as fil:
        print(new)
        fil.write(new)


================================================
FILE: setup.py
================================================

from setuptools import setup
from os import path
base_dir = path.abspath(path.dirname(__file__))
setup(
  name='tiktok_downloader',
  packages=['tiktok_downloader'],
  include_package_data=True,
  version='0.1.6',
  license='MIT',
  description='Tiktok Downloader&Scraper using bs4&requests',
  author='Krypton Byte',
  author_email='galaxyvplus6434@gmail.com',
  url='https://github.com/krypton-byte/tiktok_downloader',
  keywords=[
    'tiktok',
    'downloader',
    'scrapper',
    'tikdok-scraper',
    'tiktok-downloader'
  ],
  install_requires=[
          'bs4',
          'flask',
          'cloudscraper',
          'requests',
          'rich',
          'tqdm',
          'httpx',
          'aiohttp'
      ],
  classifiers=[
    'Development Status :: 3 - Alpha',
    'Intended Audience :: Developers',
    'Topic :: Software Development :: Build Tools',
    'License :: OSI Approved :: MIT License',
    'Programming Language :: Python :: 3.9',
  ],
)


================================================
FILE: tiktok_downloader/Except.py
================================================
class InvalidUrl(Exception):
    pass

class NoImageToSlideshow(Exception):
    pass

================================================
FILE: tiktok_downloader/__init__.py
================================================
from .snaptik import snaptik, Snaptik
from .ssstik import ssstik
from .scrapper import VideoInfo
from .tikmate import tikmate, Tikmate
from .mdown import mdown, Mdown
from .Except import InvalidUrl
from .ttdownloader import ttdownloader, TTDownloader
from .tikdown import tikdown, Tikdown
from .tikwm import tikwm, TikWM

__all__ = [
    'snaptik',
    'Snaptik',
    'ssstik',
    'VideoInfo',
    'tikmate',
    'Tikmate',
    'mdown',
    'Mdown',
    'InvalidUrl',
    'ttdownloader',
    'tikdown',
    'Tikdown',
    'TTDownloader',
    'tikwm',
    'TikWM'
]
services = {
    'snaptik': snaptik,
    'ssstik': ssstik,
    'tikmate': tikmate,
    'mdown': mdown,
    'ttdownloader': ttdownloader,
    'tikdown': tikdown,
    'tiktok': VideoInfo.service,
    'tikwm': tikwm
}


================================================
FILE: tiktok_downloader/__main__.py
================================================
import argparse
import json
import os
import sys
import requests
from . import services
from .scrapper import VideoInfo
from sys import stderr
from rich import print as print_
from rich.panel import Panel
from typing import Optional


arg = argparse.ArgumentParser(
    prog=f"python3 -m {os.path.dirname(__file__).split('/')[-1]}",
    description='Tiktok Downloader [CLI]'
)

# Services
servgroup = arg.add_argument_group('List Of Services')
serg = servgroup.add_mutually_exclusive_group()
for key, value in services.items():
    serg.add_argument(f'--{key}', dest='service', const=value, action='store_const')

# Web Configuration
servconf = arg.add_argument_group('Web Configuration')
servconf.add_argument(
    '--host',
    type=str,
    default='127.0.0.1',
    help='Set host to run this web')
servconf.add_argument(
    '--debug',
    action='store_true',
    help='Set flask mode to debug')
servconf.add_argument('--port', default=8000, type=int, help='Set port')

# Mode Server | CLI
mod = arg.add_argument_group('Mode')
mode = mod.add_mutually_exclusive_group(required=True)
mode.add_argument(
    '--server',
    action='store_true',
    help='Run as web application')
mode.add_argument('--url', type=str, help='Video URL')

# CLI
cli = arg.add_argument_group('Optional')
cli.add_argument(
    '--info',
    action='store_true',
    help='Print info video like author, id & etc')

# Output
outa = arg.add_argument_group('Output Type')
out = outa.add_mutually_exclusive_group()
out.add_argument(
    '--json',
    action='store_true',
    help='Print result to json format')
out.add_argument(
    '--save',
    type=argparse.FileType('wb'),
    help='Write the result to file')
parse = arg.parse_args()


def info(url: str, js: Optional[bool] = False):
    infojson = VideoInfo.get_info(url)
    if js:
        print(json.dumps({
            "id": infojson.id,
            "desc": infojson.desc,
            "duration": infojson.duration,
            "author": infojson.author.username,
            "wm": infojson.downloadLink(True),
            "nowm": infojson.downloadLink(False),
            "service": 'TikTok'
        }, indent=4))
    else:
        print_(Panel(
            f'[yellow bold]Id\t: [green bold]{infojson.id}\n'
            f'[yellow bold]Desc\t: [green bold]{infojson.desc}\n'
            f'[yellow bold]Duration: [green bold]{infojson.duration}s\n'
            f'[yellow bold]Author\t: [green bold]@{infojson.author.username}\n'
            f'[yellow bold]URL\t: [green bold]{infojson.downloadLink(True)}',
            title='TikTok Downloader',
            border_style='bold magenta'))


if parse.server:
    from .server import app
    app.run(host=parse.host, port=parse.port, debug=parse.debug)
elif parse.url:
    try:
        ok = parse.service(parse.url)
        if parse.json or not parse.save:
            print(
                json.dumps(
                    [
                        {
                            'type': i.type.value,
                            'url': i.json,
                            "render": bool(i.render),
                            'watermark': i.watermark
                        } for i in ok
                    ],
                    indent=4
                )
            )
        elif parse.save:
            if parse.info:
                info(parse.url, js=parse.json)
            if ok[0].render:
                ok[0].get_render().download(parse.save, bar=True)
            else:
                ok[0].download(parse.save, bar=True)
        else:
            os.system("python3 -m tiktok_downloader --help")
    except requests.exceptions.ConnectionError:
        stderr.write('[x] offline\n')
        stderr.flush()
        sys.exit(1)
    except (KeyError, AttributeError):
        stderr.write('Post Not Found\n')
        stderr.flush()
        sys.exit(1)
    except Exception as e:
        print(e)
        stderr.write('Post Not Found\n')
        stderr.flush()
        sys.exit(1)
elif parse.info and parse.url:
    info(parse.url, js=False)
else:
    os.system("python3 -m tiktok_downloader --help")


================================================
FILE: tiktok_downloader/decoder.js
================================================
/*
  kalo mau ngedec obfuscate snaptik/tikmate pake javascript/nodejs tinggal panggil fungsi decoder
  jangan lupa kasih star reponya :v
*/
var _0xc38e = [
  "",
  "split",
  "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/",
  "slice",
  "indexOf",
  "",
  "",
  ".",
  "pow",
  "reduce",
  "reverse",
  "0",
];
function _0xe48c(d, e, f) {
  var g = _0xc38e[2][_0xc38e[1]](_0xc38e[0]);
  var h = g[_0xc38e[3]](0, e);
  var i = g[_0xc38e[3]](0, f);
  var j = d[_0xc38e[1]](_0xc38e[0])
    [_0xc38e[10]]()
    [_0xc38e[9]](function (a, b, c) {
      if (h[_0xc38e[4]](b) !== -1)
        return (a += h[_0xc38e[4]](b) * Math[_0xc38e[8]](e, c));
    }, 0);
  var k = _0xc38e[0];
  while (j > 0) {
    k = i[j % f] + k;
    j = (j - (j % f)) / f;
  }
  return k || _0xc38e[11];
}

function decoder(h, u, n, t, e, r) {
  r = "";
  for (var i = 0, len = h.length; i < len; i++) {
    var s = "";
    while (h[i] !== n[e]) {
      s += h[i];
      i++;
    }
    for (var j = 0; j < n.length; j++) s = s.replace(new RegExp(n[j], "g"), j);
    r += String.fromCharCode(_0xe48c(s, e, 10) - t);
  }
  return decodeURIComponent(escape(r));
}

================================================
FILE: tiktok_downloader/decoder.py
================================================
# Menghadeh Convert dari Js ke Py
# Decryptor For Snaptik/Tikmate Obfuscate

from typing import Union
from ast import literal_eval
from re import findall
alpha = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/"


def search(d: Union[str, list], q: str):
    try:
        return d.index(q)
    except Exception:
        return -1


def main(d, e, f):
    g = list(alpha)
    h = g[0:e]
    i = g[0:f]

    def freduce(a, b, c):
        if search(h, b) != -1:
            a += search(h, b) * (e ** c)
            return a
    j = reduces(freduce, list(d)[::-1], 0)
    k = ""
    while j > 0:
        k = i[j % f] + k
        j = int((j - (j % f)) / f)
    return int(k) or 0

def from_string(text: str):
    return decoder(*literal_eval(
            findall(
                r'\(\".*?,.*?,.*?,.*?,.*?.*?\)',
                text
            )[0]
        ))

def reduces(function, iterable, initializer=None) -> int:
    """
    [!] modified reduce function like js
    :https://www.geeksforgeeks.org/reduce-in-python/
    """
    it = iter(iterable)
    if initializer is None:
        value = next(it)
    else:
        value = function(initializer, next(it), 0)
    for index, element in enumerate(it, 1):
        value = function(value, element, index)
    return value


def decoder(h, u, n, t, e, r):
    r = ""
    i = 0
    while i < h.__len__():
        s = ""
        while h[i] != n[e]:
            s += h[i]
            i += 1
        for j in range(n.__len__()):
            s = s.replace(n[j], j.__str__())
        r += chr(main(s, e, 10) - t)
        i += 1
    return r


================================================
FILE: tiktok_downloader/mdown.py
================================================
from httpx import AsyncClient
from bs4 import BeautifulSoup
import requests
from requests.models import InvalidURL
from .utils import Download, DownloadAsync


class Mdown(requests.Session):
    BASE_URL = 'https://musicaldown.com/'

    def __init__(self) -> None:
        super().__init__()
        self.headers: dict[str, str] = {
            "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
            "(KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36"
        }

    def get_media(self, url: str):
        bs = BeautifulSoup(self.get(self.BASE_URL).text, 'html.parser')
        form = {
            i['name']: i['value'] for i in bs.find_all(
                'input',
                attrs={'type': 'hidden'}
            )
        }
        form.update({bs.find('input', attrs={'type': 'text'})['name']: url})
        res = self.post(
            f'{self.BASE_URL}download',
            data=form,
            headers={
                "origin": "https://musicaldown.com",
                "referer": "https://musicaldown.com/en",
                "sec-ch-ua": '"Chromium";v="94", "Google Chrome";v="94", '
                '";Not A Brand";v="99"',
                "sec-ch-ua-mobile": "?0",
                "sec-ch-ua-platform": "Linux",
                "sec-fetch-dest": "document",
                "sec-fetch-mode": "navigate",
                "sec-fetch-site": "same-origin",
                "sec-fetch-user": "?1",
                "upgrade-insecure-requests": "1",
                "user-agent": "Mozilla/5.0 (X11; Linux x86_64) "
                "AppleWebKit/537.36 "
                "(KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36"
            }
        )
        if 'err' in res.url:
            raise InvalidURL()
        return [
            Download(
                i['href'],
                self
            ) for i in BeautifulSoup(
                res.text,
                'html.parser'
            ).find_all('a', attrs={'target': '_blank'})
            if i['href'].strip('/').count('/') > 2
        ]


class MdownAsync(AsyncClient):
    BASE_URL = 'https://musicaldown.com/'

    def __init__(self) -> None:
        super().__init__()
        self.headers = {
            "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
            "(KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36"
        }

    async def get_media(self, url: str):
        html = (await self.get(self.BASE_URL, follow_redirects=True))
        bs = BeautifulSoup(
            html.text, 'html.parser')
        form = {
            i['name']: i['value'] for i in bs.find_all(
                'input',
                attrs={'type': 'hidden'}
            )
        }
        form.update({bs.find('input', attrs={'type': 'text'})['name']: url})
        res = await self.post(
            f'{self.BASE_URL}download',
            data=form,
            headers={
                "origin": "https://musicaldown.com",
                "referer": "https://musicaldown.com/en/",
                "sec-ch-ua": '"Chromium";v="94", "Google Chrome";v="94", '
                '";Not A Brand";v="99"',
                "sec-ch-ua-mobile": "?0",
                "sec-ch-ua-platform": "Linux",
                "sec-fetch-dest": "document",
                "sec-fetch-mode": "navigate",
                "sec-fetch-site": "same-origin",
                "sec-fetch-user": "?1",
                "upgrade-insecure-requests": "1",
                "user-agent": "Mozilla/5.0 (X11; Linux x86_64) "
                "AppleWebKit/537.36 "
                "(KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36"
            }
        )
        if 'err' in res.url.path:
            raise InvalidURL()
        return [
            DownloadAsync(
                i['href'],
                self
            ) for i in BeautifulSoup(
                res.text,
                'html.parser'
            ).find_all('a', attrs={'target': '_blank'})
        ]


def mdown(url: str):
    return Mdown().get_media(url)


async def mdown_async(url: str):
    return await MdownAsync().get_media(url)


================================================
FILE: tiktok_downloader/scrapper.py
================================================
from __future__ import annotations
from httpx import AsyncClient
from requests import Session, get
from re import findall
from typing import Callable, Optional, Union
from io import BufferedWriter, BytesIO
from datetime import datetime
import requests
from .Except import InvalidUrl
from .utils import Download, DownloadAsync
import re


def extract_id(
    initf: Callable[[VideoInfo, str], VideoInfo]
) -> Callable[[VideoInfo, str], VideoInfo]:
    subdo_redirect = ['vt', 'vm']

    def regex(url: str) -> str:
        if not findall(r'[0-9]{19}', url):
            raise InvalidUrl()
        return findall(r'[0-9]{19}', url)[0]

    def apply(cls: VideoInfo, url: str) -> VideoInfo:
        subdo = re.findall(r'://(\w+)\.', url)
        if subdo and subdo[0] in subdo_redirect:
            url = get(
                url,
                allow_redirects=False).text
        return initf(cls, regex(url))
    return apply


class Author:
    def __init__(self, ascp: dict):
        self.username = ascp['unique_id']
        self.region = ascp['region']
        self.avatar = ascp['avatar_larger']['url_list'][0]
        self.avatar_thumb = ascp['avatar_thumb']['url_list'][0]
        self.signature = ascp['signature']
        self.unique_id_modify_time = datetime.fromtimestamp(
            ascp['unique_id_modify_time'])
        self.create_time = datetime.fromtimestamp(
            ascp['create_time']) if ascp['create_time'] else None

    def __repr__(self):
        return f"<[ @{self.username} ]>"


class VideoInfoAsync(AsyncClient):
    def __init__(self, js: dict, id: str):
        super().__init__()
        self.id = id
        self.aweme = js
        self.height = (
            js['aweme_detail']['video']
            ['download_addr']['height'])
        self.width = (
            js['aweme_detail']['video']
            ['download_addr']['width'])
        self.size = (
            js['aweme_detail']
            ['video']['download_addr']['data_size'])
        self.desc = js['aweme_detail']['desc']
        self.cover = (
            js['aweme_detail']
            ['video']['origin_cover']['url_list'][0])
        self.create_time = datetime.fromtimestamp(
            js['aweme_detail']['create_time'])
        self.author = Author(js['aweme_detail']['author'])
        self.music_title = js['aweme_detail']['music']['title']
        self.music_author = js['aweme_detail']['music']['author']
        self.music_duration = js['aweme_detail']['music']['duration']
        self.duration = int(
            js['aweme_detail']['video']['duration']/1000)

    @classmethod
    async def url_to_id(cls, url: str, client: AsyncClient):
        ids = findall(r'[0-9]{19}', url)
        if ids:
            return ids[0]
        url_ = (await client.get(url, follow_redirects=True)).url.__str__()
        ids = findall(r'[0-9]{19}', url_)
        if ids:
            return ids[0]
        raise InvalidUrl()

    @classmethod
    async def get_info(cls, url: str):
        client = AsyncClient()
        id = await cls.url_to_id(url, client)
        return cls((await client.get(
            'https://api.tiktokv.com/aweme/v1/aweme/detail/',
            params={'aweme_id': id})).json(), id)

    def downloadLink(self, watermark: bool = False) -> str:
        return self.aweme['aweme_detail']['video'][
            ['play_addr', 'download_addr'][watermark]
        ]['url_list'][0]

    def utils(self) -> list[DownloadAsync]:
        return [
            DownloadAsync(
                self.downloadLink(False), self),
            DownloadAsync(
                self.downloadLink(True), self, watermark=True),
            DownloadAsync(
                self.aweme['aweme_detail']['music']['play_url']['uri'],
                self,
                "music"
            )
        ]

    def __repr__(self):
        return f'<[{self.id} {self.duration}s]>'


class VideoInfo(Session):
    def __init__(self, js: dict, id: str):
        super().__init__()
        self.id = id
        self.aweme = js
        self.height = (
            self.aweme['aweme_detail']['video']
            ['download_addr']['height'])
        self.width = (
            self.aweme['aweme_detail']['video']
            ['download_addr']['width'])
        self.size = (
            self.aweme['aweme_detail']
            ['video']['download_addr']['data_size'])
        self.desc = self.aweme['aweme_detail']['desc']
        self.cover = (
            self.aweme['aweme_detail']
            ['video']['origin_cover']['url_list'][0])
        self.create_time = datetime.fromtimestamp(
            self.aweme['aweme_detail']['create_time'])
        self.author = Author(self.aweme['aweme_detail']['author'])
        self.music_title = self.aweme['aweme_detail']['music']['title']
        self.music_author = self.aweme['aweme_detail']['music']['author']
        self.music_duration = self.aweme['aweme_detail']['music']['duration']
        self.duration = int(
            self.aweme['aweme_detail']['video']['duration']/1000)

    @classmethod
    @extract_id
    def get_info(cls, id: str) -> VideoInfo:
        print('id: ', id)
        return cls((requests.get(
            'https://api.tiktokv.com/aweme/v1/aweme/detail/',
            params={'aweme_id': id})).json(), id)

    def utils(self) -> list[Download]:
        return [
            Download(
                self.downloadLink(False), self),
            Download(
                self.downloadLink(True), self, watermark=True),
            Download(
                self.aweme['aweme_detail']['music']['play_url']['uri'],
                self,
                "music"
            )
        ]

    @classmethod
    def service(cls, url: str) -> list[Download]:
        return cls.get_info(url).utils()

    def downloadLink(self, watermark: bool = False) -> str:
        return self.aweme['aweme_detail']['video'][
            ['play_addr', 'download_addr'][watermark]
        ]['url_list'][0]

    def download(
        self,
        out: Optional[str] = None,
        watermark: bool = False,
        chunk_size: int = 1024
    ) -> Union[None, BytesIO, BufferedWriter]:
        request = self.get(self.downloadLink(watermark), stream=True)
        stream = open(out, 'wb') if isinstance(out, str) else BytesIO()
        for i in request.iter_content(chunk_size):
            stream.write(i)
        return None if isinstance(out, str) else stream

    def download_music(
        self,
        out: Optional[str] = None,
        chunk_size: int = 1024
    ) -> Union[None, BytesIO, BufferedWriter]:
        request = self.get(
            self.aweme['aweme_detail']['music']['play_url']['uri'],
            stream=True)
        stream = open(out, 'wb') if isinstance(out, str) else BytesIO()
        for i in request.iter_content(chunk_size):
            stream.write(i)
        return None if isinstance(out, str) else stream

    def __repr__(self):
        return f'<[{self.id} {self.duration}s]>'


================================================
FILE: tiktok_downloader/scrapper_v2.py
================================================
from __future__ import annotations
from dataclasses import dataclass
import re
from bs4 import BeautifulSoup
import requests
import httpx
@dataclass
class VideoInfoV2:
    url: str
    caption: str
    comment: str
    like: str
    cover: str
    aweme_id: str
    username: str

    @classmethod
    def get_info(cls, url: str) -> VideoInfoV2:
        obj = BeautifulSoup(requests.get(
            url,
            headers={
                'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 UOS'
            }
        ).text)
        caption = obj.title.text
        cover = re.findall(r'cover\":\"(http[\w:/\-\.\?\=&%]+)"', obj.__str__().replace('\\u002F','/'))[0]
        username = re.findall(r'author\":"([\w]+)"', obj.__str__())[0]
        like = obj.find_all('strong', attrs={'data-e2e':'like-count'})[0].text
        comment = obj.find_all('strong', attrs={'data-e2e':'comment-count'})[0].text
        aweme_id = re.findall(r'aweme/detail/([0-9]+)', obj.__str__())[0]
        return cls(url, caption, comment, like, cover, aweme_id, username)

    @classmethod
    async def get_info_async(cls, url: str):
        obj = BeautifulSoup((await httpx.AsyncClient().get(
            url,
            headers={
                'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 UOS'
            }
        )).text)
        caption = obj.title.text
        cover = re.findall(r'cover\":\"(http[\w:/\-\.\?\=&%]+)"', obj.__str__().replace('\\u002F','/'))[0]
        username = re.findall(r'author\":"([\w]+)"', obj.__str__())[0]
        like = obj.find_all('strong', attrs={'data-e2e':'like-count'})[0].text
        comment = obj.find_all('strong', attrs={'data-e2e':'comment-count'})[0].text
        aweme_id = re.findall(r'aweme/detail/([0-9]+)', obj.__str__())[0]
        return cls(url, caption, comment, like, cover, aweme_id, username)

================================================
FILE: tiktok_downloader/server.py
================================================
from io import BytesIO
from flask import (
    Flask,
    request,
    render_template
)
from flask.wrappers import Response
from typing import List

from tiktok_downloader.scrapper_v2 import VideoInfoV2
from . import services
from .snaptik import Snaptik
from .scrapper import VideoInfo
from .utils import Download
import json
import os


app = Flask(
    __name__,
    template_folder=os.path.abspath(__file__+'/../templates'),
    static_folder=os.path.abspath(__file__+'/../static')
)


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/auto')
def auto():
    serv = services.copy()
    serv.pop('ssstik')
    try:
        if not request.args.get('url'):
            return Response(
                json.dumps(
                    {'msg': 'url parameter required'},
                    indent=4
                ),
                content_type='application/json'
            )
        for name, service in serv.items():
            try:
                b: List[Download] = service(request.args.get('url'))
                if request.args.get('type') in ['direct', 'embed']:
                    for video in filter(
                        lambda v: v.watermark and v.type == 'video',
                        b
                    ):
                        fvid = video.download()
                        if isinstance(fvid, BytesIO):
                            return Response(
                                fvid.getvalue(),
                                content_type='video/mp4'
                            )
                else:
                    return Response(
                        json.dumps(
                            list(
                                map(lambda x: {
                                    "url": x.json,
                                    "type": x.type,
                                    "service": name,
                                    "watermark": x.watermark
                                }, b)),
                            indent=4
                        ),
                        content_type='application/json'
                    )
            except Exception as e:
                return Response(
                        json.dumps(
                            {"error": str(e)},
                            indent=4),
                        content_type='application/json'
                    )
        return Response(json.dumps(
                {'msg': 'server busy'},
                indent=4
            ),
            content_type='application/json'
        )
    except Exception:
        return Response(json.dumps(
                {'msg': 'url is invalid'},
                indent=4
            ),
            content_type='application/json'
        )


@app.route('/<path:path>')
def snapt(path):
    if path == 'info':
        try:
            if not request.args.get('url'):
                return json.dumps(
                    {'msg': 'url parameter required'},
                    indent=4
                )
            if request.args.get('legacy'):
                resp = VideoInfo.get_info(request.args['url'])
                return Response(
                        json.dumps(
                            {'legacy': True, **resp.aweme},
                            indent=4
                        ),
                        content_type='application/json'
                    )
            else:
                resp = VideoInfoV2.get_info(request.args['url'])
                return Response(json.dumps({
                    'id': resp.aweme_id,
                    'author': resp.username,
                    'cover': resp.cover,
                    'caption': resp.caption
                }))
        except Exception as e:
            print(e)
            return Response(json.dumps({
                'msg': 'Url is invalid'
            }), headers={'Content-Type': 'application/json'})
    elif path not in services:
        return Response(
            json.dumps({'msg': 'Path Not Found'}, indent=4),
            status=404,
            content_type='application/json'
        )
    if request.args.get('url'):
        try:
            service = services.get(path, Snaptik)
            res = service(request.args['url'])
            if request.args.get('type') in ['embed', 'direct']:
                for i in res:
                    if i.type == 'video':
                        fvid = i.download()
                        if isinstance(fvid, BytesIO):
                            return Response(
                                fvid.getvalue(),
                                content_type='video/mp4'
                            )
            return Response(
                json.dumps(
                    [
                        {
                            'type': i.type,
                            'url': i.json,
                            'watermark': i.watermark
                        } for i in res
                    ],
                    indent=4
                ),
                headers={
                    'Content-Type': 'application/json'
                }
            )
        except Exception:
            return Response(
                json.dumps({
                    'msg': 'Url is invalid'
                }, indent=4),
                headers={'Content-Type': 'application/json'}
            )
    else:
        return json.dumps({'msg': 'url parameter required'}, indent=4)


================================================
FILE: tiktok_downloader/snaptik.py
================================================
import re
from bs4 import BeautifulSoup
from httpx import AsyncClient
from sys import stderr
from ast import literal_eval
import pyjsparser
from .utils import Download, DownloadAsync, Type, extension_to_type
from .Except import InvalidUrl
from requests import Session
from re import findall
from .decoder import decoder
import cloudscraper
from urllib.parse import urlparse


class Snaptik(Session):
    """
    :param tiktok_url:
    ```python
    >>> tik=snaptik('url')
    >>> tik.get_media()
    [<[type:video]>, <[type:video]>]
    ```
    """

    def __init__(self, tiktok_url: str) -> None:
        super().__init__()
        self.headers: dict[str, str] = {
            "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) "
            "AppleWebKit/537.36 (KHTML, like Gecko) "
            "Chrome/86.0.4240.111 Safari/537.36"
        }
        self.tiktok_url = tiktok_url

    def render(self, token, interval: int = 1):
        result = self.get('https://snaptik.app/render.php', params={'token': token}).json()
        while True:
            resp = self.get("https://snaptik.app/task.php", params={'token': result['task_id']}).json()
            if resp['progress'] == 100:
                return Download(resp['download_url'], self, Type.VIDEO) 
            
    def get_media(self) -> list[Download]:
        """
        ```python
        >>> <snaptik object>.get_media()
        [<[type:video]>, <[type:video]>]
        ```
        """
        result = []
        resp = cloudscraper.create_scraper().get(
            "https://snaptik.app/abc2.php",
            params={
                "url": self.tiktok_url,
                "lang": "en",
                **dict(
                    findall(
                        'name="(token)" value="(.*?)"',
                        self.get("https://snaptik.app/en").text,
                    )
                ),
            },
        )
        if "error_api_web;" in resp.text or "Error:" in resp.text:
            raise InvalidUrl()
        stderr.flush()
        dec = decoder(
            *literal_eval(findall(r"\(\".*?,.*?,.*?,.*?,.*?.*?\)", resp.text)[0])
        )
        dec = pyjsparser.parse(re.sub(r"(async|await)", "", dec))["body"][0][
            "consequent"
        ]["body"][0]["consequent"]["body"][1]["expression"]["right"]["value"]
        bs = BeautifulSoup(dec)
        for vl in  bs.find_all("div", attrs={"class","video-links"}):
            for a in vl.find_all("a"):
                result.append(Download(a["href"] if a['href'].startswith('http') else 'https://snaptik.app' + a['href'], self, Type.VIDEO))
            for button in vl.find_all("button"):
                try:
                    result.append(Download(button['data-backup'], self, Type.VIDEO))
                except KeyError:
                    result.append(Download('', self, Type.VIDEO, render=lambda invertal: self.render(button['data-token'])))
        result.extend(
            [
                Download(obj["href"], self, Type.IMAGE)
                for obj in bs.find_all(
                    "a", attrs={"data-event": "download_albumPhoto_photo"}
                )
            ]
        )
        return result

    def __iter__(self):
        yield from self.get_media()


class SnaptikAsync(AsyncClient):
    """
    :param tiktok_url:
    ```python
    >>> tik=snaptik('url')
    >>> tik.get_media()
    [<[type:video]>, <[type:video]>]
    ```
    """

    def __init__(self, tiktok_url: str) -> None:
        super().__init__()
        self.headers: dict[str, str] = {
            "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) "
            "AppleWebKit/537.36 (KHTML, like Gecko) "
            "Chrome/86.0.4240.111 Safari/537.36"
        }
        self.tiktok_url = tiktok_url

    async def get_media(self) -> list[DownloadAsync]:
        """
        ```python
        >>> <snaptik object>.get_media()
        [<[type:video]>, <[type:video]>]
        ```
        """
        resp = await self.get(
            "https://snaptik.app/abc2.php",
            params={
                "url": self.tiktok_url,
                "lang": "en",
                **dict(
                    findall(
                        'name="(token)" value="(.*?)"',
                        (await self.get("https://snaptik.app/en")).text,
                    )
                ),
            },
        )
        if "error_api_web;" in resp.text or "Error:" in resp.text:
            raise InvalidUrl()
        stderr.flush()
        dec = decoder(
            *literal_eval(findall(r"\(\".*?,.*?,.*?,.*?,.*?.*?\)", resp.text)[0])
        )

        stderr.flush()
        return [
            DownloadAsync(i, self)
            for i in set(
                [
                    "https://snaptik.app" + x.strip("\\")
                    for x in findall(r"(/file.php?.*?)\"", dec)
                ]
                + [i.strip("\\") for i in findall(r"\"(https?://snapxcdn.*?)\"", dec)]
            )
        ]

    async def __aiter__(self):
        return await self.get_media()


def snaptik(url: str):
    return Snaptik(url).get_media()


async def snaptik_async(url: str):
    return await SnaptikAsync(url).get_media()


================================================
FILE: tiktok_downloader/ssstik.py
================================================
from httpx import AsyncClient
from requests import Session
import re
from .utils import Download, DownloadAsync
from base64 import b64decode


class SsstikIO(Session):
    def get_media(self, url: str) -> list[Download]:
        ses = self.get('https://ssstik.io')
        resp = self.post(
            'https://ssstik.io/abc?url=dl', data={
                'id': url,
                'locale': 'en',
                'tt': re.findall(r'tt:\'([\w\d]+)\'', ses.text)[0],
            },
            headers={
                'hx-current-url': 'https://ssstik.io/id',
                'hx-request': 'true',
                'hx-target': 'target',
                'hx-trigger': '_gcaptcha_pt',
                'origin': 'https://ssstik.io',
                'pragma': 'no-cache',
                'referer': 'https://ssstik.io/id',
                'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="102", '
                '"Google Chrome";v="102"',
                'sec-ch-ua-mobile': '?0',
                'sec-ch-ua-platform': "Linux",
                'sec-fetch-dest': 'empty',
                'sec-fetch-mode': 'cors',
                'sec-fetch-site': 'same-origin',
                'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_13) '
                'AppleWebKit/537.36 (KHTML, like Gecko)'
                ' Chrome/102.0.5059.159 Safari/537.36'
                }
        )
        return [Download(
            res, self, [
                'video', 'music']['music' in res]
                ) for res in [(b64decode(
                    '/'.join(x.split('/')[5:])
                    ).decode() if 'ssscdn.io' in x else x
                    ) for x in set(re.findall('href="(.*?)"', resp.text))]]


class SsstikAIO(AsyncClient):
    async def get_media(self, url: str):
        ses = await self.get('https://ssstik.io', follow_redirects=True)
        resp = await self.post(
            'https://ssstik.io/abc?url=dl', data={
                'id': url,
                'locale': 'id',
                'tt': re.findall(r'tt:\'([\w\d]+)\'', ses.text)[0],
            },
            headers={
                'hx-current-url': 'https://ssstik.io/id',
                'hx-request': 'true',
                'hx-target': 'target',
                'hx-trigger': '_gcaptcha_pt',
                'origin': 'https://ssstik.io',
                'pragma': 'no-cache',
                'referer': 'https://ssstik.io/id',
                'sec-ch-ua': '" Not A;Brand";v="99", '
                '"Chromium";v="102", "Google Chrome";v="102"',
                'sec-ch-ua-mobile': '?0',
                'sec-ch-ua-platform': "Linux",
                'sec-fetch-dest': 'empty',
                'sec-fetch-mode': 'cors',
                'sec-fetch-site': 'same-origin',
                'user-agent': (
                    'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_13) '
                    'AppleWebKit/537.36 (KHTML, like Gecko) '
                    'Chrome/102.0.5059.159Safari/537.36')
                }
        )
        return [DownloadAsync(
            res,
            self,
            ['video', 'music']['music' in res]) for res in [(
                b64decode(
                    '/'.join(
                        x.split('/')[5:])).decode() if 'ssscdn.io' in x else x
                        ) for x in set(
                            re.findall('href="(.*?)"', resp.text))]]


def ssstik(url: str):
    return SsstikIO().get_media(url)


async def ssstik_async(url: str):
    return await SsstikAIO().get_media(url)


================================================
FILE: tiktok_downloader/static/script.js
================================================
      localStorage.mode = localStorage.mode || 'white';
      document.getElementById('mode').setAttribute('class', 'fas fa-'+(localStorage.mode === 'black'?'sun':'moon'));
      function mode(m){
        const text = (m === 'dark'|| m === 'black')?'white':'black';
        const bgcolor =(m === 'dark'|| m === 'black')?'black':'white';
        document.getElementsByTagName('body')[0].style.backgroundColor = bgcolor;
        document.getElementsByTagName('input')[0].style.borderColor = bgcolor==='black'?'#0D6EFD':'';
        document.getElementsByTagName('input')[0].style.backgroundColor=bgcolor;
        document.getElementsByTagName('input')[0].style.color=text;
        document.getElementsByTagName('img')[0].style.filter = bgcolor === 'black'?'invert(90%)':'';
        if(document.getElementsByClassName('card').length){          
          document.getElementsByClassName('card')[0].style.backgroundColor = bgcolor;
          document.getElementsByClassName('card')[0].style.borderColor = bgcolor === 'black'?'#0D6EFD':'';
          document.getElementsByTagName('p')[0].style.color = text;
        }
        localStorage.mode = bgcolor;
        document.getElementById('mode').setAttribute('class', 'fas fa-'+(localStorage.mode === 'black'?'sun':'moon'));
        document.getElementById('mode').style.color=(localStorage.mode === 'white'?'black':'white');
        document.getElementsByClassName('modal')[0].style.backgroundColor = localStorage.mode === 'black'?'rgba(0, 0, 0, .8)':'rgba( 255, 255, 255, .8 )'
      }
      document.getElementById('wrapMode').onclick = () => {
        mode(localStorage.mode==='black'?'white':'dark');
      }
      mode(localStorage.mode)
      document.getElementById('submitter').onclick = function(){
        $('body').addClass("loading");
        fetch('info?'+(new URLSearchParams({url: document.getElementById('tiktokurl').value})), {
          method: 'GET'
        }).then(async function (response){
          const data = await response.json();
          data.msg && Swal.fire({ icon: 'error', title: 'Oops...', text: data.msg, showConfirmButton: false})
          if(data.legacy){
            $(".emptydiv").empty().append(`
                <div class="row justify-content-center" id="downgrup" style="padding-bottom: 100px;">
                  <div class="card" style="width: 20 rem;background-color:${localStorage.mode === 'black'?'black; border-color: #0D6EFD':'white'}">
                    <video class="card-img-top" alt="..." poster="${data.aweme_detail.video.origin_cover.url_list[0]}" style="padding-top:7px;" controls>
                      <source src="${data.aweme_detail.video.play_addr.url_list[0]}" type="video/mp4">
                    </video>
                    
                    <div class="card-body">
                      <h5 class="card-title"><a href="https://www.tiktok.com/@${data.aweme_detail.author.unique_id}">${data.aweme_detail.author.unique_id}</a></h5>
                      <p class="card-text ${localStorage.mode === 'black'?'text-white':'text-black'}">${data.aweme_detail.desc}</p>
                    </div>
                    ${data.aweme_detail.video.play_addr.url_list.map(function(x){
                      return '<a href="'+x+'" target="_blank" class="btn btn-primary"> Video </a>&nbsp;';
                    }).join('')}
                    <a href="${data.aweme_detail.music.play_url.uri}" target="_blank" class="btn btn-primary mb-3"> Music </a>
                  </div>
              </div>
            `)
            $("body").removeClass("loading");
          }else{
            fetch('mdown?'+(new URLSearchParams({url: document.getElementById('tiktokurl').value})), {
              method: 'GET'
            }).then(async (resp) => {
              const dj = await resp.json()
              $(".emptydiv").empty().append(`
              <div class="row justify-content-center" id="downgrup" style="padding-bottom: 100px;">
                <div class="card" style="width: 20 rem;background-color:${localStorage.mode === 'black'?'black; border-color: #0D6EFD':'white'}">
                  <video class="card-img-top" alt="..." poster="${data.cover}" style="padding-top:7px;" controls>
                    <source src="${dj[0].url}" type="video/mp4">
                  </video>
                  
                  <div class="card-body">
                    <h5 class="card-title"><a href="https://www.tiktok.com/@${data.author}">${data.author}</a></h5>
                    <p class="card-text ${localStorage.mode === 'black'?'text-white':'text-black'}">${data.caption}</p>
                  </div>
                  ${dj.slice(1).map(function(x){
                    return '<a href="'+x+'" target="_blank" class="btn btn-primary"> Video </a>&nbsp;';
                  }).join('')}
                </div>
            </div>
          `)
          $("body").removeClass("loading");
            })
          }
        }).catch(function (err){
          $("body").removeClass("loading");
        })
      }

================================================
FILE: tiktok_downloader/templates/index.html
================================================
 <!-- krypton byte -->
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <title>Tiktok Downloader</title>
  </head>
  <body>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <div class="col-lg-6 offset-lg-3 " id='frm'>
        <div class="row justify-content-center">
          <div class="col-12" id="wrapMode">
            <i id="mode"></i>
          </div>
            <img src="{{ url_for('static', filename='tiktok.svg')}}" id="logo">
            <input type="text" class="form-control" placeholder="Tiktok Url" id="tiktokurl">
            <button class="btn btn-outline-primary my-1" id="submitter">Download</button>
        </div>
        <div class="emptydiv">

        </div>
    </div>
    <footer>
      <p class="copy" align="center"><a href='https://github.com/krypton-byte/tiktok-downloader'>@krypton-byte</a></p>
    </footer>
    <div class="modal"><!-- Place at bottom of page --></div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    <script src="{{ url_for('static', filename='script.js')}}"></script>
    <style>
      /* Start by setting display:none to make this hidden.
      Then we position it in relation to the viewport window
      with position:fixed. Width, height, top and left speak
      for themselves. Background we set to 80% white with
      our animation centered, and no-repeating */
    .modal {
        display:    none;
        position:   fixed;
        z-index:    1000;
        top:        0;
        left:       0;
        height:     100%;
        width:      100%;
        background: rgba( 255, 255, 255, .8 ) 
                    url("{{ url_for('static', filename='loading.svg')}}") 
                    50% 50% 
                    no-repeat;
    }
    /* When the body has the loading class, we turn
      the scrollbar off with overflow:hidden */
    body.loading .modal {
        overflow: hidden;   
    }
    #mode {
      position: absolute;
      right: 20px;
      top: 20px;
      font-size: 30px;
    }
    /* Anytime the body has the loading class, our
      modal element will be visible */
    body.loading .modal {
        display: block;
    }
    #frm {
        padding-left: 50px;
        padding-right: 50px;
    }
    #downgrup {
        padding-top: 100px;
    }
    footer {
      position: relative;
      height: 400px;
      width: 100%;
    }
    footer > .copy {
        position: absolute;
        width: 100%;
        line-height: 40px;
        text-align: center;
        bottom:0;
    }
    </style>
  </body>
</html>

================================================
FILE: tiktok_downloader/test.py
================================================
import unittest
from .scrapper import VideoInfo
from .snaptik import snaptik
from .tikmate import tikmate
from .mdown import mdown


class TikTok(unittest.TestCase):
    base_url = ('https://www.tiktok.com/' +
                '@tribunsumselcom/' +
                'video/7020708969563917595')

    def test_snaptk(self):
        self.assertTrue(bool(snaptik(self.base_url)))

    def test_info(self):
        self.assertTrue(bool(VideoInfo.get_info(self.base_url)))

    def tikmat(self):
        self.assertTrue(bool(tikmate(self.base_url)))

    def mdown_(self):
        self.assertTrue(bool(mdown(self.base_url)))


if __name__ == '__main__':
    unittest.main()


================================================
FILE: tiktok_downloader/tikdown.py
================================================
from httpx import AsyncClient
from requests import Session
import re
from .utils import DownloadAsync, Download


class Tikdown(Session):
    BASE_URL = 'https://tikdown.org/'
    headers: dict[str, str] = {
        "origin": 'https://tikdown.org',
        "referer": 'https://tikdown.org/',
        "sec-ch-ua": '"Chromium";v="94", '
        '"Google Chrome";v="94", ";Not A Brand";v="99"',
        "sec-ch-ua-mobile": '?0',
        "sec-ch-ua-platform": '"Linux"',
        "sec-fetch-dest": 'empty',
        "sec-fetch-mode": 'cors',
        "sec-fetch-site": 'same-origin',
        "user-agent": 'Mozilla/5.0 (X11; Linux x86_64) '
        'AppleWebKit/537.36 (KHTML, like Gecko) '
        'Chrome/94.0.4606.81 Safari/537.36',
        "x-requested-with": 'XMLHttpRequest'
    }

    def __init__(self, url: str) -> None:
        super().__init__()
        self.url = url

    def get_media(self) -> list[Download]:
        res = self.get(self.BASE_URL)
        _token = re.findall(
            r'type\="hidden".*?value\="([0-9a-zA-Z]+)"',
            res.text
        )[0]
        self.headers.update({'x-csrf-token': _token})
        js = self.post(self.BASE_URL+'getAjax', data={
            'url': self.url,
            '_token': _token
        }).json()
        if js.get('status'):
            video = re.findall(
                r'\"(https?://.*?\.mp4)\"',
                js['html']
            )[0]
            return [Download(video, self)]
        return []


class TikdownAsync(AsyncClient):
    BASE_URL = 'https://tikdown.org/'
    headers: dict[str, str] = {
        "origin": 'https://tikdown.org',
        "referer": 'https://tikdown.org/',
        "sec-ch-ua": '"Chromium";v="94", '
        '"Google Chrome";v="94", ";Not A Brand";v="99"',
        "sec-ch-ua-mobile": '?0',
        "sec-ch-ua-platform": '"Linux"',
        "sec-fetch-dest": 'empty',
        "sec-fetch-mode": 'cors',
        "sec-fetch-site": 'same-origin',
        "user-agent": 'Mozilla/5.0 (X11; Linux x86_64) '
        'AppleWebKit/537.36 (KHTML, like Gecko) '
        'Chrome/94.0.4606.81 Safari/537.36',
        "x-requested-with": 'XMLHttpRequest'
    }

    def __init__(self, url: str) -> None:
        super().__init__()
        self.url = url

    async def get_media(self) -> list[DownloadAsync]:
        res = await self.get(self.BASE_URL)
        _token = re.findall(
            r'type\="hidden".*?value\="([0-9a-zA-Z]+)"',
            res.text
        )[0]
        self.headers.update({'x-csrf-token': _token})
        js = (await self.post(self.BASE_URL+'getAjax', data={
            'url': self.url,
            '_token': _token
        })).json()
        if js.get('status'):
            video = re.findall(
                r'\"(https?://.*?\.mp4)\"',
                js['html']
            )[0]
            return [DownloadAsync(video, self)]
        return []


def tikdown(url: str):
    return Tikdown(url).get_media()


async def tikdown_async(url: str):
    return await TikdownAsync(url).get_media()


================================================
FILE: tiktok_downloader/tikmate.py
================================================
from typing import Generator
from httpx import AsyncClient
from requests.models import InvalidURL
from .decoder import decoder
from .utils import Download, DownloadAsync
from ast import literal_eval
import re
from base64 import b64decode
import requests
import json
import aiohttp



def decodeJWT(resp: str) -> Generator[dict[str, str], None, None]:
    urls = re.findall('https?://snap[\w./?=.&\-]+', resp)
    for i in urls:
        token: str = re.search(r'token=(.*?)&', i).group(0)
        yield {'filename':'tiktok.'+['mp4','mp3'][b'.mp3' in b64decode(token.split('.')[1] + '==========')], 'url': i}
class Tikmate(requests.Session):
    BASE_URL = 'https://tikmate.online/'

    def __init__(self) -> None:
        super().__init__()
        self.headers: dict[str, str] = {
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) '
            'AppleWebKit/537.36 (KHTML, like Gecko) '
            'Chrome/86.0.4240.111 Safari/537.36'
        }

    def get_media(self, url: str) -> list[Download]:
        media = self.post(
            self.BASE_URL+'abc.php',
            data={'url': url, **dict(re.findall(
                'name="(token)" value="(.*?)"', self.get(
                    'https://tikmate.online/?lang=id').text))},
            headers={
                "origin": "https://tikmate.online",
                "referer": "https://tikmate.online/",
                "sec-ch-ua": '"Chromium";v="94",\
                    "Google Chrome";v="94", \
                    ";Not A Brand";v="99"',
                "sec-ch-ua-mobile": "?0",
                "sec-ch-ua-platform": "Linux",
                "sec-fetch-dest": "iframe",
                "sec-fetch-mode": "navigate",
                "sec-fetch-site": "same-origin",
                "sec-fetch-user": "?1",
                "upgrade-insecure-requests": "1",
                "user-agent": "Mozilla/5.0 (X11; Linux x86_64) "
                "AppleWebKit/537.36 (KHTML, like Gecko) "
                "Chrome/94.0.4606.81 Safari/537.36"
                }
        )
        if "'error_api_get'" in media.text:
            raise InvalidURL()
        tt = re.findall(r'\(\".*?,.*?,.*?,.*?,.*?.*?\)', media.text)
        decode = decodeJWT(decoder(*literal_eval(tt[0])))
        return [
            Download(
                x['url'],
                self,
                type=(['video', 'music'][x['filename'].endswith(
                    '.mp3')])) for x in decode
        ]


class TikmateAsync(AsyncClient):
    BASE_URL = 'https://tikmate.online/'

    def __init__(self) -> None:
        super().__init__()
        self.headers: dict[str, str] = {
            "referer": "https://tikmate.online/",
            "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) "
            "AppleWebKit/537.36 (KHTML, like Gecko) "
            "Chrome/94.0.4606.81 Safari/537.36"
        }

    async def get_media(self, url: str) -> list[DownloadAsync]:
        async with aiohttp.ClientSession() as session:
            async with session.post(
                self.BASE_URL+'abc.php',
                data={'url': url, **dict(re.findall(
                    'name="(token)" value="(.*?)"', (
                        await self.get(self.BASE_URL)).text))},
                headers={
                    "Origin": "https://tikmate.online",
                    "sec-ch-ua-mobile": "?0",
                    "sec-ch-ua-platform": "Linux",
                    "sec-fetch-dest": "iframe",
                    "sec-fetch-site": "same-origin",
                    "sec-fetch-user": "?1",
                    "upgrade-insecure-requests": "1",
                    'sec-fetch-mode': 'cors',
                    'sec-fetch-site': 'same-origin',
                    'x-requested-with': 'XMLHttpRequest',
                    **self.headers
                }
            ) as media:
                text = await media.text()
                if "'error_api_get'" in text:
                    raise InvalidURL()
                tt = re.findall(r'\(\".*?,.*?,.*?,.*?,.*?.*?\)', text)
                decode = decodeJWT(decoder(*literal_eval(tt[0])))
                return [
                    DownloadAsync(
                        x['url'],
                        self,
                        type=(['video', 'music'][x['filename'].endswith(
                            '.mp3')])) for x in decode
                ]


def tikmate(url: str):
    return Tikmate().get_media(url)


async def tikmate_async(url: str):
    return await tikmateAsync().get_media(url)


================================================
FILE: tiktok_downloader/tiktok_async.py
================================================
from .scrapper import VideoInfoAsync
from .mdown import MdownAsync, mdown_async
from .snaptik import SnaptikAsync, snaptik_async
from .ssstik import SsstikAIO, ssstik_async
from .tikdown import TikdownAsync, tikdown_async
from .tikmate import tikmateAsync, tikmate_async
from .ttdownloader import TTDownloaderAsync, ttdownloader_async


__all__ = [
    'VideoInfoAsync',
    'MdownAsync',
    'mdown_async',
    'SnaptikAsync',
    'snaptik_async',
    'SsstikAIO',
    'ssstik_async',
    'TikdownAsync',
    'tikdown_async',
    'tikmateAsync',
    'tikmate_async',
    'TTDownloaderAsync',
    'ttdownloader_async'
]


================================================
FILE: tiktok_downloader/tikwm.py
================================================
from httpx import AsyncClient
from requests import Session
from requests.models import InvalidURL
from .utils import Download, DownloadAsync


class TikWM(Session):
    BASE_URL = 'https://www.tikwm.com'

    def __init__(self, url: str) -> None:
        super().__init__()
        self.url = url

    def get_media(self) -> list[Download]:
        req = self.post(self.BASE_URL + '/api/', data=dict(url=self.url, count=12, cursor=0, web=1, hd=1))
        res = req.json()
        if res['code'] == 0:
            return [
                Download(
                    self.BASE_URL + res['data'].get('hdplay', res['data']['play']),
                    self,
                    'video'
                ),
                Download(
                    self.BASE_URL + res['data']['wmplay'],
                    self,
                    'video',
                    True
                ),
                Download(
                    self.BASE_URL + res['data']['music'],
                    self,
                    'music'
                )
            ]
        else:
            raise InvalidURL(res['msg'])


class TikWMAsync(AsyncClient):
    BASE_URL = 'https://www.tikwm.com'

    def __init__(self, url: str) -> None:
        super().__init__()
        self.url = url

    async def get_media(self) -> list[DownloadAsync]:
        req = await self.post(self.BASE_URL + '/api/', data=dict(url=self.url, count=12, cursor=0, web=1, hd=1))
        res = req.json()
        if res['code'] == 0:
            return [
                DownloadAsync(
                    self.BASE_URL + res['data'].get('hdplay', res['data']['play']),
                    self,
                    'video'
                ),
                DownloadAsync(
                    self.BASE_URL + res['data']['wmplay'],
                    self,
                    'video',
                    True
                ),
                DownloadAsync(
                    self.BASE_URL + res['data']['music'],
                    self,
                    'music'
                )
            ]
        else:
            raise InvalidURL(res['msg'])


def tikwm(url: str) -> list[Download]:
    return TikWM(url).get_media()


async def tikwm_async(url: str) -> list[DownloadAsync]:
    return await TikWMAsync(url).get_media()

================================================
FILE: tiktok_downloader/ttdownloader.py
================================================
from httpx import AsyncClient
from requests import Session
import re
from .utils import Download, DownloadAsync


class TTDownloader(Session):
    BASE_URL = 'https://ttdownloader.com/'

    def __init__(self, url: str) -> None:
        super().__init__()
        self.headers: dict[str, str] = {
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) '
            'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 '
            'Safari/537.36',
            'origin': 'https://ttdownloader.com',
            'referer': 'https://ttdownloader.com/',
            'sec-ch-ua': '"Chromium";v="94",'
            '"Google Chrome";v="94", ";'
            'Not A Brand";v="99"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': "Linux",
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin',
            'x-requested-with': 'XMLHttpRequest'
        }
        self.url = url

    def get_media(self) -> list[Download]:
        indexsource = self.get(self.BASE_URL)
        token = re.findall(r'value=\"([0-9a-z]+)\"', indexsource.text)
        result = self.post(
            self.BASE_URL+'search/',
            data={'url': self.url, 'format': '', 'token': token[0]}
        )
        nowm, wm, audio = re.findall(
            r'(https?://.*?.php\?v\=.*?)\"', result.text
        )
        return [
            Download(nowm, self, 'video'),
            Download(wm, self, 'video', True),
            Download(audio, self, 'music')
        ]


class TTDownloaderAsync(AsyncClient):
    BASE_URL = 'https://ttdownloader.com/'

    def __init__(self, url: str) -> None:
        super().__init__()
        self.headers: dict[str, str] = {
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) '
            'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 '
            'Safari/537.36',
            'origin': 'https://ttdownloader.com',
            'referer': 'https://ttdownloader.com/',
            'sec-ch-ua': '"Chromium";v="94",'
            '"Google Chrome";v="94", ";'
            'Not A Brand";v="99"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': "Linux",
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin',
            'x-requested-with': 'XMLHttpRequest'
        }
        self.url = url

    async def get_media(self) -> list[DownloadAsync]:
        indexsource = await self.get(self.BASE_URL, follow_redirects=True)
        token = re.findall(r'value=\"([0-9a-z]+)\"', indexsource.text)
        result = await self.post(
            self.BASE_URL+'search/',
            data={'url': self.url, 'format': '', 'token': token[0]},
            follow_redirects=True
        )
        nowm, wm, audio = re.findall(
            r'(https?://.*?.php\?v\=.*?)\"', result.text
        )
        return [
            DownloadAsync(nowm, self, 'video'),
            DownloadAsync(wm, self, 'video', True),
            DownloadAsync(audio, self, 'music')
        ]


def ttdownloader(url: str) -> list[Download]:
    return TTDownloader(url).get_media()


async def ttdownloader_async(url: str):
    return await TTDownloaderAsync(url).get_media()


================================================
FILE: tiktok_downloader/utils.py
================================================
from __future__ import annotations
import asyncio
import httpx
from PIL import Image
from moviepy.video.VideoClip import tempfile
import numpy as np
from io import BytesIO
from typing import Callable, List, Optional, Union
from moviepy.audio.AudioClip import concatenate_audioclips
from requests import Session
from warnings import simplefilter
from io import BufferedWriter
from enum import Enum
from moviepy.editor import (
    CompositeAudioClip,
    ImageClip,
    AudioFileClip,
    CompositeVideoClip,
    VideoClip,
    concatenate_videoclips,
    transfx,
)
import re
from tiktok_downloader.Except import NoImageToSlideshow
from concurrent.futures import ThreadPoolExecutor

simplefilter("ignore")

def extension_to_type(filename: str):
    if re.search(r'\.mp3$', filename):
        return Type.AUDIO
    elif re.search(r'\.jpg$', filename):
        return Type.IMAGE
    elif re.search(r'\.mp4$', filename):
        return Type.VIDEO
    raise ValueError()

class Type(Enum):
    IMAGE = "IMAGE"
    VIDEO = "VIDEO"
    AUDIO = "AUDIO"
    SLIDESHOW = "SLIDESHOW"


class DownloadCallback:
    def __init__(self) -> None:
        self.finished = False

    async def on_open(
        self, client: httpx.AsyncClient, response: httpx.Response, info: DownloadAsync
    ):
        raise NotImplementedError()

    async def on_progress(self, binaries: bytes):
        raise NotImplementedError()

    async def on_finish(self, client: httpx.AsyncClient, response: httpx.Response):
        raise NotImplementedError()


def render_from_images(
    images: List[str | BytesIO], audio_file: str, outfile: str, fps: int = 30, *args, **kwargs
):
    img_pil = []
    max_height = 0
    max_width = 0
    for img in images:
        _img = Image.open(img).convert("RGB")
        if _img.height > max_height:
            max_height = _img.height
        if _img.width > max_width:
            max_width = _img.height
        img_pil.append(_img)
    new_img = Image.new("RGB", (max_width, max_height), (255, 255, 255))
    for idx, img in enumerate(img_pil):
        new_frame = new_img.copy()
        new_frame.paste(
            img, ((max_width - img.width) // 2, (max_height - img.height) // 2)
        )
        img_pil[idx] = new_frame
    audio = AudioFileClip(audio_file)
    duration_clip = audio.duration / images.__len__()
    frames = [ImageClip(np.array(im), duration=duration_clip) for im in img_pil]
    video = concatenate_videoclips(frames)
    video.set_audio(audio)
    video.audio = CompositeAudioClip([audio])
    video.write_videofile(filename=outfile, fps=fps, *args, **kwargs)


class RenderImageToSlidshow:
    def __init__(self, download: List[DownloadAsync] | List[Download]) -> None:
        self.list_image = [i for i in download if i.type == Type.IMAGE]
        self.audio = [i for i in download if i.type == Type.AUDIO][0]
        if not self.list_image:
            raise NoImageToSlideshow()

    def render(self, outfile: str,worker: int = 2):
        with ThreadPoolExecutor(max_workers=worker) as thread:
            result = list(thread.map(lambda x: x.download(BytesIO()), self.list_image))
            with tempfile.TemporaryFile(mode='wb', delete=True) as file:
                self.audio.download(file)
                file.close()
                render_from_images(result, file.name, outfile=outfile)

                
    async def render_async(self, image,executor: Optional[ThreadPoolExecutor] = None):
        new_loop = asyncio.new_event_loop()
        result = []
        futures =[]
        for d in self.list_image:
            result.append(BytesIO())
            futures.append(d.download(result[-1]))
        await asyncio.gather(*futures)
        with tempfile.TemporaryFile(mode="wb", delete=True) as file:
            self.audio.download(file)
            return await new_loop.run_in_executor(executor, render_from_images, (result, file.name))


class DownloadAsync:
    def __init__(
        self,
        url: str,
        Session: httpx.AsyncClient,
        type=Type.VIDEO,
        watermark: bool = False,
    ) -> None:
        self.json = url
        self.type = type
        self.Session = Session
        self.watermark = watermark

    async def get_size(self) -> int:
        return int(
            (await self.Session.stream("GET", self.json).__aenter__()).headers[
                "Content-Length"
            ]
        )

    async def download(
        self,
        out: Optional[Union[str, BufferedWriter, DownloadCallback]] = None,
        chunk_size=1024 * 1024,
    ) -> Union[None, BytesIO, BufferedWriter, DownloadCallback]:
        async with self.Session.stream("GET", self.json) as request:
            if isinstance(out, DownloadCallback):
                await out.on_open(self.Session, request, self)
            stream = (
                out
                if isinstance(out, BufferedWriter)
                else (open(out, "wb") if isinstance(out, str) else BytesIO())
            )
            if isinstance(out, DownloadCallback):
                tasks = []
                async for i in request.aiter_bytes(chunk_size):
                    tasks.append(asyncio.ensure_future(out.on_progress(i)))
                await asyncio.gather(*tasks)
            else:
                async for i in request.aiter_bytes(chunk_size):
                    stream.write(i)
            if isinstance(out, DownloadCallback):
                out.finished = True
                await out.on_finish(self.Session, request)
            return (
                None
                if isinstance(out, (str, BufferedWriter))
                else out
                if isinstance(out, DownloadCallback)
                else stream
            )

    def __str__(self) -> str:
        return f'<type: "{self.type.value}" watermark:"{self.watermark}">'

    def __repr__(self) -> str:
        return self.__str__()


class Download:
    def __init__(
        self, url: str, Session: Session, type=Type.VIDEO, render: Optional[Callable] = None, watermark: bool = False
    ) -> None:
        self.json = url
        self.type = type
        self.render = render
        self.Session = Session
        self.watermark = watermark
    def get_render(self, interval: int = 1) -> Download | None:
        if self.render:
            return self.render(interval)
    def get_size(self) -> int:
        return int(self.Session.get(self.json, stream=True).headers["Content-Length"])

    def download(
        self,
        out: Optional[Union[str, BufferedWriter]] = None,
        chunk_size=1024,
        bar=False,
    ) -> Union[None, BytesIO, BufferedWriter]:
        request = self.Session.get(self.json, stream=True)
        stream = (
            out
            if isinstance(out, BufferedWriter)
            else (open(out, "wb") if isinstance(out, str) else BytesIO())
        )
        for i in request.iter_content(chunk_size):
            stream.write(i)
        return None if isinstance(out, (str, BufferedWriter)) else stream

    def __str__(self) -> str:
        return f'<[type: "{self.type}" watermark: "{self.watermark}" render: "{bool(self.render)}">' 

    def __repr__(self) -> str:
        return self.__str__()
Download .txt
gitextract_la14e1v6/

├── .deepsource.toml
├── .github/
│   └── workflows/
│       ├── python-publish.yml
│       └── unittest.yml
├── .gitignore
├── MANIFEST
├── MANIFEST.in
├── Procfile
├── README.md
├── app.json
├── license
├── pyproject.toml
├── requirements.txt
├── resetup.py
├── setup.py
└── tiktok_downloader/
    ├── Except.py
    ├── __init__.py
    ├── __main__.py
    ├── decoder.js
    ├── decoder.py
    ├── mdown.py
    ├── scrapper.py
    ├── scrapper_v2.py
    ├── server.py
    ├── snaptik.py
    ├── ssstik.py
    ├── static/
    │   └── script.js
    ├── templates/
    │   └── index.html
    ├── test.py
    ├── tikdown.py
    ├── tikmate.py
    ├── tiktok_async.py
    ├── tikwm.py
    ├── ttdownloader.py
    └── utils.py
Download .txt
SYMBOL INDEX (125 symbols across 17 files)

FILE: tiktok_downloader/Except.py
  class InvalidUrl (line 1) | class InvalidUrl(Exception):
  class NoImageToSlideshow (line 4) | class NoImageToSlideshow(Exception):

FILE: tiktok_downloader/__main__.py
  function info (line 68) | def info(url: str, js: Optional[bool] = False):

FILE: tiktok_downloader/decoder.js
  function _0xe48c (line 19) | function _0xe48c(d, e, f) {
  function decoder (line 37) | function decoder(h, u, n, t, e, r) {

FILE: tiktok_downloader/decoder.py
  function search (line 10) | def search(d: Union[str, list], q: str):
  function main (line 17) | def main(d, e, f):
  function from_string (line 33) | def from_string(text: str):
  function reduces (line 41) | def reduces(function, iterable, initializer=None) -> int:
  function decoder (line 56) | def decoder(h, u, n, t, e, r):

FILE: tiktok_downloader/mdown.py
  class Mdown (line 8) | class Mdown(requests.Session):
    method __init__ (line 11) | def __init__(self) -> None:
    method get_media (line 18) | def get_media(self, url: str):
  class MdownAsync (line 61) | class MdownAsync(AsyncClient):
    method __init__ (line 64) | def __init__(self) -> None:
    method get_media (line 71) | async def get_media(self, url: str):
  function mdown (line 115) | def mdown(url: str):
  function mdown_async (line 119) | async def mdown_async(url: str):

FILE: tiktok_downloader/scrapper.py
  function extract_id (line 14) | def extract_id(
  class Author (line 34) | class Author:
    method __init__ (line 35) | def __init__(self, ascp: dict):
    method __repr__ (line 46) | def __repr__(self):
  class VideoInfoAsync (line 50) | class VideoInfoAsync(AsyncClient):
    method __init__ (line 51) | def __init__(self, js: dict, id: str):
    method url_to_id (line 78) | async def url_to_id(cls, url: str, client: AsyncClient):
    method get_info (line 89) | async def get_info(cls, url: str):
    method downloadLink (line 96) | def downloadLink(self, watermark: bool = False) -> str:
    method utils (line 101) | def utils(self) -> list[DownloadAsync]:
    method __repr__ (line 114) | def __repr__(self):
  class VideoInfo (line 118) | class VideoInfo(Session):
    method __init__ (line 119) | def __init__(self, js: dict, id: str):
    method get_info (line 147) | def get_info(cls, id: str) -> VideoInfo:
    method utils (line 153) | def utils(self) -> list[Download]:
    method service (line 167) | def service(cls, url: str) -> list[Download]:
    method downloadLink (line 170) | def downloadLink(self, watermark: bool = False) -> str:
    method download (line 175) | def download(
    method download_music (line 187) | def download_music(
    method __repr__ (line 200) | def __repr__(self):

FILE: tiktok_downloader/scrapper_v2.py
  class VideoInfoV2 (line 8) | class VideoInfoV2:
    method get_info (line 18) | def get_info(cls, url: str) -> VideoInfoV2:
    method get_info_async (line 34) | async def get_info_async(cls, url: str):

FILE: tiktok_downloader/server.py
  function index (line 27) | def index():
  function auto (line 32) | def auto():
  function snapt (line 95) | def snapt(path):

FILE: tiktok_downloader/snaptik.py
  class Snaptik (line 16) | class Snaptik(Session):
    method __init__ (line 26) | def __init__(self, tiktok_url: str) -> None:
    method render (line 35) | def render(self, token, interval: int = 1):
    method get_media (line 42) | def get_media(self) -> list[Download]:
    method __iter__ (line 91) | def __iter__(self):
  class SnaptikAsync (line 95) | class SnaptikAsync(AsyncClient):
    method __init__ (line 105) | def __init__(self, tiktok_url: str) -> None:
    method get_media (line 114) | async def get_media(self) -> list[DownloadAsync]:
    method __aiter__ (line 153) | async def __aiter__(self):
  function snaptik (line 157) | def snaptik(url: str):
  function snaptik_async (line 161) | async def snaptik_async(url: str):

FILE: tiktok_downloader/ssstik.py
  class SsstikIO (line 8) | class SsstikIO(Session):
    method get_media (line 9) | def get_media(self, url: str) -> list[Download]:
  class SsstikAIO (line 46) | class SsstikAIO(AsyncClient):
    method get_media (line 47) | async def get_media(self, url: str):
  function ssstik (line 87) | def ssstik(url: str):
  function ssstik_async (line 91) | async def ssstik_async(url: str):

FILE: tiktok_downloader/static/script.js
  function mode (line 3) | function mode(m){

FILE: tiktok_downloader/test.py
  class TikTok (line 8) | class TikTok(unittest.TestCase):
    method test_snaptk (line 13) | def test_snaptk(self):
    method test_info (line 16) | def test_info(self):
    method tikmat (line 19) | def tikmat(self):
    method mdown_ (line 22) | def mdown_(self):

FILE: tiktok_downloader/tikdown.py
  class Tikdown (line 7) | class Tikdown(Session):
    method __init__ (line 25) | def __init__(self, url: str) -> None:
    method get_media (line 29) | def get_media(self) -> list[Download]:
  class TikdownAsync (line 49) | class TikdownAsync(AsyncClient):
    method __init__ (line 67) | def __init__(self, url: str) -> None:
    method get_media (line 71) | async def get_media(self) -> list[DownloadAsync]:
  function tikdown (line 91) | def tikdown(url: str):
  function tikdown_async (line 95) | async def tikdown_async(url: str):

FILE: tiktok_downloader/tikmate.py
  function decodeJWT (line 15) | def decodeJWT(resp: str) -> Generator[dict[str, str], None, None]:
  class Tikmate (line 20) | class Tikmate(requests.Session):
    method __init__ (line 23) | def __init__(self) -> None:
    method get_media (line 31) | def get_media(self, url: str) -> list[Download]:
  class TikmateAsync (line 68) | class TikmateAsync(AsyncClient):
    method __init__ (line 71) | def __init__(self) -> None:
    method get_media (line 80) | async def get_media(self, url: str) -> list[DownloadAsync]:
  function tikmate (line 115) | def tikmate(url: str):
  function tikmate_async (line 119) | async def tikmate_async(url: str):

FILE: tiktok_downloader/tikwm.py
  class TikWM (line 7) | class TikWM(Session):
    method __init__ (line 10) | def __init__(self, url: str) -> None:
    method get_media (line 14) | def get_media(self) -> list[Download]:
  class TikWMAsync (line 40) | class TikWMAsync(AsyncClient):
    method __init__ (line 43) | def __init__(self, url: str) -> None:
    method get_media (line 47) | async def get_media(self) -> list[DownloadAsync]:
  function tikwm (line 73) | def tikwm(url: str) -> list[Download]:
  function tikwm_async (line 77) | async def tikwm_async(url: str) -> list[DownloadAsync]:

FILE: tiktok_downloader/ttdownloader.py
  class TTDownloader (line 7) | class TTDownloader(Session):
    method __init__ (line 10) | def __init__(self, url: str) -> None:
    method get_media (line 30) | def get_media(self) -> list[Download]:
  class TTDownloaderAsync (line 47) | class TTDownloaderAsync(AsyncClient):
    method __init__ (line 50) | def __init__(self, url: str) -> None:
    method get_media (line 70) | async def get_media(self) -> list[DownloadAsync]:
  function ttdownloader (line 88) | def ttdownloader(url: str) -> list[Download]:
  function ttdownloader_async (line 92) | async def ttdownloader_async(url: str):

FILE: tiktok_downloader/utils.py
  function extension_to_type (line 29) | def extension_to_type(filename: str):
  class Type (line 38) | class Type(Enum):
  class DownloadCallback (line 45) | class DownloadCallback:
    method __init__ (line 46) | def __init__(self) -> None:
    method on_open (line 49) | async def on_open(
    method on_progress (line 54) | async def on_progress(self, binaries: bytes):
    method on_finish (line 57) | async def on_finish(self, client: httpx.AsyncClient, response: httpx.R...
  function render_from_images (line 61) | def render_from_images(
  class RenderImageToSlidshow (line 90) | class RenderImageToSlidshow:
    method __init__ (line 91) | def __init__(self, download: List[DownloadAsync] | List[Download]) -> ...
    method render (line 97) | def render(self, outfile: str,worker: int = 2):
    method render_async (line 106) | async def render_async(self, image,executor: Optional[ThreadPoolExecut...
  class DownloadAsync (line 119) | class DownloadAsync:
    method __init__ (line 120) | def __init__(
    method get_size (line 132) | async def get_size(self) -> int:
    method download (line 139) | async def download(
    method __str__ (line 171) | def __str__(self) -> str:
    method __repr__ (line 174) | def __repr__(self) -> str:
  class Download (line 178) | class Download:
    method __init__ (line 179) | def __init__(
    method get_render (line 187) | def get_render(self, interval: int = 1) -> Download | None:
    method get_size (line 190) | def get_size(self) -> int:
    method download (line 193) | def download(
    method __str__ (line 209) | def __str__(self) -> str:
    method __repr__ (line 212) | def __repr__(self) -> str:
Condensed preview — 34 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (116K chars).
[
  {
    "path": ".deepsource.toml",
    "chars": 155,
    "preview": "version = 1\n\n[[analyzers]]\nname = \"python\"\nenabled = true\n\n  [analyzers.meta]\n  runtime_version = \"3.x.x\"\n\n[[analyzers]]"
  },
  {
    "path": ".github/workflows/python-publish.yml",
    "chars": 793,
    "preview": "name: Upload to PyPi\n\non:\n  release:\n    types:\n      - published\n\njobs:\n  build:\n    runs-on: ubuntu-latest\n    steps:\n"
  },
  {
    "path": ".github/workflows/unittest.yml",
    "chars": 860,
    "preview": "# This workflow will upload a Python Package using Twine when a release is created\n# For more information see: https://h"
  },
  {
    "path": ".gitignore",
    "chars": 62,
    "preview": "dist\nbuild\n.mypy_cache\n*.egg-info\nenv/\n__pycache__*\ncookie.txt"
  },
  {
    "path": "MANIFEST",
    "chars": 199,
    "preview": "# file GENERATED by distutils, do NOT edit\nsetup.py\ntiktok_downloader/Except.py\ntiktok_downloader/__init__.py\ntiktok_dow"
  },
  {
    "path": "MANIFEST.in",
    "chars": 125,
    "preview": "include README.md\ninclude tiktok_downloader/static/*\ninclude tiktok_downloader/templates/*\nrecursive-include templates s"
  },
  {
    "path": "Procfile",
    "chars": 71,
    "preview": "web: python -m tiktok_downloader --server --host=0.0.0.0 --port=${PORT}"
  },
  {
    "path": "README.md",
    "chars": 5950,
    "preview": "<p align=\"center\">\n<img src=\"tiktok_downloader/static/tiktok.svg\"><br>\n<img src=\"https://img.shields.io/badge/AUTHOR-KRY"
  },
  {
    "path": "app.json",
    "chars": 331,
    "preview": "{\n    \"name\":\"Tiktok Downloader\",\n    \"description\":\" Without Watermark Lightweight & No Ads (Open Source)\",\n    \"stack\""
  },
  {
    "path": "license",
    "chars": 35149,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "pyproject.toml",
    "chars": 498,
    "preview": "[tool.poetry]\nname = \"tiktok-downloader\"\nversion = \"0.1.0\"\ndescription = \"tiktok downloader\"\nauthors = [\"krypton-byte <r"
  },
  {
    "path": "requirements.txt",
    "chars": 74,
    "preview": "bs4\nflask\ncloudscraper\nrequests\ntqdm\nrich\nhttpx\naiohttp\nmoviepy\npyjsparser"
  },
  {
    "path": "resetup.py",
    "chars": 356,
    "preview": "import argparse\nimport re\narg = argparse.ArgumentParser()\narg.add_argument('--version', type=str)\nargs = arg.parse_args("
  },
  {
    "path": "setup.py",
    "chars": 967,
    "preview": "\nfrom setuptools import setup\nfrom os import path\nbase_dir = path.abspath(path.dirname(__file__))\nsetup(\n  name='tiktok_"
  },
  {
    "path": "tiktok_downloader/Except.py",
    "chars": 84,
    "preview": "class InvalidUrl(Exception):\n    pass\n\nclass NoImageToSlideshow(Exception):\n    pass"
  },
  {
    "path": "tiktok_downloader/__init__.py",
    "chars": 781,
    "preview": "from .snaptik import snaptik, Snaptik\nfrom .ssstik import ssstik\nfrom .scrapper import VideoInfo\nfrom .tikmate import ti"
  },
  {
    "path": "tiktok_downloader/__main__.py",
    "chars": 4095,
    "preview": "import argparse\nimport json\nimport os\nimport sys\nimport requests\nfrom . import services\nfrom .scrapper import VideoInfo\n"
  },
  {
    "path": "tiktok_downloader/decoder.js",
    "chars": 1147,
    "preview": "/*\n  kalo mau ngedec obfuscate snaptik/tikmate pake javascript/nodejs tinggal panggil fungsi decoder\n  jangan lupa kasih"
  },
  {
    "path": "tiktok_downloader/decoder.py",
    "chars": 1602,
    "preview": "# Menghadeh Convert dari Js ke Py\n# Decryptor For Snaptik/Tikmate Obfuscate\n\nfrom typing import Union\nfrom ast import li"
  },
  {
    "path": "tiktok_downloader/mdown.py",
    "chars": 4105,
    "preview": "from httpx import AsyncClient\nfrom bs4 import BeautifulSoup\nimport requests\nfrom requests.models import InvalidURL\nfrom "
  },
  {
    "path": "tiktok_downloader/scrapper.py",
    "chars": 6957,
    "preview": "from __future__ import annotations\nfrom httpx import AsyncClient\nfrom requests import Session, get\nfrom re import findal"
  },
  {
    "path": "tiktok_downloader/scrapper_v2.py",
    "chars": 1977,
    "preview": "from __future__ import annotations\nfrom dataclasses import dataclass\nimport re\nfrom bs4 import BeautifulSoup\nimport requ"
  },
  {
    "path": "tiktok_downloader/server.py",
    "chars": 5452,
    "preview": "from io import BytesIO\nfrom flask import (\n    Flask,\n    request,\n    render_template\n)\nfrom flask.wrappers import Resp"
  },
  {
    "path": "tiktok_downloader/snaptik.py",
    "chars": 5177,
    "preview": "import re\nfrom bs4 import BeautifulSoup\nfrom httpx import AsyncClient\nfrom sys import stderr\nfrom ast import literal_eva"
  },
  {
    "path": "tiktok_downloader/ssstik.py",
    "chars": 3521,
    "preview": "from httpx import AsyncClient\nfrom requests import Session\nimport re\nfrom .utils import Download, DownloadAsync\nfrom bas"
  },
  {
    "path": "tiktok_downloader/static/script.js",
    "chars": 5016,
    "preview": "      localStorage.mode = localStorage.mode || 'white';\n      document.getElementById('mode').setAttribute('class', 'fas"
  },
  {
    "path": "tiktok_downloader/templates/index.html",
    "chars": 3492,
    "preview": " <!-- krypton byte -->\n<!doctype html>\n<html lang=\"en\">\n  <head>\n    <!-- Required meta tags -->\n    <meta charset=\"utf-"
  },
  {
    "path": "tiktok_downloader/test.py",
    "chars": 667,
    "preview": "import unittest\nfrom .scrapper import VideoInfo\nfrom .snaptik import snaptik\nfrom .tikmate import tikmate\nfrom .mdown im"
  },
  {
    "path": "tiktok_downloader/tikdown.py",
    "chars": 3012,
    "preview": "from httpx import AsyncClient\nfrom requests import Session\nimport re\nfrom .utils import DownloadAsync, Download\n\n\nclass "
  },
  {
    "path": "tiktok_downloader/tikmate.py",
    "chars": 4505,
    "preview": "from typing import Generator\nfrom httpx import AsyncClient\nfrom requests.models import InvalidURL\nfrom .decoder import d"
  },
  {
    "path": "tiktok_downloader/tiktok_async.py",
    "chars": 620,
    "preview": "from .scrapper import VideoInfoAsync\nfrom .mdown import MdownAsync, mdown_async\nfrom .snaptik import SnaptikAsync, snapt"
  },
  {
    "path": "tiktok_downloader/tikwm.py",
    "chars": 2307,
    "preview": "from httpx import AsyncClient\nfrom requests import Session\nfrom requests.models import InvalidURL\nfrom .utils import Dow"
  },
  {
    "path": "tiktok_downloader/ttdownloader.py",
    "chars": 3254,
    "preview": "from httpx import AsyncClient\nfrom requests import Session\nimport re\nfrom .utils import Download, DownloadAsync\n\n\nclass "
  },
  {
    "path": "tiktok_downloader/utils.py",
    "chars": 7201,
    "preview": "from __future__ import annotations\nimport asyncio\nimport httpx\nfrom PIL import Image\nfrom moviepy.video.VideoClip import"
  }
]

About this extraction

This page contains the full source code of the krypton-byte/tiktok-downloader GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 34 files (108.0 KB), approximately 27.2k tokens, and a symbol index with 125 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!