From 1c682dcdfc12a9731512a79d4daf39be967cd9d5 Mon Sep 17 00:00:00 2001 From: Mario Corchero Date: Mon, 10 Jun 2024 10:16:50 +0200 Subject: [PATCH] lamadava: Fallback to GQL if v2 fails --- eas/api/instagram/lamadava.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/eas/api/instagram/lamadava.py b/eas/api/instagram/lamadava.py index 2259dda..2841843 100644 --- a/eas/api/instagram/lamadava.py +++ b/eas/api/instagram/lamadava.py @@ -25,6 +25,16 @@ def _session(): # pragma: no cover ) ) def fetch_comments(media_pk): # pragma: no cover + try: + return _fetch_comments_v2(media_pk) + except Exception: # pylint: disable=W0703 + LOG.info( + "Failed to fetch comments via v2 API, falling back to gql", exc_info=True + ) + return _fetch_comments_gql(media_pk) + + +def _fetch_comments_v2(media_pk): # pragma: no cover LOG.info("Sending request to lamadava for %s", media_pk) response = _session().get( "https://api.lamadava.com/v2/media/comments", @@ -45,3 +55,23 @@ def fetch_comments(media_pk): # pragma: no cover except KeyError: LOG.warning("Failed lamadava request! %s", response.text) raise + + +def _fetch_comments_gql(media_pk): # pragma: no cover + LOG.info("Sending request to lamadava for %s", media_pk) + response = _session().get( + "https://api.lamadava.com/gql/comments", + params={ + "media_id": media_pk, + "amount": 50, + "access_key": LAMADAVA_APIK, + }, + timeout=ONE_MINUTE * 2, + ) + if not response.ok: + LOG.warning("Failed lamadava request! %s", response.text) + with contextlib.suppress(Exception): + if response.json()["exc_type"] == "NotFoundError": + return [] + response.raise_for_status() + return response.json()