Example #1
0
    def get(self, request):
        account_id = request.query_params.get('account_id')
        keywords = request.query_params.get('keywords')
        number = request.query_params.get('number', 40)
        if account_id and keywords and number:
            account = TwitterAccount.objects_raw.get(pk=account_id)
            oauth_token = account.tw_twitter_user_id.oauth_token or settings.TW_ACCESS_TOKEN
            oauth_secret = account.tw_twitter_user_id.oauth_secret or settings.TW_ACCESS_SECRET
            if not account_id:
                return Response([])
            account_id = long(account_id)
            if isinstance(account_id, (int, long)):
                account_id = int_to_base36(account_id)

            client = Client(settings.TW_CONSUMER_KEY,
                            settings.TW_CONSUMER_SECRET, oauth_token,
                            oauth_secret)
            if settings.TW_SANDBOX:
                client.sandbox = settings.TW_SANDBOX

            api_domain = 'https://ads.twitter.com'
            resource = '/accounts/%s/keyword_recommendations.json?keywords=%s&number=%s' % \
                       (account_id, urllib.quote_plus(keywords), number)
            response = Request(client, 'get', resource,
                               domain=api_domain).perform()

            return Response(response.body)
        else:
            return Response(
                {'errors': 'account_id, keywords or number is missing.'},
                status=status.HTTP_400_BAD_REQUEST)
Example #2
0
    def fetch_behaviors(self, data, oauth_token=settings.TW_ACCESS_TOKEN, oauth_token_secret=settings.TW_ACCESS_SECRET):
        res = {}
        res['data'] = []
        res['success'] = False
        account_id = data.get('account_id')
        country_code = data.get('country_code', 'US')

        if isinstance(account_id,(int,long)):
            account_id = int_to_base36(account_id)

        if account_id is None:
            res = {
                'success': False,
                'message': "Missing Twitter Account ID"
            }
            return res

        client = Client(settings.TW_CONSUMER_KEY, settings.TW_CONSUMER_SECRET, oauth_token,
                        oauth_token_secret)
        if settings.TW_SANDBOX:
            client.sandbox = settings.TW_SANDBOX
        try:
            resource = '/{api_version}/targeting_criteria/behaviors?count=1000&country_code={country_code}'.format(api_version=settings.TW_API_VERSION, country_code=country_code)
            response = Request(client, 'get', resource).perform()

            if response.headers['x-rate-limit-remaining'] == "0" and settings.TW_RATE_LIMIT_ALERT:
                send_twitter_alert_email({"account_id": account_id, "endpoint": resource})

            res['data'] = response.body['data']
            next_cursor = response.body.get('next_cursor', False)
            while next_cursor:
                resource = '/{api_version}/targeting_criteria/behaviors?count=1000&cursor={next_cursor}&country_code={country_code}'.format(next_cursor=next_cursor, country_code=country_code, api_version=settings.TW_API_VERSION)
                response = Request(client, 'get', resource).perform()
                next_cursor = response.body.get('next_cursor', False)
                res['data'] += response.body['data']

            res['success'] = True

        except Error as e:
            code = None
            if e.code:
                code = e.code
            elif e.details[0]['code']:
                code = e.details[0]['code']
            res = {
                'data': {},
                'success': False,
                'message': e.details[0]['message'] if e.details and e.details[0] and e.details[0]['message'] else '',
                'errors': { str(code): True } if code else {}
            }
        except Exception as e:
            res = {
                'success': False,
                'message': str(e)
            }
        return res
    def get(self, request, oauth_token=settings.TW_ACCESS_TOKEN, oauth_token_secret=settings.TW_ACCESS_SECRET):
        account_id = request.query_params.get('account_id')
        if not account_id:
            return Response([])

        client = Client(settings.TW_CONSUMER_KEY, settings.TW_CONSUMER_SECRET, oauth_token,
                            oauth_token_secret)
        if settings.TW_SANDBOX:
            client.sandbox = settings.TW_SANDBOX
        resource = '/{api_version}/accounts/{account_id}/app_lists'.format(api_version=settings.TW_API_VERSION, account_id=account_id)
        response = Request(client, 'get', resource).perform()
        json = response.body['data']
        return Response(json)
Example #4
0
    def get(self, request):
        account_id = request.query_params.get('account_id')
        handles = request.query_params.get('handles')
        number = request.query_params.get('number', 40)
        if account_id and handles and number:
            account = TwitterAccount.objects_raw.get(pk=account_id)
            oauth_token = account.tw_twitter_user_id.oauth_token or settings.TW_ACCESS_TOKEN
            oauth_secret = account.tw_twitter_user_id.oauth_secret or settings.TW_ACCESS_SECRET
            if not account_id:
                return Response([])
            account_id = long(account_id)
            if isinstance(account_id, (int, long)):
                account_id = int_to_base36(account_id)

            client = Client(settings.TW_CONSUMER_KEY,
                            settings.TW_CONSUMER_SECRET, oauth_token,
                            oauth_secret)
            if settings.TW_SANDBOX:
                client.sandbox = settings.TW_SANDBOX

            api_domain = 'https://ads.twitter.com'
            resource = '/accounts/%s/handle_recommendation.json?handles=%s&number=%s' % (
                account_id, handles, number)
            response = Request(client, 'get', resource,
                               domain=api_domain).perform()
            if not (int(number) == 2):
                res = []
                api_domain = 'https://api.twitter.com'
                i = 0
                while i < len(response.body):
                    temp = response.body[i:i + 100]
                    i += 100
                    resource = '/1.1/users/lookup.json?screen_name=%s' % ','.join(
                        temp)
                    resource = resource.replace('@', '')
                    result = Request(client,
                                     'get',
                                     resource,
                                     domain=api_domain).perform()
                    for r in result.body:
                        r['followers_count_str'] = human_format(
                            r['followers_count'])
                    res = res + result.body
                return Response(res)
            return Response(response.body)
        else:
            return Response(
                {'errors': 'account_id, keywords or number is missing.'},
                status=status.HTTP_400_BAD_REQUEST)
Example #5
0
    def fetch_accounts(self, data, oauth_token=settings.TW_ACCESS_TOKEN, oauth_token_secret=settings.TW_ACCESS_SECRET):
        res = {}
        account_id = data.get('account_id')

        if isinstance(account_id,(int,long)):
            account_id = int_to_base36(account_id)

        if account_id is None:
            res = {
                'data': {},
                'success': False,
                'message': "Missing Twitter Account ID"
            }
            return res

        client = Client(settings.TW_CONSUMER_KEY, settings.TW_CONSUMER_SECRET, oauth_token, oauth_token_secret)
        if settings.TW_SANDBOX:
            client.sandbox = settings.TW_SANDBOX

        try:
            account = client.accounts(account_id)
            resource = '/{api_version}/accounts/{account_id}'.format(api_version=settings.TW_API_VERSION, account_id=account_id)
            response = Request(client, 'get', resource).perform()

            if response.headers['x-rate-limit-remaining'] == "0" and settings.TW_RATE_LIMIT_ALERT:
                send_twitter_alert_email({"account_id": account_id, "endpoint": resource})

            res['data'] = response.body['data']
            res['success'] = True

        except Error as e:
            code = None
            if e.code:
                code = e.code
            elif e.details[0]['code']:
                code = e.details[0]['code']
            res = {
                'data': {},
                'success': False,
                'message': e.details[0]['message'] if e.details and e.details[0] and e.details[0]['message'] else '',
                'errors': { str(code): True } if code else {}
            }
        except Exception as e:
            res = {
                'data': {},
                'success': False,
                'message': str(e)
            }
        return res
