Exemple #1
0
def stats(request, service_id):
    """Create up some stats."""
    
    service = get_object_or_404(UserService, pk=service_id)

    if check_is_service_id(service, PACKAGE):
        # get tweets
        tweets = service.handler.get_items(date.today() - timedelta(days=7))
        retweets = 0
        template_values = {}

        # retweet ratio
        # who you tweet the most
        ats = {}
        
        template_values['days_tweeted'] = generate_days_dict()
            
        if tweets:
            for tweet in tweets:
                if tweet.has_location():
                    template_values['tweet_centre'] = tweet
                if re.match('RT', tweet.body):
                    retweets = retweets + 1
                else:
                    atteds = re.findall('@[\w]*', tweet.body)
                    for user in atteds:
                        username = user.split('@')[1]
                        if username:
                            if ats.has_key(user):
                                ats[user]['count'] += 1
                            else:
                                ats[user] = {'avatar': 'http://api.twitter.com/1/users/profile_image/%s.json' % (username),
                                          'count' : 1
                                }
    
                if template_values['days_tweeted'].has_key(tweet.created.date()):
                    template_values['days_tweeted'][tweet.created.date()] = \
                               template_values['days_tweeted'][tweet.created.date()] + 1

            template_values['retweets'] = retweets
            template_values['non_retweets'] = len(tweets) - retweets
            template_values['total_tweets'] = len(tweets)
            template_values['tweets'] = tweets

            # order by value and reverse to put most popular at the top
            template_values['atters'] = SortedDict(
                sorted(ats.items(), reverse=True, key=lambda x: x[1]['count']))
            
            template_values['days_tweeted'] = SortedDict(sorted(template_values['days_tweeted'].items(), reverse=False, key=lambda x: x[0]))
            
            max_tweeted_on_a_day = SortedDict(sorted(template_values['days_tweeted'].items(), reverse=True, key=lambda x: x[1]))
            template_values['max_tweeted_on_a_day'] = max_tweeted_on_a_day[max_tweeted_on_a_day.keyOrder[0]] + 1
            
        return render(
            request,
            template_values,
            'causal/twitter/stats.html'
        )
    else:
        return redirect('/%s' %(request.user.username))
Exemple #2
0
    def _convert_stats_feed(self, feed, since):
        """Take the user's atom feed.
        """

        items = []
        avatar = ""

        if feed and feed[0]['actor_attributes'].has_key('gravatar_id'):
            avatar = 'http://www.gravatar.com/avatar/%s' % (feed[0]['actor_attributes']['gravatar_id'],)

        commit_times = {}
        
        days_committed = generate_days_dict()
        
        for entry in feed:
            if entry['public']:
                dated, time, offset = entry['created_at'].rsplit(' ')
                created = self._convert_date(entry)

                if created.date() >= since:

                    # extract commits from push event
                    if entry['type'] == 'PushEvent':
                        
                        # fetch and get the stats on commits
                        for commit in entry['payload']['shas']:
                            url = "https://api.github.com/repos/%s/%s/git/commits/%s" % (self.service.auth.username, entry['repository']['name'], commit[0])
                            commit_detail = get_data(self.service, url, disable_oauth=True)
                            item = ServiceItem()
                            item.title = "Commit for %s" % (entry['repository']['name'])
                            item.body = '"%s"' % (commit_detail['message']) 
                            item.created = self._convert_commit_date(commit_detail)
                            
                            if commit_detail.has_key('url'):
                                item.link_back = commit_detail['url']

                            item.service = self.service
                            items.append(item)
                            
                            if days_committed.has_key(item.created.date()):
                                days_committed[item.created.date()] = days_committed[item.created.date()] + 1
                        
                            hour = created.strftime('%H')
                            if commit_times.has_key(hour):
                                commit_times[hour] += + 1
                            else:
                                commit_times[hour] = 1
                    else:
                        item = ServiceItem()
                        self._set_title_body(entry, item)
                        item.created = created
                        if entry.has_key('url'):
                            item.link_back = entry['url']
                        item.service = self.service
                        items.append(item)

        commit_times = SortedDict(sorted(
            commit_times.items(),
            reverse=True,
            key=lambda x: x[1]
        ))
        
        days_committed = SortedDict(sorted(days_committed.items(), reverse=False, key=lambda x: x[0]))
        max_commits_on_a_day = SortedDict(sorted(days_committed.items(), reverse=True, key=lambda x: x[1]))
        max_commits_on_a_day = max_commits_on_a_day[max_commits_on_a_day.keyOrder[0]] + 1

        return items, avatar, commit_times, self._most_common_commit_time(commit_times), days_committed, max_commits_on_a_day
