platzi 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.
platzi/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .async_api import AsyncPlatzi
2
+ from .m3u8 import m3u8_dl
3
+
4
+ __all__ = ["m3u8_dl", "AsyncPlatzi"]
platzi/async_api.py ADDED
@@ -0,0 +1,208 @@
1
+ import functools
2
+ import json
3
+ from pathlib import Path
4
+
5
+ from playwright.async_api import BrowserContext, Page, async_playwright
6
+
7
+ from .collectors import get_chapters_urls, get_course_title, get_unit
8
+ from .constants import HEADERS, LOGIN_DETAILS_URL, LOGIN_URL, SESSION_FILE
9
+ from .helpers import read_json, write_json
10
+ from .logger import Logger
11
+ from .m3u8 import m3u8_dl
12
+ from .models import TypeUnit, User
13
+ from .utils import progressive_scroll, slugify
14
+
15
+
16
+ def login_required(func):
17
+ @functools.wraps(func)
18
+ async def wrapper(*args, **kwargs):
19
+ self = args[0]
20
+ if not isinstance(self, AsyncPlatzi):
21
+ Logger.error(f"{login_required.__name__} can only decorate Platzi class.")
22
+ return
23
+ if not self.loggedin:
24
+ Logger.error("Login first!")
25
+ return
26
+ return await func(*args, **kwargs)
27
+
28
+ return wrapper
29
+
30
+
31
+ def try_except_request(func):
32
+ @functools.wraps(func)
33
+ async def wrapper(*args, **kwargs):
34
+ self = args[0]
35
+ if not isinstance(self, AsyncPlatzi):
36
+ Logger.error(
37
+ f"{try_except_request.__name__} can only decorate Platzi class."
38
+ )
39
+ return
40
+
41
+ try:
42
+ return await func(*args, **kwargs)
43
+ except Exception as e:
44
+ if str(e):
45
+ Logger.error(e)
46
+ return
47
+
48
+ return wrapper
49
+
50
+
51
+ class AsyncPlatzi:
52
+ def __init__(self, headless=False):
53
+ self.loggedin = False
54
+ self.headless = headless
55
+ self.user = None
56
+
57
+ async def __aenter__(self):
58
+ self._playwright = await async_playwright().start()
59
+ self._browser = await self._playwright.chromium.launch(headless=self.headless)
60
+ self._context = await self._browser.new_context(
61
+ java_script_enabled=True,
62
+ is_mobile=True,
63
+ )
64
+
65
+ try:
66
+ await self._load_state()
67
+ except Exception:
68
+ pass
69
+
70
+ await self._set_profile()
71
+
72
+ return self
73
+
74
+ async def __aexit__(self, exc_type, exc, tb):
75
+ await self._context.close()
76
+ await self._browser.close()
77
+ await self._playwright.stop()
78
+
79
+ @property
80
+ async def page(self) -> Page:
81
+ return await self._context.new_page()
82
+
83
+ @property
84
+ def context(self) -> BrowserContext:
85
+ return self._context
86
+
87
+ @try_except_request
88
+ async def _set_profile(self) -> None:
89
+ try:
90
+ data = await self.get_json(LOGIN_DETAILS_URL)
91
+ self.user = User(**data)
92
+ except Exception:
93
+ return
94
+
95
+ if self.user.is_authenticated:
96
+ self.loggedin = True
97
+ Logger.info(f"Hi, {self.user.username}!")
98
+
99
+ @try_except_request
100
+ async def login(self) -> None:
101
+ Logger.info("Please login, in the opened browser")
102
+ Logger.info("You have to login manually, you have 2 minutes to do it")
103
+
104
+ page = await self.page
105
+ await page.goto(LOGIN_URL)
106
+ try:
107
+ avatar = await page.wait_for_selector(
108
+ ".styles-module_Menu__Avatar__FTuh-",
109
+ timeout=2 * 60 * 1000,
110
+ )
111
+ if avatar:
112
+ self.loggedin = True
113
+ await self._save_state()
114
+ Logger.info("Logged in successfully")
115
+ except Exception:
116
+ raise Exception("Login failed")
117
+ finally:
118
+ await page.close()
119
+
120
+ @try_except_request
121
+ async def logout(self):
122
+ SESSION_FILE.unlink(missing_ok=True)
123
+ Logger.info("Logged out successfully")
124
+
125
+ @try_except_request
126
+ @login_required
127
+ async def download(self, url: str, **kwargs):
128
+ page = await self.page
129
+ await page.goto(url)
130
+
131
+ # course title
132
+ course_title = await get_course_title(page)
133
+ Logger.print(course_title, "[COURSE]")
134
+
135
+ # download directory
136
+ DL_DIR = Path("Platzi") / slugify(course_title)
137
+ DL_DIR.mkdir(parents=True, exist_ok=True)
138
+
139
+ # save page as mhtml
140
+ await self.save_page(
141
+ page,
142
+ path=DL_DIR / "presentation.mhtml",
143
+ )
144
+
145
+ # iterate over chapters
146
+ chapters_urls = await get_chapters_urls(page)
147
+ for idx, (title, urls) in enumerate(chapters_urls, 1):
148
+ print(f"{title}")
149
+
150
+ CHAP_DIR = DL_DIR / f"{idx:02}_{slugify(title)}"
151
+ CHAP_DIR.mkdir(parents=True, exist_ok=True)
152
+
153
+ # iterate over units
154
+ for jdx, unit_url in enumerate(urls, 1):
155
+ unit = await get_unit(self.context, unit_url)
156
+ name = f"{jdx:02}_{slugify(unit.title)}"
157
+
158
+ if unit.video:
159
+ dst = CHAP_DIR / f"{name}.mp4"
160
+ Logger.print(f"[{name}.mp4]", "[DOWNLOADING][VIDEO]")
161
+ await m3u8_dl(unit.video.url, dst.as_posix(), headers=HEADERS)
162
+
163
+ if unit.type == TypeUnit.LECTURE:
164
+ Logger.print(f"[{name}.mhtml]", "[DOWNLOADING][LECTURE]")
165
+ await self.save_page(
166
+ unit.url,
167
+ path=CHAP_DIR / f"{name}.mhtml",
168
+ )
169
+
170
+ print("=" * 100)
171
+
172
+ @try_except_request
173
+ async def save_page(self, src: str | Page, path: str = "source.mhtml"):
174
+ if isinstance(src, str):
175
+ page = await self.page
176
+ await page.goto(src)
177
+ else:
178
+ page = src
179
+
180
+ await progressive_scroll(page)
181
+
182
+ try:
183
+ client = await page.context.new_cdp_session(page)
184
+ response = await client.send("Page.captureSnapshot")
185
+ with open(path, "w", encoding="utf-8", newline="\n") as file:
186
+ file.write(response["data"])
187
+ except Exception:
188
+ raise Exception("Error saving page as mhtml")
189
+
190
+ if isinstance(src, str):
191
+ await page.close()
192
+
193
+ @try_except_request
194
+ async def get_json(self, url: str) -> dict:
195
+ page = await self.page
196
+ await page.goto(url)
197
+ content = await page.locator("pre").first.text_content()
198
+ await page.close()
199
+ return json.loads(content or "{}")
200
+
201
+ async def _save_state(self):
202
+ cookies = await self.context.cookies()
203
+ write_json(SESSION_FILE, cookies)
204
+
205
+ async def _load_state(self):
206
+ SESSION_FILE.touch()
207
+ cookies = read_json(SESSION_FILE)
208
+ await self.context.add_cookies(cookies)
platzi/cli.py ADDED
@@ -0,0 +1,70 @@
1
+ import asyncio
2
+
3
+ import typer
4
+ from typing_extensions import Annotated
5
+
6
+ from platzi import AsyncPlatzi
7
+
8
+ app = typer.Typer(rich_markup_mode="rich")
9
+
10
+
11
+ @app.command()
12
+ def login():
13
+ """
14
+ Open a browser window to Login to Platzi.
15
+
16
+ Usage:
17
+ platzi login
18
+ """
19
+ asyncio.run(_login())
20
+
21
+
22
+ @app.command()
23
+ def logout():
24
+ """
25
+ Delete the Platzi session from the local storage.
26
+
27
+ Usage:
28
+ platzi logout
29
+ """
30
+ asyncio.run(_logout())
31
+
32
+
33
+ @app.command()
34
+ def download(
35
+ url: Annotated[
36
+ str,
37
+ typer.Argument(
38
+ help="The URL of the course to download",
39
+ show_default=False,
40
+ ),
41
+ ],
42
+ ):
43
+ """
44
+ Download a Platzi course from the given URL.
45
+
46
+ Arguments:
47
+ url: str - The URL of the course to download.
48
+
49
+ Usage:
50
+ platzi download <url>
51
+
52
+ Example:
53
+ platzi download https://platzi.com/cursos/fastapi-2023/
54
+ """
55
+ asyncio.run(_download(url))
56
+
57
+
58
+ async def _login():
59
+ async with AsyncPlatzi() as platzi:
60
+ await platzi.login()
61
+
62
+
63
+ async def _logout():
64
+ async with AsyncPlatzi() as platzi:
65
+ await platzi.logout()
66
+
67
+
68
+ async def _download(url: str):
69
+ async with AsyncPlatzi() as platzi:
70
+ await platzi.download(url)
platzi/collectors.py ADDED
@@ -0,0 +1,91 @@
1
+ from playwright.async_api import BrowserContext, Page
2
+
3
+ from .constants import PLATZI_URL
4
+ from .models import TypeUnit, Unit, Video
5
+ from .utils import get_m3u8_url, get_subtitles_url
6
+
7
+
8
+ async def get_course_title(page: Page) -> str:
9
+ SELECTOR = ".Hero-content-title"
10
+ EXCEPTION = Exception("No course title found")
11
+ try:
12
+ title = await page.locator(SELECTOR).first.text_content()
13
+ if not title:
14
+ raise EXCEPTION
15
+ except Exception:
16
+ await page.close()
17
+ raise EXCEPTION
18
+
19
+ return title
20
+
21
+
22
+ async def get_chapters_urls(page: Page) -> list[tuple[str, list[str]]]:
23
+ SELECTOR = ".Content-feed div.ContentBlock"
24
+ EXCEPTION = Exception("No sections found")
25
+ try:
26
+ locator = page.locator(SELECTOR)
27
+ items = []
28
+ for i in range(await locator.count()):
29
+ title = await locator.nth(i).locator("h3").first.text_content()
30
+
31
+ if not title:
32
+ raise EXCEPTION
33
+
34
+ block_list_locator = locator.nth(i).locator(".ContentBlock-list a")
35
+
36
+ urls: list[str] = []
37
+ for j in range(await block_list_locator.count()):
38
+ url = await block_list_locator.nth(j).get_attribute("href")
39
+
40
+ if not url:
41
+ raise EXCEPTION
42
+
43
+ urls.append(PLATZI_URL + url)
44
+
45
+ items.append((title, urls))
46
+
47
+ except Exception as e:
48
+ await page.close()
49
+ raise EXCEPTION from e
50
+
51
+ return items
52
+
53
+
54
+ async def get_unit(context: BrowserContext, url: str) -> Unit:
55
+ TYPE_SELECTOR = ".VideoPlayer"
56
+ TITLE_SELECTOR = ".MaterialDesktopHeading_MaterialDesktopHeading-info__title__DaYr2"
57
+ EXCEPTION = Exception("Could not collect unit data")
58
+
59
+ try:
60
+ page = await context.new_page()
61
+ await page.goto(url)
62
+
63
+ title = await page.locator(TITLE_SELECTOR).first.text_content()
64
+
65
+ if not title:
66
+ raise EXCEPTION
67
+
68
+ if await page.locator(TYPE_SELECTOR).count() == 0:
69
+ type = TypeUnit.LECTURE
70
+ video = None
71
+
72
+ else:
73
+ content = await page.content()
74
+ type = TypeUnit.VIDEO
75
+ video = Video(
76
+ url=get_m3u8_url(content),
77
+ subtitles_url=get_subtitles_url(content),
78
+ )
79
+
80
+ return Unit(
81
+ url=url,
82
+ title=title,
83
+ type=type,
84
+ video=video,
85
+ )
86
+
87
+ except Exception:
88
+ raise EXCEPTION
89
+
90
+ finally:
91
+ await page.close()
platzi/constants.py ADDED
@@ -0,0 +1,23 @@
1
+ import tempfile
2
+ from pathlib import Path
3
+
4
+ SESSION_DIR = Path(tempfile.gettempdir()) / ".platzi"
5
+ SESSION_FILE = SESSION_DIR / "state.json"
6
+
7
+ LOGIN_URL = "https://platzi.com/login"
8
+ LOGIN_DETAILS_URL = "https://api.platzi.com/api/v1/components/headerv2/user/"
9
+
10
+
11
+ PLATZI_URL = "https://platzi.com"
12
+ HOME_URL = PLATZI_URL + "/home"
13
+
14
+ USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
15
+
16
+ HEADERS = {
17
+ "User-Agent": USER_AGENT,
18
+ "Referer": HOME_URL,
19
+ }
20
+
21
+
22
+ # --- Session directory ---
23
+ SESSION_FILE.parent.mkdir(parents=True, exist_ok=True)
platzi/helpers.py ADDED
@@ -0,0 +1,22 @@
1
+ import hashlib
2
+ import json
3
+
4
+
5
+ def read_json(path: str) -> dict:
6
+ with open(path, "r", encoding="utf-8") as file:
7
+ return json.load(file)
8
+
9
+
10
+ def write_json(path: str, data: dict) -> None:
11
+ with open(path, "w", encoding="utf-8") as file:
12
+ json.dump(data, file, indent=4, ensure_ascii=False)
13
+
14
+
15
+ def write_file(path: str, content: str) -> None:
16
+ with open(path, "w", encoding="utf-8") as file:
17
+ file.write(content)
18
+
19
+
20
+ def hash_id(input_string: str) -> str:
21
+ hash_object = hashlib.sha256(input_string.encode("utf-8"))
22
+ return hash_object.hexdigest()
platzi/logger.py ADDED
@@ -0,0 +1,39 @@
1
+ import sys
2
+
3
+ from rich import print
4
+
5
+
6
+ class Logger:
7
+ show_warnings = True
8
+ is_writing = False
9
+
10
+ @classmethod
11
+ def error(cls, text):
12
+ Logger.print(text, "ERROR:", "red")
13
+
14
+ @classmethod
15
+ def clear(cls):
16
+ sys.stdout.write("\r" + " " * 100 + "\r")
17
+
18
+ @classmethod
19
+ def warning(cls, text):
20
+ if cls.show_warnings:
21
+ Logger.print(text, "WARNING:", "yellow")
22
+
23
+ @classmethod
24
+ def info(cls, text):
25
+ Logger.print(text, "INFO:", "green")
26
+
27
+ @classmethod
28
+ def print(cls, text, head, color="green", end="\n"):
29
+ cls.is_writing = True
30
+ Logger.clear()
31
+ print(f"[{color}]{head} {text}[/{color}]", end=end, flush=True)
32
+ cls.is_writing = False
33
+
34
+ @classmethod
35
+ def clear_and_print(cls, text):
36
+ cls.is_writing = True
37
+ Logger.clear()
38
+ print(text, flush=True)
39
+ cls.is_writing = False
platzi/m3u8.py ADDED
@@ -0,0 +1,163 @@
1
+ import asyncio
2
+ import functools
3
+ import hashlib
4
+ import os
5
+ import re
6
+ import shutil
7
+ import subprocess
8
+ from pathlib import Path
9
+
10
+ import aiohttp
11
+ from tqdm.asyncio import tqdm
12
+
13
+ from .logger import Logger
14
+
15
+
16
+ def ffmpeg_required(func):
17
+ @functools.wraps(func)
18
+ async def wrapper(*args, **kwargs):
19
+ if not shutil.which("ffmpeg"):
20
+ Logger.error("ffmpeg is not installed")
21
+ return
22
+ return await func(*args, **kwargs)
23
+
24
+ return wrapper
25
+
26
+
27
+ def _hash_id(input: str) -> str:
28
+ hash_object = hashlib.sha256(input.encode("utf-8"))
29
+ return hash_object.hexdigest()
30
+
31
+
32
+ async def _ts_dl(url: str, path: Path, **kwargs):
33
+ overrides = kwargs.get("overrides", False)
34
+ headers = kwargs.get("headers", None)
35
+
36
+ if not overrides and path.exists():
37
+ return
38
+
39
+ path.unlink(missing_ok=True)
40
+ path.parent.mkdir(parents=True, exist_ok=True)
41
+
42
+ async with aiohttp.ClientSession() as session:
43
+ async with session.get(url, headers=headers) as response:
44
+ if response.status != 200:
45
+ raise Exception("Error downloading from .ts url")
46
+ with open(path.as_posix(), "wb") as file:
47
+ file.write(await response.read())
48
+
49
+
50
+ async def _worker_ts_dl(urls: list, dir: Path, **kwargs):
51
+ BATCH_SIZE = 10
52
+ IDX = 1
53
+
54
+ with tqdm(total=len(urls)) as bar:
55
+ for i in range(0, len(urls), BATCH_SIZE):
56
+ urls_batch = urls[i : i + BATCH_SIZE]
57
+ tasks = []
58
+ for ts_url in urls_batch:
59
+ ts_path = dir / f"{IDX}.ts"
60
+ tasks.append(_ts_dl(ts_url, ts_path, **kwargs))
61
+ IDX += 1
62
+
63
+ try:
64
+ await asyncio.gather(*tasks)
65
+ except Exception:
66
+ raise Exception("Error downloading ts m3u8")
67
+
68
+ bar.update(len(urls_batch))
69
+
70
+
71
+ async def _m3u8_dl(
72
+ url: str,
73
+ path: str,
74
+ tmp_dir: str = ".tmp",
75
+ **kwargs,
76
+ ) -> None:
77
+ overrides = kwargs.get("overrides", False)
78
+ headers = kwargs.get("headers", None)
79
+
80
+ if not overrides and Path(path).exists():
81
+ return
82
+
83
+ hash = _hash_id(url)
84
+
85
+ Path(path).unlink(missing_ok=True)
86
+ Path(path).parent.mkdir(parents=True, exist_ok=True)
87
+ Path(tmp_dir).mkdir(parents=True, exist_ok=True)
88
+
89
+ async with aiohttp.ClientSession() as session:
90
+ async with session.get(url, headers=headers) as response:
91
+ if response.status != 200:
92
+ raise Exception("Error downloading m3u8")
93
+
94
+ pattern = r"https?://[^\s]+"
95
+ ts_urls = re.findall(pattern, await response.text())
96
+
97
+ if not ts_urls:
98
+ raise Exception("No ts urls found")
99
+
100
+ dir = Path(tmp_dir) / _hash_id(url)
101
+
102
+ await _worker_ts_dl(ts_urls, dir, **kwargs)
103
+
104
+ ts_files = os.listdir(dir)
105
+ ts_files = [ts for ts in ts_files if ts.endswith(".ts")]
106
+ ts_files = sorted(ts_files, key=lambda x: int(x.split(".")[0]))
107
+ ts_paths = [Path(hash) / ts for ts in ts_files]
108
+
109
+ list_file = Path(tmp_dir) / f"{hash}.txt"
110
+ with open(list_file.as_posix(), "w") as file:
111
+ for ts_path in ts_paths:
112
+ file.write(f"file '{ts_path.as_posix()}'\n")
113
+
114
+ Path(path).parent.mkdir(parents=True, exist_ok=True)
115
+
116
+ command = [
117
+ "ffmpeg",
118
+ "-f",
119
+ "concat",
120
+ "-safe",
121
+ "0",
122
+ "-i",
123
+ list_file.as_posix(),
124
+ "-c",
125
+ "copy",
126
+ "-y" if overrides else "-n",
127
+ path,
128
+ ]
129
+
130
+ try:
131
+ subprocess.run(
132
+ command,
133
+ stdout=subprocess.DEVNULL,
134
+ stderr=subprocess.DEVNULL,
135
+ )
136
+ list_file.unlink(missing_ok=True)
137
+ shutil.rmtree(dir)
138
+
139
+ except Exception:
140
+ raise Exception("Error converting m3u8 to mp4")
141
+
142
+
143
+ async def m3u8_dl(
144
+ url: str,
145
+ path: str,
146
+ tmp_dir: str = ".tmp",
147
+ **kwargs,
148
+ ):
149
+ # TODO: implement quality selection
150
+ headers = kwargs.get("headers", None)
151
+
152
+ async with aiohttp.ClientSession() as session:
153
+ async with session.get(url, headers=headers) as response:
154
+ if response.status != 200:
155
+ raise Exception("Error downloading m3u8")
156
+
157
+ pattern = r"https?://[^\s]+"
158
+ m3u8_urls = re.findall(pattern, await response.text())
159
+
160
+ if not m3u8_urls:
161
+ raise Exception("No m3u8 urls found")
162
+
163
+ await _m3u8_dl(m3u8_urls[0], path, **kwargs)
platzi/models.py ADDED
@@ -0,0 +1,62 @@
1
+ from enum import Enum
2
+
3
+ from humps import camelize
4
+ from pydantic import BaseModel
5
+ from pydantic.config import ConfigDict
6
+
7
+
8
+ class User(BaseModel):
9
+ model_config = ConfigDict(alias_generator=camelize)
10
+
11
+ avatar: str
12
+ name: str
13
+ username: str
14
+ email: str
15
+ user_id: int
16
+ plan: str
17
+ is_authenticated: bool
18
+ user_type: str
19
+ phone_number: str
20
+
21
+
22
+ class TypeUnit(Enum):
23
+ LECTURE = "lecture"
24
+ VIDEO = "video"
25
+ QUIZ = "quiz"
26
+
27
+
28
+ class Video(BaseModel):
29
+ id: int | None = None
30
+ url: str
31
+ subtitles_url: str | None = None
32
+
33
+
34
+ class Resource(BaseModel):
35
+ name: str
36
+ url: str
37
+
38
+
39
+ class Unit(BaseModel):
40
+ id: int | None = None
41
+ type: TypeUnit
42
+ title: str
43
+ url: str
44
+ video: Video | None = None
45
+ resources: list[Resource] | None = None
46
+
47
+
48
+ class Chapter(BaseModel):
49
+ id: int | None = None
50
+ name: str
51
+ slug: str
52
+ description: str | None = None
53
+ units: list[Unit]
54
+
55
+
56
+ class Course(BaseModel):
57
+ id: int | None = None
58
+ name: str
59
+ slug: str
60
+ url: str
61
+ description: str | None = None
62
+ chapters: list[Chapter]
platzi/utils.py ADDED
@@ -0,0 +1,107 @@
1
+ import asyncio
2
+ import re
3
+ from pathlib import Path
4
+
5
+ import aiohttp
6
+ from playwright.async_api import Page
7
+ from unidecode import unidecode
8
+
9
+
10
+ async def progressive_scroll(
11
+ page: Page, time: float = 3, delay: float = 0.1, steps: int = 250
12
+ ):
13
+ delta, total_time = 0.0, 0.0
14
+ while total_time < time:
15
+ await asyncio.sleep(delay)
16
+ await page.mouse.wheel(0, steps)
17
+ delta += steps
18
+ total_time += delay
19
+
20
+
21
+ def get_course_slug(url: str) -> str:
22
+ """
23
+ Extracts the course slug from a Platzi course URL.
24
+
25
+ Args:
26
+ url (str): The Platzi course URL.
27
+
28
+ Returns:
29
+ str: The course slug.
30
+
31
+ Raises:
32
+ Exception: If the URL is not a valid Platzi course URL.
33
+ """
34
+ pattern = r"https://platzi\.com/cursos/([^/]+)/?"
35
+ match = re.search(pattern, url)
36
+ if not match:
37
+ raise Exception("Invalid course url")
38
+ return match.group(1)
39
+
40
+
41
+ def clean_string(text: str) -> str:
42
+ """
43
+ Cleans the input string by removing special characters and
44
+ leading/trailing white spaces.
45
+
46
+ Args:
47
+ text (str): The input string to be cleaned.
48
+
49
+ Returns:
50
+ str: The cleaned string, with special characters removed and
51
+ leading/trailing spaces stripped.
52
+ """
53
+ pattern = r"[ºª]|[^\w\s]"
54
+ return re.sub(pattern, "", text).strip()
55
+
56
+
57
+ def slugify(text: str) -> str:
58
+ """
59
+ Slugify a string by removing special characters and
60
+ leading/trailing white spaces, and replacing spaces with hyphens.
61
+
62
+ Args:
63
+ text (str): The input string to be slugified.
64
+ Returns:
65
+ str: The slugified string.
66
+ """
67
+ return unidecode(clean_string(text)).lower().replace(" ", "-")
68
+
69
+
70
+ def get_m3u8_url(content: str) -> str:
71
+ pattern = r"https?://[^\s\"'}]+\.m3u8"
72
+ matches = re.findall(pattern, content)
73
+
74
+ if not matches:
75
+ raise Exception("No m3u8 urls found")
76
+
77
+ return matches[0]
78
+
79
+
80
+ def get_subtitles_url(content: str) -> str | None:
81
+ pattern = r"https?://[^\s\"'}]+\.vtt"
82
+ matches = re.findall(pattern, content)
83
+
84
+ if not matches:
85
+ return None
86
+
87
+ return matches[0]
88
+
89
+
90
+ async def download(url: str, path: Path, **kwargs):
91
+ overrides = kwargs.get("overrides", False)
92
+ headers = kwargs.get("headers", None)
93
+
94
+ if not overrides and path.exists():
95
+ return
96
+
97
+ path.unlink(missing_ok=True)
98
+ path.parent.mkdir(parents=True, exist_ok=True)
99
+
100
+ async with aiohttp.ClientSession() as session:
101
+ async with session.get(url, headers=headers) as response:
102
+ if response.status != 200:
103
+ raise Exception(f"Error downloading file: [{path.name}]")
104
+
105
+ with open(path.as_posix(), "wb") as file:
106
+ async for chunk in response.content.iter_chunked(1024):
107
+ file.write(chunk)
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 ivansaul
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.
@@ -0,0 +1,149 @@
1
+ Metadata-Version: 2.1
2
+ Name: platzi
3
+ Version: 0.2.0
4
+ Summary: Download your courses from platzi
5
+ Home-page: https://github.com/ivansaul/platzi-downloader
6
+ License: MIT
7
+ Keywords: Platzi,downloader,courses
8
+ Author: ivansaul
9
+ Author-email: ivansaul@no-reply.com
10
+ Requires-Python: >=3.10,<4.0
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Requires-Dist: aiohttp (>=3.11.2,<4.0.0)
19
+ Requires-Dist: pydantic (>=2.9.2,<3.0.0)
20
+ Requires-Dist: pyhumps (>=3.8.0,<4.0.0)
21
+ Requires-Dist: pytest-playwright (>=0.5.2,<0.6.0)
22
+ Requires-Dist: tqdm (>=4.67.0,<5.0.0)
23
+ Requires-Dist: typer (>=0.13.0,<0.14.0)
24
+ Requires-Dist: unidecode (>=1.3.8,<2.0.0)
25
+ Project-URL: Repository, https://github.com/ivansaul/platzi-downloader
26
+ Description-Content-Type: text/markdown
27
+
28
+ ![Repo Banner](https://i.imgur.com/I6zFXds.png)
29
+
30
+ <div align="center">
31
+
32
+ <h1 style="border-bottom: none">
33
+ <b><a href="#">Platzi Downloader</a></b>
34
+ </h1>
35
+
36
+ Descarga automática de los cursos de `Platzi` con un script creado en `Python` utilizando `yt-dlp` como un subproceso.
37
+
38
+ ![GitHub repo size](https://img.shields.io/github/repo-size/ivansaul/platzi-downloader)
39
+ ![GitHub stars](https://img.shields.io/github/stars/ivansaul/platzi-downloader)
40
+ ![GitHub forks](https://img.shields.io/github/forks/ivansaul/platzi-downloader)
41
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
42
+ [![Discord](https://img.shields.io/badge/-Discord-424549?style=social&logo=discord)](https://discord.gg/tDvybtJ7y9)
43
+
44
+ </div>
45
+
46
+ ---
47
+
48
+ ## Instalación
49
+
50
+ El script utiliza **Selenium & Google Chrome (chrome driver)**, así que asegúrate de tener instalado y actualizado **Chrome browser** en tu ordenador.
51
+
52
+ ```bash
53
+ git clone https://github.com/ivansaul/platzi-downloader.git
54
+ cd platzi-downloader
55
+ pip install -r requirements.txt
56
+ ```
57
+
58
+ ### **Linux**
59
+
60
+ **En Ubuntu:**
61
+
62
+ ```bash
63
+ sudo apt update -y
64
+ # Install Google Chrome ...
65
+ sudo apt install ffmpeg aria2 -y
66
+ pip install -U yt-dlp
67
+ ```
68
+
69
+ **En Archlinux:**
70
+
71
+ ```bash
72
+ sudo pacman -Syu
73
+ sudo pacman -S ffmpeg aria2 yt-dlp
74
+ yay -S google-chrome
75
+ ```
76
+
77
+ ### **Windows**
78
+
79
+ > **Nota:** Asegurate de tener instalados [Python][python], [Google Chrome][chrome] , [yt-dlp][yt-dlp] y [ffmpeg][ffmpeg].
80
+
81
+ ```bash
82
+ # Install Python ...
83
+ # Install ffmpeg ...
84
+ # Install Google Chrome ...
85
+ pip install -U yt-dlp
86
+ ```
87
+
88
+ ## Instrucciones
89
+
90
+ 1. Ejecuta el script `platzi.py` para obtener las url de los videos.
91
+
92
+ ```bash
93
+ python platzi.py
94
+ ```
95
+
96
+ El script te pedirá tu correo y contraseña, así como la URL del curso a descargar (la URL puede ser de cualquier video del curso).
97
+
98
+ ```bash
99
+ Ingresa tus credenciales de Platzi
100
+ Ingresa tu e-mail: tu@email.com
101
+ Ingresa tu contraseña: tu_comtraseña
102
+ Ingresa la URL del curso a descargar: https://platzi.com/clases/2292-terminal/37344-manipulando-archivos-y-directorios/
103
+ .
104
+ .
105
+ .
106
+ ```
107
+
108
+ 2. Finalmente para descargar los vídeos ejecute.
109
+
110
+ ```bash
111
+ python downloader.py
112
+ ```
113
+
114
+ Por defecto, los vídeos se descargarán automáticamente en una carpeta con el mismo nombre del curso, con la mejor calidad existente (`best`) y usando `aria2` como gestor de descargas. Para personalizar la descarga, puedes usar las siguientes opciones.
115
+
116
+ ```bash
117
+ Usage: python downloader.py [OPTIONS]
118
+
119
+ Options:
120
+ -d [yt-dlp|wget|aria2] Select the external downloader (yt-dlp, or aria2). Default: aria2.
121
+ -q [360|480|720|1080|best] Select the video quality (360, 480, 720, 1080 or best). Default: best
122
+ --help Show this message and exit.
123
+
124
+ Examples:
125
+ python downloader.py -q 1080
126
+ python downloader.py -d yt-dlp
127
+ python downloader.py -d yt-dlp -q 720
128
+ python downloader.py --help
129
+ ```
130
+
131
+ > **Nota:** Si por algún motivo se cancela la descarga, vuelve a ejecutar `python downloader.py [OPTIONS]` para retomar la descarga.
132
+
133
+
134
+
135
+ # **Aviso de Uso**
136
+
137
+ Este proyecto se realiza con fines exclusivamente educativos y de aprendizaje. El código proporcionado se ofrece "tal cual", sin ninguna garantía de su funcionamiento o idoneidad para ningún propósito específico.
138
+
139
+ No me hago responsable por cualquier mal uso, daño o consecuencia que pueda surgir del uso de este proyecto. Es responsabilidad del usuario utilizarlo de manera adecuada y dentro de los límites legales y éticos.
140
+
141
+
142
+ [python]: https://www.python.org/downloads/
143
+ [ffmpeg]: https://ffmpeg.org
144
+ [chrome]: https://www.google.com/chrome/
145
+ [yt-dlp]: https://github.com/yt-dlp/yt-dlp/wiki/Installation
146
+ [aria2]: https://github.com/aria2/aria2/releases/tag/release-1.36.0
147
+ [demo]: https://youtu.be/GbQwB0hYvQU
148
+ [ffmpeg-win]:https://youtu.be/0zN9oZ98ZgE
149
+
@@ -0,0 +1,15 @@
1
+ platzi/__init__.py,sha256=M8TNRpd804iCyQnqNIoBU9nI2NnbbA99gY7GjRM94cE,99
2
+ platzi/async_api.py,sha256=SH90kwPer47RYuuJbVZHfFV6TApR_NfCwjn0m6357BQ,6358
3
+ platzi/cli.py,sha256=z0rMKMmisXXK3q59OSw3CuENX9QTRYRxxruIQhSS4BE,1232
4
+ platzi/collectors.py,sha256=T4p_Xrv3AhASDdISEqee1GcqURrTrME9-xr8H1jXofk,2483
5
+ platzi/constants.py,sha256=SKgq_CsXYxy_uHsjlaoNvW-Mcrc8fGaA7M8GU-Vi3m4,607
6
+ platzi/helpers.py,sha256=Ucjh_M-DxYi12RfQBZi6oZlDEFQPsrISas9tB5-_P8M,577
7
+ platzi/logger.py,sha256=5C2L_rUdXh7AyVZtyntQPT9j-Wcx7ng97i_bi_dq3wA,893
8
+ platzi/m3u8.py,sha256=btQ0Tcqp-02MUXNPaRaZEmxEKudHhHPT2AnUkaxHKs0,4382
9
+ platzi/models.py,sha256=MuaZjYJSvwQe3nYxDH3WZe0ZH3PogIxz-LHkf4VtmBk,1077
10
+ platzi/utils.py,sha256=YcOwSqDjI7tX6_hlJSiX633X5g8L77S2DRhaazwlm-s,2766
11
+ platzi-0.2.0.dist-info/LICENCE,sha256=MICUTOiebbpu1_drke5Pweq_MkMwvaHEK--uCjrSZp0,1064
12
+ platzi-0.2.0.dist-info/METADATA,sha256=f3TBOZuovq591jSRHSLfCXGa42DqdeIWWxKLXb25Jzo,4811
13
+ platzi-0.2.0.dist-info/WHEEL,sha256=Nq82e9rUAnEjt98J6MlVmMCZb-t9cYE2Ir1kpBmnWfs,88
14
+ platzi-0.2.0.dist-info/entry_points.txt,sha256=r4dgnvhd0obD8WAHLgYYu7X_lQ-bch6S4qbLxWJkuZQ,41
15
+ platzi-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 1.9.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ platzi=platzi.cli:app
3
+