def chat_presence(request): """Sets user presence on mattermost.""" if not request.user.is_authenticated: raise Http404 profile = request.user.profile if not profile.chat_id: raise Http404 # 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()) return JsonResponse({'status': 'OK'})
def increment_view_count(self, pks, content_type, user_id, view_type, retry: bool = True) -> None: """ :param self: :param pk: :param content_type: :param user_id: :param view_type: :return: """ user = None if user_id: user = User.objects.get(pk=user_id) redis = RedisService().redis for pk in pks: key = f"{content_type}_{pk}" print(key) result = redis.incr(key) ObjectView.objects.create( viewer=user, target_id=pk, target_type=ContentType.objects.filter(model=content_type).first(), view_type=view_type, )
def get_view_count(self): try: redis = RedisService().redis result = redis.get(self.view_count_redis_key) if not result: return 0 return int(result.decode('utf-8')) except KeyError: return 0
def video_presence(request): """Sets user presence on mattermost.""" if not request.user.is_authenticated: return Http404 roomname = request.POST.get('roomname', '').replace('meet', '') participants = request.POST.get('participants', '') activity = Activity.objects.filter(pk=roomname).first() set_status = activity and int(participants) >= 0 # if so, make it so if set_status: redis = RedisService().redis seconds = 100 if not settings.DEBUG else 9999999 redis.setex(roomname, seconds, participants) return JsonResponse({'status': 'OK'})
from django.conf import settings from app.redis_service import RedisService from celery import app, group from celery.utils.log import get_task_logger from dashboard.models import Profile from marketing.mails import func_name, send_mail from retail.emails import render_share_bounty logger = get_task_logger(__name__) redis = RedisService().redis # Lock timeout of 2 minutes (just in the case that the application hangs to avoid a redis deadlock) LOCK_TIMEOUT = 60 * 2 @app.shared_task(bind=True, max_retries=3) def bounty_on_create(self, team_id, new_bounty, retry: bool = True) -> None: # what has to happen that we want to chain data from one another together # from chat.tasks import create_channel tasks = list() tasks.append( create_channel.si({ 'team_id': team_id, 'channel_name': f'bounty-{new_bounty.id}', 'channel_display_name': f'bounty-{new_bounty.id}' }))
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'])
def set_view_count(self, amount): try: redis = RedisService().redis result = redis.set(self.view_count_redis_key, amount) except KeyError: return 0