Exemple #3
0
def stats(request, service_id):
    """Create up some stats.
    """

    service = get_object_or_404(UserService, pk=service_id)

    if check_is_service_id(service, PACKAGE_NAME):
        pictures = service.handler.get_stats_items(date.today() - timedelta(days=7))
        template_values = {}
        # Most commented
        comments = 0
        template_values["most_commented_picture"] = None
        template_values["number_of_pictures_favorites"] = 0
        template_values["cameras_used"] = {}
        template_values["days_taken"] = generate_days_dict()

        number_of_pictures_favorites = 0

        for pic in pictures:
            if pic.has_location():
                template_values["pic_centre"] = pic

            if pic.favorite:
                template_values["number_of_pictures_favorites"] = number_of_pictures_favorites + 1

            if hasattr(pic, "number_of_comments"):
                if int(pic.number_of_comments) > comments:
                    comments = pic.number_of_comments
                    template_values["most_commented_picture"] = pic

            # Get camera used count
            if template_values["cameras_used"].has_key(pic.camera_make + " - " + pic.camera_model):
                template_values["cameras_used"][pic.camera_make + " - " + pic.camera_model] = (
                    template_values["cameras_used"][pic.camera_make + " - " + pic.camera_model] + 1
                )
            else:
                if hasattr(pic, "camera_make"):
                    template_values["cameras_used"][pic.camera_make + " - " + pic.camera_model] = 1

            if template_values["days_taken"].has_key(pic.created.date()):
                template_values["days_taken"][pic.created.date()] = (
                    template_values["days_taken"][pic.created.date()] + 1
                )

        template_values["cameras_used"] = SortedDict(
            sorted(template_values["cameras_used"].items(), reverse=True, key=lambda x: x[1])
        )
        template_values["pictures"] = pictures
        template_values["number_of_pictures_uploaded"] = len(pictures)
        template_values["days_taken"] = SortedDict(
            sorted(template_values["days_taken"].items(), reverse=False, key=lambda x: x[0])
        )

        max_taken_on_a_day = SortedDict(sorted(template_values["days_taken"].items(), reverse=True, key=lambda x: x[1]))
        template_values["max_taken_on_a_day"] = max_taken_on_a_day[max_taken_on_a_day.keyOrder[0]] + 1

        if template_values["number_of_pictures_favorites"] == 0:
            template_values["number_of_pictures_favorites"] = "No favourite pictures this week."

        return render(request, template_values, "causal/flickr/stats.html")
    else:
        return redirect("/%s" % (request.user.username,))
