Make lint happier

This commit is contained in:
Lonami Exo
2017-09-04 17:10:04 +02:00
parent 7f700c3bc1
commit 97cab7347b
22 changed files with 210 additions and 117 deletions
+3 -1
View File
@@ -14,7 +14,9 @@ class AuthKey:
self.key_id = reader.read_long(signed=False)
def calc_new_nonce_hash(self, new_nonce, number):
"""Calculates the new nonce hash based on the current class fields' values"""
"""Calculates the new nonce hash based on
the current class fields' values
"""
with BinaryWriter() as writer:
writer.write(new_nonce)
writer.write_byte(number)
+2 -1
View File
@@ -31,7 +31,8 @@ class CdnDecrypter:
# https://core.telegram.org/cdn
cdn_aes = AESModeCTR(
key=cdn_redirect.encryption_key,
iv=cdn_redirect.encryption_iv[:12] + (offset >> 4).to_bytes(4, 'big')
iv=
cdn_redirect.encryption_iv[:12] + (offset >> 4).to_bytes(4, 'big')
)
# Create a new client on said CDN
+3 -1
View File
@@ -61,7 +61,9 @@ class Factorization:
@staticmethod
def factorize(pq):
"""Factorizes the given number and returns both the divisor and the number divided by the divisor"""
"""Factorizes the given number and returns both
the divisor and the number divided by the divisor
"""
if sympy:
return tuple(sympy.ntheory.factorint(pq).keys())
else:
+1 -1
View File
@@ -10,7 +10,7 @@ from ..extensions import BinaryWriter
# {fingerprint: Crypto.PublicKey.RSA._RSAobj} dictionary
_server_keys = { }
_server_keys = {}
def get_byte_array(integer):
+2 -1
View File
@@ -30,7 +30,8 @@ class InvalidChecksumError(Exception):
def __init__(self, checksum, valid_checksum):
super().__init__(
self,
'Invalid checksum ({} when {} was expected). This packet should be skipped.'
'Invalid checksum ({} when {} was expected). '
'This packet should be skipped.'
.format(checksum, valid_checksum))
self.checksum = checksum
+12 -6
View File
@@ -26,7 +26,8 @@ class BinaryReader:
# region Reading
# "All numbers are written as little endian." |> Source: https://core.telegram.org/mtproto
# "All numbers are written as little endian."
# https://core.telegram.org/mtproto
def read_byte(self):
"""Reads a single byte value"""
return self.read(1)[0]
@@ -56,8 +57,7 @@ class BinaryReader:
"""Read the given amount of bytes"""
result = self.reader.read(length)
if len(result) != length:
raise BufferError(
'Trying to read outside the data bounds (no more data left to read)')
raise BufferError('No more data left to read')
return result
@@ -70,7 +70,9 @@ class BinaryReader:
# region Telegram custom reading
def tgread_bytes(self):
"""Reads a Telegram-encoded byte array, without the need of specifying its length"""
"""Reads a Telegram-encoded byte array,
without the need of specifying its length
"""
first_byte = self.read_byte()
if first_byte == 254:
length = self.read_byte() | (self.read_byte() << 8) | (
@@ -102,7 +104,9 @@ class BinaryReader:
raise ValueError('Invalid boolean code {}'.format(hex(value)))
def tgread_date(self):
"""Reads and converts Unix time (used by Telegram) into a Python datetime object"""
"""Reads and converts Unix time (used by Telegram)
into a Python datetime object
"""
value = self.read_int()
return None if value == 0 else datetime.fromtimestamp(value)
@@ -152,7 +156,9 @@ class BinaryReader:
self.reader.seek(position)
def seek(self, offset):
"""Seeks the stream position given an offset from the current position. May be negative"""
"""Seeks the stream position given an offset from the
current position. The offset may be negative
"""
self.reader.seek(offset, os.SEEK_CUR)
# endregion
+13 -6
View File
@@ -22,21 +22,22 @@ class BinaryWriter:
# region Writing
# "All numbers are written as little endian." |> Source: https://core.telegram.org/mtproto
# "All numbers are written as little endian."
# https://core.telegram.org/mtproto
def write_byte(self, value):
"""Writes a single byte value"""
self.writer.write(pack('B', value))
self.written_count += 1
def write_int(self, value, signed=True):
"""Writes an integer value (4 bytes), which can or cannot be signed"""
"""Writes an integer value (4 bytes), optionally signed"""
self.writer.write(
int.to_bytes(
value, length=4, byteorder='little', signed=signed))
self.written_count += 4
def write_long(self, value, signed=True):
"""Writes a long integer value (8 bytes), which can or cannot be signed"""
"""Writes a long integer value (8 bytes), optionally signed"""
self.writer.write(
int.to_bytes(
value, length=8, byteorder='little', signed=signed))
@@ -101,7 +102,9 @@ class BinaryWriter:
self.write_int(0x997275b5 if boolean else 0xbc799737, signed=False)
def tgwrite_date(self, datetime):
"""Converts a Python datetime object into Unix time (used by Telegram) and writes it"""
"""Converts a Python datetime object into Unix time
(used by Telegram) and writes it
"""
value = 0 if datetime is None else int(datetime.timestamp())
self.write_int(value)
@@ -127,14 +130,18 @@ class BinaryWriter:
self.writer.close()
def get_bytes(self, flush=True):
"""Get the current bytes array content from the buffer, optionally flushing first"""
"""Get the current bytes array content from the buffer,
optionally flushing first
"""
if flush:
self.writer.flush()
return self.writer.raw.getvalue()
def get_written_bytes_count(self):
"""Gets the count of bytes written in the buffer.
This may NOT be equal to the stream length if one was provided when initializing the writer"""
This may NOT be equal to the stream length if one
was provided when initializing the writer
"""
return self.written_count
# with block
+6 -2
View File
@@ -22,7 +22,9 @@ def ensure_parent_dir_exists(file_path):
def calc_key(shared_key, msg_key, client):
"""Calculate the key based on Telegram guidelines, specifying whether it's the client or not"""
"""Calculate the key based on Telegram guidelines,
specifying whether it's the client or not
"""
x = 0 if client else 8
sha1a = sha1(msg_key + shared_key[x:x + 32]).digest()
@@ -56,7 +58,9 @@ def generate_key_data_from_nonce(server_nonce, new_nonce):
def get_password_hash(pw, current_salt):
"""Gets the password hash for the two-step verification.
current_salt should be the byte array provided by invoking GetPasswordRequest()"""
current_salt should be the byte array provided by
invoking GetPasswordRequest()
"""
# Passwords are encoded as UTF-8
# At https://github.com/DrKLO/Telegram/blob/e31388
+4 -2
View File
@@ -217,6 +217,8 @@ def do_authentication(connection):
def get_int(byte_array, signed=True):
"""Gets the specified integer from its byte array. This should be used by the authenticator,
who requires the data to be in big endian"""
"""Gets the specified integer from its byte array.
This should be used by the authenticator,
who requires the data to be in big endian
"""
return int.from_bytes(byte_array, byteorder='big', signed=signed)
+4 -3
View File
@@ -61,7 +61,8 @@ class Connection:
setattr(self, 'send', self._send_intermediate)
setattr(self, 'recv', self._recv_intermediate)
elif mode in (ConnectionMode.TCP_ABRIDGED, ConnectionMode.TCP_OBFUSCATED):
elif mode in (ConnectionMode.TCP_ABRIDGED,
ConnectionMode.TCP_OBFUSCATED):
setattr(self, 'send', self._send_abridged)
setattr(self, 'recv', self._recv_abridged)
@@ -90,8 +91,8 @@ class Connection:
while True:
random = os.urandom(64)
if (random[0] != b'\xef' and
random[:4] not in keywords and
random[4:4] != b'\0\0\0\0'):
random[:4] not in keywords and
random[4:4] != b'\0\0\0\0'):
# Invalid random generated
break
+6 -2
View File
@@ -4,7 +4,9 @@ from ..extensions import BinaryReader, BinaryWriter
class MtProtoPlainSender:
"""MTProto Mobile Protocol plain sender (https://core.telegram.org/mtproto/description#unencrypted-messages)"""
"""MTProto Mobile Protocol plain sender
(https://core.telegram.org/mtproto/description#unencrypted-messages)
"""
def __init__(self, connection):
self._sequence = 0
@@ -19,7 +21,9 @@ class MtProtoPlainSender:
self._connection.close()
def send(self, data):
"""Sends a plain packet (auth_key_id = 0) containing the given message body (data)"""
"""Sends a plain packet (auth_key_id = 0) containing the
given message body (data)
"""
with BinaryWriter(known_length=len(data) + 20) as writer:
writer.write_long(0)
writer.write_long(self._get_new_msg_id())
+12 -5
View File
@@ -31,7 +31,7 @@ class MtProtoSender:
# Store an RLock instance to make this class safely multi-threaded
self._lock = RLock()
# Used when logging out, the only request that seems to use 'ack' requests
# Used when logging out, the only request that seems to use 'ack'
# TODO There might be a better way to handle msgs_ack requests
self.logging_out = False
@@ -114,7 +114,10 @@ class MtProtoSender:
def _send_packet(self, packet, request):
"""Sends the given packet bytes with the additional
information of the original request. This does NOT lock the threads!"""
information of the original request.
This does NOT lock the threads!
"""
request.request_msg_id = self.session.get_new_msg_id()
# First calculate plain_text to encrypt it
@@ -183,7 +186,7 @@ class MtProtoSender:
reader.seek(-4)
# The following codes are "parsed manually"
if code == 0xf35c6d01: # rpc_result, (response of an RPC call, i.e., we sent a request)
if code == 0xf35c6d01: # rpc_result, (response of an RPC call)
return self._handle_rpc_result(msg_id, sequence, reader)
if code == 0x347773c5: # pong
@@ -219,11 +222,15 @@ class MtProtoSender:
if code in tlobjects:
result = reader.tgread_object()
if self.unhandled_callbacks:
self._logger.debug('Passing TLObject to callbacks %s', repr(result))
self._logger.debug(
'Passing TLObject to callbacks %s', repr(result)
)
for callback in self.unhandled_callbacks:
callback(result)
else:
self._logger.debug('Ignoring unhandled TLObject %s', repr(result))
self._logger.debug(
'Ignoring unhandled TLObject %s', repr(result)
)
return True
+8 -5
View File
@@ -184,8 +184,9 @@ class TelegramBareClient:
except (RPCError, ConnectionError) as error:
# Probably errors from the previous session, ignore them
self.disconnect()
self._logger.debug('Could not stabilise initial connection: {}'
.format(error))
self._logger.debug(
'Could not stabilise initial connection: {}'.format(error)
)
return None if initial_query else False
def disconnect(self):
@@ -493,7 +494,7 @@ class TelegramBareClient:
CdnDecrypter.prepare_decrypter(
client, TelegramBareClient, result,
offset, part_size
)
)
except FileMigrateError as e:
client = self._get_exported_client(e.new_dc)
@@ -515,8 +516,10 @@ class TelegramBareClient:
progress_callback(f.tell(), file_size)
finally:
if cdn_decrypter:
try: cdn_decrypter.client.disconnect()
except: pass
try:
cdn_decrypter.client.disconnect()
except:
pass
if isinstance(file, str):
f.close()
-1
View File
@@ -124,7 +124,6 @@ class TelegramClient(TelegramBareClient):
# Constantly read for results and updates from within the main client
self._recv_thread = None
# endregion
# region Connecting
+2 -2
View File
@@ -73,8 +73,8 @@ class Session:
'time_offset': self.time_offset,
'server_address': self.server_address,
'auth_key_data':
b64encode(self.auth_key.key).decode('ascii')\
if self.auth_key else None
b64encode(self.auth_key.key).decode('ascii')
if self.auth_key else None
}, file)
def delete(self):