2016-08-28 15:16:52 +03:00
|
|
|
from os.path import isfile as file_exists
|
2016-09-16 14:35:14 +03:00
|
|
|
import os
|
2016-08-28 15:16:52 +03:00
|
|
|
import time
|
|
|
|
import pickle
|
2016-09-04 22:07:09 +03:00
|
|
|
import random
|
2016-09-17 21:42:34 +03:00
|
|
|
import telethon.helpers as utils
|
2016-08-28 15:16:52 +03:00
|
|
|
|
|
|
|
|
|
|
|
class Session:
|
|
|
|
def __init__(self, session_user_id):
|
|
|
|
self.session_user_id = session_user_id
|
|
|
|
self.server_address = '91.108.56.165'
|
|
|
|
self.port = 443
|
|
|
|
self.auth_key = None
|
|
|
|
self.id = utils.generate_random_long(signed=False)
|
|
|
|
self.sequence = 0
|
|
|
|
self.salt = 0 # Unsigned long
|
|
|
|
self.time_offset = 0
|
|
|
|
self.last_message_id = 0 # Long
|
|
|
|
self.user = None
|
|
|
|
|
|
|
|
def save(self):
|
|
|
|
"""Saves the current session object as session_user_id.session"""
|
2016-09-08 17:11:37 +03:00
|
|
|
if self.session_user_id:
|
|
|
|
with open('{}.session'.format(self.session_user_id), 'wb') as file:
|
|
|
|
pickle.dump(self, file)
|
2016-08-28 15:16:52 +03:00
|
|
|
|
2016-09-16 14:35:14 +03:00
|
|
|
def delete(self):
|
|
|
|
"""Deletes the current session file"""
|
|
|
|
try:
|
|
|
|
os.remove('{}.session'.format(self.session_user_id))
|
|
|
|
return True
|
|
|
|
except:
|
|
|
|
return False
|
|
|
|
|
2016-08-28 15:16:52 +03:00
|
|
|
@staticmethod
|
2016-09-04 12:07:18 +03:00
|
|
|
def try_load_or_create_new(session_user_id):
|
2016-09-08 17:11:37 +03:00
|
|
|
"""Loads a saved session_user_id session, or creates a new one if none existed before.
|
|
|
|
If the given session_user_id is None, we assume that it is for testing purposes"""
|
|
|
|
if session_user_id is None:
|
|
|
|
return Session(None)
|
2016-08-28 15:16:52 +03:00
|
|
|
|
|
|
|
else:
|
2016-09-08 17:11:37 +03:00
|
|
|
filepath = '{}.session'.format(session_user_id)
|
|
|
|
|
|
|
|
if file_exists(filepath):
|
|
|
|
with open(filepath, 'rb') as file:
|
|
|
|
return pickle.load(file)
|
|
|
|
else:
|
|
|
|
return Session(session_user_id)
|
2016-08-28 15:16:52 +03:00
|
|
|
|
|
|
|
def get_new_msg_id(self):
|
|
|
|
"""Generates a new message ID based on the current time (in ms) since epoch"""
|
|
|
|
# Refer to mtproto_plain_sender.py for the original method, this is a simple copy
|
2016-09-04 22:07:09 +03:00
|
|
|
ms_time = int(time.time() * 1000)
|
|
|
|
new_msg_id = (((ms_time // 1000 + self.time_offset) << 32) | # "must approximately equal unixtime*2^32"
|
|
|
|
((ms_time % 1000) << 22) | # "approximate moment in time the message was created"
|
|
|
|
random.randint(0, 524288) << 2) # "message identifiers are divisible by 4"
|
|
|
|
|
2016-09-04 12:07:18 +03:00
|
|
|
if self.last_message_id >= new_msg_id:
|
2016-09-04 22:07:09 +03:00
|
|
|
new_msg_id = self.last_message_id + 4
|
2016-08-28 15:16:52 +03:00
|
|
|
|
2016-09-04 22:07:09 +03:00
|
|
|
self.last_message_id = new_msg_id
|
2016-08-28 15:16:52 +03:00
|
|
|
return new_msg_id
|