apyrat 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,92 @@
1
+ Metadata-Version: 2.4
2
+ Name: apyrat
3
+ Version: 0.2.0
4
+ Summary: An Aparat video downloader. simple, but elegant.
5
+ Project-URL: Homepage, https://github.com/codewithemad/apyrat
6
+ Project-URL: Issues, https://github.com/codewithemad/apyrat/issues
7
+ Author: Emad Rad
8
+ Author-email: codewithemad@gmail.com
9
+ License: MIT License
10
+
11
+ Copyright (c) 2023, Emad Rad
12
+
13
+ Permission is hereby granted, free of charge, to any person obtaining a copy
14
+ of this software and associated documentation files (the "Software"), to deal
15
+ in the Software without restriction, including without limitation the rights
16
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17
+ copies of the Software, and to permit persons to whom the Software is
18
+ furnished to do so, subject to the following conditions:
19
+
20
+ The above copyright notice and this permission notice shall be included in all
21
+ copies or substantial portions of the Software.
22
+
23
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29
+ SOFTWARE.
30
+
31
+ License-File: LICENSE
32
+ Classifier: Development Status :: 5 - Production/Stable
33
+ Classifier: License :: OSI Approved :: MIT License
34
+ Classifier: Operating System :: OS Independent
35
+ Classifier: Programming Language :: Python
36
+ Classifier: Programming Language :: Python :: 3.8
37
+ Classifier: Programming Language :: Python :: 3.9
38
+ Classifier: Programming Language :: Python :: 3.10
39
+ Classifier: Programming Language :: Python :: 3.11
40
+ Classifier: Programming Language :: Python :: 3.12
41
+ Requires-Python: >=3.8
42
+ Requires-Dist: click>=8.0.4
43
+ Requires-Dist: requests>=2.31.0
44
+ Requires-Dist: wget>=3.2
45
+ Provides-Extra: dev
46
+ Requires-Dist: coverage>=7.2.7; extra == 'dev'
47
+ Requires-Dist: pytest-sugar>=1.0.0; extra == 'dev'
48
+ Requires-Dist: pytest>=7.4.4; extra == 'dev'
49
+ Requires-Dist: ruff>=0.9.7; extra == 'dev'
50
+ Description-Content-Type: text/markdown
51
+
52
+
53
+ # Apyrat ![download badge](.pypi_chart/badge.svg)
54
+
55
+ ![PyPI releases](https://img.shields.io/pypi/v/apyrat?logo=python&logoColor=white)
56
+ [PyPI](https://pypi.python.org/pypi/apyrat)
57
+
58
+ ![Python Versions](https://img.shields.io/pypi/pyversions/apyrat.svg)
59
+ [PyPI Project](https://pypi.org/project/apyrat)
60
+
61
+ ![MIT License](https://img.shields.io/github/license/CodeWithEmad/apyrat.svg?style=flat-square)
62
+ [MIT License](https://opensource.org/license/mit/)
63
+
64
+ Yet another `Aparat <https://www.aparat.com>`__ video downloader.
65
+
66
+ ## Getting Started
67
+
68
+ you can install Apyrat from PyPi:
69
+
70
+ ``` bash
71
+ pip install -U apyrat
72
+ ```
73
+
74
+ for example you want to download the video hosted `here <https://www.aparat.com/v/qur3I>`__. just run:
75
+
76
+ ``` bash
77
+ apyrat https://www.aparat.com/v/qur3I
78
+ ```
79
+
80
+ you can also download playlists:
81
+
82
+ ``` bash
83
+ apyrat https://www.aparat.com/playlist/448747
84
+ ```
85
+
86
+ ## Contributing
87
+
88
+ Any contributions are welcome here! To learn how you can contribute, please check the `contributing doc <https://github.com/CodeWithEmad/apyrat/blob/master/CONTRIBUTING.rst>`__.
89
+
90
+ ## License
91
+
92
+ This work is licensed under the terms of the `MIT <https://github.com/CodeWithEmad/apyrat/blob/master/LICENSE>`_.
@@ -0,0 +1,9 @@
1
+ src/__init__.py,sha256=8PzB-VChJDfXVbH4dqca7jL0Xhs3ZB7a0WkxJYmEQVQ,36
2
+ src/apyrat.py,sha256=2lL6Pzfh9lGZdfUWQHlDODrBIeXy_NqESYerenaCqWk,5290
3
+ src/cli.py,sha256=EjgW4x-OdaDeIRFjUbrO3RBkEEM1W6LisEJdR9O-zbg,2392
4
+ src/utils.py,sha256=U8k92Fe-Mpe3KqGpl9vNrYB-LBS1EczP_XVK5ZQfdP0,885
5
+ apyrat-0.2.0.dist-info/METADATA,sha256=N9sQoNZvNV2sL_w07xA-AHWs57wq5IFGMbcvw4I-aDc,3539
6
+ apyrat-0.2.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
7
+ apyrat-0.2.0.dist-info/entry_points.txt,sha256=H0P6NsjjW_Symi8ULnTjCcsDeMkVwq7O9a49lHDm400,40
8
+ apyrat-0.2.0.dist-info/licenses/LICENSE,sha256=5PtY86mY0NSuspr--88tWE-wAyvjLxuqeJfbZ5X6UUI,1067
9
+ apyrat-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ apyrat = src.cli:main
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023, Emad Rad
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
src/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Top-level package for Apyrat."""
src/apyrat.py ADDED
@@ -0,0 +1,162 @@
1
+ import hashlib
2
+ import os
3
+ from concurrent.futures import ThreadPoolExecutor, as_completed
4
+ from enum import Enum
5
+ from urllib.parse import urlparse
6
+
7
+ import click
8
+ import requests
9
+ import wget
10
+
11
+ from src.utils import check_domain_validity, prepare_headers
12
+
13
+
14
+ # Enum declarations
15
+ class URLType(Enum):
16
+ VIDEO = "video"
17
+ PLAYLIST = "playlist"
18
+
19
+
20
+ class VideoQuality(Enum):
21
+ FULL_HD = "1080p"
22
+ HD = "720p"
23
+ FOUR_EIGHTY = "480p"
24
+ THREE_SIXTY = "360p"
25
+ TWO_FORTY = "240p"
26
+ ONE_FORTY_FOUR = "144p"
27
+
28
+
29
+ # CONSTANTS
30
+ API_BASE_URL = "https://www.aparat.com/api/fa/v1"
31
+
32
+
33
+ class Downloader:
34
+ def __init__(self, url, filename=None) -> None:
35
+ self.file_name = filename
36
+ self.links = []
37
+ self.url = self._cleanup_url(url)
38
+ self.url_type = self._url_type()
39
+ self.videos = self._get_available_videos()
40
+ self.qualities = self._get_available_qualities()
41
+
42
+ @staticmethod
43
+ def _cleanup_url(url: str):
44
+ url = url.replace("https://", "").replace("www.", "").rstrip("/")
45
+ return url.split("?", 1)[0]
46
+
47
+ def _url_type(self) -> URLType:
48
+ if not check_domain_validity(self.url):
49
+ raise ValueError("Invalid URL")
50
+ if "/v/" in self.url:
51
+ self.video_uid = self.url.rsplit("/", 1)[-1]
52
+ return URLType.VIDEO
53
+ elif "/playlist/" in self.url:
54
+ self.playlist_id = self.url.rsplit("/", 1)[-1]
55
+ return URLType.PLAYLIST
56
+ else:
57
+ raise ValueError("Invalid URL")
58
+
59
+ def _get_available_videos(self) -> list:
60
+ if self.url_type == URLType.VIDEO:
61
+ return [self._get_single_video_qualities(self.video_uid)]
62
+ elif self.url_type == URLType.PLAYLIST:
63
+ click.echo("Loading playlist videos")
64
+ all_videos = []
65
+ playlist_data = requests.get(
66
+ f"{API_BASE_URL}/video/playlist/one/playlist_id/{self.playlist_id}", # noqa
67
+ headers=prepare_headers(),
68
+ ).json()
69
+ video_urls = [
70
+ item
71
+ for item in playlist_data["included"]
72
+ if item["type"] == "Video" # noqa
73
+ ]
74
+
75
+ with ThreadPoolExecutor(max_workers=10) as executor:
76
+ futures = [
77
+ executor.submit(
78
+ self._get_single_video_qualities,
79
+ video["attributes"]["uid"],
80
+ self.playlist_id,
81
+ )
82
+ for video in video_urls
83
+ ]
84
+
85
+ for future in as_completed(futures):
86
+ all_videos.append(future.result())
87
+
88
+ return all_videos
89
+
90
+ def _get_single_video_qualities(self, video_uid, playlist_id=None):
91
+ query = f"?playlist={playlist_id}&pr=1&mf=1" if playlist_id else ""
92
+ video_data = requests.get(
93
+ f"{API_BASE_URL}/video/video/show/videohash/{video_uid}{query}",
94
+ headers=prepare_headers(),
95
+ ).json()
96
+
97
+ video_attrs = video_data["data"]["attributes"]
98
+ return [
99
+ {
100
+ "title": video_attrs["title"],
101
+ "profile": attr.get("profile"),
102
+ "url": attr.get("urls")[0],
103
+ }
104
+ for attr in video_attrs["file_link_all"]
105
+ ]
106
+
107
+ def _get_available_qualities(self):
108
+ qualities = {
109
+ video_quality.get("profile")
110
+ for video in self.videos
111
+ for video_quality in video
112
+ }
113
+ return sorted(qualities, key=lambda x: int(x[:-1]))
114
+
115
+ def default_quality(self):
116
+ return (
117
+ VideoQuality.HD.value
118
+ if VideoQuality.HD.value in self.qualities
119
+ else self.qualities[-1]
120
+ )
121
+
122
+ def find_closest_quality(self, video_list, target_quality):
123
+ exact_quality_videos = [
124
+ video for video in video_list if video["profile"] == target_quality
125
+ ]
126
+ if exact_quality_videos:
127
+ return exact_quality_videos[0]
128
+
129
+ video_qualities = [
130
+ int(video["profile"][:-1]) for video in video_list
131
+ ] # Extract the qualities and convert to integers
132
+ closest_quality = min(
133
+ video_qualities, key=lambda x: abs(x - int(target_quality[:-1]))
134
+ )
135
+
136
+ for video in video_list:
137
+ if video["profile"] == str(closest_quality) + "p":
138
+ return video
139
+
140
+ def download(self, quality: str):
141
+ for video_qualities in self.videos:
142
+ video = self.find_closest_quality(video_qualities, quality)
143
+ self._download_video(video)
144
+
145
+ def _download_video(self, video):
146
+ url = video.get("url")
147
+ title = video.get("title")
148
+ click.echo(f"{title}\n{url}")
149
+ file_name = self.file_name or video.get("title")
150
+ output_file = f"{file_name}.{self._get_file_format(url)}"
151
+ # Check if file already exists
152
+ if os.path.isfile(output_file):
153
+ # Create a hash of the filename
154
+ hash_object = hashlib.md5(output_file.encode())
155
+ hex_dig = hash_object.hexdigest()
156
+ # Append the hash to the filename
157
+ output_file = f"{hex_dig}{output_file}"
158
+ wget.download(url, out=output_file)
159
+
160
+ @staticmethod
161
+ def _get_file_format(url):
162
+ return urlparse(url).path.rsplit(".", 1)[-1]
src/cli.py ADDED
@@ -0,0 +1,102 @@
1
+ """Console script for apyrat."""
2
+
3
+ import click
4
+
5
+ from src.apyrat import Downloader, URLType, VideoQuality
6
+ from src.utils import get_about_information
7
+
8
+
9
+ def display_version(ctx, param, value):
10
+ if not value or ctx.resilient_parsing:
11
+ return
12
+ else:
13
+ ABOUT = get_about_information()
14
+ click.echo(ABOUT["__version__"])
15
+ ctx.exit()
16
+
17
+
18
+ def display_help(ctx, param, value):
19
+ if not value or ctx.resilient_parsing:
20
+ return
21
+ click.echo(ctx.get_help())
22
+ ctx.exit()
23
+
24
+
25
+ @click.command(context_settings={"help_option_names": ["-h", "--help"]})
26
+ @click.option(
27
+ "-v",
28
+ "--version",
29
+ is_flag=True,
30
+ callback=display_version,
31
+ expose_value=False,
32
+ is_eager=True,
33
+ help="Show version and exit.",
34
+ )
35
+ @click.option(
36
+ "-f",
37
+ "--filename",
38
+ type=click.Path(),
39
+ default=None,
40
+ help="Specify the output filename.",
41
+ )
42
+ @click.option(
43
+ "-q",
44
+ "--quality",
45
+ type=str,
46
+ default=None,
47
+ help="Quality of the video.",
48
+ )
49
+ @click.option(
50
+ "-y",
51
+ "--confirm",
52
+ is_flag=True,
53
+ default=False,
54
+ help="Use default video quality if not available.",
55
+ )
56
+ @click.argument("url", type=str, required=True)
57
+ @click.pass_context
58
+ def main(ctx, url: str, quality: str, filename: str, confirm: bool):
59
+ """
60
+ Download Aparat videos from your terminal
61
+ """
62
+ try:
63
+ downloader = Downloader(url)
64
+ except ValueError:
65
+ click.echo("Invalid URL provided.", err=True)
66
+ ctx.exit(1)
67
+
68
+ # set filename if the url type is URLType.VIDEO
69
+ if filename and downloader.url_type == URLType.VIDEO:
70
+ downloader.file_name = filename
71
+
72
+ quality_choice = str(
73
+ downloader.default_quality()
74
+ if confirm
75
+ else get_quality(
76
+ downloader,
77
+ quality,
78
+ )
79
+ )
80
+
81
+ downloader.download(quality_choice)
82
+
83
+
84
+ def get_quality(downloader: Downloader, quality: VideoQuality):
85
+ if quality and quality not in downloader.qualities:
86
+ click.echo(f"Quality {quality} is not available", err=True)
87
+ quality = None
88
+
89
+ if not quality:
90
+ quality_choice = click.prompt(
91
+ "Enter the quality you want to download",
92
+ type=click.Choice(downloader._get_available_qualities()),
93
+ default=downloader.default_quality(),
94
+ )
95
+ else:
96
+ quality_choice = quality
97
+
98
+ return quality_choice
99
+
100
+
101
+ if __name__ == "__main__":
102
+ main()
src/utils.py ADDED
@@ -0,0 +1,33 @@
1
+ """Initialization script."""
2
+
3
+ import io
4
+ import os
5
+ from typing import Dict
6
+
7
+ CURRENT_DIRECTORY = os.path.abspath(os.path.dirname(__file__))
8
+
9
+
10
+ def get_about_information() -> Dict[str, str]:
11
+ about_information: Dict[str, str] = {}
12
+ with io.open(
13
+ os.path.join(CURRENT_DIRECTORY, "__about__.py"), "rt", encoding="utf-8"
14
+ ) as file:
15
+ exec(file.read(), about_information) # pylint: disable=exec-used
16
+ return about_information
17
+
18
+
19
+ def check_domain_validity(domain: str) -> bool:
20
+ if domain.startswith("https://"):
21
+ domain = domain[8:]
22
+ if domain.startswith("www."):
23
+ domain = domain[4:]
24
+
25
+ return domain.startswith("aparat.com/v/") or domain.startswith(
26
+ "aparat.com/playlist/"
27
+ )
28
+
29
+
30
+ def prepare_headers():
31
+ return {
32
+ "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0" # noqa
33
+ }