Example #6
0
    def fetch_tv_genres(self, data, oauth_token=settings.TW_ACCESS_TOKEN, oauth_token_secret=settings.TW_ACCESS_SECRET):
        res = {}
        res['data'] = []
        res['success'] = False
        tv_market_id = data.get('tw_tv_market_id')


        client = Client(settings.TW_CONSUMER_KEY, settings.TW_CONSUMER_SECRET, settings.TW_ACCESS_TOKEN,
                        settings.TW_ACCESS_SECRET)
        if settings.TW_SANDBOX:
            client.sandbox = settings.TW_SANDBOX
        try:
            tv_market = TwitterTVMarket.objects.get(pk=tv_market_id)
            resource = '/%s/targeting_criteria/tv_channels?tv_market_locale=%s' % (settings.TW_API_VERSION, tv_market.locale)
            response = Request(client, 'get', resource).perform()

            if response.headers['x-rate-limit-remaining'] == "0" and settings.TW_RATE_LIMIT_ALERT:
                send_twitter_alert_email({"account_id": "", "endpoint": resource})

            res['data'] = response.body['data']
            res['success'] = True

        except Error as e:
            code = None
            if e.code:
                code = e.code
            elif e.details[0]['code']:
                code = e.details[0]['code']
            res = {
                'data': {},
                'success': False,
                'message': e.details[0]['message'] if e.details and e.details[0] and e.details[0]['message'] else '',
                'errors': { str(code): True } if code else {}
            }
        except Exception as e:
            res = {
                'success': False,
                'message': str(e)
            }
        return res
