platzi 0.4.2__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,227 @@
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_course_title, get_draft_chapters, get_unit
8
+ from .constants import HEADERS, LOGIN_DETAILS_URL, LOGIN_URL, SESSION_FILE
9
+ from .helpers import hash_id, read_json, write_json
10
+ from .logger import Logger
11
+ from .m3u8 import m3u8_dl
12
+ from .models import TypeUnit, Unit, User
13
+ from .utils import Cache, download, 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
+ draft_chapters = await get_draft_chapters(page)
147
+ for idx, draft_chapter in enumerate(draft_chapters, 1):
148
+ Logger.info(f"Downloading {draft_chapter.name}")
149
+
150
+ CHAP_DIR = DL_DIR / f"{idx:02}_{draft_chapter.slug}"
151
+ CHAP_DIR.mkdir(parents=True, exist_ok=True)
152
+
153
+ # iterate over units
154
+ for jdx, draft_unit in enumerate(draft_chapter.units, 1):
155
+ cache_hash = hash_id(draft_unit.url)
156
+ cache_data = Cache.get(cache_hash)
157
+
158
+ if cache_data:
159
+ unit = Unit.model_validate(cache_data)
160
+ else:
161
+ unit = await get_unit(self.context, draft_unit.url)
162
+ Cache.set(cache_hash, unit.model_dump())
163
+
164
+ file_name = f"{jdx:02}_{unit.slug}"
165
+
166
+ # download video
167
+ if unit.video:
168
+ dst = CHAP_DIR / f"{file_name}.mp4"
169
+ Logger.print(f"[{dst.name}]", "[DOWNLOADING]")
170
+ await m3u8_dl(unit.video.url, dst.as_posix(), headers=HEADERS)
171
+
172
+ if unit.video.subtitles_url:
173
+ dst = CHAP_DIR / f"{file_name}.vtt"
174
+ Logger.print(f"[{dst.name}]", "[DOWNLOADING]")
175
+ await download(unit.video.subtitles_url, dst)
176
+
177
+ # download lecture
178
+ if unit.type == TypeUnit.LECTURE:
179
+ dst = CHAP_DIR / f"{file_name}.mhtml"
180
+ Logger.print(f"[{dst.name}]", "[DOWNLOADING]")
181
+ await self.save_page(unit.url, path=dst)
182
+
183
+ # download quiz
184
+ if unit.type == TypeUnit.QUIZ:
185
+ dst = CHAP_DIR / f"{file_name}.mhtml"
186
+ Logger.print(f"[{dst.name}]", "[DOWNLOADING]")
187
+ await self.save_page(unit.url, path=dst)
188
+
189
+ print("=" * 100)
190
+
191
+ @try_except_request
192
+ async def save_page(self, src: str | Page, path: str = "source.mhtml"):
193
+ if isinstance(src, str):
194
+ page = await self.page
195
+ await page.goto(src)
196
+ else:
197
+ page = src
198
+
199
+ await progressive_scroll(page)
200
+
201
+ try:
202
+ client = await page.context.new_cdp_session(page)
203
+ response = await client.send("Page.captureSnapshot")
204
+ with open(path, "w", encoding="utf-8", newline="\n") as file:
205
+ file.write(response["data"])
206
+ except Exception:
207
+ raise Exception("Error saving page as mhtml")
208
+
209
+ if isinstance(src, str):
210
+ await page.close()
211
+
212
+ @try_except_request
213
+ async def get_json(self, url: str) -> dict:
214
+ page = await self.page
215
+ await page.goto(url)
216
+ content = await page.locator("pre").first.text_content()
217
+ await page.close()
218
+ return json.loads(content or "{}")
219
+
220
+ async def _save_state(self):
221
+ cookies = await self.context.cookies()
222
+ write_json(SESSION_FILE, cookies)
223
+
224
+ async def _load_state(self):
225
+ SESSION_FILE.touch()
226
+ cookies = read_json(SESSION_FILE)
227
+ 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,121 @@
1
+ import asyncio
2
+
3
+ from playwright.async_api import BrowserContext, Page
4
+
5
+ from .constants import PLATZI_URL
6
+ from .models import Chapter, TypeUnit, Unit, Video
7
+ from .utils import get_m3u8_url, get_subtitles_url, slugify
8
+
9
+
10
+ async def get_course_title(page: Page) -> str:
11
+ SELECTOR = ".CourseInfo_CourseInfo__Title__4Fwov"
12
+ EXCEPTION = Exception("No course title found")
13
+ try:
14
+ title = await page.locator(SELECTOR).first.text_content()
15
+ if not title:
16
+ raise EXCEPTION
17
+ except Exception:
18
+ await page.close()
19
+ raise EXCEPTION
20
+
21
+ return title
22
+
23
+
24
+ async def get_draft_chapters(page: Page) -> list[Chapter]:
25
+ SELECTOR = ".Syllabus_Syllabus__bVYL_ article"
26
+ EXCEPTION = Exception("No sections found")
27
+ try:
28
+ locator = page.locator(SELECTOR)
29
+
30
+ chapters: list[Chapter] = []
31
+ for i in range(await locator.count()):
32
+ chapter_name = await locator.nth(i).locator("h2").first.text_content()
33
+
34
+ if not chapter_name:
35
+ raise EXCEPTION
36
+
37
+ block_list_locator = locator.nth(i).locator(".SyllabusSection_SyllabusSection__Materials__C2hlu a")
38
+
39
+ units: list[Unit] = []
40
+ for j in range(await block_list_locator.count()):
41
+ ITEM_LOCATOR = block_list_locator.nth(j)
42
+
43
+ unit_url = await ITEM_LOCATOR.get_attribute("href")
44
+ unit_title = await ITEM_LOCATOR.locator("h3").first.text_content()
45
+
46
+ if not unit_url or not unit_title:
47
+ raise EXCEPTION
48
+
49
+ units.append(
50
+ Unit(
51
+ type=TypeUnit.VIDEO,
52
+ title=unit_title,
53
+ url=PLATZI_URL + unit_url,
54
+ slug=slugify(unit_title),
55
+ )
56
+ )
57
+
58
+ chapters.append(
59
+ Chapter(
60
+ name=chapter_name,
61
+ slug=slugify(chapter_name),
62
+ units=units,
63
+ )
64
+ )
65
+
66
+ except Exception as e:
67
+ await page.close()
68
+ raise EXCEPTION from e
69
+
70
+ return chapters
71
+
72
+
73
+ async def get_unit(context: BrowserContext, url: str) -> Unit:
74
+ TYPE_SELECTOR = ".VideoPlayer"
75
+ TITLE_SELECTOR = ".MaterialDesktopHeading_MaterialDesktopHeading-info__title__XMhhQ"
76
+ EXCEPTION = Exception("Could not collect unit data")
77
+
78
+ if "/quiz/" in url:
79
+ return Unit(
80
+ url=url,
81
+ title="Quiz",
82
+ type=TypeUnit.QUIZ,
83
+ slug=slugify("Quiz"),
84
+ )
85
+
86
+ try:
87
+ page = await context.new_page()
88
+ await page.goto(url)
89
+
90
+ await asyncio.sleep(5) # delay to avoid rate limiting
91
+
92
+ title = await page.locator(TITLE_SELECTOR).first.text_content()
93
+
94
+ if not title:
95
+ raise EXCEPTION
96
+
97
+ if await page.locator(TYPE_SELECTOR).count() == 0:
98
+ type = TypeUnit.LECTURE
99
+ video = None
100
+
101
+ else:
102
+ content = await page.content()
103
+ type = TypeUnit.VIDEO
104
+ video = Video(
105
+ url=get_m3u8_url(content),
106
+ subtitles_url=get_subtitles_url(content),
107
+ )
108
+
109
+ return Unit(
110
+ url=url,
111
+ title=title,
112
+ type=type,
113
+ video=video,
114
+ slug=slugify(title),
115
+ )
116
+
117
+ except Exception:
118
+ raise EXCEPTION
119
+
120
+ finally:
121
+ await page.close()
platzi/constants.py ADDED
@@ -0,0 +1,25 @@
1
+ from pathlib import Path
2
+
3
+ import platformdirs
4
+
5
+ APP_NAME = "Platzi"
6
+ SESSION_DIR = Path(platformdirs.user_data_dir(APP_NAME))
7
+ SESSION_FILE = SESSION_DIR / "state.json"
8
+
9
+ LOGIN_URL = "https://platzi.com/login"
10
+ LOGIN_DETAILS_URL = "https://api.platzi.com/api/v1/components/headerv2/user/"
11
+
12
+
13
+ PLATZI_URL = "https://platzi.com"
14
+ HOME_URL = PLATZI_URL + "/home"
15
+
16
+ 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"
17
+
18
+ HEADERS = {
19
+ "User-Agent": USER_AGENT,
20
+ "Referer": HOME_URL,
21
+ }
22
+
23
+
24
+ # --- Session directory ---
25
+ 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 = 5
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,63 @@
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(str, 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
+ slug: str
45
+ video: Video | None = None
46
+ resources: list[Resource] | None = None
47
+
48
+
49
+ class Chapter(BaseModel):
50
+ id: int | None = None
51
+ name: str
52
+ slug: str
53
+ description: str | None = None
54
+ units: list[Unit]
55
+
56
+
57
+ class Course(BaseModel):
58
+ id: int | None = None
59
+ name: str
60
+ slug: str
61
+ url: str
62
+ description: str | None = None
63
+ chapters: list[Chapter]
platzi/utils.py ADDED
@@ -0,0 +1,130 @@
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
+ from .constants import SESSION_DIR
10
+ from .helpers import read_json, write_json
11
+
12
+
13
+ async def progressive_scroll(
14
+ page: Page, time: float = 3, delay: float = 0.1, steps: int = 250
15
+ ):
16
+ await asyncio.sleep(3) # delay to avoid rate limiting
17
+ delta, total_time = 0.0, 0.0
18
+ while total_time < time:
19
+ await asyncio.sleep(delay)
20
+ await page.mouse.wheel(0, steps)
21
+ delta += steps
22
+ total_time += delay
23
+
24
+
25
+ def get_course_slug(url: str) -> str:
26
+ """
27
+ Extracts the course slug from a Platzi course URL.
28
+
29
+ Args:
30
+ url (str): The Platzi course URL.
31
+
32
+ Returns:
33
+ str: The course slug.
34
+
35
+ Raises:
36
+ Exception: If the URL is not a valid Platzi course URL.
37
+ """
38
+ pattern = r"https://platzi\.com/cursos/([^/]+)/?"
39
+ match = re.search(pattern, url)
40
+ if not match:
41
+ raise Exception("Invalid course url")
42
+ return match.group(1)
43
+
44
+
45
+ def clean_string(text: str) -> str:
46
+ """
47
+ Cleans the input string by removing special characters and
48
+ leading/trailing white spaces.
49
+
50
+ Args:
51
+ text (str): The input string to be cleaned.
52
+
53
+ Returns:
54
+ str: The cleaned string, with special characters removed and
55
+ leading/trailing spaces stripped.
56
+ """
57
+ pattern = r"[ºª]|[^\w\s]"
58
+ return re.sub(pattern, "", text).strip()
59
+
60
+
61
+ def slugify(text: str) -> str:
62
+ """
63
+ Slugify a string by removing special characters and
64
+ leading/trailing white spaces, and replacing spaces with hyphens.
65
+
66
+ Args:
67
+ text (str): The input string to be slugified.
68
+ Returns:
69
+ str: The slugified string.
70
+ """
71
+ return unidecode(clean_string(text)).lower().replace(" ", "-")
72
+
73
+
74
+ def get_m3u8_url(content: str) -> str:
75
+ pattern = r"https?://[^\s\"'}]+\.m3u8"
76
+ matches = re.findall(pattern, content)
77
+
78
+ if not matches:
79
+ raise Exception("No m3u8 urls found")
80
+
81
+ return matches[0]
82
+
83
+
84
+ def get_subtitles_url(content: str) -> str | None:
85
+ pattern = r"https?://[^\s\"'}]+\.vtt"
86
+ matches = re.findall(pattern, content)
87
+
88
+ if not matches:
89
+ return None
90
+
91
+ return matches[0]
92
+
93
+
94
+ async def download(url: str, path: Path, **kwargs):
95
+ overrides = kwargs.get("overrides", False)
96
+ headers = kwargs.get("headers", None)
97
+
98
+ if not overrides and path.exists():
99
+ return
100
+
101
+ path.unlink(missing_ok=True)
102
+ path.parent.mkdir(parents=True, exist_ok=True)
103
+
104
+ async with aiohttp.ClientSession() as session:
105
+ async with session.get(url, headers=headers) as response:
106
+ if response.status != 200:
107
+ raise Exception(f"Error downloading file: [{path.name}]")
108
+
109
+ with open(path.as_posix(), "wb") as file:
110
+ async for chunk in response.content.iter_chunked(1024):
111
+ file.write(chunk)
112
+
113
+
114
+ class Cache:
115
+ @classmethod
116
+ def get(cls, id: str) -> dict | None:
117
+ path = SESSION_DIR / f"{id}.json"
118
+ try:
119
+ return read_json(path.as_posix())
120
+ except Exception:
121
+ return None
122
+
123
+ @classmethod
124
+ def set(cls, id: str, content: dict) -> None:
125
+ path = SESSION_DIR / f"{id}.json"
126
+ path.parent.mkdir(parents=True, exist_ok=True)
127
+ try:
128
+ write_json(path.as_posix(), content)
129
+ except Exception:
130
+ pass
@@ -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,151 @@
1
+ Metadata-Version: 2.3
2
+ Name: platzi
3
+ Version: 0.4.2
4
+ Summary: Download your courses from platzi
5
+ License: MIT
6
+ Keywords: Platzi,downloader,courses
7
+ Author: ivansaul
8
+ Author-email: ivansaul@no-reply.com
9
+ Requires-Python: >=3.10,<4.0
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Requires-Dist: aiohttp (>=3.11.2,<4.0.0)
18
+ Requires-Dist: platformdirs (>=4.3.6,<5.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: Homepage, https://github.com/ivansaul/platzi-downloader
26
+ Project-URL: Repository, https://github.com/ivansaul/platzi-downloader
27
+ Description-Content-Type: text/markdown
28
+
29
+ <!-- markdownlint-disable MD033 MD036 MD041 MD045 MD046 -->
30
+
31
+ ![Repo Banner](https://i.imgur.com/I6zFXds.png)
32
+
33
+ <div align="center">
34
+
35
+ <h1 style="border-bottom: none">
36
+ <b><a href="#">Platzi Downloader</a></b>
37
+ </h1>
38
+
39
+ Es una herramienta de línea de comandos para descargar cursos directamente desde la terminal. Utiliza ***`Python`*** y ***`Playwright`*** para automatizar el proceso de descarga y proporciona una interfaz de usuario amigable.
40
+
41
+ ![GitHub repo size](https://img.shields.io/github/repo-size/ivansaul/platzi-downloader)
42
+ ![GitHub stars](https://img.shields.io/github/stars/ivansaul/platzi-downloader)
43
+ ![GitHub forks](https://img.shields.io/github/forks/ivansaul/platzi-downloader)
44
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
45
+ [![Discord](https://img.shields.io/badge/-Discord-424549?style=social&logo=discord)](https://discord.gg/tDvybtJ7y9)
46
+
47
+ </div>
48
+
49
+ ---
50
+
51
+ ## Instalación | Actualización
52
+
53
+ Para [`instalar` | `actualizar` ], ejecuta el siguiente comando en tu terminal:
54
+
55
+ ```console
56
+ pip install -U platzi
57
+ ```
58
+
59
+ Instala las dependencias de `playwright`:
60
+
61
+ ```console
62
+ playwright install chromium
63
+ ```
64
+
65
+ > [!IMPORTANT]
66
+ > El script utiliza ***`ffmpeg`***, como un subproceso, así que asegúrate de tener instalado y actualizado.
67
+
68
+ <details>
69
+
70
+ <summary>Tips & Tricks</summary>
71
+
72
+ ## FFmpeg Instalación
73
+
74
+ ### Ubuntu / Debian
75
+
76
+ ```console
77
+ sudo apt install ffmpeg -y
78
+ ```
79
+
80
+ ### Arch Linux
81
+
82
+ ```console
83
+ sudo pacman -S ffmpeg
84
+ ```
85
+
86
+ ### Windows [[Tutorial]][ffmpeg-youtube]
87
+
88
+ Puedes descargar la versión de `ffmpeg` para Windows desde [aquí][ffmpeg]. o algún gestor de paquetes como [`Scoop`][scoop] o [`Chocolatey`][chocolatey].
89
+
90
+ ```console
91
+ scoop install ffmpeg
92
+ ```
93
+
94
+ </details>
95
+
96
+ ## Guía de uso
97
+
98
+ ### Iniciar Sesión
99
+
100
+ Para iniciar sesión en Platzi, usa el comando login. Esto abrirá una ventana de navegador para autenticarte e iniciar sesión en Platzi.
101
+
102
+ ```console
103
+ platzi login
104
+ ```
105
+
106
+ ### Cerrar Sesión
107
+
108
+ Para cerrar sesión en Platzi y borrar tu sesión del almacenamiento local, usa el comando `logout`.
109
+
110
+ ```console
111
+ platzi logout
112
+ ```
113
+
114
+ ### Descargar un Curso
115
+
116
+ Para descargar un curso de Platzi, usa el comando download seguido de la URL del curso que deseas descargar. La URL puede encontrarse en la barra de direcciones al visualizar la página del curso en Platzi.
117
+
118
+ ```console
119
+ platzi download <url-del-curso>
120
+ ```
121
+
122
+ Ejemplo:
123
+
124
+ ```console
125
+ platzi download https://platzi.com/cursos/fastapi-2023/
126
+ ```
127
+
128
+ > [!IMPORTANT]
129
+ > Asegúrate de estar logueado antes de intentar descargar los cursos.
130
+
131
+ <br>
132
+
133
+ > [!TIP]
134
+ > Si por algún motivo se cancela la descarga, vuelve a ejecutar `platzi download <url-del-curso>` para retomar la descarga.
135
+
136
+ <br>
137
+
138
+ > [!TIP]
139
+ > Si obtienes algún error relacionado a `m3u8`o `ts` como por ejemplo; `Error downloading from .ts url` o `Error downloading m3u8`, elimina la carpeta temporal `.tmp` y vuelve a ejecutar el comando.
140
+
141
+ ## **Aviso de Uso**
142
+
143
+ 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.
144
+
145
+ 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.
146
+
147
+ [ffmpeg]: https://ffmpeg.org
148
+ [chocolatey]: https://community.chocolatey.org
149
+ [scoop]: https://scoop.sh
150
+ [ffmpeg-youtube]: https://youtu.be/JR36oH35Fgg?si=Gerco7SP8WlZVaKM
151
+
@@ -0,0 +1,15 @@
1
+ platzi/__init__.py,sha256=M8TNRpd804iCyQnqNIoBU9nI2NnbbA99gY7GjRM94cE,99
2
+ platzi/async_api.py,sha256=KwrMLgtYDR6GXbh9romlx4Seh__QWIk7dtmHuS_fyBE,7266
3
+ platzi/cli.py,sha256=z0rMKMmisXXK3q59OSw3CuENX9QTRYRxxruIQhSS4BE,1232
4
+ platzi/collectors.py,sha256=N-niY_BSlMvZrI3Wvkm84AenmYJSH-XpHvHuoZnTqOo,3420
5
+ platzi/constants.py,sha256=Yx2SsCxa7ANXh4GO5PTeTA2GVT19bh8-LB5gdTETDLw,635
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=TmjLqxCxgVIaj9sYygt8vD6zG_X9d9RbIyr53uI07ZA,4381
9
+ platzi/models.py,sha256=JxV6QO8Uiz6V6VYXQ9pDPFialF0GKvNVtQ6ofaBck8M,1096
10
+ platzi/utils.py,sha256=B08Egg1A9mOBxNlEi1H7tmjB78YvqwVD3RS1cCRDprI,3399
11
+ platzi-0.4.2.dist-info/LICENCE,sha256=MICUTOiebbpu1_drke5Pweq_MkMwvaHEK--uCjrSZp0,1064
12
+ platzi-0.4.2.dist-info/METADATA,sha256=HBqVOiN8u9OBrGzT3BxL_Qtt7bzacsxyRD0N-a1bJS8,4617
13
+ platzi-0.4.2.dist-info/WHEEL,sha256=XbeZDeTWKc1w7CSIyre5aMDU_-PohRwTQceYnisIYYY,88
14
+ platzi-0.4.2.dist-info/entry_points.txt,sha256=r4dgnvhd0obD8WAHLgYYu7X_lQ-bch6S4qbLxWJkuZQ,41
15
+ platzi-0.4.2.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 2.1.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ platzi=platzi.cli:app
3
+