From fb63ff0db86f6b3118b5f1b65f3f9f462afb5c10 Mon Sep 17 00:00:00 2001 From: Mads Marquart Date: Wed, 8 Jan 2020 08:46:22 +0100 Subject: [PATCH] Fix cookie header extraction Only worked when the cookies were loaded from file, hence the reason I didn't spot it the first time. Thanks to @gave92 for the suggestion. Fixes #495 --- fbchat/_mqtt.py | 11 ++++++++++- fbchat/_util.py | 5 +++-- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/fbchat/_mqtt.py b/fbchat/_mqtt.py index c35433c..cc9ad06 100644 --- a/fbchat/_mqtt.py +++ b/fbchat/_mqtt.py @@ -122,6 +122,13 @@ class Mqtt(object): raise def _on_connect_handler(self, client, userdata, flags, rc): + if rc == 21: + raise _exception.FBchatException( + "Failed connecting. Maybe your cookies are wrong?" + ) + if rc != 0: + return # Don't try to send publish if the connection failed + # configure receiving messages. payload = { "sync_api_version": 10, @@ -228,7 +235,9 @@ class Mqtt(object): headers = { # TODO: Make this access thread safe - "Cookie": _util.get_cookie_header(self._state._session, self._HOST), + "Cookie": _util.get_cookie_header( + self._state._session, "https://edge-chat.facebook.com/chat" + ), "User-Agent": self._state._session.headers["User-Agent"], "Origin": "https://www.facebook.com", "Host": self._HOST, diff --git a/fbchat/_util.py b/fbchat/_util.py index 6228989..920e374 100644 --- a/fbchat/_util.py +++ b/fbchat/_util.py @@ -70,10 +70,11 @@ def strip_json_cruft(text): raise FBchatException("No JSON object found: {!r}".format(text)) -def get_cookie_header(session, host): +def get_cookie_header(session, url): """Extract a cookie header from a requests session.""" + # The cookies are extracted this way to make sure they're escaped correctly return requests.cookies.get_cookie_header( - session.cookies, requests.Request("GET", host), + session.cookies, requests.Request("GET", url), )