Skip to content

Commit

Permalink
upgrade sockets
Browse files Browse the repository at this point in the history
  • Loading branch information
AugustLigh committed Apr 12, 2024
1 parent cd6e194 commit 077a462
Show file tree
Hide file tree
Showing 6 changed files with 89 additions and 125 deletions.
12 changes: 6 additions & 6 deletions AminoLightPy/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ def login(self, email: str, password: str, self_device: bool = True):
"secret": f"0 {password}",
"clientType": 100,
"deviceID": self.session.headers["NDCDEVICEID"],
"v": 2
"v": 2,
}

response = self.session.post(f"{api}/g/s/auth/login", json=data)
Expand Down Expand Up @@ -282,9 +282,9 @@ def logout(self):
})

self.profile.session = None

if self.socket_enabled:
self.close()
#TODO
# if self.socket_enabled:
# self.close()

return response.status_code

Expand Down Expand Up @@ -912,7 +912,7 @@ def get_blocker_users(self, start: int = 0, size: int = 25):
response = self.session.get(f"{api}/g/s/block/full-list?start={start}&size={size}")
return response.json()["blockerUidList"]

def get_wall_comments(self, userId: str, sorting: str, start: int = 0, size: int = 25):
def get_wall_comments(self, userId: str, sorting: str = "newest", start: int = 0, size: int = 25):
"""
List of Wall Comments of an User.
Expand Down Expand Up @@ -1184,7 +1184,7 @@ def edit_chat(self, chatId: str, doNotDisturb: bool = None, pinChat: bool = None
res.append(response.status_code)
if coHosts is not None:
data = {"uidList": coHosts}
response = self.session.post(f"{api}/g/s/chat/thread/{chatId}/co-host", data=data)
response = self.session.post(f"{api}/g/s/chat/thread/{chatId}/co-host", json=data)
res.append(response.status_code)
if viewOnly is not None:
if viewOnly:
Expand Down
10 changes: 6 additions & 4 deletions AminoLightPy/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ def __init__(self) -> None:
super().__init__()
self.headers.update({
"NDCDEVICEID": device_id,
"Accept-Encoding": "gzip, deflate",
"User-Agent": "Apple iPhone13,1 iOS v16.5 Main/3.19.0"
})

Expand All @@ -30,10 +31,11 @@ def request(self, method, url, *args, **kwargs):

if method.lower() == "post":
if "json" in kwargs and data is None:
data = kwargs.get("json")

data = kwargs.get("json") or {}
data["timestamp"] = int(time() * 1000)

data = dumps(data)

headers["Content-Type"] = "application/json"
headers["NDC-MSG-SIG"] = signature(data)

Expand Down Expand Up @@ -85,10 +87,10 @@ def upload_media(self, file: BinaryIO, fileType: str) -> str:
response = self.session.post(
url=f"{api}/g/s/media/upload",
data=data,
headers=custom_headers
headers=custom_headers,
stream=True
)


cache[file_hash] = response.json()["mediaValue"]
if len(cache) >= 32:
cache.popitem(last=False)
Expand Down
2 changes: 1 addition & 1 deletion AminoLightPy/lib/util/objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -1227,7 +1227,7 @@ class Message:
def __init__(self, data):
self.json = data

self.author: UserProfile = UserProfile(data.get("author", [])).UserProfile
self.author: UserProfile = UserProfile(data.get("author", None)).UserProfile

extensions = data.get("extensions") or {}
videoExtensions = extensions.get("videoExtensions") or {}
Expand Down
177 changes: 67 additions & 110 deletions AminoLightPy/socket.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
# pylint: disable=invalid-name

import traceback
import threading

from json import loads, dumps
from time import time, sleep
from threading import Thread
from websocket import WebSocketApp

from .lib.util.objects import Event
Expand All @@ -11,90 +13,79 @@

class SocketHandler:
def __init__(self, client, debug=False):
self.socket_url = "wss://ws1.aminoapps.com"
self.socket_url = "ws://ws1.aminoapps.com"
self.client = client
self.debug = debug
self.active = False
self.headers = None
self.socket = None
self.reconnectTime = 180

if self.socket_enabled:
self.reconnect_thread = Thread(target=self.reconnect_handler)
self.reconnect_thread.start()

def reconnect_handler(self):
while True:
sleep(self.reconnectTime)
self.event = threading.Event()

if self.active:
self.debug_print("[socket][reconnect_handler] Reconnecting Socket")
self.close()
self.run_amino_socket()

def handle_message(self, ws, data):
def on_message(self, ws, data):
print(data)
self.client.handle_socket_message(data)

def is_connected(self):
return self.socket.sock and self.socket.sock.connected

def send(self, data):
self.debug_print(f"[socket][send] Sending Data : {data}")

if not self.socket_thread:
if not self.is_connected():
self.run_amino_socket()
sleep(5)

self.socket.send(data)

def run_amino_socket(self):
try:
self.debug_print("[socket][start] Starting Socket")
def on_close(self, ws, data, status):
self.debug_print("[socket][reconnect_handler] Reconnecting Socket")
self.starting_process()

if self.client.sid is None:
return

deviceId = gen_deviceId()
def on_error(self, ws, error):
traceback.print_exc()
print("On error: ", error)

final = f"{deviceId}|{int(time() * 1000)}"
def on_open(self, ws):
self.debug_print("[socket][start] Socket Started")
self.event.set()

self.headers = {
"NDCDEVICEID": deviceId,
"NDCAUTH": f"sid={self.client.sid}",
"NDC-MSG-SIG": signature(final)
}
def starting_process(self):
deviceId = gen_deviceId()

self.socket = WebSocketApp(
f"{self.socket_url}/?signbody={final.replace('|', '%7C')}",
on_message=self.handle_message,
header=self.headers
)
final = f"{deviceId}|{int(time() * 1000)}"

self.active = True
self.socket_thread = Thread(target=self.socket.run_forever)
self.socket_thread.start()
headers = {
"NDCDEVICEID": deviceId,
"NDCAUTH": f"sid={self.client.sid}",
"NDC-MSG-SIG": signature(final)
}

if self.reconnect_thread is None:
self.reconnect_thread = Thread(target=self.reconnect_handler)
self.reconnect_thread.start()
self.socket = WebSocketApp(
f"{self.socket_url}/?signbody={final.replace('|', '%7C')}",
on_open=self.on_open,
on_error=self.on_error,
on_message=self.on_message,
on_close=self.on_close,
header=headers,
)

self.debug_print("[socket][start] Socket Started")
except Exception as e:
print(e)
threading.Thread(target=self.socket.run_forever, kwargs={
"ping_interval": 10,
"ping_payload": '{"t": 116, "o": {"threadChannelUserInfoList": []}}'
}).start()

def close(self):
self.debug_print("[socket][close] Closing Socket")
def run_amino_socket(self):
if self.client.sid is None:
return

self.active = False
try:
self.socket.close()
except Exception as closeError:
self.debug_print(f"[socket][close] Error while closing Socket : {closeError}")
threading.Thread(target=self.starting_process).start()
self.event.wait()

def debug_print(self, message):
if self.debug:
print(message)


class SocketRequests:
def __init__(self) -> None:
def __init__(self: SocketHandler) -> None:
self.active_live_chats = set()

def join_voice_chat(self, comId: int, chatId: str, joinType: int = 1):
Expand Down Expand Up @@ -140,19 +131,6 @@ def join_video_chat(self, comId: int, chatId: str, joinType: int = 1):
data = dumps(data)
self.send(data)

def join_video_chat_as_viewer(self, comId: int, chatId: str):
data = {
"o":
{
"ndcId": int(comId),
"threadId": chatId,
"joinRole": 2,
},
"t": 112
}
data = dumps(data)
self.send(data)


# Fixed by vedansh#4039
def leave_from_live_chat(self, chatId: str):
Expand All @@ -163,32 +141,22 @@ def leave_from_live_chat(self, chatId: str):
def run_vc(self, comId: int, chatId: str, joinType: str):
while chatId in self.active_live_chats:
try:
data = {
"o": {
"ndcId": int(comId),
"threadId": chatId,
"joinRole": joinType,
},
"t": 112
}
data = dumps(data)
self.send(data)
self.join_video_chat(
comId=comId,
chatId=chatId,
joinType=joinType
)
sleep(60)

except Exception as e:
print(e)

def start_vc(self, comId: int, chatId: str, joinType: int = 1):
data = {
"o": {
"ndcId": int(comId),
"threadId": chatId,
"joinRole": joinType,
},
"t": 112
}
data = dumps(data)
self.send(data)
self.join_video_chat(
comId=comId,
chatId=chatId,
joinType=joinType
)
data = {
"o": {
"ndcId": int(comId),
Expand All @@ -200,21 +168,15 @@ def start_vc(self, comId: int, chatId: str, joinType: int = 1):
data = dumps(data)
self.send(data)
self.active_live_chats.add(chatId)
Thread(target=self.run_vc, args=(comId, chatId, joinType)).start()
threading.Thread(target=self.run_vc, args=(comId, chatId, joinType)).start()

def end_vc(self, comId: int, chatId: str, joinType: int = 2):
self.leave_from_live_chat(chatId)
data = {
"o": {
"ndcId": int(comId),
"threadId": chatId,
"joinRole": joinType,
},
"t": 112
}
data = dumps(data)
self.send(data)
self.active_live_chats.remove(chatId)
self.join_video_chat(
comId=comId,
chatId=chatId,
joinType=joinType
)

def Browsing(self, comId: int, blogId: str = None, blogType: int = 0):
"""
Expand Down Expand Up @@ -309,16 +271,11 @@ def LeaderBoards(self, comId: int,):
self.send(data)

