# service_fb_external.py from facebook_business.api import FacebookAdsApi from .service_fb import FbServiceCore from .service_fb_db_handler import DbFbServiceHandler class FbServiceHandlerExternal(FbServiceCore): """Main class to work with client's own business accounts Inherits methods from FbSErviceHanlde - note that majority of methods of parent class will throw Runtime Error as those are not suppose to work""" business_id = "" def __init__(self, schema): super().__init__() self.schema = schema self.fb_credentials = self.get_credentials_from_db() self.fb_user_id = self.fb_credentials["user_id"] try: FacebookAdsApi.init(access_token=self.fb_credentials["access_token"]) except Exception as e: raise RuntimeError(f"Could not initiate FacebookAdsApi - {e}") def get_credentials_from_db(self): """Getting FB credentials from db Triggers RuntimeError if no fb user connected through SDK """ try: db_io = DbFbServiceHandler() df = db_io.get_fb_user(schema=self.schema) df = df.iloc[0] data = df.to_dict() except IndexError as e: raise RuntimeError(f"No facebook user connected - {e}") return data def list_connected_businesses(self): """Using provided user_id to list connected businesses""" fields = ["permitted_roles", "name"] params = {"fields": fields} method = "GET" endpoint = f"{self.fb_user_id}/businesses" response = self.make_request(method=method, endpoint=endpoint, params=params) return response def list_business_owned_adaccounts(self): """Using provided business_id getting the list of owned adaccounts""" # fields = ['description', 'name'] # params = {'fields': fields} method = "GET" endpoint = f"{self.business_id}/owned_ad_accounts" response = self.make_request(method=method, endpoint=endpoint) return response def list_user_owned_adaccounts(self): """Using provided user_id getting the lsit of owned adaccounts""" fields = ["name", "account_status", "age"] params = {"fields": fields} method = "GET" endpoint = f"{self.fb_user_id}/adaccounts" response = self.make_request(method=method, endpoint=endpoint, params=params) return response def revoke_all_user_access(self): """Completely removing fb user from the app (user will need to re-authenticate)""" method = "DELETE" endpoint = f"{self.fb_user_id}/permissions" response = self.make_request(method=method, endpoint=endpoint) return response def revoke_specific_user_access(self, scopes): """Removing specific scopes granted to the app by user""" response_list = [] for scope in scopes: method = "DELETE" endpoint = f"{self.fb_user_id}/permissions/{scope}" response = self.make_request(method=method, endpoint=endpoint) response_list.append({"scope": scope, "response": response}) return response_list def get_granted_permissions(self): """Check with permissions are granted to Fansifter by user_id""" method = "GET" endpoint = f"{self.fb_user_id}/permissions" response = self.make_request(method=method, endpoint=endpoint) return response