Пример #1
0
def chat_presence(request):
    """Sets user presence on mattermost."""
    if not request.user.is_authenticated:
        return JsonResponse({'status': 'OK'})

    profile = request.user.profile
    if not profile.chat_id:
        return JsonResponse({'status': 'OK'})

    # setup driver
    driver = get_driver()

    # determine current status/ should we set the user as online in mm?
    current_status = driver.client.post('/users/status/ids', [profile.chat_id])
    manual = current_status[0]['manual']
    current_status = current_status[0]['status']
    set_status = current_status == 'offline' or manual or settings.DEBUG

    # if so, make it so
    if set_status:
        new_status = 'online'
        if current_status in ['away', 'dnd']:
            new_status = current_status
        driver.client.put(f'/users/{profile.chat_id}/status', {
            'user_id': profile.chat_id,
            'status': new_status
        })
        # set a marker of when this user was last seen..
        # so that get_user_prsence can clean it up later
        redis = RedisService().redis
        redis.set(profile.chat_id, timezone.now().timestamp())
        redis.set(f"chat:{profile.chat_id}", new_status)

    return JsonResponse({'status': 'OK'})
Пример #2
0
    def handle(self, *args, **options):
        # connect to API
        d = get_driver()
        teams = d.teams.get_teams()

        # outer vars
        all_usernames = []
        all_user_statuses = {}
        all_response = []

        for team in teams:
            if team['display_name'] == 'Codefund':
                continue

            # pull back users on team
            print(team['display_name'])
            all_users = []
            cont = True
            per_page = 60
            page = 0
            while cont:
                params = {'in_team':team['id'], 'sort':'last_activity_at', 'per_page': per_page, 'page': page}
                users = d.users.get_users(params=params)
                all_users += users
                cont = len(users) == per_page
                page += 1
                #for testing on small amount of data
                #if settings.DEBUG:
                #    cont = False
            for user in users:
                pass

            # get through all users
            print(f"- {len(all_users)}")
            users_status = d.client.post('/users/status/ids', [ele['id'] for ele in all_users])
            all_response += users_status
            users_status_by_id = { ele['user_id']: ele for ele in users_status }
            all_usernames += [ele['username'].lower() for ele in all_users]

            # iterate through each one, and sync it to our DB
            for user in all_users:
                last_activity_at_1 = user['last_activity_at']
                last_activity_at_2 = users_status_by_id[user['id']]['last_activity_at']
                status = users_status_by_id[user['id']]['status']
                last_activity_at = max(last_activity_at_2, last_activity_at_1)
                username = user['username']
                timestamp = int(last_activity_at/1000)
                timestamp = timezone.datetime.utcfromtimestamp(timestamp).replace(tzinfo=pytz.utc)
                all_user_statuses[username] = (status, timestamp, user['id'])

            # look for manual statuses set by /api/v0.1/chat route and clean them up if needed
            redis = RedisService().redis
            for ele in all_response:

                user_id = ele['user_id']
                status = ele['status']
                if status == 'offline':
                    continue

                # user has been offline for 10 mins
                # update mattermost, and redis
                max_delta = (10*60)

                # calc it
                now = timezone.now().timestamp()
                last_action_mattermost = int(ele['last_activity_at']/1000)
                redis_response = redis.get(user_id)
                last_seen_gc = int(float(redis_response)) if redis_response else now

                # do update
                is_away_mm = ((now - last_action_mattermost) > max_delta)
                is_away_gc = (now - last_seen_gc) > max_delta
                manual = ele['manual']
                update_ele = (manual and is_away_gc) or (not manual and is_away_mm)
                if update_ele or settings.DEBUG:
                    new_status = 'offline' 
                    d.client.put(f'/users/{user_id}/status', {'user_id': user_id, 'status': new_status})
                    redis.set(user_id, 0)
        # update all usernames
        profiles = Profile.objects.filter(handle__in=all_usernames)
        for profile in profiles:
            profile.last_chat_status, profile.last_chat_seen, profile.chat_id = all_user_statuses[profile.handle]
        bulk_update(profiles, update_fields=['last_chat_seen', 'last_chat_status', 'chat_id'])  
Пример #3
0
 def set_view_count(self, amount):
     try:
         redis = RedisService().redis
         result = redis.set(self.view_count_redis_key, amount)
     except KeyError:
         return 0