< Summary

Class:LastReadMessagesService
Assembly:SocialBarHUD
File(s):/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/Controllers/HUD/SocialBarHUD/LastReadMessagesService.cs
Covered lines:16
Uncovered lines:52
Coverable lines:68
Total lines:162
Line coverage:23.5% (16 of 68)
Covered branches:0
Total branches:0

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity NPath complexity Sequence coverage
LastReadMessagesService(...)0%110100%
Initialize()0%2.032080%
MarkAllRead(...)0%12300%
GetUnreadCount(...)0%12300%
GetAllUnreadCount()0%6200%
Dispose()0%2.152066.67%
LoadLastReadTimestamps()0%5.23037.5%
LoadChannelsUnreadCount()0%7.613020%
HandleMessageReceived(...)0%42600%
GetChannelId(...)0%12300%
GetLastReadTimestamp(...)0%12300%
Persist()0%6200%

File(s)

/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/Controllers/HUD/SocialBarHUD/LastReadMessagesService.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.Linq;
 4using DCL.Helpers;
 5using DCL.Interface;
 6using Newtonsoft.Json;
 7using UnityEngine;
 8
 9public class LastReadMessagesService : ILastReadMessagesService
 10{
 11    private const string PLAYER_PREFS_LAST_READ_CHAT_MESSAGES = "LastReadChatMessages";
 12
 13    private readonly ReadMessagesDictionary memoryRepository;
 14    private readonly IChatController chatController;
 15    private readonly IPlayerPrefs persistentRepository;
 16    private readonly IUserProfileBridge userProfileBridge;
 8817    private readonly Dictionary<string, int> channelUnreadCount = new Dictionary<string, int>();
 18
 19    public event Action<string> OnUpdated;
 20
 8821    public LastReadMessagesService(ReadMessagesDictionary memoryRepository,
 22        IChatController chatController,
 23        IPlayerPrefs persistentRepository,
 24        IUserProfileBridge userProfileBridge)
 25    {
 8826        this.memoryRepository = memoryRepository;
 8827        this.chatController = chatController;
 8828        this.persistentRepository = persistentRepository;
 8829        this.userProfileBridge = userProfileBridge;
 8830    }
 31
 32    public void Initialize()
 33    {
 8834        if (chatController != null)
 035            chatController.OnAddMessage += HandleMessageReceived;
 8836        LoadLastReadTimestamps();
 8837        LoadChannelsUnreadCount();
 8838    }
 39
 40    public void MarkAllRead(string chatId)
 41    {
 042        if (string.IsNullOrEmpty(chatId))
 43        {
 044            Debug.LogWarning("Trying to clear last read messages for an empty chatId");
 045            return;
 46        }
 47
 048        var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
 049        memoryRepository.Remove(chatId);
 050        memoryRepository.Add(chatId, timestamp);
 051        channelUnreadCount.Remove(chatId);
 052        Persist();
 053        OnUpdated?.Invoke(chatId);
 054    }
 55
 56    public int GetUnreadCount(string chatId)
 57    {
 058        if (string.IsNullOrEmpty(chatId))
 59        {
 060            Debug.LogWarning("Trying to get unread messages count for an empty chatId");
 061            return 0;
 62        }
 63
 064        return channelUnreadCount.ContainsKey(chatId) ? channelUnreadCount[chatId] : 0;
 65    }
 66
 067    public int GetAllUnreadCount() => channelUnreadCount.Sum(pair => pair.Value);
 68
 69    public void Dispose()
 70    {
 8871        if (chatController != null)
 072            chatController.OnAddMessage -= HandleMessageReceived;
 8873    }
 74
 75    private void LoadLastReadTimestamps()
 76    {
 8877        var lastReadChatMessagesList =
 78            JsonConvert.DeserializeObject<List<KeyValuePair<string, long>>>(
 79                persistentRepository.GetString(PLAYER_PREFS_LAST_READ_CHAT_MESSAGES));
 17680        if (lastReadChatMessagesList == null) return;
 081        foreach (var item in lastReadChatMessagesList)
 082            memoryRepository.Add(item.Key, item.Value);
 083    }
 84
 85    private void LoadChannelsUnreadCount()
 86    {
 17687        if (chatController == null) return;
 088        var ownUserId = userProfileBridge.GetOwn().userId;
 089        using var iterator = memoryRepository.GetEnumerator();
 090        while (iterator.MoveNext())
 91        {
 092            var channelId = iterator.Current.Key;
 093            var timestamp = GetLastReadTimestamp(channelId);
 094            channelUnreadCount[channelId] = chatController.GetEntries()
 95                .Count(message =>
 96                {
 097                    var messageChannelId = GetChannelId(message);
 098                    if (string.IsNullOrEmpty(messageChannelId)) return false;
 099                    if (messageChannelId == ownUserId) return false;
 0100                    return messageChannelId == channelId
 101                           && message.timestamp >= timestamp;
 102                });;
 103        }
 0104    }
 105
 106    private void HandleMessageReceived(ChatMessage message)
 107    {
 0108        var channelId = GetChannelId(message);
 0109        if (string.IsNullOrEmpty(channelId)) return;
 0110        if (channelId == userProfileBridge.GetOwn().userId) return;
 111
 0112        var timestamp = GetLastReadTimestamp(channelId);
 0113        if (message.timestamp >= timestamp)
 114        {
 0115            if (!channelUnreadCount.ContainsKey(channelId))
 0116                channelUnreadCount[channelId] = 0;
 0117            channelUnreadCount[channelId]++;
 118        }
 119
 0120        OnUpdated?.Invoke(channelId);
 0121    }
 122
 123    private string GetChannelId(ChatMessage message)
 124    {
 0125        return message.messageType switch
 126        {
 127            ChatMessage.Type.PRIVATE => message.sender,
 128            // TODO: solve public channelId from chatMessage information when is done from catalyst side
 129            ChatMessage.Type.PUBLIC => "general",
 130            _ => null
 131        };
 132    }
 133
 134    private ulong GetLastReadTimestamp(string chatId)
 135    {
 0136        var oldNotificationsFilteringTimestamp = DateTime.UtcNow
 137            .Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))
 138            .Subtract(TimeSpan.FromDays(1))
 139            .TotalMilliseconds;
 140
 0141        return (ulong) (memoryRepository.ContainsKey(chatId)
 142            ? memoryRepository.Get(chatId)
 143            : oldNotificationsFilteringTimestamp);
 144    }
 145
 146    private void Persist()
 147    {
 0148        var lastReadChatMessagesList = new List<KeyValuePair<string, long>>();
 0149        using (var iterator = memoryRepository.GetEnumerator())
 150        {
 0151            while (iterator.MoveNext())
 152            {
 0153                lastReadChatMessagesList.Add(new KeyValuePair<string, long>(iterator.Current.Key,
 154                    iterator.Current.Value));
 155            }
 0156        }
 157
 0158        persistentRepository.Set(PLAYER_PREFS_LAST_READ_CHAT_MESSAGES,
 159            JsonConvert.SerializeObject(lastReadChatMessagesList));
 0160        persistentRepository.Save();
 0161    }
 162}