Example #7
0
    def get(self, request):
        account_id = request.query_params.get('account_id')

        account = TwitterAccount.objects_raw.get(pk=account_id)
        oauth_token = account.tw_twitter_user_id.oauth_token or settings.TW_ACCESS_TOKEN
        oauth_secret = account.tw_twitter_user_id.oauth_secret or settings.TW_ACCESS_SECRET
        if not account_id:
            return Response([])
        account_id = long(account_id)
        if isinstance(account_id, (int, long)):
            account_id = int_to_base36(account_id)

        client = Client(settings.TW_CONSUMER_KEY, settings.TW_CONSUMER_SECRET,
                        oauth_token, oauth_secret)
        if settings.TW_SANDBOX:
            client.sandbox = settings.TW_SANDBOX
        resource = '/{api_version}/accounts/{account_id}/web_event_tags'.format(
            api_version=settings.TW_API_VERSION, account_id=account_id)
        response = Request(client, 'get', resource).perform()
        json = response.body['data']

        return Response(json)
    def fetch_campaigns(self,
                        data,
                        syncData=False,
                        oauth_token=settings.TW_ACCESS_TOKEN,
                        oauth_token_secret=settings.TW_ACCESS_SECRET):
        res = {}
        res['data'] = []
        res['success'] = False
        account_id = data.get('account_id')
        campaign_id = data.get('campaign_id')
        tw_campaign_id = data.get('tw_campaign_id')

        if isinstance(account_id, (int, long)):
            account_id_int = account_id
            account_id = int_to_base36(account_id)

        if isinstance(tw_campaign_id, (int, long)):
            tw_campaign_id_int = tw_campaign_id
            tw_campaign_id = int_to_base36(tw_campaign_id)

        if account_id is None:
            res = {
                'data': {},
                'success': False,
                'message': "Missing Twitter Account ID"
            }
            return res

        client = Client(settings.TW_CONSUMER_KEY, settings.TW_CONSUMER_SECRET,
                        oauth_token, oauth_token_secret)
        if settings.TW_SANDBOX:
            client.sandbox = settings.TW_SANDBOX
        try:
            account = client.accounts(account_id)
            # If Manage Campaign ID passed, fetch all Campaigns and find Manage Campaign
            if campaign_id:
                resource = '/{api_version}/accounts/{account_id}/campaigns?count=1000&with_deleted=true'.format(
                    api_version=settings.TW_API_VERSION, account_id=account.id)
                response = Request(client, 'get', resource).perform()

                if response.headers[
                        'x-rate-limit-remaining'] == "0" and settings.TW_RATE_LIMIT_ALERT:
                    send_twitter_alert_email({
                        "account_id": account_id,
                        "endpoint": resource
                    })

                for campaign in response.body['data']:
                    campaign_id_match = re.findall(r'\s*{(\d+)}\s*$',
                                                   campaign['name'])[:1]
                    if campaign_id_match and campaign_id_match[0] and int(
                            campaign_id_match[0]) == int(campaign_id):
                        res['data'].append(campaign)
                res['success'] = True
            else:
                if tw_campaign_id:
                    resource = '/{api_version}/accounts/{account_id}/campaigns/{tw_campaign_id}?count=1000&with_deleted=true'.format(
                        api_version=settings.TW_API_VERSION,
                        account_id=account.id,
                        tw_campaign_id=tw_campaign_id)
                else:
                    resource = '/{api_version}/accounts/{account_id}/campaigns?count=1000&with_deleted=true'.format(
                        api_version=settings.TW_API_VERSION,
                        account_id=account.id)

                response = Request(client, 'get', resource).perform()

                if response.headers[
                        'x-rate-limit-remaining'] == "0" and settings.TW_RATE_LIMIT_ALERT:
                    send_twitter_alert_email({
                        "account_id": account_id,
                        "endpoint": resource
                    })

                res['data'] = response.body['data']

                next_cursor = None
                if response.body['next_cursor'] and response.body[
                        'next_cursor'] is not 0:
                    next_cursor = response.body['next_cursor']
                    while next_cursor is not 0:
                        if tw_campaign_id:
                            resource = '/{api_version}/accounts/{account_id}/campaigns/{tw_campaign_id}?cursor={next_cursor}&count=1000&with_deleted=true'.format(
                                api_version=settings.TW_API_VERSION,
                                account_id=account.id,
                                tw_campaign_id=tw_campaign_id,
                                next_cursor=next_cursor)
                        else:
                            resource = '/{api_version}/accounts/{account_id}/campaigns?cursor={next_cursor}&count=1000&with_deleted=true'.format(
                                api_version=settings.TW_API_VERSION,
                                account_id=account.id,
                                next_cursor=next_cursor)

                        response = Request(client, 'get', resource).perform()
                        next_cursor = response.body['next_cursor'] or 0
                        res['data'] += response.body['data']

                res['success'] = True

        except Error as e:
            code = None
            if e.code:
                code = e.code
            elif e.details[0]['code']:
                code = e.details[0]['code']
            res = {
                'data': {},
                'success':
                False,
                'message':
                e.details[0]['message'] if e.details and e.details[0]
                and e.details[0]['message'] else '',
                'errors': {
                    str(code): True
                } if code else {}
            }
        except Exception as e:
            res = {'data': {}, 'success': False, 'message': str(e)}

        if syncData and res['data'] and res['success']:
            res['sync'] = {}
            if isinstance(res['data'], (list, tuple)):
                sync_success = 0
                sync_fail = 0
                new_count = 0
                existing_count = 0
                for index, api_campaign in enumerate(res['data'], start=0):
                    campaign_res = self.sync_campaign(account_id_int,
                                                      api_campaign)
                    if 'success' in campaign_res and campaign_res[
                            'success'] is True:
                        if campaign_res['type'] == 'existing':
                            existing_count += 1
                        if campaign_res['type'] == 'new':
                            new_count += 1
                        sync_success += 1

                    elif 'success' in campaign_res and campaign_res[
                            'success'] is False:
                        sync_fail += 1

                res['os_platform'] = campaign_res['os_platform']
                res['sync']['type'] = {}
                res['sync']['type']['existing'] = existing_count
                res['sync']['type']['new'] = new_count
                res['sync']['total'] = sync_success
                if sync_fail == 0:
                    res['sync']['success'] = True
                else:
                    res['sync']['success'] = False

            elif isinstance(res['data'], dict):
                campaign_res = self.sync_campaign(account_id_int, res['data'])

                if 'success' in campaign_res and campaign_res[
                        'success'] is True:
                    res['data'] = campaign_res['data']
                    res['os_platform'] = campaign_res['os_platform']
                    res['sync']['success'] = campaign_res['success']
                    res['sync']['type'] = {}
                    res['sync']['type'][campaign_res['type']] = 1
                    res['sync']['total'] = 1

                elif 'success' in campaign_res and campaign_res[
                        'success'] is False:
                    res['data'] = campaign_res['data']
                    res['sync']['success'] = campaign_res['success']
                    res['sync']['message'] = campaign_res['message']
        return res
    def batch_create_update_campaign(
            self,
            data,
            account_id,
            oauth_token=settings.TW_ACCESS_TOKEN,
            oauth_token_secret=settings.TW_ACCESS_SECRET,
            request_type="post"):
        res = {}
        res['success'] = False
        campaign_id_int = None

        if isinstance(account_id, (int, long)):
            account_id_int = account_id
            account_id = int_to_base36(account_id)

        if account_id is None:
            res = {
                'data': [],
                'success': False,
                'message': "Missing Twitter Account ID"
            }
            return res

        if isinstance(data, (list, tuple)):
            post_data = []
            for campaign in data:
                campaign_data = {}
                params = {}
                params['daily_budget_amount_local_micro'] = campaign.get(
                    'daily_budget_amount_local_micro', None)
                params['duration_in_days'] = campaign.get(
                    'duration_in_days', None)
                params['end_time'] = campaign.get('end_time', None)
                params['frequency_cap'] = campaign.get('frequency_cap', None)
                params['funding_instrument_id'] = campaign.get(
                    'funding_instrument_id', None)
                params['name'] = campaign.get('name', None)
                if campaign.get('paused', None) is not None:
                    params['paused'] = 'true' if campaign.get(
                        'paused') else 'false'
                params['standard_delivery'] = str(
                    campaign.get('standard_delivery')).lower() if campaign.get(
                        'standard_delivery') else None
                params['start_time'] = campaign.get('start_time', None)
                params['total_budget_amount_local_micro'] = campaign.get(
                    'total_budget_amount_local_micro', None)

                # total_budget_amount_local_micro = 0 is not permitted
                if not params['total_budget_amount_local_micro']:
                    params['total_budget_amount_local_micro'] = None
                params = dict((k, v) for k, v in params.iteritems()
                              if v is not None and v is not "")

                if request_type == 'post':
                    campaign_data['operation_type'] = 'Create'
                if request_type == 'put':
                    campaign_data['operation_type'] = 'Update'

                campaign_data['params'] = params
                post_data.append(campaign_data)

            client = Client(settings.TW_CONSUMER_KEY,
                            settings.TW_CONSUMER_SECRET, oauth_token,
                            oauth_token_secret)

            if settings.TW_SANDBOX:
                client.sandbox = settings.TW_SANDBOX

            # Split up requests into batches of 20
            batch = []
            batches = []
            for x in range(0, len(post_data), 20):
                batch = post_data[x:x + 20]
                batches.append(batch)

            success_batch = []
            error_batch = []
            error_details = []
            success = False
            error = False

            for batch_post in batches:
                try:
                    account = client.accounts(account_id)
                    headers = {"Content-Type": "application/json"}
                    resource = '/{api_version}/batch/accounts/{account_id}/campaigns'.format(
                        api_version=settings.TW_API_VERSION,
                        account_id=account.id)
                    response = Request(client,
                                       'post',
                                       resource,
                                       body=json.dumps(batch_post),
                                       headers=headers).perform()

                    if response.code == 200 or response.code == 201:
                        success = True
                        success_batch.extend(response.body['data'])

                except Error as e:
                    error = True
                    if e.response.body.get('operation_errors',
                                           None) is not None:
                        for err in e.response.body.get('operation_errors'):
                            if err:
                                if isinstance(err, dict):
                                    err = [err]
                                error_details.extend(err)
                    if e.response.body.get('errors', None) is not None:
                        for err in e.response.body.get('errors'):
                            if err:
                                if isinstance(err, dict):
                                    err = [err]
                                error_details.extend(err)

                    error_batch.extend(batch_post)

                except Exception as e:
                    res = {'data': [], 'success': False, 'message': str(e)}
                    error_batch.extend(batch_post)

            if success_batch and success:
                res['sync'] = {}

                if isinstance(success_batch, dict):
                    success_batch = [success_batch]

                sync_success = 0
                sync_fail = 0
                new_count = 0
                existing_count = 0

                for index, api_campaign in enumerate(success_batch, start=0):
                    campaign_res = self.sync_campaign(account_id_int,
                                                      api_campaign)
                    if 'success' in campaign_res and campaign_res[
                            'success'] is True:
                        if campaign_res['type'] == 'existing':
                            existing_count += 1
                        if campaign_res['type'] == 'new':
                            new_count += 1
                        sync_success += 1

                    elif 'success' in campaign_res and campaign_res[
                            'success'] is False:
                        sync_fail += 1

                res['sync']['type'] = {}
                res['sync']['type']['existing'] = existing_count
                res['sync']['type']['new'] = new_count
                res['sync']['total'] = sync_success

                if sync_fail == 0:
                    res['sync']['success'] = True
                else:
                    res['sync']['success'] = False

            res['success'] = success
            res['count'] = {}
            res['count']['success'] = len(success_batch)
            res['count']['total'] = len(data)
            res['count']['error'] = len(error_batch)
            res['data'] = success_batch

            if error:
                res['success'] = False
                res['error'] = {}
                res['error']['data'] = error_batch
                res['error']['messages'] = filter(None, error_details)

            return res

        elif isinstance(data, dict):
            if request_type == 'post':
                return self.create(data, oauth_token, oauth_token_secret)
            if request_type == 'put':
                return self.update(data, oauth_token, oauth_token_secret)
    def create_update_campaign(self,
                               data,
                               oauth_token=settings.TW_ACCESS_TOKEN,
                               oauth_token_secret=settings.TW_ACCESS_SECRET,
                               request_type="post"):
        res = {}
        res['sync'] = {}
        res['success'] = False
        account_id = data.get('account_id')
        campaign_id = data.get('tw_campaign_id')

        if isinstance(campaign_id, (int, long)):
            campaign_id_int = campaign_id
            campaign_id = int_to_base36(campaign_id)

        if isinstance(account_id, (int, long)):
            account_id_int = account_id
            account_id = int_to_base36(account_id)

        if account_id is None:
            res = {
                'data': {},
                'success': False,
                'message': "Missing Twitter Account ID"
            }
            return res

        if request_type == 'put':
            if campaign_id is None:
                res = {
                    'data': {},
                    'success': False,
                    'message': "Missing Twitter Campaign ID"
                }
                return res
        params = {}
        params['daily_budget_amount_local_micro'] = data.get(
            'daily_budget_amount_local_micro', None)
        params['duration_in_days'] = data.get('duration_in_days', None)
        params['end_time'] = data.get('end_time', None)
        params['frequency_cap'] = data.get('frequency_cap', None)
        params['funding_instrument_id'] = data.get('funding_instrument_id',
                                                   None)
        params['name'] = data.get('name', None)
        if data.get('paused', None) is not None:
            params['paused'] = 'true' if data.get('paused') else 'false'
        params['standard_delivery'] = str(data.get('standard_delivery')).lower(
        ) if data.get('standard_delivery') else None
        params['start_time'] = data.get('start_time', None)
        params['total_budget_amount_local_micro'] = data.get(
            'total_budget_amount_local_micro', None)

        # total_budget_amount_local_micro = 0 is not permitted
        if not params['total_budget_amount_local_micro']:
            params['total_budget_amount_local_micro'] = None

        params = dict((k, v) for k, v in params.iteritems()
                      if v is not None and v is not "")

        client = Client(settings.TW_CONSUMER_KEY, settings.TW_CONSUMER_SECRET,
                        oauth_token, oauth_token_secret)

        if settings.TW_SANDBOX:
            client.sandbox = settings.TW_SANDBOX

        try:
            account = client.accounts(account_id)

            if request_type == 'put':
                resource = '/{api_version}/accounts/{account_id}/campaigns/{campaign_id}'.format(
                    api_version=settings.TW_API_VERSION,
                    account_id=account.id,
                    campaign_id=campaign_id)
            elif request_type == 'post':
                resource = '/{api_version}/accounts/{account_id}/campaigns'.format(
                    api_version=settings.TW_API_VERSION, account_id=account.id)

            response = Request(client, request_type, resource,
                               params=params).perform()

            if response.code == 200 or response.code == 201:
                res['success'] = True

            res['data'] = response.body['data']

            if res['data'] and res['success']:
                campaign_res = self.sync_campaign(account_id_int, res['data'])

                if 'success' in campaign_res and campaign_res[
                        'success'] is True:
                    res['data'] = campaign_res['data']
                    res['sync']['success'] = campaign_res['success']
                    res['sync']['type'] = {}
                    res['sync']['type'][campaign_res['type']] = 1
                    res['sync']['total'] = 1

                elif 'success' in campaign_res and campaign_res[
                        'success'] is False:
                    res['data'] = campaign_res['data']
                    res['sync']['success'] = campaign_res['success']
                    res['sync']['message'] = campaign_res['message']

        except Error as e:
            code = None
            if e.code:
                code = e.code
            elif e.details[0]['code']:
                code = e.details[0]['code']
            res = {
                'data': {},
                'success':
                False,
                'message':
                e.details[0]['message'] if e.details and e.details[0]
                and e.details[0]['message'] else '',
                'errors': {
                    str(code): True
                } if code else {}
            }
        except Exception as e:
            res = {'data': {}, 'success': False, 'message': str(e)}
        return res
    def fetch_tweet(self, data, syncData=False, oauth_token=settings.TW_ACCESS_TOKEN,
                    oauth_secret=settings.TW_ACCESS_SECRET):
        res = {}
        res['success'] = True
        account_id = data.get('account_id')
        tweet_id = data.get('tweet_id')

        if isinstance(account_id,(int,long)):
            account_id_int = account_id
            account_id = int_to_base36(account_id)

        if not _cache.get(account_id):
            try:
                tw_account = TwitterAccount.objects_raw.filter(tw_account_id=account_id_int).first()
                if tw_account.promotable_user_id.tw_twitter_user_id:
                    _cache[account_id] = tw_account.promotable_user_id.tw_twitter_user_id
            except TwitterUser.DoesNotExist:
                _cache[account_id] = 0
            except TwitterAccount.DoesNotExist:
                _cache[account_id] = 0

        if account_id is None:
            res = {
                'data': {},
                'success': False,
                'message': "Missing Twitter Account ID"
            }
            return res

        client = Client(settings.TW_CONSUMER_KEY, settings.TW_CONSUMER_SECRET, oauth_token, oauth_secret)
        if settings.TW_SANDBOX:
            client.sandbox = settings.TW_SANDBOX
        try:
            api_domain = 'https://api.twitter.com'
            resource = '/{api_version}/statuses/show.json?id={tweet_id}'.format(api_version="1.1", tweet_id=tweet_id)
            response = Request(client, 'get', resource, domain=api_domain).perform()
            entities = response.body['entities']

            #print response.headers['x-rate-limit-remaining']
            if response.headers['x-rate-limit-remaining'] == "0" and settings.TW_RATE_LIMIT_ALERT:
                send_twitter_alert_email({"account_id": account_id, "endpoint": resource})

            expanded_url = None
            if entities and entities['urls'] and entities['urls'][0] and entities['urls'][0]['expanded_url']:
                expanded_url = entities['urls'][0]['expanded_url']

            account = client.accounts(account_id)
            as_user_id = ('?as_user_id=%s' % _cache[account_id]) if _cache[account_id] else ''
            resource = '/{api_version}/accounts/{account_id}/tweet/preview/{tweet_id}{as_user_id}'.format(api_version=settings.TW_API_VERSION, account_id=account.id, tweet_id=tweet_id, as_user_id=as_user_id)
            response = Request(client, 'get', resource).perform()
            res['data'] = response.body['data']
            res['card_url'] = expanded_url

        except Error as e:
            code = None
            if e.code:
                code = e.code
            elif e.details[0]['code']:
                code = e.details[0]['code']
            res = {
                'data': {},
                'success': False,
                'message': e.details[0]['message'] if e.details and e.details[0] and e.details[0]['message'] else '',
                'errors': { str(code): True } if code else {}
            }
        except Exception as e:
            res = {
                'data': {},
                'success': False,
                'message': str(e)
            }
        return res
    def fetch_tailored_audience(self,
                                data,
                                syncData=False,
                                oauth_token=settings.TW_ACCESS_TOKEN,
                                oauth_token_secret=settings.TW_ACCESS_SECRET):
        res = {}
        res['data'] = []
        res['success'] = False
        account_id = data.get('account_id')

        if isinstance(account_id, (int, long)):
            account_id_int = account_id
            account_id = int_to_base36(account_id)

        if account_id is None:
            res = {
                'data': {},
                'success': False,
                'message': "Missing Twitter Account ID"
            }
            return res

        client = Client(settings.TW_CONSUMER_KEY, settings.TW_CONSUMER_SECRET,
                        oauth_token, oauth_token_secret)
        if settings.TW_SANDBOX:
            client.sandbox = settings.TW_SANDBOX
        try:
            account = client.accounts(account_id)
            resource = '/{api_version}/accounts/{account_id}/tailored_audiences?count=1000'.format(
                api_version=settings.TW_API_VERSION, account_id=account_id)
            response = Request(client, 'get', resource).perform()
            tailored_audiences = response.body['data']

            next_cursor = None
            if response.body['next_cursor'] and response.body[
                    'next_cursor'] is not 0:
                next_cursor = response.body['next_cursor']
                while next_cursor is not 0:
                    resource = '/{api_version}/accounts/{account_id}/tailored_audiences?cursor={next_cursor}&count=1000'.format(
                        api_version=settings.TW_API_VERSION,
                        account_id=account_id,
                        next_cursor=next_cursor)
                    response = Request(client, 'get', resource).perform()
                    next_cursor = response.body['next_cursor'] or 0
                    tailored_audiences += response.body['data']

            api_domain = 'https://ads.twitter.com'

            resource = '/accounts/{account_id}/apps.json'.format(
                account_id=account_id)
            response = Request(client, 'get', resource,
                               domain=api_domain).perform()

            apps = response.body.get('apps_info', {})
            app_table = []
            for (k, v) in apps.iteritems():
                app_store_identifier = v.get('app_store_identifier')
                app_name = v.get('title')
                if app_store_identifier and app_name:
                    app_table.append({
                        'id': app_store_identifier,
                        'name': app_name
                    })

            def replace_app_name(app_name):
                for app_info in app_table:
                    app_name = app_name.replace(app_info['id'],
                                                app_info['name'])

                return app_name.replace('_', ' ')

            def human_format(num):
                magnitude = 0
                while abs(num) >= 1000:
                    magnitude += 1
                    num /= 1000.0
                # add more suffixes if you need them
                return '%.2f%s' % (num, ['', 'K', 'M', 'G', 'T', 'P'
                                         ][magnitude])

            for audience in tailored_audiences:
                audience['name'] = replace_app_name(audience['name'])
                if audience['audience_size']:
                    audience['audience_size'] = human_format(
                        audience['audience_size'])
                    audience['name'] = '%s (%s users)' % (
                        audience['name'], audience['audience_size'])

            res['success'] = True
            res['data'] = tailored_audiences

        except Exception as e:
            res = {'data': {}, 'success': False, 'message': str(e)}

        if syncData and res['data'] and res['success']:
            res['sync'] = {}
            if isinstance(res['data'], (list, tuple)):
                sync_success = 0
                sync_fail = 0
                new_count = 0
                existing_count = 0
                for index, audience in enumerate(res['data'], start=0):
                    audience_res = self.sync_tailored_audience(
                        account_id_int, audience)
                    if 'success' in audience_res and audience_res[
                            'success'] is True:
                        if audience_res['type'] == 'existing':
                            existing_count += 1
                        if audience_res['type'] == 'new':
                            new_count += 1
                        sync_success += 1

                    elif 'success' in audience_res and audience_res[
                            'success'] is False:
                        sync_fail += 1

                res['sync']['type'] = {}
                res['sync']['type']['existing'] = existing_count
                res['sync']['type']['new'] = new_count
                res['sync']['total'] = sync_success
                if sync_fail == 0:
                    res['sync']['success'] = True
                else:
                    res['sync']['success'] = False

            elif isinstance(res['data'], dict):
                audience_res = self.sync_tailored_audience(
                    account_id_int, res['data'])

                if 'success' in audience_res and audience_res[
                        'success'] is True:
                    res['data'] = audience_res['data']
                    res['sync']['success'] = audience_res['success']
                    res['sync']['type'] = {}
                    res['sync']['type'][audience_res['type']] = 1
                    res['sync']['total'] = 1

                elif 'success' in audience_res and audience_res[
                        'success'] is False:
                    res['data'] = audience_res['data']
                    res['sync']['success'] = audience_res['success']
                    res['sync']['message'] = audience_res['message']
        return res
