Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added authentication via username and password rather than the auth token #1

Merged
merged 2 commits into from
May 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file removed client/__init__.py
Empty file.
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
[tool.poetry]
name = "client"
name = "truthbrush"
version = "0.1.0"
description = "API client for Truth Social"
authors = ["R. Miles McCain <github@sendmiles.email>"]
license = "Apache 2.0"

[tool.poetry.scripts]
ts = "client.cli:cli"
truthbrush = "truthbrush.cli:cli"

[tool.poetry.dependencies]
python = "^3.9"
Expand Down
1 change: 1 addition & 0 deletions truthbrush/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from truthbrush.api import Api
69 changes: 64 additions & 5 deletions client/api.py → truthbrush/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,26 @@
logging.basicConfig(level=logging.DEBUG)


BASE_URL = "https://truthsocial.com/api"
BASE_URL = "https://truthsocial.com"
API_BASE_URL = "https://truthsocial.com/api"
USER_AGENT = "TruthSocial/71 CFNetwork/1331.0.7 Darwin/21.4.0"

# Oauth client credentials, from https://truthsocial.com/packs/js/application-e63292e218e83e726270.js
CLIENT_ID = "9X1Fdd-pxNsAgEDNi_SfhJWi8T-vLuV2WVzKIbkTCw4"
CLIENT_SECRET = "ozF8jzI4968oTKFkEnsBC-UbLPCdrSv0MkXGQu2o_-M"

proxies = {"http": os.getenv("http_proxy"), "https": os.getenv("https_proxy")}


class Api:
def __init__(self, auth_id):
self.auth_id = auth_id
def __init__(self, username, password):
self.username = username
self.password = password
self.ratelimit_max = 300
self.ratelimit_remaining = None
self.ratelimit_reset = None
if username and password:
self.auth_id = self.get_auth_id(username, password)

def _make_session(self):
s = requests.Session()
Expand Down Expand Up @@ -63,7 +71,7 @@ def _check_ratelimit(self, resp):

def _get(self, url: str, params: dict = None) -> Any:
resp = self._make_session().get(
BASE_URL + url,
API_BASE_URL + url,
params=params,
headers={
"authorization": "Bearer " + self.auth_id,
Expand All @@ -77,7 +85,7 @@ def _get(self, url: str, params: dict = None) -> Any:
return resp.json()

def _get_paginated(self, url: str, params: dict = None, resume: str = None) -> Any:
next_link = BASE_URL + url
next_link = API_BASE_URL + url

if resume is not None:
next_link += f"?max_id={resume}"
Expand Down Expand Up @@ -140,6 +148,26 @@ def user_followers(
if maximum is not None and n_output >= maximum:
return

def user_following(
self,
user_handle: str = None,
user_id: str = None,
maximum: int = 1000,
resume: str = None,
) -> Iterator[dict]:
assert user_handle is not None or user_id is not None
user_id = user_id if user_id is not None else self.lookup(user_handle)["id"]

n_output = 0
for followers_batch in self._get_paginated(
f"/v1/accounts/{user_id}/following", resume=resume
):
for f in followers_batch:
yield f
n_output += 1
if maximum is not None and n_output >= maximum:
return

def pull_statuses(
self, username: str, created_after: date, replies: bool
) -> List[dict]:
Expand Down Expand Up @@ -198,3 +226,34 @@ def pull_statuses(
all_posts.append(post)

return all_posts

def get_auth_id(self, username: str, password: str) -> str:
"""Logs in to Truth account and returns the session token"""
url = BASE_URL + "/oauth/token"
try:

payload = {
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"grant_type": "password",
"username": username,
"password": password,
}

sess_req = requests.request(
"POST",
url,
params=payload,
headers={
"user-agent": USER_AGENT,
},
)
sess_req.raise_for_status()
except requests.exceptions.HTTPError as e:
logger.error(f"Failed login request: {str(e)}")
return None

if not sess_req.json()["access_token"]:
raise ValueError("Invalid truthsocial.com credentials provided!")

return sess_req.json()["access_token"]
2 changes: 1 addition & 1 deletion client/cli.py → truthbrush/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from .api import Api

load_dotenv() # take environment variables from .env.
api = Api(os.getenv("TRUTHSOCIAL_TOKEN"))
api = Api(os.getenv("TRUTHSOCIAL_USERNAME"), os.getenv("TRUTHSOCIAL_PASSWORD"))


@click.group()
Expand Down