def get_page_posts(token, limit, since, until, page='me'):
    page_auth = SMAuth.set_token(token)
    try:
        profile = page_auth.get_object(page)
    except Exception, err:
        if err.message == ('Error validating access token: This may be because the user logged out or may be due to a system error.') \
            or ('Error validating access token: The session is invalid because the user logged out.'):
                raise ValueError(err)
def twitter_acc_info(params):
        tokens = ast.literal_eval(params.tokens)
        id_list = ast.literal_eval(params.ids)
        try:
            api = SMAuth.tweepy_auth(tokens['consumer_key'], tokens['consumer_secret'], tokens['access_token'], tokens['access_token_secret'])
            data_ = Tw.get_account_summary(api, id_list)
            data = cmg.format_response(True,data_,'Data successfully processed!')
        except Exception, err:
            data = cmg.format_response(False,err,'Error occurred while getting data from Twitter API',sys.exc_info())
def build_word_cloud(params):

        tokens = ast.literal_eval(params.tokens)
        hash_tag = params.hash_tag
        try:
            api = SMAuth.tweepy_auth(tokens['consumer_key'], tokens['consumer_secret'], tokens['access_token'], tokens['access_token_secret'])
            data_ = Tw.hashtag_search(api, hash_tag)
            wc_data = json.loads(wc.wordcloud_json(data_))
            data = cmg.format_response(True,wc_data,'Data successfully processed!')
        except ValueError, err:
            data = cmg.format_response(False,err,'Error validating access token: This may be because the user logged out or may be due to a system error.',sys.exc_info())
def get_page_fans_city(token):
    page_auth = SMAuth.set_token(token)
    try:
        request_result = page_auth.request('me/insights/page_fans_city')['data'][0]['values'][0]
        summation = page_auth.request('me/insights/page_fans_country')['data'][0]['values'][0]['value']
    except Exception, err:
        logger.error("Error fetching data from API %s" % err)
        if err.message == ('Error validating access token: This may be because the user logged out or may be due to a system error.') \
                or ('Error validating access token: The session is invalid because the user logged out.'):
                    raise ValueError(err)
        raise
def get_overview(token, insight_nodes, since=None, until=None):
    """
    :param token: access_token for the page
    :param insight_nodes: Any node mentioned in https://developers.facebook.com/docs/graph-api/reference/v2.5/insights#page_users
    :param since: From date [Optional]
    :param until: To Date [Optional]
    :return: json
    """
    if insight_nodes is None:
        metrics = ["page_views", "page_stories", "page_fan_adds"]
    else:
        metrics = insight_nodes
    page_auth = SMAuth.set_token(token)
    output = []

    def dictionary_builder(ori_list, new_dict, name):
        data = []
        for line in new_dict:
            # append the new number to the existing array at this slot
            date_counts = [line['end_time'], 0 if 'value' not in line else line['value']]
            data.append(date_counts)
        ori_list.append({'name': name, 'data': data})
        return ori_list

    for i in metrics:
        try:
            if since is None or until is None:
                request_result = page_auth.request('me/insights/%s' % i)['data'][0]['values']


            else:
                request_result = page_auth.request('me/insights/%s' % i,
                                                 args={'since': since,
                                                      'until': until}
                                                )['data'][0]['values']
        except IndexError:
                request_result = [{'end_time': strftime("%Y-%m-%d %H:%M:%S", gmtime()), 'value': None}]
                pass
        except Exception, err:
            if err.message == ('Error validating access token: This may be because the user logged out or may be due to a system error.') \
                    or ('Error validating access token: The session is invalid because the user logged out.'):
                        raise ValueError(err)

        print request_result
        output = dictionary_builder(output, request_result, i)
def sentiment_analysis(params):

        try:
            tokens = ast.literal_eval(params.token)
        except ValueError:
            tokens = params.token
        source = str(params.source)
        try:
            limit = params.limit
        except AttributeError:
            limit = ''
        try:
            since = params.since
        except AttributeError:
            since = ''
        try:
            until = params.until
        except AttributeError:
            until = ''
        try:
            post_ids = ast.literal_eval(params.post_ids)
        except AttributeError:
            post_ids = None
        page = 'me'
        try:
            page = str(params.page)
        except AttributeError:
            pass
        try:
            hash_tag = str(params.hash_tag)
        except AttributeError:
            hash_tag = ''
        #analyzed_data = 'Incorrect datasource name provided!'
        if source == 'twitter':
            api = SMAuth.tweepy_auth(tokens['consumer_key'], tokens['consumer_secret'], tokens['access_token'], tokens['access_token_secret'])
            data_ = Tw.hashtag_search(api,hash_tag)
            #lsi.initialize_stream(hash_tag, unique_id, tokens) # if already exits do something
            #analyzed_data = smlf.process_social_media_data(unique_id, hash_tag)
            data = sa.sentiment(data_)
            result = cmg.format_response(True,data,'Data successfully processed!')
            return result

        elif source == 'facebook':
            try:
                data = FB.get_page_posts_comments(tokens, limit, since, until, page, post_ids)
            except ValueError, err:
                data = cmg.format_response(False,err,'Error validating access token: This may be because the user logged out or may be due to a system error.',sys.exc_info())
                return data

            #full_comment = []
            analyzed_data = []

            def _calculate_sentiment(post_id, comment_string):
                full_comment_str = ''
                for j in filtered_comments:
                    for comment in j['comments']:
                        full_comment_str += ' '
                        full_comment_str += comment['message'].encode('UTF8')
                logger.debug(full_comment_str)
                data_ = sa.sentiment(full_comment_str)
                full_comment_str = ''
                data_['post_id'] = post_id
                analyzed_data.append(data_)

            threads = []
            if post_ids is not None:
                for post_id in post_ids:
                    filtered_comments = filter(lambda d: d['post_id'] in post_id, data)
                    t = threading.Thread(target=_calculate_sentiment, args=(post_id, filtered_comments))
                    t.start()
                    print "Thread started to calculate sentiment analysis for post_id: {0}".format(post_id)
                    threads.append(t)
                    #full_comment_str.join(full_comment)
                    #analysed_data = sa.sentiment(full_comment_str.join(filtered_comments))
                for t in threads:
                    try:
                        t.join()
                    except Exception, err:
                        print err

                data = cmg.format_response(True,analyzed_data,'Data successfully processed!')
                return data
def get_promotional_info(token, promotion_node):
    page_auth = SMAuth.set_token(token)
    data = page_auth.get_connections("me", "Comments")
    return data