2022-09-08 12:32:31 +00:00
|
|
|
from .http import HTTPRequest, urlopen
|
|
|
|
from .message import Message
|
2022-01-22 07:12:24 +00:00
|
|
|
|
2022-09-08 12:32:31 +00:00
|
|
|
from urllib.error import HTTPError
|
|
|
|
|
|
|
|
from const import API_URL, X_API_KEY
|
|
|
|
|
|
|
|
import json
|
2022-01-22 07:12:24 +00:00
|
|
|
|
|
|
|
class RomeoAPI:
|
2022-09-08 12:32:31 +00:00
|
|
|
def __init__(self, login=True, username=None, password=None):
|
|
|
|
self.session = None
|
|
|
|
|
2022-01-22 07:12:24 +00:00
|
|
|
if login:
|
|
|
|
self.login(username, password)
|
2022-09-08 12:32:31 +00:00
|
|
|
|
2022-01-22 07:12:24 +00:00
|
|
|
|
|
|
|
def login(self, username, password):
|
2022-09-08 12:32:31 +00:00
|
|
|
payload = {"username": username,
|
|
|
|
"password": password,
|
2022-01-22 07:12:24 +00:00
|
|
|
"keep_login": True}
|
|
|
|
|
2022-09-08 12:32:31 +00:00
|
|
|
try:
|
|
|
|
response = urlopen(HTTPRequest(API_URL + "session?lang=en", headers=self.build_headers()),
|
2022-01-22 07:12:24 +00:00
|
|
|
json.dumps(payload).encode("utf-8"))
|
2022-09-08 12:32:31 +00:00
|
|
|
except HTTPError as e:
|
|
|
|
print(e.read())
|
|
|
|
raise
|
2022-01-22 07:12:24 +00:00
|
|
|
|
|
|
|
data = json.load(response)
|
|
|
|
self.session = data
|
|
|
|
|
|
|
|
def build_headers(self, additional={}):
|
|
|
|
headers = {
|
2022-09-08 12:32:31 +00:00
|
|
|
"X-Api-Key": X_API_KEY,
|
|
|
|
"X-Session-Id": self.session["session_id"] if self.session else ""
|
2022-01-22 07:12:24 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
for key, value in additional:
|
|
|
|
headers[key] = value
|
|
|
|
|
|
|
|
return headers
|
|
|
|
|
|
|
|
def messages(self, count=16384):
|
|
|
|
headers = self.build_headers()
|
|
|
|
response = urlopen(
|
|
|
|
HTTPRequest(API_URL + "messages?lang=en&length=%i" % count, headers=headers))
|
|
|
|
data = json.load(response)
|
|
|
|
|
|
|
|
for message in data["items"]:
|
2022-09-08 12:32:31 +00:00
|
|
|
if messageobj := Message.from_dict(message):
|
|
|
|
yield messageobj
|