Merge pull request #98 from madsmtm/master

Added functions to save and load session cookies to and from file
This commit is contained in:
Taehoon Kim
2017-02-07 16:59:55 +09:00
committed by GitHub
2 changed files with 110 additions and 55 deletions

View File

@@ -94,6 +94,22 @@ Example Echobot
bot.listen() bot.listen()
Saving session
==========================
.. code-block:: python
client.saveSession(sessionfile)
Loading session
==========================
.. code-block:: python
client = fbchat.Client(None, None, do_login=False)
client.loadSession(sessionfile)
Authors Authors
======= =======

View File

@@ -59,7 +59,7 @@ class Client(object):
""" """
def __init__(self, email, password, debug=True, user_agent=None , max_retries=5): def __init__(self, email, password, debug=True, user_agent=None , max_retries=5, do_login=True):
"""A client for the Facebook Chat (Messenger). """A client for the Facebook Chat (Messenger).
:param email: Facebook `email` or `id` or `phone number` :param email: Facebook `email` or `id` or `phone number`
@@ -70,11 +70,9 @@ class Client(object):
""" """
if not (email and password): if do_login and not (email and password):
raise Exception("id and password or config is needed") raise Exception("id and password or config is needed")
self.email = email
self.password = password
self.debug = debug self.debug = debug
self._session = requests.session() self._session = requests.session()
self.req_counter = 1 self.req_counter = 1
@@ -120,20 +118,8 @@ class Client(object):
log.addHandler(handler) log.addHandler(handler)
log.setLevel(logging.DEBUG) log.setLevel(logging.DEBUG)
# Logging in if do_login:
log.info("Logging in...") self.login(email, password, max_retries)
for i in range(1,max_retries+1):
if not self.login():
log.warning("Attempt #{} failed{}".format(i,{True:', retrying'}.get(i<5,'')))
time.sleep(1)
continue
else:
log.info("Login successful")
break
else:
raise Exception("login failed. Check id/password")
self.threads = [] self.threads = []
@@ -146,7 +132,7 @@ class Client(object):
>>> from fbchat.client import Client, log >>> from fbchat.client import Client, log
>>> log.setLevel(logging.DEBUG) >>> log.setLevel(logging.DEBUG)
You can do the same thing by addint the 'debug' argument: You can do the same thing by adding the 'debug' argument:
>>> from fbchat import Client >>> from fbchat import Client
>>> client = Client("...", "...", debug=True) >>> client = Client("...", "...", debug=True)
@@ -193,24 +179,8 @@ class Client(object):
payload=self._generatePayload(None) payload=self._generatePayload(None)
return self._session.post(url, data=payload, timeout=timeout, files=files) return self._session.post(url, data=payload, timeout=timeout, files=files)
def _post_login(self):
def login(self): self.payloadDefault = {}
if not (self.email and self.password):
raise Exception("id and password or config is needed")
soup = bs(self._get(MobileURL).text, "lxml")
data = dict((elem['name'], elem['value']) for elem in soup.findAll("input") if elem.has_attr('value') and elem.has_attr('name'))
data['email'] = self.email
data['pass'] = self.password
data['login'] = 'Log In'
r = self._cleanPost(LoginURL, data)
# Sometimes Facebook tries to show the user a "Save Device" dialog
if 'save-device' in r.url:
r = self._cleanGet(SaveDeviceURL)
if 'home' in r.url:
self.client_id = hex(int(random()*2147483648))[2:] self.client_id = hex(int(random()*2147483648))[2:]
self.start_time = now() self.start_time = now()
self.uid = int(self._session.cookies['c_user']) self.uid = int(self._session.cookies['c_user'])
@@ -219,6 +189,8 @@ class Client(object):
r = self._get(BaseURL) r = self._get(BaseURL)
soup = bs(r.text, "lxml") soup = bs(r.text, "lxml")
log.debug(r.text)
log.debug(r.url)
self.fb_dtsg = soup.find("input", {'name':'fb_dtsg'})['value'] self.fb_dtsg = soup.find("input", {'name':'fb_dtsg'})['value']
self.fb_h = soup.find("input", {'name':'h'})['value'] self.fb_h = soup.find("input", {'name':'h'})['value']
self._setttstamp() self._setttstamp()
@@ -245,10 +217,77 @@ class Client(object):
self.tmp_prev = now() self.tmp_prev = now()
self.last_sync = now() self.last_sync = now()
def _login(self):
if not (self.email and self.password):
raise Exception("id and password or config is needed")
soup = bs(self._get(MobileURL).text, "lxml")
data = dict((elem['name'], elem['value']) for elem in soup.findAll("input") if elem.has_attr('value') and elem.has_attr('name'))
data['email'] = self.email
data['pass'] = self.password
data['login'] = 'Log In'
r = self._cleanPost(LoginURL, data)
# Sometimes Facebook tries to show the user a "Save Device" dialog
if 'save-device' in r.url:
r = self._cleanGet(SaveDeviceURL)
if 'home' in r.url:
self._post_login()
return True return True
else: else:
return False return False
def saveSession(self, sessionfile):
"""Dumps the session cookies to (sessionfile).
WILL OVERWRITE ANY EXISTING FILE
:param sessionfile: location of saved session file
"""
log.info('Saving session')
with open(sessionfile, 'w') as f:
# Grab cookies from current session, and save them as JSON
f.write(json.dumps(self._session.cookies.get_dict(), ensure_ascii=False))
def loadSession(self, sessionfile):
"""Loads session cookies from (sessionfile)
:param sessionfile: location of saved session file
"""
log.info('Loading session')
with open(sessionfile, 'r') as f:
try:
j = json.load(f)
if not j or 'c_user' not in j:
return False
# Load cookies into current session
self._session.cookies = requests.cookies.merge_cookies(self._session.cookies, j)
self._post_login()
return True
except Exception as e:
raise Exception('Invalid json in {}, or bad merging of cookies'.format(sessionfile))
def login(self, email, password, max_retries=5):
# Logging in
log.info("Logging in...")
self.email = email
self.password = password
for i in range(1,max_retries+1):
if not self._login():
log.warning("Attempt #{} failed{}".format(i,{True:', retrying'}.get(i<5,'')))
time.sleep(1)
continue
else:
log.info("Login successful")
break
else:
raise Exception("login failed. Check id/password")
def logout(self, timeout=30): def logout(self, timeout=30):
data = {} data = {}
data['ref'] = "mb" data['ref'] = "mb"