| 38 | |
| 39 | |
| 40 | class MediumParser: |
| 41 | __slots__ = ( |
| 42 | "cache", |
| 43 | "host_address", |
| 44 | "jinja_template", |
| 45 | "post_template", |
| 46 | "timeout", |
| 47 | "medium_api", |
| 48 | ) |
| 49 | |
| 50 | def __init__( |
| 51 | self, |
| 52 | cache: AbstractCacheBackend, |
| 53 | medium_api: MediumApi, |
| 54 | timeout: int, |
| 55 | host_address: str, |
| 56 | template_folder: str = "./templates", |
| 57 | ): |
| 58 | self.timeout: int = timeout |
| 59 | self.cache: AbstractCacheBackend = cache |
| 60 | self.host_address: str = host_address |
| 61 | self.jinja_template: jinja2.Environment = jinja2.Environment( |
| 62 | loader=jinja2.FileSystemLoader(template_folder) |
| 63 | ) |
| 64 | self.post_template: jinja2.Template = self.jinja_template.get_template( |
| 65 | "post.html" |
| 66 | ) |
| 67 | self.medium_api: MediumApi = medium_api |
| 68 | |
| 69 | async def resolve(self, unknown: str) -> str: |
| 70 | logger.debug(f"We got some unknown data: {unknown=}. Trying resolve them...///") |
| 71 | post_id = None |
| 72 | |
| 73 | try: |
| 74 | logger.debug("...maybe it's URL. Let's checkout...") |
| 75 | post_id = await self.resolve_url(unknown) |
| 76 | except Exception as e: |
| 77 | logger.exception(e) |
| 78 | logger.error(f"Error while resolving URL: {e}") |
| 79 | |
| 80 | if is_has_valid_medium_post_id(unknown): |
| 81 | logger.debug("Seems like it's valid post_id") |
| 82 | return extract_hex_string(unknown) |
| 83 | |
| 84 | logger.error(f"Unknown data: {unknown}") |
| 85 | |
| 86 | raise e |
| 87 | |
| 88 | return post_id |
| 89 | |
| 90 | async def resolve_url(self, url: str) -> str: |
| 91 | sanitized_url = correct_url(url) |
| 92 | if not is_valid_url(url) or not await is_valid_medium_url(sanitized_url): |
| 93 | raise InvalidURL(f"Invalid Medium URL: {sanitized_url}") |
| 94 | |
| 95 | post_id = await resolve_medium_url(sanitized_url, self.timeout) |
| 96 | if not post_id: |
| 97 | raise InvalidMediumPostURL( |
no outgoing calls