class PeopleSourcesHandler(BaseHandler):
    @web.authenticated
    @cache(CACHE_EXPIRES)  # set the cache expires
    @unblock
    def get(self):
        """
        Returns people sources, how they find you. Result dictionary contains headers and rows.

        Example:
        headers:
        {'columnHeaders': [{'columnType': 'DIMENSION',
                    'dataType': 'STRING',
                    'name': 'ga:source'},
                   {'columnType': 'DIMENSION',
                    'dataType': 'STRING',
                    'name': 'ga:medium'},
                   {'columnType': 'METRIC',
                    'dataType': 'INTEGER',
                    'name': 'ga:sessions'},
                   {'columnType': 'METRIC',
                    'dataType': 'INTEGER',
                    'name': 'ga:pageviews'},
                   {'columnType': 'METRIC',
                    'dataType': 'TIME',
                    'name': 'ga:sessionDuration'},
                   {'columnType': 'METRIC',
                    'dataType': 'INTEGER',
                    'name': 'ga:exits'}],

        rows:
        ['google', 'organic', '7598', '10480', '366955.0', '7598'],
         ['(direct)', '(none)', '3563', '4376', '134037.0', '3562'],
         ['reddit.com', 'referral', '1026', '1236', '39638.0', '1026'],

        :return:
        """
        try:
            service_account = self.settings['service_account_email']
            self.service = GAcess(service_account_email=service_account,
                                  key_file_location=self.settings['key_file_location'])

            query_result = self.service.get_people_sources(profile_id=self.settings['ga_profile_id'],
                                                           days=self.settings['start_days_ago'])
            try:
                data = query_result['rows']
            except KeyError:
                self.set_status(400, reason='Failed to fetch people source data')
            else:
                # formatting seconds to more human readable version
                for row in data:
                    m, s = divmod(int(float(row[4])), 60)
                    h, m = divmod(m, 60)
                    row[4] = "%d:%02d:%02d" % (h, m, s)

                table_title = 'How did people found our pages?'
                headers = ['Source', 'Medium', 'Sessions', 'Page views', 'Avg. duration']
                return self.render_string('webhandler/data_table.html',
                                          data=data,
                                          table_title=table_title,
                                          headers=headers)
        except Exception as ex:
            self.set_status(403)
            return self.render_string('error.html',
                                      error=ex)
class PeopleSourcesHandler(BaseHandler):
    @web.authenticated
    @cache(CACHE_EXPIRES)  # set the cache expires
    @unblock
    def get(self):
        """
        Returns people sources, how they find you. Result dictionary contains headers and rows.

        Example:
        headers:
        {'columnHeaders': [{'columnType': 'DIMENSION',
                    'dataType': 'STRING',
                    'name': 'ga:source'},
                   {'columnType': 'DIMENSION',
                    'dataType': 'STRING',
                    'name': 'ga:medium'},
                   {'columnType': 'METRIC',
                    'dataType': 'INTEGER',
                    'name': 'ga:sessions'},
                   {'columnType': 'METRIC',
                    'dataType': 'INTEGER',
                    'name': 'ga:pageviews'},
                   {'columnType': 'METRIC',
                    'dataType': 'TIME',
                    'name': 'ga:sessionDuration'},
                   {'columnType': 'METRIC',
                    'dataType': 'INTEGER',
                    'name': 'ga:exits'}],

        rows:
        ['google', 'organic', '7598', '10480', '366955.0', '7598'],
         ['(direct)', '(none)', '3563', '4376', '134037.0', '3562'],
         ['reddit.com', 'referral', '1026', '1236', '39638.0', '1026'],

        :return:
        """
        try:
            service_account = self.settings['service_account_email']
            self.service = GAcess(service_account_email=service_account,
                                  key_file_location=self.settings['key_file_location'])

            query_result = self.service.get_people_sources(profile_id=self.settings['ga_profile_id'],
                                                           days=self.settings['start_days_ago'])
            try:
                data = query_result['rows']
            except KeyError:
                self.set_status(400, reason='Failed to fetch people source data')
            else:
                # formatting seconds to more human readable version
                for row in data:
                    m, s = divmod(int(float(row[4])), 60)
                    h, m = divmod(m, 60)
                    row[4] = "%d:%02d:%02d" % (h, m, s)

                table_title = 'How did people found our pages?'
                headers = ['Source', 'Medium', 'Sessions', 'Page views', 'Avg. duration']
                return self.render_string('webhandler/data_table.html',
                                          data=data,
                                          table_title=table_title,
                                          headers=headers)
        except Exception as ex:
            self.set_status(403)
            return self.render_string('error.html',
                                      error=ex)