Skip to content

Commit

Permalink
formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
joeyagreco committed Jan 26, 2024
1 parent 3f7174f commit ce80607
Show file tree
Hide file tree
Showing 21 changed files with 303 additions and 249 deletions.
19 changes: 10 additions & 9 deletions pythontextnow/api/Client.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ class ClientConfig:
"""
Used to hold the Client config.
"""

username: str
headers: dict
cookies: dict
Expand All @@ -22,19 +23,19 @@ class Client:
"""
This class is used to store and set up initial Client configuration.
"""

client_config: Optional[ClientConfig] = None

@classmethod
def set_client_config(cls, *, username: str, sid_cookie: str) -> None:
headers = {
"user-agent": get_random_user_agent(),
"Cookie": f"connect.sid={sid_cookie};",
}

client_config = ClientConfig(username=username,
headers=headers,
cookies=dict(), # for now, no cookies are needed
last_call_time=datetime.datetime.now())
headers = {"user-agent": get_random_user_agent(), "Cookie": f"connect.sid={sid_cookie};"}

client_config = ClientConfig(
username=username,
headers=headers,
cookies=dict(), # for now, no cookies are needed
last_call_time=datetime.datetime.now(),
)
cls.client_config = client_config

@classmethod
Expand Down
171 changes: 91 additions & 80 deletions pythontextnow/api/TextNowAPI.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

from pythontextnow.api.Client import Client, ClientConfig
from pythontextnow.decorator.cooldown import enforce_cooldown
from pythontextnow.enum import MessageType, MessageDirection, ContactType, ReadStatus
from pythontextnow.enum import ContactType, MessageDirection, MessageType, ReadStatus
from pythontextnow.model.Group import Group
from pythontextnow.model.Message import Message
from pythontextnow.model.MultiMediaMessage import MultiMediaMessage
Expand Down Expand Up @@ -39,46 +39,59 @@ def __client_config(self) -> ClientConfig:

@enforce_cooldown
def send_message(self, *, message: str, send_to: str) -> None:
json_data = {"contact_value": send_to,
"contact_type": ContactType.DEFAULT.value,
"message": message,
"read": ReadStatus.READ.value,
"message_direction": MessageDirection.OUTGOING.value,
"message_type": MessageType.TEXT.value,
"from_name": self.__client_config.username,
"has_video": False,
"new": True,
"date": datetime.now().isoformat()}
json_data = {
"contact_value": send_to,
"contact_type": ContactType.DEFAULT.value,
"message": message,
"read": ReadStatus.READ.value,
"message_direction": MessageDirection.OUTGOING.value,
"message_type": MessageType.TEXT.value,
"from_name": self.__client_config.username,
"has_video": False,
"new": True,
"date": datetime.now().isoformat(),
}

data = {"json": json.dumps(json_data)}

response = requests.post(
f"{self.__BASE_URL}{self.__API_ROUTE}{self.__USERS_ROUTE}/{self.__client_config.username}{self.__MESSAGES_ROUTE}",
headers=self.__client_config.headers,
cookies=self.__client_config.cookies,
data=data)
data=data,
)
response.raise_for_status()

@enforce_cooldown
def get_messages(self, conversation_phone_number: str,
*,
start_message_id: Optional[str] = None,
page_size: Optional[int],
get_archived: Optional[bool]) -> list[Message]:
def get_messages(
self,
conversation_phone_number: str,
*,
start_message_id: Optional[str] = None,
page_size: Optional[int],
get_archived: Optional[bool],
) -> list[Message]:
"""
This gets messages from the conversation with the given phone number.
This will get all messages before (but not including) the message with the given start_message_id.
If the given page_size is greater than the max allowed (30), will default to 30.
"""
page_size = page_size if page_size <= self.__MAX_MESSAGE_RESPONSE_SIZE else self.__MAX_MESSAGE_RESPONSE_SIZE
contact_value = f"+{conversation_phone_number}" if not conversation_phone_number.startswith(
"+") else conversation_phone_number
page_size = (
page_size
if page_size <= self.__MAX_MESSAGE_RESPONSE_SIZE
else self.__MAX_MESSAGE_RESPONSE_SIZE
)
contact_value = (
f"+{conversation_phone_number}"
if not conversation_phone_number.startswith("+")
else conversation_phone_number
)
params = {
"contact_value": contact_value,
"direction": "past",
"page_size": page_size,
"get_archived": 1 if get_archived else 0
"get_archived": 1 if get_archived else 0,
}
if start_message_id is not None:
params["start_message_id"] = start_message_id
Expand All @@ -88,7 +101,8 @@ def get_messages(self, conversation_phone_number: str,
response = requests.get(
url_with_params,
headers=self.__client_config.headers,
cookies=self.__client_config.cookies)
cookies=self.__client_config.cookies,
)
response.raise_for_status()

