Skip to content

Commit

Permalink
Adding reddit url functions
Browse files Browse the repository at this point in the history
  • Loading branch information
jpontoire committed Oct 7, 2024
1 parent 5a50ce3 commit 06c8ba4
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
39 changes: 39 additions & 0 deletions ural/reddit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import re

from ural.patterns import DOMAIN_TEMPLATE
from ural.utils import SplitResult
from ural import get_domain_name, urlpathsplit


REDDIT_DOMAIN_RE = re.compile(r"(?:reddit\.[^.]+$|redd\.it$)", re.I)
REDDIT_URL_RE = re.compile(DOMAIN_TEMPLATE % r"(?:[^.]+\.)*(?:reddit\.[^.]+|redd\.it)", re.I)


def is_reddit_url(url):
if isinstance(url, SplitResult):
return bool(re.search(REDDIT_DOMAIN_RE, url.hostname))

return bool(re.match(REDDIT_URL_RE, url))


def is_reddit_post_url(url):
if not is_reddit_url(url):
return False

return (
'/r/' in url and '/comments/' in url
)


def convert_reddit_url_to_old_url(url):
domain = get_domain_name(url)
path = urlpathsplit(url)
return f"https://old.{domain}/" + "/".join(path) + "/"


def convert_old_reddit_url_to_new_url(url):
domain = get_domain_name(url)
path = urlpathsplit(url)
return f"https://www.{domain}/" + "/".join(path) + "/"


7 changes: 7 additions & 0 deletions ural/reddit.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from typing import Optional
from ural.types import AnyUrlTarget

def is_reddit_url(url: str) -> bool : ...
def is_reddit_post_url(url: str) -> bool : ...
def convert_reddit_url_to_old_url(url: str) -> bool : ...
def convert_old_reddit_url_to_new_url(url: str) -> bool : ...

0 comments on commit 06c8ba4

Please sign in to comment.