import json import logging from facebook_business.adobjects.adaccount import AdAccount from requests.exceptions import ConnectionError from service.conf import settings from service.utils.appsync_communication.message_types import ServiceInfoError from .service_fb_error_handler import FbErrorHandler logger = logging.getLogger(__name__) if settings.PROFILE == "live": FANSIFTER_ADACCOUNT_ID = "act_189985595389694" else: FANSIFTER_ADACCOUNT_ID = "act_753526402044185" FB_SECRET = { "act_189985595389694": "fb_credentials_live", "act_753526402044185": "fb_credentials", } class FbServiceCore: """ Cire FB Serivce Class providing common methods between Internal and External Classes """ base_path = "https://graph.facebook.com/v12.0/" def __init__(self, account_id=None): # !TODO: Needs to be in global app settings if account_id is None: account_id = FANSIFTER_ADACCOUNT_ID self.fansifter_adaccount_id = ( account_id if account_id.startswith("act_") else f"act_{account_id}" ) @FbErrorHandler def make_request(self, method, endpoint, params=None, json_response=True): """Handling general requests""" endpoint = self.base_path + endpoint if method not in ["POST", "GET", "DELETE"]: raise RuntimeError(f"Unsupported method provided - {method}") else: try: response = ( AdAccount(self.fansifter_adaccount_id) .get_api_assured() .call(method, endpoint, params=params) ) if response.status() == 503: raise ServiceInfoError( "There is something wrong with the service. " "Please try again later or check on https://status.fb.com/" ) else: logger.info( f"FB API REQUEST to {method} /{endpoint}: {json.dumps(params)}" ) if json_response: logger.info( f"FB API RESPONSE from {method} /{endpoint}: {json.dumps(response.json())}" ) return {"data": response.json(), "headers": response.headers()} else: logger.info(f"FB API RESPONSE: {json.dumps(response.body())}") return {"data": response.body(), "headers": response.headers()} except ConnectionError as e: logger.info(msg=e) raise ServiceInfoError( "There is something wrong with the service. " "Please try again later or check on https://status.fb.com/" )