Example #13
0
    def batch_create_update_line_item(
            self,
            data,
            account_id,
            oauth_token=settings.TW_ACCESS_TOKEN,
            oauth_token_secret=settings.TW_ACCESS_SECRET,
            request_type="post"):
        res = {}
        res['success'] = False
        campaign_id_int = None

        if isinstance(account_id, (int, long)):
            account_id_int = account_id
            account_id = int_to_base36(account_id)

        if account_id is None:
            res = {
                'data': [],
                'success': False,
                'message': "Missing Twitter Account ID"
            }
            return res

        if isinstance(data, (list, tuple)):
            post_data = []
            for line_item in data:
                line_item_data = {}
                params = {}
                params['bid_amount_local_micro'] = line_item.get(
                    'bid_amount_local_micro', None)
                params['bid_type'] = line_item.get('bid_type', None)
                params['bid_unit'] = line_item.get('bid_unit', None)
                params['campaign_id'] = line_item.get('campaign_id', None)
                params['categories'] = line_item.get('categories', None)
                params['charge_by'] = line_item.get('charge_by', None)
                params['end_time'] = line_item.get('end_time', None)
                params['include_sentiment'] = line_item.get(
                    'include_sentiment', None)
                params['line_item_id'] = line_item.get('line_item_id', None)
                params['name'] = line_item.get('name', None)
                params['objective'] = line_item.get('objective',
                                                    'APP_INSTALLS')
                params['primary_web_event_tag'] = line_item.get(
                    'primary_web_event_tag', None)
                params['optimization'] = line_item.get('optimization', None)
                params['paused'] = str(line_item.get(
                    'paused')).lower() if line_item.get('paused') else None
                params['placements'] = line_item.get('placements',
                                                     'ALL_ON_TWITTER')
                params['product_type'] = line_item.get('product_type',
                                                       'PROMOTED_TWEETS')
                params['start_time'] = line_item.get('start_time', None)
                params['total_budget_amount_local_micro'] = line_item.get(
                    'total_budget_amount_local_micro', None)

                # total_budget_amount_local_micro = 0 is not permitted
                if not params['total_budget_amount_local_micro']:
                    params['total_budget_amount_local_micro'] = None

                params = dict((k, v) for k, v in params.iteritems()
                              if v is not None and v is not "")

                if request_type == 'post':
                    line_item_data['operation_type'] = 'Create'
                if request_type == 'put':
                    line_item_data['operation_type'] = 'Update'
                line_item_data['params'] = params
                post_data.append(line_item_data)

            client = Client(settings.TW_CONSUMER_KEY,
                            settings.TW_CONSUMER_SECRET, oauth_token,
                            oauth_token_secret)

            if settings.TW_SANDBOX:
                client.sandbox = settings.TW_SANDBOX

            # Split up requests into batches of 20
            batch = []
            batches = []
            for x in range(0, len(post_data), 20):
                batch = post_data[x:x + 20]
                batches.append(batch)

            success_batch = []
            error_batch = []
            error_details = []
            success = False
            error = False

            for batch_post in batches:
                try:
                    account = client.accounts(account_id)
                    headers = {"Content-Type": "application/json"}
                    resource = '/{api_version}/batch/accounts/{account_id}/line_items'.format(
                        api_version=settings.TW_API_VERSION,
                        account_id=account.id)
                    response = Request(client,
                                       'post',
                                       resource,
                                       body=json.dumps(batch_post),
                                       headers=headers).perform()

                    if response.code == 200 or response.code == 201:
                        success = True
                        success_batch.extend(response.body['data'])

                except Error as e:
                    error = True
                    if e.response.body.get('operation_errors',
                                           None) is not None:
                        for err in e.response.body.get('operation_errors'):
                            if err:
                                if isinstance(err, dict):
                                    err = [err]
                                error_details.extend(err)
                    if e.response.body.get('errors', None) is not None:
                        for err in e.response.body.get('errors'):
                            if err:
                                if isinstance(err, dict):
                                    err = [err]
                                error_details.extend(err)

                    error_batch.extend(batch_post)

                except Exception as e:
                    res = {'data': [], 'success': False, 'message': str(e)}
                    error_batch.extend(batch_post)

            if success_batch and success:
                res['sync'] = {}

                if isinstance(success_batch, dict):
                    success_batch = [success_batch]

                sync_success = 0
                sync_fail = 0
                new_count = 0
                existing_count = 0

                for index, api_line_item in enumerate(success_batch, start=0):
                    #campaign_id could be different in line item bach
                    campaign_id_int = base36_to_int(
                        api_line_item['campaign_id'])
                    line_item_res = self.sync_line_item(
                        account_id_int, campaign_id_int, api_line_item)
                    if 'success' in line_item_res and line_item_res[
                            'success'] is True:
                        if line_item_res['type'] == 'existing':
                            existing_count += 1
                        if line_item_res['type'] == 'new':
                            new_count += 1
                        sync_success += 1

                    elif 'success' in line_item_res and line_item_res[
                            'success'] is False:
                        sync_fail += 1

                res['sync']['type'] = {}
                res['sync']['type']['existing'] = existing_count
                res['sync']['type']['new'] = new_count
                res['sync']['total'] = sync_success

                if sync_fail == 0:
                    res['sync']['success'] = True
                else:
                    res['sync']['success'] = False

            res['success'] = success
            res['count'] = {}
            res['count']['success'] = len(success_batch)
            res['count']['total'] = len(data)
            res['count']['error'] = len(error_batch)
            res['data'] = success_batch

            if error:
                res['success'] = False
                res['error'] = {}
                res['error']['data'] = error_batch
                res['error']['messages'] = filter(None, error_details)

            return res

        elif isinstance(data, dict):
            if request_type == 'post':
                return self.create(data, oauth_token, oauth_token_secret)
            if request_type == 'put':
                return self.update(data, oauth_token, oauth_token_secret)
