mirror of
https://github.com/Sneed-Group/pypush-plus-plus
synced 2024-12-23 19:32:29 -06:00
Fix ignoring gateway parameter (#34)
* Add custom exceptions and fix logging * Fix "done" message * Fix gateway stuff * Fix `P:` * Fix cscook's `--reg-notify` code
This commit is contained in:
parent
b4a288171b
commit
9a0f55ab18
3 changed files with 90 additions and 22 deletions
24
demo.py
24
demo.py
|
@ -16,6 +16,8 @@ import imessage
|
||||||
import trio
|
import trio
|
||||||
import argparse
|
import argparse
|
||||||
|
|
||||||
|
from exceptions import *
|
||||||
|
|
||||||
logging.basicConfig(
|
logging.basicConfig(
|
||||||
level=logging.NOTSET, format="%(message)s", datefmt="[%X]", handlers=[RichHandler()]
|
level=logging.NOTSET, format="%(message)s", datefmt="[%X]", handlers=[RichHandler()]
|
||||||
)
|
)
|
||||||
|
@ -107,10 +109,9 @@ async def main(args: argparse.Namespace):
|
||||||
print("Would you like to register a phone number? (y/n)")
|
print("Would you like to register a phone number? (y/n)")
|
||||||
if input("> ").lower() == "y":
|
if input("> ").lower() == "y":
|
||||||
import sms_registration
|
import sms_registration
|
||||||
if args.gateway is not None:
|
|
||||||
sms_registration.GATEWAY = args.gateway
|
if args.phone is None:
|
||||||
if args.phone is not None:
|
raise GatewayConnectionError("You did not supply an IP address.")
|
||||||
sms_registration.PHONE_IP = args.phone
|
|
||||||
|
|
||||||
if "phone" in CONFIG:
|
if "phone" in CONFIG:
|
||||||
phone_sig = b64decode(CONFIG["phone"].get("sig"))
|
phone_sig = b64decode(CONFIG["phone"].get("sig"))
|
||||||
|
@ -119,7 +120,9 @@ async def main(args: argparse.Namespace):
|
||||||
phone_number, phone_sig = sms_registration.parse_pdu(args.pdu, None)
|
phone_number, phone_sig = sms_registration.parse_pdu(args.pdu, None)
|
||||||
else:
|
else:
|
||||||
import sms_registration
|
import sms_registration
|
||||||
phone_number, phone_sig = sms_registration.register(conn.credentials.token, args.trigger_pdu)
|
phone_number, phone_sig = sms_registration.register(push_token=conn.credentials.token,
|
||||||
|
no_parse=args.trigger_pdu, gateway=args.gateway,
|
||||||
|
phone_ip=args.phone)
|
||||||
CONFIG["phone"] = {
|
CONFIG["phone"] = {
|
||||||
"number": phone_number,
|
"number": phone_number,
|
||||||
"sig": b64encode(phone_sig).decode(),
|
"sig": b64encode(phone_sig).decode(),
|
||||||
|
@ -152,7 +155,7 @@ async def main(args: argparse.Namespace):
|
||||||
|
|
||||||
if args.reregister:
|
if args.reregister:
|
||||||
print("Re-registering...")
|
print("Re-registering...")
|
||||||
users = register(conn, users)
|
register(conn, users)
|
||||||
|
|
||||||
CONFIG["users"] = []
|
CONFIG["users"] = []
|
||||||
for user in users:
|
for user in users:
|
||||||
|
@ -165,10 +168,11 @@ async def main(args: argparse.Namespace):
|
||||||
"id_cert": user.id_cert,
|
"id_cert": user.id_cert,
|
||||||
"handles": user.handles,
|
"handles": user.handles,
|
||||||
})
|
})
|
||||||
|
|
||||||
if "P:" in str(user.user_id):
|
if "P:" in str(user.user_id):
|
||||||
expiration = get_not_valid_after_timestamp(user.id_cert)
|
expiration = get_not_valid_after_timestamp(user.id_cert)
|
||||||
expiration = str(expiration) + " UTC"
|
expiration = str(expiration) + " UTC"
|
||||||
print("Number registration is valid until "+ expiration)
|
print(f"Number registration is valid until {expiration}. (YYYY/MM/DD)")
|
||||||
else:
|
else:
|
||||||
email_user = user
|
email_user = user
|
||||||
for n in range(len(user.handles)):
|
for n in range(len(user.handles)):
|
||||||
|
@ -178,9 +182,10 @@ async def main(args: argparse.Namespace):
|
||||||
safe_config()
|
safe_config()
|
||||||
if args.reg_notify:
|
if args.reg_notify:
|
||||||
im = imessage.iMessageUser(conn, email_user)
|
im = imessage.iMessageUser(conn, email_user)
|
||||||
|
im.current_handle = email_addr
|
||||||
await im.send(imessage.iMessage.create(im, "Number registration is valid until " + expiration, [email_addr]))
|
await im.send(imessage.iMessage.create(im, "Number registration is valid until " + expiration, [email_addr]))
|
||||||
|
|
||||||
print(f"Done?")
|
print("Done!")
|
||||||
|
|
||||||
if args.alive:
|
if args.alive:
|
||||||
logging.getLogger("apns").setLevel(logging.DEBUG)
|
logging.getLogger("apns").setLevel(logging.DEBUG)
|
||||||
|
@ -313,7 +318,6 @@ if __name__ == "__main__":
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
if args.pdu is not None and not args.pdu.startswith("REG-RESP"):
|
if args.pdu is not None and not args.pdu.startswith("REG-RESP"):
|
||||||
print("Invalid REG-RESP PDU")
|
raise InvalidResponseError("Received invalid REG-RESP PDU from Gateway Client.")
|
||||||
exit(1)
|
|
||||||
|
|
||||||
trio.run(main, args)
|
trio.run(main, args)
|
||||||
|
|
31
exceptions.py
Normal file
31
exceptions.py
Normal file
|
@ -0,0 +1,31 @@
|
||||||
|
|
||||||
|
class GatewayError(Exception):
|
||||||
|
def __init__(self, reason):
|
||||||
|
self.reason = reason
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return self.reason
|
||||||
|
|
||||||
|
|
||||||
|
class GatewayConnectionError(Exception):
|
||||||
|
def __init__(self, reason):
|
||||||
|
self.reason = reason
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return self.reason
|
||||||
|
|
||||||
|
|
||||||
|
class DecodeError(Exception):
|
||||||
|
def __init__(self, reason):
|
||||||
|
self.reason = reason
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return self.reason
|
||||||
|
|
||||||
|
|
||||||
|
class InvalidResponseError(Exception):
|
||||||
|
def __init__(self, reason):
|
||||||
|
self.reason = reason
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return self.reason
|
|
@ -1,37 +1,70 @@
|
||||||
import requests
|
import requests
|
||||||
|
from requests.exceptions import ConnectionError
|
||||||
import random
|
import random
|
||||||
import apns
|
import apns
|
||||||
import trio
|
import trio
|
||||||
import gateway_fetch
|
import gateway_fetch
|
||||||
from base64 import b64decode, b64encode
|
from base64 import b64decode, b64encode
|
||||||
|
|
||||||
|
|
||||||
|
from exceptions import *
|
||||||
|
|
||||||
import urllib3
|
import urllib3
|
||||||
urllib3.disable_warnings()
|
urllib3.disable_warnings()
|
||||||
|
|
||||||
PHONE_IP = "192.168.5.120"
|
|
||||||
API_PORT = 8080
|
API_PORT = 8080
|
||||||
GATEWAY = "22223333"
|
|
||||||
|
|
||||||
def register(push_token: bytes, no_parse = False, gateway = None) -> tuple[str, bytes]:
|
def register(push_token: bytes, no_parse, gateway: str | None, phone_ip: str) -> tuple[str, bytes]:
|
||||||
"""Forwards a registration request to the phone and returns the phone number, signature for the provided push token"""
|
"""Forwards a registration request to the phone and returns the phone number, signature for the provided push token"""
|
||||||
if gateway is None:
|
if gateway is None:
|
||||||
print("Requesting device MCC+MNC for gateway detection...")
|
print("Requesting device MCC+MNC for gateway detection...")
|
||||||
mccmnc = requests.get(f"http://{PHONE_IP}:{API_PORT}/info", timeout=30).text
|
|
||||||
|
try:
|
||||||
|
mccmnc = requests.get(f"http://{phone_ip}:{API_PORT}/info", timeout=30).text
|
||||||
|
except ConnectionError:
|
||||||
|
|
||||||
|
raise GatewayConnectionError("Could not connect to device! Please open the Pypush SMS Helper App.")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
|
||||||
|
raise GatewayError(f"ERROR: An unknown error occurred: '{e}'")
|
||||||
|
|
||||||
print("MCC+MNC received! " + mccmnc)
|
print("MCC+MNC received! " + mccmnc)
|
||||||
print("Determining gateway...")
|
print("Determining gateway...")
|
||||||
|
print(mccmnc)
|
||||||
gateway = gateway_fetch.getGatewayMCCMNC(mccmnc)
|
gateway = gateway_fetch.getGatewayMCCMNC(mccmnc)
|
||||||
if gateway is not None:
|
if gateway is not None:
|
||||||
print("Gateway found! " + str(gateway))
|
print("Gateway found! " + str(gateway))
|
||||||
else:
|
else:
|
||||||
print("No gateway was provided, and automatic gateway detection failed. Please run again with the --gateway flag.")
|
|
||||||
# gateway = GATEWAY
|
raise GatewayError(f"No gateway was provided, and automatic gateway detection failed. Please run again with the --gateway flag.")
|
||||||
raise
|
|
||||||
token = push_token.hex().upper()
|
token = push_token.hex().upper()
|
||||||
req_id = random.randint(0, 2**32)
|
req_id = random.randint(0, 2**32)
|
||||||
sms = f"REG-REQ?v=3;t={token};r={req_id};"
|
sms = f"REG-REQ?v=3;t={token};r={req_id};"
|
||||||
print("Sending message and waiting for response...")
|
print("Sending message and waiting for response...")
|
||||||
r = requests.get(f"http://{PHONE_IP}:{API_PORT}/register", params={"sms": sms, "gateway": gateway}, timeout=30)
|
|
||||||
print("Received response from device!")
|
try:
|
||||||
|
r = requests.get(f"http://{phone_ip}:{API_PORT}/register", params={"sms": sms, "gateway": gateway}, timeout=30)
|
||||||
|
except Exception as e:
|
||||||
|
raise GatewayError(f"ERROR: An unknown error occurred: '{e}'")
|
||||||
|
|
||||||
|
if 'error' in r.text.lower():
|
||||||
|
|
||||||
|
if 'permission.SEND_SMS' in r.text.lower():
|
||||||
|
raise GatewayError(f"Please allow the SMS permission!")
|
||||||
|
|
||||||
|
raise GatewayError(f"An error was thrown from PNRgateway Client: '{r.text}'")
|
||||||
|
|
||||||
|
# POSSIBLE ERRORS FROM APP:
|
||||||
|
|
||||||
|
# Error: timeout waiting for response from gateway (unlikely, timeout is implemented here too)
|
||||||
|
# Error sending SMS
|
||||||
|
# Error: sms parameter not found
|
||||||
|
# Error: gateway parameter not found
|
||||||
|
|
||||||
|
print('\033[92m', "Received response from device!", '\033[0m')
|
||||||
|
|
||||||
if no_parse:
|
if no_parse:
|
||||||
print("Now do the next part and rerun with --pdu")
|
print("Now do the next part and rerun with --pdu")
|
||||||
exit()
|
exit()
|
||||||
|
|
Loading…
Reference in a new issue