|
| 1 | +# |
| 2 | +# Licensed to the Apache Software Foundation (ASF) under one |
| 3 | +# or more contributor license agreements. See the NOTICE file |
| 4 | +# distributed with this work for additional information |
| 5 | +# regarding copyright ownership. The ASF licenses this file |
| 6 | +# to you under the Apache License, Version 2.0 (the |
| 7 | +# "License"); you may not use this file except in compliance |
| 8 | +# with the License. You may obtain a copy of the License at |
| 9 | +# |
| 10 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +# |
| 12 | +# Unless required by applicable law or agreed to in writing, |
| 13 | +# software distributed under the License is distributed on an |
| 14 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | +# KIND, either express or implied. See the License for the |
| 16 | +# specific language governing permissions and limitations |
| 17 | +# under the License. |
| 18 | +""" |
| 19 | +This module contains Facebook Ads Reporting hooks |
| 20 | +""" |
| 21 | +import time |
| 22 | +from enum import Enum |
| 23 | +from typing import Any, Dict, List |
| 24 | + |
| 25 | +from cached_property import cached_property |
| 26 | +from facebook_business.adobjects.adaccount import AdAccount |
| 27 | +from facebook_business.adobjects.adreportrun import AdReportRun |
| 28 | +from facebook_business.adobjects.adsinsights import AdsInsights |
| 29 | +from facebook_business.api import FacebookAdsApi |
| 30 | + |
| 31 | +from airflow.exceptions import AirflowException |
| 32 | +from airflow.hooks.base_hook import BaseHook |
| 33 | + |
| 34 | + |
| 35 | +class JobStatus(Enum): |
| 36 | + """ |
| 37 | + Available options for facebook async task status |
| 38 | + """ |
| 39 | + COMPLETED = 'Job Completed' |
| 40 | + STARTED = 'Job Started' |
| 41 | + RUNNING = 'Job Running' |
| 42 | + FAILED = 'Job Failed' |
| 43 | + SKIPPED = 'Job Skipped' |
| 44 | + |
| 45 | + |
| 46 | +class FacebookAdsReportingHook(BaseHook): |
| 47 | + """ |
| 48 | + Hook for the Facebook Ads API |
| 49 | +
|
| 50 | + .. seealso:: |
| 51 | + For more information on the Facebook Ads API, take a look at the API docs: |
| 52 | + https://developers.facebook.com/docs/marketing-apis/ |
| 53 | +
|
| 54 | + :param facebook_conn_id: Airflow Facebook Ads connection ID |
| 55 | + :type facebook_conn_id: str |
| 56 | + :param api_version: The version of Facebook API. Default to v6.0 |
| 57 | + :type api_version: str |
| 58 | +
|
| 59 | + """ |
| 60 | + |
| 61 | + def __init__( |
| 62 | + self, |
| 63 | + facebook_conn_id: str = "facebook_default", |
| 64 | + api_version: str = "v6.0", |
| 65 | + ) -> None: |
| 66 | + super().__init__() |
| 67 | + self.facebook_conn_id = facebook_conn_id |
| 68 | + self.api_version = api_version |
| 69 | + self.client_required_fields = ["app_id", |
| 70 | + "app_secret", |
| 71 | + "access_token", |
| 72 | + "account_id"] |
| 73 | + |
| 74 | + def _get_service(self) -> FacebookAdsApi: |
| 75 | + """ Returns Facebook Ads Client using a service account""" |
| 76 | + config = self.facebook_ads_config |
| 77 | + missings = [_each for _each in self.client_required_fields if _each not in config] |
| 78 | + if missings: |
| 79 | + message = "{missings} fields are missing".format(missings=missings) |
| 80 | + raise AirflowException(message) |
| 81 | + return FacebookAdsApi.init(app_id=config["app_id"], |
| 82 | + app_secret=config["app_secret"], |
| 83 | + access_token=config["access_token"], |
| 84 | + account_id=config["account_id"], |
| 85 | + api_version=self.api_version) |
| 86 | + |
| 87 | + @cached_property |
| 88 | + def facebook_ads_config(self) -> None: |
| 89 | + """ |
| 90 | + Gets Facebook ads connection from meta db and sets |
| 91 | + facebook_ads_config attribute with returned config file |
| 92 | + """ |
| 93 | + self.log.info("Fetching fb connection: %s", self.facebook_conn_id) |
| 94 | + conn = self.get_connection(self.facebook_conn_id) |
| 95 | + if "facebook_ads_client" not in conn.extra_dejson: |
| 96 | + raise AirflowException("facebook_ads_client not found") |
| 97 | + return conn.extra_dejson["facebook_ads_client"] |
| 98 | + |
| 99 | + def bulk_facebook_report( |
| 100 | + self, |
| 101 | + params: Dict[str, Any], |
| 102 | + fields: List[str], |
| 103 | + sleep_time: int = 5, |
| 104 | + ) -> List[AdsInsights]: |
| 105 | + """ |
| 106 | + Pulls data from the Facebook Ads API |
| 107 | +
|
| 108 | + :param fields: List of fields that is obtained from Facebook. Found in AdsInsights.Field class. |
| 109 | + https://developers.facebook.com/docs/marketing-api/insights/parameters/v6.0 |
| 110 | + :type fields: List[str] |
| 111 | + :param params: Parameters that determine the query for Facebook |
| 112 | + https://developers.facebook.com/docs/marketing-api/insights/parameters/v6.0 |
| 113 | + :type fields: Dict[str, Any] |
| 114 | + :param sleep_time: Time to sleep when async call is happening |
| 115 | + :type sleep_time: int |
| 116 | +
|
| 117 | + :return: Facebook Ads API response, converted to Facebook Ads Row objects |
| 118 | + :rtype: List[AdsInsights] |
| 119 | + """ |
| 120 | + api = self._get_service() |
| 121 | + ad_account = AdAccount(api.get_default_account_id(), api=api) |
| 122 | + _async = ad_account.get_insights(params=params, fields=fields, is_async=True) |
| 123 | + while True: |
| 124 | + request = _async.api_get() |
| 125 | + async_status = request[AdReportRun.Field.async_status] |
| 126 | + percent = request[AdReportRun.Field.async_percent_completion] |
| 127 | + self.log.info("%s %s completed, async_status: %s", percent, "%", async_status) |
| 128 | + if async_status == JobStatus.COMPLETED.value: |
| 129 | + self.log.info("Job run completed") |
| 130 | + break |
| 131 | + if async_status in [JobStatus.SKIPPED.value, JobStatus.FAILED.value]: |
| 132 | + message = "{async_status}. Please retry.".format(async_status=async_status) |
| 133 | + raise AirflowException(message) |
| 134 | + time.sleep(sleep_time) |
| 135 | + report_run_id = _async.api_get()["report_run_id"] |
| 136 | + report_object = AdReportRun(report_run_id, api=api) |
| 137 | + insights = report_object.get_insights() |
| 138 | + self.log.info("Extracting data from returned Facebook Ads Iterators") |
| 139 | + return list(insights) |
0 commit comments