From 88394d4e55e64000b3ced1c263e2831ddac9fe24 Mon Sep 17 00:00:00 2001 From: Alexander Maassen Date: Tue, 16 Jan 2024 17:05:39 +0000 Subject: [PATCH 1/2] PEP8 compliance enforcement --- pyVoIP/RTP.py | 14 ++++----- pyVoIP/SIP.py | 76 ++++++++++++++++++++++----------------------- pyVoIP/VoIP/VoIP.py | 30 +++++++++--------- 3 files changed, 60 insertions(+), 60 deletions(-) diff --git a/pyVoIP/RTP.py b/pyVoIP/RTP.py index 412a68c..882e57d 100644 --- a/pyVoIP/RTP.py +++ b/pyVoIP/RTP.py @@ -371,7 +371,7 @@ def recv(self) -> None: while self.NSD: try: packet = self.sin.recv(8192) - self.parsePacket(packet) + self.parse_packet(packet) except BlockingIOError: time.sleep(0.01) except RTPParseError as e: @@ -383,7 +383,7 @@ def trans(self) -> None: while self.NSD: last_sent = time.monotonic_ns() payload = self.pmout.read() - payload = self.encodePacket(payload) + payload = self.encode_packet(payload) packet = b"\x80" # RFC 1889 V2 No Padding Extension or CC. packet += chr(int(self.preference)).encode("utf8") try: @@ -435,11 +435,11 @@ def parsePacket(self, packet: bytes) -> None: def parse_packet(self, packet: bytes) -> None: msg = RTPMessage(packet, self.assoc) if msg.payload_type == PayloadType.PCMU: - self.parsePCMU(msg) + self.parse_pcmu(msg) elif msg.payload_type == PayloadType.PCMA: - self.parsePCMA(msg) + self.parse_pcma(msg) elif msg.payload_type == PayloadType.EVENT: - self.parseTelephoneEvent(msg) + self.parse_telephone_event(msg) else: raise RTPParseError( "Unsupported codec (parse): " + str(msg.payload_type) @@ -456,9 +456,9 @@ def encodePacket(self, payload: bytes) -> bytes: def encode_packet(self, payload: bytes) -> bytes: if self.preference == PayloadType.PCMU: - return self.encodePCMU(payload) + return self.encode_pcmu(payload) elif self.preference == PayloadType.PCMA: - return self.encodePCMA(payload) + return self.encode_pcmu(payload) else: raise RTPParseError( "Unsupported codec (encode): " + str(self.preference) diff --git a/pyVoIP/SIP.py b/pyVoIP/SIP.py index 0337e3e..7a91360 100644 --- a/pyVoIP/SIP.py +++ b/pyVoIP/SIP.py @@ -383,10 +383,10 @@ def parse(self, data: bytes) -> None: if check in self.SIPCompatibleVersions: self.type = SIPMessageType.RESPONSE - self.parseSIPResponse(data) + self.parse_sip_response(data) elif check in self.SIPCompatibleMethods: self.type = SIPMessageType.MESSAGE - self.parseSIPMessage(data) + self.parse_sip_message(data) else: raise SIPParseError( "Unable to decipher SIP request: " + str(heading, "utf8") @@ -772,9 +772,9 @@ def parse_sip_response(self, data: bytes) -> None: self.status = SIPStatus(int(self.heading.split(b" ")[1])) - self.parse_raw_header(headers_raw, self.parseHeader) + self.parse_raw_header(headers_raw, self.parse_header) - self.parse_raw_body(body, self.parseBody) + self.parse_raw_body(body, self.parse_body) def parseSIPMessage(self, data: bytes) -> None: warnings.warn( @@ -796,9 +796,9 @@ def parse_sip_message(self, data: bytes) -> None: self.method = str(self.heading.split(b" ")[0], "utf8") - self.parse_raw_header(headers_raw, self.parseHeader) + self.parse_raw_header(headers_raw, self.parse_header) - self.parse_raw_body(body, self.parseBody) + self.parse_raw_body(body, self.parse_body) class SIPClient: @@ -827,7 +827,7 @@ def __init__( self.fatalCallback = fatalCallback self.tags: List[str] = [] - self.tagLibrary = {"register": self.genTag()} + self.tagLibrary = {"register": self.gen_tag()} self.myPort = myPort @@ -863,12 +863,12 @@ def recv(self) -> None: try: message = SIPMessage(raw) debug(message.summary()) - self.parseMessage(message) + self.parse_message(message) except Exception as ex: debug(f"Error on header parsing: {ex}") except SIPParseError as e: if "SIP Version" in str(e): - request = self.genSIPVersionNotSupported(message) + request = self.gen_sip_version_not_supported(message) self.out.sendto( request.encode("utf8"), (self.server, self.port) ) @@ -918,7 +918,7 @@ def parse_message(self, message: SIPMessage) -> None: return elif message.method == "INVITE": if self.callCallback is None: - request = self.genBusy(message) + request = self.gen_busy(message) self.out.sendto( request.encode("utf8"), (self.server, self.port) ) @@ -927,7 +927,7 @@ def parse_message(self, message: SIPMessage) -> None: elif message.method == "BYE": # TODO: If callCallback is None, the call doesn't exist, 481 self.callCallback(message) # type: ignore - response = self.genOk(message) + response = self.gen_ok(message) try: # BYE comes from client cause server only acts as mediator (_sender_adress, _sender_port) = message.headers["Via"][0][ @@ -947,7 +947,7 @@ def parse_message(self, message: SIPMessage) -> None: elif message.method == "CANCEL": # TODO: If callCallback is None, the call doesn't exist, 481 self.callCallback(message) # type: ignore - response = self.genOk(message) + response = self.gen_ok(message) self.out.sendto(response.encode("utf8"), (self.server, self.port)) else: debug("TODO: Add 400 Error on non processable request") @@ -1049,7 +1049,7 @@ def gen_sip_version_not_supported(self, request: SIPMessage) -> str: + f"{request.headers['From']['tag']}\r\n" ) response += ( - f"To: {request.headers['To']['raw']};tag=" + f"{self.genTag()}\r\n" + f"To: {request.headers['To']['raw']};tag=" + f"{self.gen_tag()}\r\n" ) response += f"Call-ID: {request.headers['Call-ID']}\r\n" response += ( @@ -1132,7 +1132,7 @@ def gen_first_response(self, deregister=False) -> str: regRequest = f"REGISTER sip:{self.server} SIP/2.0\r\n" regRequest += ( f"Via: SIP/2.0/UDP {self.myIP}:{self.myPort};" - + f"branch={self.genBranch()};rport\r\n" + + f"branch={self.gen_branch()};rport\r\n" ) regRequest += ( f'From: "{self.username}" ' @@ -1143,7 +1143,7 @@ def gen_first_response(self, deregister=False) -> str: f'To: "{self.username}" ' + f"\r\n" ) - regRequest += f"Call-ID: {self.genCallID()}\r\n" + regRequest += f"Call-ID: {self.gen_call_id()}\r\n" regRequest += f"CSeq: {self.registerCounter.next()} REGISTER\r\n" regRequest += ( "Contact: " @@ -1178,12 +1178,12 @@ def gen_subscribe(self, response: SIPMessage) -> str: subRequest = f"SUBSCRIBE sip:{self.username}@{self.server} SIP/2.0\r\n" subRequest += ( f"Via: SIP/2.0/UDP {self.myIP}:{self.myPort};" - + f"branch={self.genBranch()};rport\r\n" + + f"branch={self.gen_branch()};rport\r\n" ) subRequest += ( f'From: "{self.username}" ' + f";tag=" - + f"{self.genTag()}\r\n" + + f"{self.gen_tag()}\r\n" ) subRequest += f"To: \r\n" subRequest += f'Call-ID: {response.headers["Call-ID"]}\r\n' @@ -1215,14 +1215,14 @@ def genRegister(self, request: SIPMessage, deregister=False) -> str: return self.gen_register(request, deregister) def gen_register(self, request: SIPMessage, deregister=False) -> str: - response = str(self.genAuthorization(request), "utf8") + response = str(self.gen_authorization(request), "utf8") nonce = request.authentication["nonce"] realm = request.authentication["realm"] regRequest = f"REGISTER sip:{self.server} SIP/2.0\r\n" regRequest += ( f"Via: SIP/2.0/UDP {self.myIP}:{self.myPort};branch=" - + f"{self.genBranch()};rport\r\n" + + f"{self.gen_branch()};rport\r\n" ) regRequest += ( f'From: "{self.username}" ' @@ -1278,7 +1278,7 @@ def gen_busy(self, request: SIPMessage) -> str: + f"{request.headers['From']['tag']}\r\n" ) response += ( - f"To: {request.headers['To']['raw']};tag=" + f"{self.genTag()}\r\n" + f"To: {request.headers['To']['raw']};tag=" + f"{self.gen_tag()}\r\n" ) response += f"Call-ID: {request.headers['Call-ID']}\r\n" response += ( @@ -1311,7 +1311,7 @@ def gen_ok(self, request: SIPMessage) -> str: + f"{request.headers['From']['tag']}\r\n" ) okResponse += ( - f"To: {request.headers['To']['raw']};tag=" + f"{self.genTag()}\r\n" + f"To: {request.headers['To']['raw']};tag=" + f"{self.gen_tag()}\r\n" ) okResponse += f"Call-ID: {request.headers['Call-ID']}\r\n" okResponse += ( @@ -1334,7 +1334,7 @@ def genRinging(self, request: SIPMessage) -> str: return self.gen_ringing(request) def gen_ringing(self, request: SIPMessage) -> str: - tag = self.genTag() + tag = self.gen_tag() regRequest = "SIP/2.0 180 Ringing\r\n" regRequest += self._gen_response_via_header(request) regRequest += ( @@ -1477,7 +1477,7 @@ def gen_invite( body += "a=maxptime:150\r\n" body += f"a={sendtype}\r\n" - tag = self.genTag() + tag = self.gen_tag() self.tagLibrary[call_id] = tag invRequest = f"INVITE sip:{number}@{self.server} SIP/2.0\r\n" @@ -1560,7 +1560,7 @@ def gen_ack(self, request: SIPMessage) -> str: ackMessage += self._gen_response_via_header(request) ackMessage += "Max-Forwards: 70\r\n" ackMessage += ( - f"To: {request.headers['To']['raw']};tag=" + f"{self.genTag()}\r\n" + f"To: {request.headers['To']['raw']};tag=" + f"{self.gen_tag()}\r\n" ) ackMessage += f"From: {request.headers['From']['raw']};tag={tag}\r\n" ackMessage += f"Call-ID: {request.headers['Call-ID']}\r\n" @@ -1596,10 +1596,10 @@ def invite( ms: Dict[int, Dict[str, "RTP.PayloadType"]], sendtype: "RTP.TransmitType", ) -> Tuple[SIPMessage, str, int]: - branch = "z9hG4bK" + self.genCallID()[0:25] - call_id = self.genCallID() + branch = "z9hG4bK" + self.gen_call_id()[0:25] + call_id = self.gen_call_id() sess_id = self.sessID.next() - invite = self.genInvite( + invite = self.gen_invite( number, str(sess_id), ms, sendtype, branch, call_id ) with self.recvLock: @@ -1614,7 +1614,7 @@ def invite( ) or response.headers["Call-ID"] != call_id: if not self.NSD: break - self.parseMessage(response) + self.parse_message(response) response = SIPMessage(self.s.recv(8192)) if response.status == SIPStatus( @@ -1622,10 +1622,10 @@ def invite( ) or response.status == SIPStatus(180): return SIPMessage(invite.encode("utf8")), call_id, sess_id debug(f"Received Response: {response.summary()}") - ack = self.genAck(response) + ack = self.gen_ack(response) self.out.sendto(ack.encode("utf8"), (self.server, self.port)) debug("Acknowledged") - authhash = self.genAuthorization(response) + authhash = self.gen_authorization(response) nonce = response.authentication["nonce"] realm = response.authentication["realm"] auth = ( @@ -1635,7 +1635,7 @@ def invite( + "algorithm=MD5\r\n" ) - invite = self.genInvite( + invite = self.gen_invite( number, str(sess_id), ms, sendtype, branch, call_id ) invite = invite.replace( @@ -1647,7 +1647,7 @@ def invite( return SIPMessage(invite.encode("utf8")), call_id, sess_id def bye(self, request: SIPMessage) -> None: - message = self.genBye(request) + message = self.gen_bye(request) # TODO: Handle bye to server vs. bye to connected client self.out.sendto(message.encode("utf8"), (self.server, self.port)) @@ -1675,7 +1675,7 @@ def deregister(self) -> bool: def __deregister(self) -> bool: self.phone._status = PhoneStatus.DEREGISTERING - firstRequest = self.genFirstRequest(deregister=True) + firstRequest = self.gen_first_response(deregister=True) self.out.sendto(firstRequest.encode("utf8"), (self.server, self.port)) self.out.setblocking(False) @@ -1691,7 +1691,7 @@ def __deregister(self) -> bool: if response.status == SIPStatus(401): # Unauthorized, likely due to being password protected. - regRequest = self.genRegister(response, deregister=True) + regRequest = self.gen_register(response, deregister=True) self.out.sendto( regRequest.encode("utf8"), (self.server, self.port) ) @@ -1771,7 +1771,7 @@ def __start_register_timer(self, delay: Optional[int] = None): def __register(self) -> bool: self.phone._status = PhoneStatus.REGISTERING - firstRequest = self.genFirstRequest() + firstRequest = self.gen_first_response() self.out.sendto(firstRequest.encode("utf8"), (self.server, self.port)) self.out.setblocking(False) @@ -1795,7 +1795,7 @@ def __register(self) -> bool: if response.status == SIPStatus(401): # Unauthorized, likely due to being password protected. - regRequest = self.genRegister(response) + regRequest = self.gen_register(response) self.out.sendto( regRequest.encode("utf8"), (self.server, self.port) ) @@ -1850,7 +1850,7 @@ def __register(self) -> bool: raise RetryRequiredError("Response SIP status of 500") else: # TODO: determine if needed here - self.parseMessage(response) + self.parse_message(response) debug(response.summary()) debug(response.raw) @@ -1874,7 +1874,7 @@ def _handle_bad_request(self) -> None: def subscribe(self, lastresponse: SIPMessage) -> None: # TODO: check if needed and maybe implement fully with self.recvLock: - subRequest = self.genSubscribe(lastresponse) + subRequest = self.gen_subscribe(lastresponse) self.out.sendto( subRequest.encode("utf8"), (self.server, self.port) ) diff --git a/pyVoIP/VoIP/VoIP.py b/pyVoIP/VoIP/VoIP.py index f6132ad..fe88472 100644 --- a/pyVoIP/VoIP/VoIP.py +++ b/pyVoIP/VoIP/VoIP.py @@ -170,7 +170,7 @@ def __init__( # TODO: If no codecs are compatible then send error to PBX. port = self.phone.request_port() - self.createRTPClients( + self.create_rtp_clients( codecs, self.myIP, port, request, i["port"] ) elif callstate == CallState.DIALING: @@ -217,7 +217,7 @@ def create_rtp_clients( request.body["c"][ii]["address"], baseport + ii, self.sendmode, - dtmf=self.dtmfCallback, + dtmf=self.dtmf_callback, ) self.RTPClients.append(c) @@ -279,8 +279,8 @@ def gen_ms(self) -> Dict[int, Dict[int, RTP.PayloadType]]: return m def renegotiate(self, request: SIP.SIPMessage) -> None: - m = self.genMs() - message = self.sip.genAnswer( + m = self.gen_ms() + message = self.sip.gen_answer( request, self.session_id, m, self.sendmode ) self.sip.out.sendto( @@ -298,8 +298,8 @@ def renegotiate(self, request: SIP.SIPMessage) -> None: def answer(self) -> None: if self.state != CallState.RINGING: raise InvalidStateError("Call is not ringing") - m = self.genMs() - message = self.sip.genAnswer( + m = self.gen_ms() + message = self.sip.gen_answer( self.request, self.session_id, m, self.sendmode ) self.sip.out.sendto( @@ -334,7 +334,7 @@ def answered(self, request: SIP.SIPMessage) -> None: "RTP Payload type could not be derived from SDP." ) - self.createRTPClients( + self.create_rtp_clients( assoc, self.myIP, self.port, request, i["port"] ) @@ -405,7 +405,7 @@ def unavailable(self, request: SIP.SIPMessage) -> None: def deny(self) -> None: if self.state != CallState.RINGING: raise InvalidStateError("Call is not ringing") - message = self.sip.genBusy(self.request) + message = self.sip.gen_busy(self.request) self.sip.out.sendto( message.encode("utf8"), (self.phone.server, self.phone.port) ) @@ -562,7 +562,7 @@ def _callback_MSG_Invite(self, request: SIP.SIPMessage) -> None: self.calls[call_id].renegotiate(request) return # Raise Error if self.callCallback is None: - message = self.sip.genBusy(request) + message = self.sip.gen_busy(request) self.sip.out.sendto( message.encode("utf8"), (self.server, self.port) ) @@ -574,7 +574,7 @@ def _callback_MSG_Invite(self, request: SIP.SIPMessage) -> None: if proposed not in self.session_ids: self.session_ids.append(proposed) sess_id = proposed - message = self.sip.genRinging(request) + message = self.sip.gen_ringing(request) self.sip.out.sendto( message.encode("utf8"), (self.server, self.port) ) @@ -586,7 +586,7 @@ def _callback_MSG_Invite(self, request: SIP.SIPMessage) -> None: self.threads.append(t) self.threadLookup[t] = call_id except Exception: - message = self.sip.genBusy(request) + message = self.sip.gen_busy(request) self.sip.out.sendto( message.encode("utf8"), (self.server, self.port) ) @@ -609,7 +609,7 @@ def _callback_RESP_OK(self, request: SIP.SIPMessage) -> None: # issue here or your invite is wrong. self.calls[call_id].answered(request) debug("Answered") - ack = self.sip.genAck(request) + ack = self.sip.gen_ack(request) self.sip.out.sendto(ack.encode("utf8"), (self.server, self.port)) def _callback_RESP_NotFound(self, request: SIP.SIPMessage) -> None: @@ -621,9 +621,9 @@ def _callback_RESP_NotFound(self, request: SIP.SIPMessage) -> None: "TODO: Add 481 here as server is probably waiting for " + "an ACK" ) - self.calls[call_id].notFound(request) + self.calls[call_id].not_found(request) debug("Terminating Call") - ack = self.sip.genAck(request) + ack = self.sip.gen_ack(request) self.sip.out.sendto(ack.encode("utf8"), (self.server, self.port)) def _callback_RESP_Unavailable(self, request: SIP.SIPMessage) -> None: @@ -637,7 +637,7 @@ def _callback_RESP_Unavailable(self, request: SIP.SIPMessage) -> None: ) self.calls[call_id].unavailable(request) debug("Terminating Call") - ack = self.sip.genAck(request) + ack = self.sip.gen_ack(request) self.sip.out.sendto(ack.encode("utf8"), (self.server, self.port)) def _create_Call(self, request: SIP.SIPMessage, sess_id: int) -> None: From 0b0d354ae82a45d349b78220a5c8780496d4d7d8 Mon Sep 17 00:00:00 2001 From: Alexander Maassen Date: Tue, 16 Jan 2024 17:14:06 +0000 Subject: [PATCH 2/2] and black strikes again... --- pyVoIP/SIP.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/pyVoIP/SIP.py b/pyVoIP/SIP.py index 7a91360..d3c33cc 100644 --- a/pyVoIP/SIP.py +++ b/pyVoIP/SIP.py @@ -1049,7 +1049,8 @@ def gen_sip_version_not_supported(self, request: SIPMessage) -> str: + f"{request.headers['From']['tag']}\r\n" ) response += ( - f"To: {request.headers['To']['raw']};tag=" + f"{self.gen_tag()}\r\n" + f"To: {request.headers['To']['raw']};tag=" + + f"{self.gen_tag()}\r\n" ) response += f"Call-ID: {request.headers['Call-ID']}\r\n" response += ( @@ -1278,7 +1279,8 @@ def gen_busy(self, request: SIPMessage) -> str: + f"{request.headers['From']['tag']}\r\n" ) response += ( - f"To: {request.headers['To']['raw']};tag=" + f"{self.gen_tag()}\r\n" + f"To: {request.headers['To']['raw']};tag=" + + f"{self.gen_tag()}\r\n" ) response += f"Call-ID: {request.headers['Call-ID']}\r\n" response += ( @@ -1311,7 +1313,8 @@ def gen_ok(self, request: SIPMessage) -> str: + f"{request.headers['From']['tag']}\r\n" ) okResponse += ( - f"To: {request.headers['To']['raw']};tag=" + f"{self.gen_tag()}\r\n" + f"To: {request.headers['To']['raw']};tag=" + + f"{self.gen_tag()}\r\n" ) okResponse += f"Call-ID: {request.headers['Call-ID']}\r\n" okResponse += ( @@ -1560,7 +1563,8 @@ def gen_ack(self, request: SIPMessage) -> str: ackMessage += self._gen_response_via_header(request) ackMessage += "Max-Forwards: 70\r\n" ackMessage += ( - f"To: {request.headers['To']['raw']};tag=" + f"{self.gen_tag()}\r\n" + f"To: {request.headers['To']['raw']};tag=" + + f"{self.gen_tag()}\r\n" ) ackMessage += f"From: {request.headers['From']['raw']};tag={tag}\r\n" ackMessage += f"Call-ID: {request.headers['Call-ID']}\r\n"