Example #14
0
    def create_update_line_item(self,
                                data,
                                oauth_token=settings.TW_ACCESS_TOKEN,
                                oauth_token_secret=settings.TW_ACCESS_SECRET,
                                request_type="post"):
        res = {}
        res['sync'] = {}
        account_id = data.get('account_id', None)
        campaign_id = data.get('campaign_id', None)
        line_item_id = data.get('line_item_id', None)
        campaign_id_int = None

        if isinstance(campaign_id, (int, long)):
            campaign_id_int = campaign_id
            campaign_id = int_to_base36(campaign_id)
            data['campaign_id'] = campaign_id

        if isinstance(line_item_id, (int, long)):
            line_item_id_int = line_item_id
            line_item_id = int_to_base36(line_item_id)

        if isinstance(account_id, (int, long)):
            account_id_int = account_id
            account_id = int_to_base36(account_id)

        if account_id is None:
            res = {
                'data': [],
                'success': False,
                'message': "Missing Twitter Account ID"
            }
            return res

        if request_type == 'post':
            if campaign_id is None:
                res = {
                    'data': [],
                    'success': False,
                    'message': "Missing Twitter Campaign ID"
                }
                return res

        if request_type == 'put':
            if line_item_id is None:
                res = {
                    'data': [],
                    'success': False,
                    'message': "Missing Twitter Line Item ID"
                }
                return res

        params = {}
        params['advertiser_domain'] = data.get('advertiser_domain', None)
        # automatically_set_bid and bid_type cannot be set in the same request
        # See https://dev.twitter.com/ads/reference/post/accounts/%3Aaccount_id/line_items#api-param-line-item-bid_type
        if data.get('automatically_select_bid', False) is True:
            params['automatically_select_bid'] = str(True).lower()
        else:
            params['bid_type'] = data.get('bid_type', None)
            params['bid_amount_local_micro'] = data.get(
                'bid_amount_local_micro', None)

        params['bid_amount_local_micro'] = data.get('bid_amount_local_micro',
                                                    None)
        params['bid_type'] = data.get('bid_type', None)
        params['bid_unit'] = data.get('bid_unit', None)
        params['campaign_id'] = data.get('campaign_id', None)
        params['categories'] = data.get('categories', None)
        params['charge_by'] = data.get('charge_by', None)
        params['end_time'] = data.get('end_time', None)
        params['include_sentiment'] = data.get('include_sentiment',
                                               'POSITIVE_ONLY')
        params['name'] = data.get('name', None)
        params['objective'] = data.get('objective', 'APP_INSTALLS')
        params['optimization'] = data.get('optimization', None)
        if data.get('paused', None) is not None:
            params['paused'] = 'true' if data.get('paused') else 'false'
        params['placements'] = data.get('placements', 'ALL_ON_TWITTER')
        params['product_type'] = data.get('product_type', 'PROMOTED_TWEETS')
        params['start_time'] = data.get('start_time', None)
        params['total_budget_amount_local_micro'] = data.get(
            'total_budget_amount_local_micro', None)

        # total_budget_amount_local_micro = 0 is not permitted
        if not params['total_budget_amount_local_micro']:
            params['total_budget_amount_local_micro'] = None

        params = dict((k, v) for k, v in params.iteritems()
                      if v is not None and v is not "")

        client = Client(settings.TW_CONSUMER_KEY, settings.TW_CONSUMER_SECRET,
                        oauth_token, oauth_token_secret)
        if settings.TW_SANDBOX:
            client.sandbox = settings.TW_SANDBOX

        try:
            account = client.accounts(account_id)

            if request_type == 'put':
                resource = '/{api_version}/accounts/{account_id}/line_items/{line_item_id}'.format(
                    api_version=settings.TW_API_VERSION,
                    account_id=account.id,
                    line_item_id=line_item_id)

            elif request_type == 'post':
                resource = '/{api_version}/accounts/{account_id}/line_items'.format(
                    api_version=settings.TW_API_VERSION, account_id=account.id)

            response = Request(client, request_type, resource,
                               params=params).perform()

            if response.code == 200 or response.code == 201:
                res['success'] = True

            res['data'] = response.body['data']

            if res['data'] and res['success']:
                if campaign_id_int is None and res['data']['campaign_id']:
                    campaign_id_int = base36_to_int(res['data']['campaign_id'])

                line_item_res = self.sync_line_item(account_id_int,
                                                    campaign_id_int,
                                                    res['data'])

                if 'success' in line_item_res and line_item_res[
                        'success'] is True:
                    res['data'] = line_item_res['data']
                    res['sync']['success'] = line_item_res['success']
                    res['sync']['type'] = {}
                    res['sync']['total'] = 1
                    res['sync']['type'][line_item_res['type']] = 1

                elif 'success' in line_item_res and line_item_res[
                        'success'] is False:
                    res['data'] = line_item_res['data']
                    res['sync']['success'] = line_item_res['success']
                    res['sync']['message'] = line_item_res['message']

        except Error as e:
            code = None
            if e.code:
                code = e.code
            elif e.details[0]['code']:
                code = e.details[0]['code']
            res = {
                'data': {},
                'success':
                False,
                'message':
                e.details[0]['message'] if e.details and e.details[0]
                and e.details[0]['message'] else '',
                'errors': {
                    str(code): True
                } if code else {}
            }
        except Exception as e:
            res = {'data': {}, 'success': False, 'message': str(e)}

        return res
