Skip to content

Commit

Permalink
Fix token regexp expression
Browse files Browse the repository at this point in the history
  • Loading branch information
mobeigi committed Dec 25, 2023
1 parent 1061426 commit 28278c7
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
15 changes: 13 additions & 2 deletions fb2cal/facebook_browser.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import json

from .logger import Logger
from .utils import remove_anti_hijacking_protection

class FacebookBrowser:
def __init__(self):
Expand Down Expand Up @@ -84,7 +85,7 @@ def get_token(self):
return self.__cached_token

FACEBOOK_BIRTHDAY_EVENT_PAGE_URL = 'https://www.facebook.com/events/birthdays/' # token is present on this page
FACEBOOK_TOKEN_REGEXP_STRING = r'{\"token\":\"(.*?)\"'
FACEBOOK_TOKEN_REGEXP_STRING = r'\[\"DTSGInitialData\",\[],{\"token\":\"(.*?)\"'
regexp = re.compile(FACEBOOK_TOKEN_REGEXP_STRING, re.MULTILINE)

birthday_event_page = self.browser.get(FACEBOOK_BIRTHDAY_EVENT_PAGE_URL)
Expand Down Expand Up @@ -128,9 +129,19 @@ def query_graph_ql_birthday_comet_monthly(self, offset_month):

response = self.browser.post(FACEBOOK_GRAPHQL_ENDPOINT, data=payload)

# Sanity failsafe, GraphQL relay endpoint will always return 200
if response.status_code != 200:
self.logger.debug(response.text)
self.logger.error(f'Failed to get {FACEBOOK_GRAPHQL_API_REQ_FRIENDLY_NAME} response. Payload: {payload}. Status code: {response.status_code}.')
raise SystemError

return response.json()
trimmed_response = remove_anti_hijacking_protection(response.text)
response_json = json.loads(trimmed_response)

# Validate for errors
if 'error' in response_json:
self.logger.debug(response.text)
self.logger.error(f'Failed to parse {FACEBOOK_GRAPHQL_API_REQ_FRIENDLY_NAME} response. Payload: {payload}. Error: {response_json["errorSummary"]} - {response_json["errorDescription"]}')
raise SystemError

return response_json
11 changes: 11 additions & 0 deletions fb2cal/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,14 @@
# This is needed in many cases as the vanity url may change over time
def generate_facebook_profile_url_permalink(facebook_user: FacebookUser):
return f'https://www.facebook.com/{facebook_user.id}'

# Facebook prepends an infinite while loop to their API responses as anti hijacking protection
# It must be stripped away before parsing a response as JSON
def remove_anti_hijacking_protection(text: str):
return remove_prefix(text, "for (;;);")

# Replace with str.removeprefix in Python 3.9+
def remove_prefix(text, prefix):
if text.startswith(prefix):
return text[len(prefix):]
return text

0 comments on commit 28278c7

Please sign in to comment.