message_dicts = response.json()["messages"]
Expand All @@ -105,22 +119,20 @@ def get_messages(self, conversation_phone_number: str,

@enforce_cooldown
def mark_message_as_read(self, message: Message) -> None:

clean_number = quote(message.number)
url = f"{self.__BASE_URL}{self.__API_ROUTE}{self.__USERS_ROUTE}/{self.__client_config.username}{self.__CONVERSATIONS_ROUTE}/{clean_number}"

params = {
"latest_message_id": message.id_,
"http_method": "PATCH"
}
params = {"latest_message_id": message.id_, "http_method": "PATCH"}

data = {"read": True}

response = requests.patch(url,
params=params,
data=data,
cookies=self.__client_config.cookies,
headers=self.__client_config.headers)
response = requests.patch(
url,
params=params,
data=data,
cookies=self.__client_config.cookies,
headers=self.__client_config.headers,
)
response.raise_for_status()

@enforce_cooldown
Expand All @@ -130,9 +142,9 @@ def delete_message(self, *, message_id: str) -> None:
"""

url = f"{self.__BASE_URL}{self.__API_ROUTE}{self.__USERS_ROUTE}/{self.__client_config.username}{self.__MESSAGES_ROUTE}/{message_id}"
response = requests.delete(url,
cookies=self.__client_config.cookies,
headers=self.__client_config.headers)
response = requests.delete(
url, cookies=self.__client_config.cookies, headers=self.__client_config.headers
)
response.raise_for_status()

@enforce_cooldown
Expand All @@ -147,7 +159,8 @@ def get_attachment_url(self, *, message_type: MessageType) -> str:
response = requests.get(
url_with_params,
headers=self.__client_config.headers,
cookies=self.__client_config.cookies)
cookies=self.__client_config.cookies,
)
response.raise_for_status()

return response.json()["result"]
Expand All @@ -158,28 +171,29 @@ def upload_raw_media(self, *, attachment_url: str, raw_media: bytes, media_type:
Uploads the given raw_media to the given URL.
"""
headers = {
'accept': '*/*',
'content-type': media_type,
'accept-language': 'en-US,en;q=0.9',
"accept": "*/*",
"content-type": media_type,
"accept-language": "en-US,en;q=0.9",
"mode": "cors",
"method": "PUT",
"credentials": 'omit'
"credentials": "omit",
}

response = requests.put(attachment_url,
data=raw_media,
headers=headers,
cookies=self.__client_config.cookies)
response = requests.put(
attachment_url, data=raw_media, headers=headers, cookies=self.__client_config.cookies
)
response.raise_for_status()

@enforce_cooldown
def send_attachment(self, *,
conversation_phone_number: str,
message_type: MessageType,
file_type: str,
is_video: bool,
attachment_url: str) -> None:

def send_attachment(
self,
*,
conversation_phone_number: str,
message_type: MessageType,
file_type: str,
is_video: bool,
attachment_url: str,
) -> None:
data = {
"contact_value": conversation_phone_number,
"contact_type": ContactType.ALTERNATE.value,
Expand All @@ -191,23 +205,25 @@ def send_attachment(self, *,
"new": True,
"date": datetime.now().isoformat(),
"attachment_url": attachment_url,
"media_type": file_type
"media_type": file_type,
}

url = f"{self.__BASE_URL}{self.__API_ROUTE}/{self.__VERSION}{self.__SEND_ATTACHMENT_ROUTE}"

response = requests.post(url,
data=data,
headers=self.__client_config.headers,
cookies=self.__client_config.cookies)
response = requests.post(
url,
data=data,
headers=self.__client_config.headers,
cookies=self.__client_config.cookies,
)
response.raise_for_status()

@enforce_cooldown
def get_groups(self) -> list[Group]:
url = f"{self.__BASE_URL}{self.__API_ROUTE}{self.__USERS_ROUTE}/{self.__client_config.username}{self.__GROUPS_ROUTE}"
response = requests.get(url,
headers=self.__client_config.headers,
cookies=self.__client_config.cookies)
response = requests.get(
url, headers=self.__client_config.headers, cookies=self.__client_config.cookies
)
response.raise_for_status()

group_list = list()
Expand All @@ -218,9 +234,9 @@ def get_groups(self) -> list[Group]:
@enforce_cooldown
def get_user(self) -> User:
url = f"{self.__BASE_URL}{self.__API_ROUTE}{self.__USERS_ROUTE}/{self.__client_config.username}"
response = requests.get(url,
headers=self.__client_config.headers,
cookies=self.__client_config.cookies)
response = requests.get(
url, headers=self.__client_config.headers, cookies=self.__client_config.cookies
)
response.raise_for_status()

return User.from_dict(response.json())
Expand All @@ -232,17 +248,10 @@ def create_group(self, *, phone_numbers: list[str]) -> Group:
"""
url = f"{self.__BASE_URL}{self.__API_ROUTE}{self.__USERS_ROUTE}/{self.__client_config.username}{self.__GROUPS_ROUTE}"

data = {
"json": {
"members": list()
}
}
data = {"json": {"members": list()}}

for phone_number in phone_numbers:
member = {
"contact_value": phone_number,
"contact_type": ContactType.ALTERNATE.value
}
member = {"contact_value": phone_number, "contact_type": ContactType.ALTERNATE.value}
data["json"]["members"].append(member)

data = parse.urlencode(data, quote_via=urllib.parse.quote)
Expand All @@ -252,10 +261,9 @@ def create_group(self, *, phone_numbers: list[str]) -> Group:
headers = self.__client_config.headers
headers["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8"

response = requests.post(url,
data=data,
headers=headers,
cookies=self.__client_config.cookies)
response = requests.post(
url, data=data, headers=headers, cookies=self.__client_config.cookies
)
response.raise_for_status()

return Group.from_dict(response.json())
Expand All @@ -265,11 +273,14 @@ def delete_conversation(self, *, conversation_phone_number: str) -> None:
"""
Deletes the conversation with the given phone number.
"""
conversation_phone_number = conversation_phone_number if not conversation_phone_number.startswith(
"+") else conversation_phone_number[1:]
conversation_phone_number = (
conversation_phone_number
if not conversation_phone_number.startswith("+")
else conversation_phone_number[1:]
)
url = f"{self.__BASE_URL}{self.__API_ROUTE}{self.__USERS_ROUTE}/{self.__client_config.username}{self.__CONVERSATIONS_ROUTE}/%2B{conversation_phone_number}"

response = requests.delete(url,
headers=self.__client_config.headers,
cookies=self.__client_config.cookies)
response = requests.delete(
url, headers=self.__client_config.headers, cookies=self.__client_config.cookies
)
response.raise_for_status()
4 changes: 3 additions & 1 deletion pythontextnow/decorator/cooldown.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ def wrapFunction(*args, **kwargs):
difference_seconds = (now - client_config.last_call_time).total_seconds()
if difference_seconds < cooldown_seconds:
# enforce cooldown
CustomLogger.getLogger().warning(f"ENFORCING COOLDOWN FOR {cooldown_seconds} SECONDS...")
CustomLogger.getLogger().warning(
f"ENFORCING COOLDOWN FOR {cooldown_seconds} SECONDS..."
)
time.sleep(cooldown_seconds)
Client.update(last_call_time=now)
return function(*args, **kwargs)
Expand Down
2 changes: 1 addition & 1 deletion pythontextnow/enum/ContactType.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from __future__ import annotations

from enum import unique, Enum
from enum import Enum, unique


@unique
Expand Down
2 changes: 1 addition & 1 deletion pythontextnow/enum/MessageDirection.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from __future__ import annotations

from enum import unique, Enum
from enum import Enum, unique


@unique
Expand Down
2 changes: 1 addition & 1 deletion pythontextnow/enum/ReadStatus.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from enum import unique, Enum
from enum import Enum, unique


@unique
Expand Down
4 changes: 2 additions & 2 deletions pythontextnow/model/Avatar.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ def from_dict(cls, avatar_dict: dict) -> Avatar:
return Avatar(
background_color=avatar_dict["background_colour"],
picture=avatar_dict["picture"],
initials=avatar_dict["initials"]
initials=avatar_dict["initials"],
)

@classmethod
def to_dict(cls, avatar: Avatar) -> dict:
return {
"background_colour": avatar.background_color,
"picture": avatar.picture,
"initials": avatar.initials
"initials": avatar.initials,
}
Loading

0 comments on commit ce80607

Please sign in to comment.