Example #15
0
    def get_line_item(self,
                      data,
                      oauth_token=settings.TW_ACCESS_TOKEN,
                      oauth_token_secret=settings.TW_ACCESS_SECRET):
        res = {}
        account_id = data.get('account_id')
        line_item_id = data.get('line_item_id')

        if isinstance(line_item_id, (int, long)):
            line_item_id = int_to_base36(line_item_id)

        if isinstance(account_id, (int, long)):
            account_id = int_to_base36(account_id)

        if account_id is None:
            res = {
                'data': {},
                'success': False,
                'message': "Missing Twitter Account ID"
            }
            return res

        if line_item_id is None:
            res = {
                'data': {},
                'success': False,
                'message': "Missing Twitter Line Item ID"
            }
            return res

        client = Client(settings.TW_CONSUMER_KEY, settings.TW_CONSUMER_SECRET,
                        oauth_token, oauth_token_secret)
        if settings.TW_SANDBOX:
            client.sandbox = settings.TW_SANDBOX
        try:
            account = client.accounts(account_id)
            resource = '/{api_version}/accounts/{account_id}/line_items/{line_item_id}?count=1000&with_deleted=true'.format(
                api_version=settings.TW_API_VERSION,
                account_id=account.id,
                line_item_id=line_item_id)
            response = Request(client, 'get', resource).perform()
            res['data'] = response.body['data']
            res['success'] = True
        except Error as e:
            code = None
            if e.code:
                code = e.code
            elif e.details[0]['code']:
                code = e.details[0]['code']
            res = {
                'data': {},
                'success':
                False,
                'message':
                e.details[0]['message'] if e.details and e.details[0]
                and e.details[0]['message'] else '',
                'errors': {
                    str(code): True
                } if code else {}
            }
        except Exception as e:
            res = {'data': {}, 'success': False, 'message': str(e)}
        return res