def start_video_chat(self, comId: str, chatId: str, joinType: int = 1):
data = {
"o": {
"ndcId": comId,
"threadId": chatId,
"joinRole": joinType,
},
"t": 112
}
data = dumps(data)
self.send(data)
self.join_video_chat(
comId=comId,
chatId=chatId,
joinType=joinType
)

data = {
"o": {
Expand Down
11 changes: 8 additions & 3 deletions AminoLightPy/sub_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1382,10 +1382,15 @@ def get_wall_comments(self, userId: str, sorting: str, start: int = 0, size: int
return objects.CommentList(response.json()["commentList"]).CommentList

def get_recent_blogs(self, pageToken: str = None, start: int = 0, size: int = 25):
if pageToken is not None: url = f"{api}/x{self.comId}/s/feed/blog-all?pagingType=t&pageToken={pageToken}&size={size}"
else: url = f"{api}/x{self.comId}/s/feed/blog-all?pagingType=t&start={start}&size={size}"
params = {
"pagingType": "t",
"start": start,
"size": size,
}
if pageToken:
params["pageToken"] = pageToken

response = self.session.get(url)
response = self.session.get(f"{api}/x{self.comId}/s/feed/blog-all", params=params)
return objects.RecentBlogs(response.json()).RecentBlogs

def get_chat_users(self, chatId: str, start: int = 0, size: int = 25):
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@

setup(
name="amino.light.py",
version="0.1.4",
version="0.1.5",
url="https://github.com/AugustLigh/AminoLightPy",
license="MIT",
description="Best Amino.py alternative",
Expand Down

0 comments on commit 077a462

Please sign in to comment.