Skip to content

Commit

Permalink
Refactoring (#3)
Browse files Browse the repository at this point in the history
New Post class supporting all the capabilities
Static typiing
  • Loading branch information
NicKoehler authored Jun 16, 2023
1 parent f7ea26d commit 06017f4
Show file tree
Hide file tree
Showing 11 changed files with 408 additions and 39 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -127,3 +127,6 @@ dmypy.json

# Pyre type checker
.pyre/

# vscode
.vscode
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@ from pythorhead import Lemmy
lemmy = Lemmy("https://lemmy.dbzer0.com")
lemmy.log_in("username", "password")
community_id = lemmy.discover_community("botart")
lemmy.post(community_id, "Hello Lemmy World")
```
lemmy.post.create(community_id, "Hello Lemmy World")
```
2 changes: 1 addition & 1 deletion pythorhead/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
from pythorhead.lemmy import Lemmy
from pythorhead.lemmy import Lemmy
33 changes: 33 additions & 0 deletions pythorhead/auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import requests
from loguru import logger


class Singleton(type):
_instances = {}

def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]


class Authentication(metaclass=Singleton):
token: str | None = None
api_base_url: str | None = None

def log_in(self, username_or_email: str, password: str) -> bool:
payload = {
"username_or_email": username_or_email,
"password": password,
}
try:
re = requests.post(f"{self.api_base_url}/user/login", json=payload)
self.token = re.json()["jwt"]

except Exception as err:
logger.error(f"Something went wrong while logging in as {username_or_email}: {err}")
return False
return True

def log_out(self) -> None:
self.token = None
51 changes: 15 additions & 36 deletions pythorhead/lemmy.py
Original file line number Diff line number Diff line change
@@ -1,52 +1,31 @@
import requests
from loguru import logger

class Lemmy:
from pythorhead.auth import Authentication
from pythorhead.post import Post


_auth_token = None
_api_base_url = None
class Lemmy:
post: Post
_auth: Authentication
_known_communities = {}

def __init__(self, api_base_url):
self._api_base_url = api_base_url
def __init__(self, api_base_url: str) -> None:
self._auth = Authentication()
self._auth.api_base_url = f"{api_base_url}/api/v3"
self.post = Post()

def log_in(self, username_or_email: str, password: str) -> bool:
return Authentication().log_in(username_or_email, password)

def log_in(self, username_or_email, password):
payload = {
"username_or_email": username_or_email,
"password": password
}
try:
re = requests.post(f"{self._api_base_url}/api/v3/user/login", json=payload)
self._auth_token = re.json()["jwt"]
except Exception as err:
logger.error(f"Something went wrong while logging in as {username_or_email}: {err}")
return False
return True

def discover_community(self, community_name):
def discover_community(self, community_name: str) -> int | None:
if community_name in self._known_communities:
return self._known_communities[community_name]
try:
req = requests.get(f"{self._api_base_url}/api/v3/community?name={community_name}")
req = requests.get(f"{self._auth.api_base_url}/community?name={community_name}")
community_id = req.json()["community_view"]["community"]["id"]
self._known_communities[community_name] = community_id
except Exception as err:
logger.error(f"Error when looking up community '{community_name}': {err}")
return None
return
return community_id

def post(self, community_id, post_name, post_url = None, post_body = None):
new_post = {
"auth": self._auth_token,
"community_id": community_id,
"name": post_name,
}
if post_url:
new_post["url"] = post_url
if post_body:
new_post["body"] = post_body
re = requests.post(f"{self._api_base_url}/api/v3/post", json=new_post)
if not re.ok:
logger.error(f"Error encountered while posting: {re.text}")
return re.ok
Loading

0 comments on commit 06017f4

Please sign in to comment.