Esempio n. 1
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
Esempio n. 2
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
Esempio n. 3
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
    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 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
Esempio n. 6
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