Example #16
0
    def fetch_line_items(self,
                         data,
                         syncData=False,
                         oauth_token=settings.TW_ACCESS_TOKEN,
                         oauth_token_secret=settings.TW_ACCESS_SECRET):
        res = {}
        res['data'] = []
        res['success'] = False
        account_id = data.get('account_id')
        campaign_id = data.get('campaign_id')
        line_item_id = data.get('line_item_id')
        campaign_id_int = None

        if isinstance(account_id, (int, long)):
            account_id_int = account_id
            account_id = int_to_base36(account_id)

        if isinstance(campaign_id, (int, long)):
            campaign_id_int = campaign_id
            campaign_id = int_to_base36(campaign_id)

        if isinstance(line_item_id, (int, long)):
            line_item_id = int_to_base36(line_item_id)

        if account_id is None:
            res = {
                'data': {},
                'success': False,
                'message': "Missing Twitter Account ID"
            }
            return res

        client = Client(settings.TW_CONSUMER_KEY, settings.TW_CONSUMER_SECRET,
                        oauth_token, oauth_token_secret)

        if settings.TW_SANDBOX:
            client.sandbox = settings.TW_SANDBOX

        try:
            account = client.accounts(account_id)
            resource = '/{api_version}/accounts/{account_id}/line_items?with_deleted=true'.format(
                api_version=settings.TW_API_VERSION, account_id=account.id)
            if campaign_id is not None:
                resource = '/{api_version}/accounts/{account_id}/line_items?campaign_ids={campaign_id}&count=1000&with_deleted=true'.format(
                    api_version=settings.TW_API_VERSION,
                    account_id=account.id,
                    campaign_id=campaign_id)

            response = Request(client, 'get', resource).perform()

            if response.headers[
                    'x-rate-limit-remaining'] == "0" and settings.TW_RATE_LIMIT_ALERT:
                send_twitter_alert_email({
                    "account_id": account_id,
                    "endpoint": resource
                })

            res['data'] = response.body['data']

            next_cursor = None
            if response.body['next_cursor'] and response.body[
                    'next_cursor'] is not 0:
                next_cursor = response.body['next_cursor']
                while next_cursor is not 0:
                    resource = '/{api_version}/accounts/{account_id}/line_items?cursor={next_cursor}&count=1000&with_deleted=true'.format(
                        api_version=settings.TW_API_VERSION,
                        account_id=account.id,
                        next_cursor=next_cursor)
                    if campaign_id is not None:
                        resource = '/{api_version}/accounts/{account_id}/line_items?campaign_ids={campaign_id}&count=1000&cursor={next_cursor}&with_deleted=true'.format(
                            api_version=settings.TW_API_VERSION,
                            account_id=account.id,
                            campaign_id=campaign_id,
                            next_cursor=next_cursor)

                    response = Request(client, 'get', resource).perform()
                    next_cursor = response.body['next_cursor'] or 0
                    res['data'] += response.body['data']

            res['success'] = True

        except Error as e:
            code = None
            if e.code:
                code = e.code
            elif e.details[0]['code']:
                code = e.details[0]['code']
            res = {
                'data': {},
                'success':
                False,
                'message':
                e.details[0]['message'] if e.details and e.details[0]
                and e.details[0]['message'] else '',
                'errors': {
                    str(code): True
                } if code else {}
            }
        except Exception as e:
            res = {'data': {}, 'success': False, 'message': str(e)}

        if syncData and res['data'] and res['success']:
            res['sync'] = {}
            if isinstance(res['data'], (list, tuple)):
                sync_success = 0
                sync_fail = 0
                new_count = 0
                existing_count = 0
                for index, api_line_item in enumerate(res['data'], start=0):
                    if campaign_id_int is None:
                        campaign_id_int = base36_to_int(
                            api_line_item['campaign_id'])

                    line_item_res = self.sync_line_item(
                        account_id_int, campaign_id_int, api_line_item)
                    if 'success' in line_item_res and line_item_res[
                            'success'] is True:
                        if line_item_res['type'] == 'existing':
                            existing_count += 1
                        if line_item_res['type'] == 'new':
                            new_count += 1
                        sync_success += 1

                    elif 'success' in line_item_res and line_item_res[
                            'success'] is False:
                        sync_fail += 1
                res['sync']['type'] = {}
                res['sync']['type']['existing'] = existing_count
                res['sync']['type']['new'] = new_count
                res['sync']['total'] = sync_success
                if sync_fail == 0:
                    res['sync']['success'] = True
                else:
                    res['sync']['success'] = False

            elif isinstance(res['data'], dict):
                line_item_res = self.sync_line_item(account_id_int,
                                                    campaign_id_int,
                                                    res['data'])

                if 'success' in line_item_res and line_item_res[
                        'success'] is True:
                    res['data'] = line_item_res['data']
                    res['sync']['success'] = line_item_res['success']
                    res['sync']['type'] = {}
                    res['sync']['total'] = 1
                    res['sync']['type'][line_item_res['type']] = 1

                elif 'success' in line_item_res and line_item_res[
                        'success'] is False:
                    res['data'] = line_item_res['data']
                    res['sync']['success'] = line_item_res['success']
                    res['sync']['message'] = line_item_res['message']
        return res
    def fetch_app_cards(self,
                        data,
                        syncData=False,
                        oauth_token=settings.TW_ACCESS_TOKEN,
                        oauth_secret=settings.TW_ACCESS_SECRET):
        res = {}
        account_id = data.get('account_id')

        if isinstance(account_id, (int, long)):
            account_id_int = account_id
            account_id = int_to_base36(account_id)
        else:
            account_id_int = base36_to_int(account_id)

        if account_id is None:
            res = {
                'data': {},
                'success': False,
                'message': "Missing Twitter Account ID"
            }
            return res

        client = Client(settings.TW_CONSUMER_KEY, settings.TW_CONSUMER_SECRET,
                        oauth_token, oauth_secret)
        if settings.TW_SANDBOX:
            client.sandbox = settings.TW_SANDBOX
        try:
            res['data'] = []
            account = client.accounts(account_id)
            resource = '/{api_version}/accounts/{account_id}/cards/app_download'.format(
                api_version=settings.TW_API_VERSION, account_id=account.id)
            response = Request(client, 'get', resource).perform()
            for card in response.body['data']:
                res['data'].append(card)

            resource = '/{api_version}/accounts/{account_id}/cards/image_app_download'.format(
                api_version=settings.TW_API_VERSION, account_id=account.id)
            response = Request(client, 'get', resource).perform()
            for card in response.body['data']:
                res['data'].append(card)

            resource = '/{api_version}/accounts/{account_id}/cards/video_app_download'.format(
                api_version=settings.TW_API_VERSION, account_id=account.id)
            response = Request(client, 'get', resource).perform()

            if response.headers[
                    'x-rate-limit-remaining'] == "0" and settings.TW_RATE_LIMIT_ALERT:
                send_twitter_alert_email({
                    "account_id": account_id,
                    "endpoint": resource
                })

            for card in response.body['data']:
                res['data'].append(card)
            res['success'] = True

        except Error as e:
            code = None
            if e.code:
                code = e.code
            elif e.details[0]['code']:
                code = e.details[0]['code']
            res = {
                'data': {},
                'success':
                False,
                'message':
                e.details[0]['message'] if e.details and e.details[0]
                and e.details[0]['message'] else '',
                'errors': {
                    str(code): True
                } if code else {}
            }
        except Exception as e:
            res = {'data': {}, 'success': False, 'message': str(e)}

        if syncData and res['data'] and res['success']:
            res['sync'] = {}
            if isinstance(res['data'], (list, tuple)):
                sync_success = 0
                sync_fail = 0
                new_count = 0
                existing_count = 0
                for index, api_app_card in enumerate(res['data'], start=0):
                    app_card_res = self.sync_app_card(account_id_int,
                                                      api_app_card)

                    if 'success' in app_card_res and app_card_res[
                            'success'] is True:
                        if app_card_res['type'] == 'existing':
                            existing_count += 1
                        if app_card_res['type'] == 'new':
                            new_count += 1
                        sync_success += 1
                    elif 'success' in app_card_res and app_card_res[
                            'success'] is False:
                        sync_fail += 1

                res['sync']['type'] = {}
                res['sync']['type']['existing'] = existing_count
                res['sync']['type']['new'] = new_count
                res['sync']['total'] = sync_success
                if sync_fail == 0:
                    res['sync']['success'] = True
                else:
                    res['sync']['success'] = False

            elif isinstance(res['data'], dict):
                app_card_res = self.sync_app_card(account_id_int, res['data'])
                if 'success' in app_card_res and app_card_res[
                        'success'] is True:
                    res['data'] = app_card_res['data']
                    res['sync']['success'] = app_card_res['success']
                    res['sync']['type'] = {}
                    res['sync']['total'] = 1
                    res['sync']['type'][app_card_res['type']] = 1
                    # sync_success

                if 'success' in app_card_res and app_card_res[
                        'success'] is False:
                    res['data'] = app_card_res['data']
                    res['sync']['success'] = app_card_res['success']
                    res['sync']['message'] = app_card_res['message']

        return res