Exemple #4
0
    def _convert_stats_feed(self, feed, since):
        """Take the user's atom feed.
        """

        items = []
        commits = []
        commit_times = {}
        repos = {}
        avatar = ""
        
        list_of_commits = {}
        
        username, name = self._get_details()
        
        if not username or not feed:
            return 

        if feed and feed[0]['actor_attributes'].has_key('gravatar_id'):
            avatar = 'http://www.gravatar.com/avatar/%s' % (feed[0]['actor_attributes']['gravatar_id'],)

        days_committed = generate_days_dict()
                
        for entry in feed:
            if entry['public']:
                dated, time, offset = entry['created_at'].rsplit(' ')
                if entry.has_key('created_at'):
                    created = self._convert_date(entry['created_at'])

                if created.date() >= since:
                    if entry.has_key('repository') \
                       and entry['repository'].has_key('name') \
                       and entry['repository'].has_key('owner'):
                        url = "https://api.github.com/repos/%s/%s?" % (
                            entry['repository']['owner'],
                            entry['repository']['name'])
                        repo = self.get_data(url)
                        if repo:                
                            repos[entry['repository']['owner'] + entry['repository']['name']] = repo
                        
                    # extract commits from push event
                    if entry['type'] == 'PushEvent':
                        
                        # fetch and get the stats on commits
                        for commit in entry['payload']['shas']:
                            
                            # test it we have seen the commit before
                            if not list_of_commits.has_key(commit[0]):
                                list_of_commits[commit[0]] = True
                                item = ServiceItem()
                                if name == commit[-1]:
                                    commit_detail = None
                                    if entry.has_key('repository'):
                                        url = "https://api.github.com/repos/%s/%s/git/commits/%s?" % (
                                            entry['repository']['owner'],
                                            entry['repository']['name'], 
                                            commit[0])
                                        
                                        commit_detail = self.get_data(url)
                                        item.body = '"%s"' % (commit_detail['message'])
                                    
                                        item.title = "Commit for %s" % (entry['repository']['name'])
                                    else:
                                        if entry['type'] == 'PushEvent':
                                            item.title = "Push for %s" % (entry['url'].split('/')[4])
                                            item.body = entry['payload']['shas'][0][2]
                                    
                                    if commit_detail and commit_detail.has_key('author') and commit_detail['author'].has_key('date'):
                                        item.created = self._convert_date(commit_detail['author']['date'])
                                    else:
                                        item.created = self._convert_date(entry['created_at'])
                                    # tag entry as private as the repo is marked private
                                    if repo and repo.has_key('private'):
                                        item.private = repo['private']
                                    
                                    if commit_detail and commit_detail.has_key('url'):
                                        # https://github.com/bassdread/causal/commit/7aef64a152ec28846111612620b6042b21615423
                                        #item.link_back = "https://github.com/%s/%s/commit/%s" %(entry['repository']['owner'], entry['repository']['name'], commit[0])
                                        item.link_back = commit_detail['url']
                                    else:
                                        item.link_back = entry['url']
        
                                    item.service = self.service
                                    commits.append(item)
                                    
                                    if days_committed.has_key(item.created_local.date()):
                                        days_committed[item.created_local.date()] = days_committed[item.created_local.date()] + 1
                                
                                    hour = item.created_local.strftime('%H')
                                    if commit_times.has_key(hour):
                                        commit_times[hour] += 1
                                    else:
                                        commit_times[hour] = 1
                                        
                                    del(item)
                    else:
                        item = ServiceItem()
                        self._set_title_body(entry, item)
                        item.created = created
                        if entry.has_key('url'):
                            item.link_back = entry['url']
                        item.service = self.service
                        items.append(item)

        commit_times = SortedDict(sorted(
            commit_times.items(),
            reverse=True,
            key=lambda x: x[1]
        ))
        
        days_committed = SortedDict(sorted(days_committed.items(), reverse=False, key=lambda x: x[0]))
        max_commits_on_a_day = SortedDict(sorted(days_committed.items(), reverse=True, key=lambda x: x[1]))
        max_commits_on_a_day = max_commits_on_a_day[max_commits_on_a_day.keyOrder[0]] + 1
        commits.sort(key=lambda commit: commit.created_local, reverse=True)
        
        return { 'events' : items,
                 'commits' : commits, 
                 'avatar' : avatar, 
                 'commit_times' : commit_times,
                 'most_common_commit_time' : self._most_common_commit_time(commit_times), 
                 'days_committed' : days_committed, 
                 'max_commits_on_a_day' : max_commits_on_a_day, 
                 'repos' : repos}