Example #18
0
    def create_update_promoted_tweet(
            self,
            data,
            oauth_token=settings.TW_ACCESS_TOKEN,
            oauth_token_secret=settings.TW_ACCESS_SECRET,
            request_type="post"):
        res = {}
        res['sync'] = {}
        account_id = data.get('account_id', None)
        line_item_id = data.get('line_item_id', None)
        tweet_ids = data.get('tweet_ids', None)
        promoted_tweet_id = data.get('promoted_tweet_id', None)
        line_item_id_int = None

        line_item_id_int = line_item_id
        line_item_id_base_36 = int_to_base36(line_item_id)
        account_id_int = account_id
        account_id_base36 = int_to_base36(account_id)

        if account_id is None:
            res = {
                'data': {},
                'success': False,
                'message': "Missing Twitter Account ID"
            }
            return res

        if request_type == 'put' or request_type == 'delete':
            if promoted_tweet_id is None:
                res = {
                    'data': {},
                    'success': False,
                    'message': "Missing Twitter Promoted Tweet ID"
                }
                return res

        if request_type == 'post':
            if tweet_ids is None:
                res = {
                    'data': {},
                    'success': False,
                    'message': "Missing Twitter Tweet IDs"
                }
                return res

            if line_item_id is None:
                res = {
                    'data': {},
                    'success': False,
                    'message': "Missing Twitter Line Item ID"
                }
                return res

        params = {}
        params['display_properties'] = data.get('display_properties', None)
        params['tweet_ids'] = data.get('tweet_ids', None)
        params['line_item_id'] = line_item_id_base_36
        params = dict((k, v) for k, v in params.iteritems()
                      if v is not None and v is not "")
        client = Client(settings.TW_CONSUMER_KEY, settings.TW_CONSUMER_SECRET,
                        oauth_token, oauth_token_secret)

        if settings.TW_SANDBOX:
            client.sandbox = settings.TW_SANDBOX

        try:
            account = client.accounts(account_id_base36)

            if request_type == 'put' or request_type == 'delete':
                resource = '/{api_version}/accounts/{account_id}/promoted_tweets/{promoted_tweet_id}'.format(
                    api_version=settings.TW_API_VERSION,
                    account_id=account.id,
                    promoted_tweet_id=promoted_tweet_id)

            elif request_type == 'post':
                resource = '/{api_version}/accounts/{account_id}/promoted_tweets'.format(
                    api_version=settings.TW_API_VERSION, account_id=account.id)
            response = Request(client, request_type, resource,
                               params=params).perform()
            if response.code == 200 or response.code == 201:
                res['success'] = True

            res['data'] = response.body['data']

            if res['data'] and res['success']:

                sync_success = 0
                sync_fail = 0
                new_count = 0
                existing_count = 0
                deleted_count = 0
                if request_type == 'delete':
                    res['data'] = [res['data']]
                for index, api_line_item_promoted_tweet in enumerate(
                        res['data'], start=0):
                    line_item_id_int = base36_to_int(
                        api_line_item_promoted_tweet['line_item_id'])
                    api_line_item_promoted_tweet['account_id'] = account_id

                    line_item_promoted_tweet_res = self.sync_promoted_tweet(
                        account_id_int, line_item_id_int,
                        api_line_item_promoted_tweet)

                    if 'success' in line_item_promoted_tweet_res and line_item_promoted_tweet_res[
                            'success'] is True:
                        if 'skip' in line_item_promoted_tweet_res:
                            continue

                        if line_item_promoted_tweet_res['type'] == 'existing':
                            existing_count += 1
                        if line_item_promoted_tweet_res['type'] == 'new':
                            new_count += 1
                        if line_item_promoted_tweet_res['type'] == 'delete':
                            deleted_count += 1
                        sync_success += 1
                    elif 'success' in line_item_promoted_tweet_res and line_item_promoted_tweet_res[
                            'success'] is False:
                        sync_fail += 1

                res['sync']['success'] = sync_fail == 0
                res['sync']['type'] = {}
                res['sync']['type']['existing'] = existing_count
                res['sync']['type']['new'] = new_count
                res['sync']['type']['delete'] = deleted_count

        except Error as e:
            code = None
            if e.code:
                code = e.code
            elif e.details[0]['code']:
                code = e.details[0]['code']
            res = {
                'data': {},
                'success':
                False,
                'message':
                e.details[0]['message'] if e.details and e.details[0]
                and e.details[0]['message'] else '',
                'errors': {
                    str(code): True
                } if code else {}
            }
        except Exception as e:
            res = {'data': {}, 'success': False, 'message': str(e)}

        return res