< Summary

Class:DCL.Social.Friends.FriendsHUDController
Assembly:FriendsHUD
File(s):/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/Controllers/HUD/FriendsHUD/Scripts/FriendsHUDController.cs
Covered lines:269
Uncovered lines:118
Coverable lines:387
Total lines:803
Line coverage:69.5% (269 of 387)
Covered branches:0
Total branches:0

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity NPath complexity Sequence coverage
FriendsHUDController(...)0%110100%
Initialize(...)0%550100%
SetVisiblePanelList(...)0%220100%
Dispose()0%990100%
SetVisibility(...)0%8.128087.5%
HandleViewClosed()0%6200%
HandleFriendsInitialized()0%11.37055.56%
HandleProfileUpdated(...)0%110100%
UpdateBlockStatus()0%13.2111073.68%
HandleRequestFriendship(...)0%110100%
HandleRequestFriendshipAsync()0%62.9417045.83%
AreAlreadyFriends(...)0%330100%
HandleUserStatusUpdated(...)0%110100%
UpdateUserStatus(...)0%37.1411040%
HandleFriendshipUpdated(...)0%54.8413037.21%
RemoveFriendship(...)0%110100%
HandleFriendProfileUpdated(...)0%3.13077.78%
IsUserBlocked(...)0%3.333066.67%
OnFriendNotFound(...)0%110100%
UpdateNotificationsCounter()0%220100%
HandleOpenWhisperChat(...)0%220100%
HandleUnfriend(...)0%12300%
HandleRequestRejected(...)0%2100%
HandleRequestRejectedAsync()0%90900%
HandleRequestCancelledAsync()0%90900%
HandleRequestCancelled(...)0%2100%
HandleRequestAccepted(...)0%2100%
HandleRequestAcceptedAsync()0%90900%
DisplayFriendsIfAnyIsLoaded()0%3.333066.67%
DisplayMoreFriends()0%220100%
DisplayMoreFriendsAsync()0%5.024060%
DisplayMoreFriendRequests()0%3.333066.67%
DisplayMoreFriendRequestsAsync()0%4.594066.67%
AddFriendRequests(...)0%330100%
ShowFriendRequest(...)0%6.096086.67%
DisplayFriendRequestsIfAnyIsLoaded()0%4.844062.5%
ShowOrHideMoreFriendRequestsToLoadHint()0%220100%
ShowOrHideMoreFriendsToLoadHint()0%330100%
SearchFriends(...)0%110100%
SearchFriendsAsync()0%5.395075%
OpenFriendRequestDetails(...)0%64050%
RestartFriendsOperationsCancellationToken()0%110100%

File(s)

/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/Controllers/HUD/FriendsHUD/Scripts/FriendsHUDController.cs

#LineLine coverage
 1using Cysharp.Threading.Tasks;
 2using DCL.Tasks;
 3using SocialFeaturesAnalytics;
 4using System;
 5using System.Collections.Generic;
 6using System.Threading;
 7using UnityEngine;
 8
 9namespace DCL.Social.Friends
 10{
 11    public class FriendsHUDController : IHUD
 12    {
 13        private const int LOAD_FRIENDS_ON_DEMAND_COUNT = 30;
 14        private const int MAX_SEARCHED_FRIENDS = 100;
 15        private const string NEW_FRIEND_REQUESTS_FLAG = "new_friend_requests";
 16        private const string ENABLE_QUICK_ACTIONS_FOR_FRIEND_REQUESTS_FLAG = "enable_quick_actions_on_friend_requests";
 17        private const int GET_FRIENDS_TIMEOUT = 10;
 18
 4219        private readonly Dictionary<string, FriendEntryModel> friends = new ();
 4220        private readonly Dictionary<string, FriendEntryModel> onlineFriends = new ();
 21        private readonly DataStore dataStore;
 22        private readonly IFriendsController friendsController;
 23        private readonly IUserProfileBridge userProfileBridge;
 24        private readonly ISocialAnalytics socialAnalytics;
 25        private readonly IChatController chatController;
 26        private readonly IMouseCatcher mouseCatcher;
 4027        private BaseVariable<HashSet<string>> visibleTaskbarPanels => dataStore.HUDs.visibleTaskbarPanels;
 2028        private bool isNewFriendRequestsEnabled => dataStore.featureFlags.flags.Get().IsFeatureEnabled(NEW_FRIEND_REQUES
 729        private bool isQuickActionsForFriendRequestsEnabled => !isNewFriendRequestsEnabled || dataStore.featureFlags.fla
 4230        private CancellationTokenSource friendOperationsCancellationToken = new ();
 31
 32        private UserProfile ownUserProfile;
 33        private bool searchingFriends;
 34        private int lastSkipForFriends;
 35        private int lastSkipForFriendRequests;
 36
 12337        public bool IsVisible { get; private set; }
 96738        public IFriendsHUDComponentView View { get; private set; }
 39
 40        public event Action<string> OnPressWhisper;
 41        public event Action OnOpened;
 42        public event Action OnClosed;
 43        public event Action OnViewClosed;
 44
 4245        public FriendsHUDController(DataStore dataStore,
 46            IFriendsController friendsController,
 47            IUserProfileBridge userProfileBridge,
 48            ISocialAnalytics socialAnalytics,
 49            IChatController chatController,
 50            IMouseCatcher mouseCatcher)
 51        {
 4252            this.dataStore = dataStore;
 4253            this.friendsController = friendsController;
 4254            this.userProfileBridge = userProfileBridge;
 4255            this.socialAnalytics = socialAnalytics;
 4256            this.chatController = chatController;
 4257            this.mouseCatcher = mouseCatcher;
 4258        }
 59
 60        public void Initialize(IFriendsHUDComponentView view = null, bool isVisible = true)
 61        {
 4262            view ??= FriendsHUDComponentView.Create();
 4263            View = view;
 64
 4265            view.Initialize(chatController, friendsController, socialAnalytics);
 4266            view.RefreshFriendsTab();
 4267            view.OnFriendRequestApproved += HandleRequestAccepted;
 4268            view.OnCancelConfirmation += HandleRequestCancelled;
 4269            view.OnRejectConfirmation += HandleRequestRejected;
 4270            view.OnFriendRequestSent += HandleRequestFriendship;
 4271            view.OnFriendRequestOpened += OpenFriendRequestDetails;
 4272            view.OnWhisper += HandleOpenWhisperChat;
 4273            view.OnClose += HandleViewClosed;
 4274            view.OnRequireMoreFriends += DisplayMoreFriends;
 4275            view.OnRequireMoreFriendRequests += DisplayMoreFriendRequests;
 4276            view.OnSearchFriendsRequested += SearchFriends;
 4277            view.OnFriendListDisplayed += DisplayFriendsIfAnyIsLoaded;
 4278            view.OnRequestListDisplayed += DisplayFriendRequestsIfAnyIsLoaded;
 4279            view.OnDeleteConfirmation += HandleUnfriend;
 80
 4281            if (mouseCatcher != null)
 4182                mouseCatcher.OnMouseLock += HandleViewClosed;
 83
 4284            ownUserProfile = userProfileBridge.GetOwn();
 4285            ownUserProfile.OnUpdate -= HandleProfileUpdated;
 4286            ownUserProfile.OnUpdate += HandleProfileUpdated;
 87
 4288            if (friendsController != null)
 89            {
 4290                friendsController.OnUpdateFriendship += HandleFriendshipUpdated;
 4291                friendsController.OnUpdateUserStatus += HandleUserStatusUpdated;
 4292                friendsController.OnFriendNotFound += OnFriendNotFound;
 4293                friendsController.OnFriendRequestReceived += ShowFriendRequest;
 94
 4295                if (friendsController.IsInitialized)
 296                    view.HideLoadingSpinner();
 97                else
 98                {
 4099                    view.ShowLoadingSpinner();
 40100                    friendsController.OnInitialized -= HandleFriendsInitialized;
 40101                    friendsController.OnInitialized += HandleFriendsInitialized;
 102                }
 103            }
 104
 42105            ShowOrHideMoreFriendsToLoadHint();
 42106            ShowOrHideMoreFriendRequestsToLoadHint();
 107
 42108            SetVisibility(isVisible);
 42109            IsVisible = isVisible;
 42110        }
 111
 112        private void SetVisiblePanelList(bool visible)
 113        {
 20114            HashSet<string> newSet = visibleTaskbarPanels.Get();
 115
 20116            if (visible)
 16117                newSet.Add("FriendsPanel");
 118            else
 4119                newSet.Remove("FriendsPanel");
 120
 20121            visibleTaskbarPanels.Set(newSet, true);
 20122        }
 123
 124        public void Dispose()
 125        {
 43126            friendOperationsCancellationToken?.Cancel();
 43127            friendOperationsCancellationToken?.Dispose();
 43128            friendOperationsCancellationToken = null;
 129
 43130            if (friendsController != null)
 131            {
 43132                friendsController.OnInitialized -= HandleFriendsInitialized;
 43133                friendsController.OnUpdateFriendship -= HandleFriendshipUpdated;
 43134                friendsController.OnUpdateUserStatus -= HandleUserStatusUpdated;
 135            }
 136
 43137            if (View != null)
 138            {
 43139                View.OnFriendRequestApproved -= HandleRequestAccepted;
 43140                View.OnCancelConfirmation -= HandleRequestCancelled;
 43141                View.OnRejectConfirmation -= HandleRequestRejected;
 43142                View.OnFriendRequestSent -= HandleRequestFriendship;
 43143                View.OnFriendRequestOpened -= OpenFriendRequestDetails;
 43144                View.OnWhisper -= HandleOpenWhisperChat;
 43145                View.OnDeleteConfirmation -= HandleUnfriend;
 43146                View.OnClose -= HandleViewClosed;
 43147                View.OnRequireMoreFriends -= DisplayMoreFriends;
 43148                View.OnRequireMoreFriendRequests -= DisplayMoreFriendRequests;
 43149                View.OnSearchFriendsRequested -= SearchFriends;
 43150                View.OnFriendListDisplayed -= DisplayFriendsIfAnyIsLoaded;
 43151                View.OnRequestListDisplayed -= DisplayFriendRequestsIfAnyIsLoaded;
 43152                View.Dispose();
 153            }
 154
 43155            if (ownUserProfile != null)
 43156                ownUserProfile.OnUpdate -= HandleProfileUpdated;
 157
 43158            if (userProfileBridge != null)
 159            {
 118160                foreach (string friendId in friends.Keys)
 161                {
 16162                    var profile = userProfileBridge.Get(friendId);
 16163                    if (profile == null) continue;
 16164                    profile.OnUpdate -= HandleFriendProfileUpdated;
 165                }
 166            }
 43167        }
 168
 169        public void SetVisibility(bool visible)
 170        {
 61171            if (IsVisible == visible)
 41172                return;
 173
 20174            IsVisible = visible;
 20175            SetVisiblePanelList(visible);
 176
 20177            if (visible)
 178            {
 16179                lastSkipForFriends = 0;
 16180                lastSkipForFriendRequests = 0;
 16181                View.ClearAll();
 16182                View.Show();
 16183                UpdateNotificationsCounter();
 184
 32185                foreach (var friend in onlineFriends)
 0186                    View.Set(friend.Key, friend.Value);
 187
 16188                if (View.IsFriendListActive)
 7189                    DisplayMoreFriends();
 9190                else if (View.IsRequestListActive)
 5191                    DisplayMoreFriendRequests();
 192
 16193                OnOpened?.Invoke();
 194            }
 195            else
 196            {
 4197                View.Hide();
 4198                View.DisableSearchMode();
 4199                searchingFriends = false;
 4200                OnClosed?.Invoke();
 201            }
 0202        }
 203
 204        private void HandleViewClosed()
 205        {
 0206            OnViewClosed?.Invoke();
 0207            SetVisibility(false);
 0208        }
 209
 210        private void HandleFriendsInitialized()
 211        {
 1212            friendsController.OnInitialized -= HandleFriendsInitialized;
 1213            View.HideLoadingSpinner();
 214
 1215            if (View.IsActive())
 216            {
 0217                if (View.IsFriendListActive && lastSkipForFriends <= 0)
 0218                    DisplayMoreFriendsAsync(RestartFriendsOperationsCancellationToken()).Forget();
 0219                else if (View.IsRequestListActive && lastSkipForFriendRequests <= 0 && !searchingFriends)
 0220                    DisplayMoreFriendRequestsAsync(RestartFriendsOperationsCancellationToken()).Forget();
 221            }
 222
 1223            UpdateNotificationsCounter();
 1224        }
 225
 226        private void HandleProfileUpdated(UserProfile profile) =>
 2227            UpdateBlockStatus(profile).Forget();
 228
 229        private async UniTask UpdateBlockStatus(UserProfile profile)
 230        {
 231            const int ITERATIONS_PER_FRAME = 10;
 232
 233            //NOTE(Brian): HashSet to check Contains quicker.
 2234            var allBlockedUsers = profile.blocked != null
 235                ? new HashSet<string>(profile.blocked)
 236                : new HashSet<string>();
 237
 2238            var iterations = 0;
 239
 8240            foreach (var friendPair in friends)
 241            {
 2242                string friendId = friendPair.Key;
 2243                var model = friendPair.Value;
 244
 2245                model.blocked = allBlockedUsers.Contains(friendId);
 2246                await UniTask.SwitchToMainThread();
 2247                View.UpdateBlockStatus(friendId, model.blocked);
 248
 2249                iterations++;
 250
 2251                if (iterations > 0 && iterations % ITERATIONS_PER_FRAME == 0)
 0252                    await UniTask.NextFrame();
 2253            }
 2254        }
 255
 256        private void HandleRequestFriendship(string userNameOrId)
 257        {
 3258            HandleRequestFriendshipAsync(userNameOrId, RestartFriendsOperationsCancellationToken()).Forget();
 3259        }
 260
 261        private async UniTaskVoid HandleRequestFriendshipAsync(string userNameOrId, CancellationToken cancellationToken)
 262        {
 3263            if (AreAlreadyFriends(userNameOrId))
 1264                View.ShowRequestSendError(FriendRequestError.AlreadyFriends);
 265            else
 266            {
 2267                if (isNewFriendRequestsEnabled)
 268                {
 269                    FriendRequest request;
 270
 271                    try
 272                    {
 2273                        request = await friendsController.RequestFriendshipAsync(userNameOrId, "", cancellationToken);
 274
 2275                        socialAnalytics.SendFriendRequestSent(request.From, request.To, request.MessageBody?.Length ?? 0
 276                            PlayerActionSource.FriendsHUD);
 2277                    }
 0278                    catch (Exception e) when (e is not OperationCanceledException)
 279                    {
 0280                        e.ReportFriendRequestErrorToAnalyticsAsSender(userNameOrId, PlayerActionSource.FriendsHUD.ToStri
 281                            userProfileBridge, socialAnalytics);
 282
 0283                        throw;
 284                    }
 285
 286                    // we do require the user profile to be valid, otherwise we lack of information to be able to add th
 2287                    if (userProfileBridge.Get(request.To) == null)
 288                    {
 289                        // TODO: make use of a service instead of the bridge itself
 0290                        await userProfileBridge.RequestFullUserProfileAsync(request.To, cancellationToken);
 291
 0292                        await UniTask.SwitchToMainThread(cancellationToken);
 293                    }
 294
 2295                    ShowFriendRequest(request);
 2296                }
 297                else
 298                {
 0299                    friendsController.RequestFriendship(userNameOrId);
 300
 0301                    socialAnalytics.SendFriendRequestSent(ownUserProfile?.userId, userNameOrId, 0,
 302                        PlayerActionSource.FriendsHUD);
 303                }
 304
 2305                View.ShowRequestSendSuccess();
 306            }
 3307        }
 308
 309        private bool AreAlreadyFriends(string userNameOrId)
 310        {
 3311            var userId = userNameOrId;
 3312            var profile = userProfileBridge.GetByName(userNameOrId);
 313
 3314            if (profile != default)
 1315                userId = profile.userId;
 316
 3317            return friendsController != null
 318                   && friendsController.ContainsStatus(userId, FriendshipStatus.FRIEND);
 319        }
 320
 321        private void HandleUserStatusUpdated(string userId, UserStatus status) =>
 2322            UpdateUserStatus(userId, status);
 323
 324        private void UpdateUserStatus(string userId, UserStatus status)
 325        {
 3326            switch (status.friendshipStatus)
 327            {
 328                case FriendshipStatus.FRIEND:
 3329                    var friend = friends.ContainsKey(userId)
 330                        ? new FriendEntryModel(friends[userId])
 331                        : new FriendEntryModel();
 332
 3333                    friend.CopyFrom(status);
 3334                    friend.blocked = IsUserBlocked(userId);
 3335                    friends[userId] = friend;
 3336                    View.Set(userId, friend);
 337
 3338                    if (status.presence == PresenceStatus.ONLINE)
 2339                        onlineFriends[userId] = friend;
 340                    else
 1341                        onlineFriends.Remove(userId);
 342
 1343                    break;
 344                case FriendshipStatus.NOT_FRIEND:
 0345                    View.Remove(userId);
 0346                    friends.Remove(userId);
 0347                    onlineFriends.Remove(userId);
 0348                    break;
 349                case FriendshipStatus.REQUESTED_TO: // TODO (NEW FRIEND REQUESTS): remove when we don't need to keep the
 0350                    if (isNewFriendRequestsEnabled)
 0351                        return;
 352
 0353                    var sentRequest = friends.ContainsKey(userId)
 354                        ? new FriendRequestEntryModel(friends[userId], string.Empty, false, 0, isQuickActionsForFriendRe
 355                        : new FriendRequestEntryModel { bodyMessage = string.Empty, isReceived = false, timestamp = 0, i
 356
 0357                    sentRequest.CopyFrom(status);
 0358                    sentRequest.blocked = IsUserBlocked(userId);
 0359                    friends[userId] = sentRequest;
 0360                    onlineFriends.Remove(userId);
 0361                    View.Set(userId, sentRequest);
 0362                    break;
 363                case FriendshipStatus.REQUESTED_FROM: // TODO (NEW FRIEND REQUESTS): remove when we don't need to keep t
 0364                    if (isNewFriendRequestsEnabled)
 0365                        return;
 366
 0367                    var receivedRequest = friends.ContainsKey(userId)
 368                        ? new FriendRequestEntryModel(friends[userId], string.Empty, true, 0, isQuickActionsForFriendReq
 369                        : new FriendRequestEntryModel { bodyMessage = string.Empty, isReceived = true, timestamp = 0, is
 370
 0371                    receivedRequest.CopyFrom(status);
 0372                    receivedRequest.blocked = IsUserBlocked(userId);
 0373                    friends[userId] = receivedRequest;
 0374                    onlineFriends.Remove(userId);
 0375                    View.Set(userId, receivedRequest);
 376                    break;
 377            }
 378
 3379            UpdateNotificationsCounter();
 3380            ShowOrHideMoreFriendsToLoadHint();
 3381            ShowOrHideMoreFriendRequestsToLoadHint();
 3382        }
 383
 384        private void HandleFriendshipUpdated(string userId, FriendshipAction friendshipAction)
 385        {
 10386            var userProfile = userProfileBridge.Get(userId);
 387
 388            switch (friendshipAction)
 389            {
 390                case FriendshipAction.NONE:
 391                case FriendshipAction.REJECTED:
 392                case FriendshipAction.CANCELLED:
 393                case FriendshipAction.DELETED:
 3394                    RemoveFriendship(userId);
 3395                    break;
 396                case FriendshipAction.APPROVED:
 7397                    if (userProfile == null)
 398                    {
 0399                        Debug.LogError($"UserProfile is null for {userId}! ... friendshipAction {friendshipAction}");
 0400                        return;
 401                    }
 402
 7403                    var approved = friends.ContainsKey(userId)
 404                        ? new FriendEntryModel(friends[userId])
 405                        : new FriendEntryModel();
 406
 7407                    approved.CopyFrom(userProfile);
 7408                    approved.blocked = IsUserBlocked(userId);
 7409                    friends[userId] = approved;
 7410                    View.Set(userId, approved);
 7411                    userProfile.OnUpdate -= HandleFriendProfileUpdated;
 7412                    userProfile.OnUpdate += HandleFriendProfileUpdated;
 7413                    break;
 414                case FriendshipAction.REQUESTED_FROM: // TODO (NEW FRIEND REQUESTS): remove when we don't need to keep t
 0415                    if (isNewFriendRequestsEnabled)
 0416                        return;
 417
 0418                    if (userProfile == null)
 419                    {
 0420                        Debug.LogError($"UserProfile is null for {userId}! ... friendshipAction {friendshipAction}");
 0421                        return;
 422                    }
 423
 0424                    var requestReceived = friends.ContainsKey(userId)
 425                        ? new FriendRequestEntryModel(friends[userId], string.Empty, true, 0, isQuickActionsForFriendReq
 426                        : new FriendRequestEntryModel { bodyMessage = string.Empty, isReceived = true, timestamp = 0, is
 427
 0428                    requestReceived.CopyFrom(userProfile);
 0429                    requestReceived.blocked = IsUserBlocked(userId);
 0430                    friends[userId] = requestReceived;
 0431                    View.Set(userId, requestReceived);
 0432                    userProfile.OnUpdate -= HandleFriendProfileUpdated;
 0433                    userProfile.OnUpdate += HandleFriendProfileUpdated;
 0434                    break;
 435                case FriendshipAction.REQUESTED_TO: // TODO (NEW FRIEND REQUESTS): remove when we don't need to keep the
 0436                    if (isNewFriendRequestsEnabled)
 0437                        return;
 438
 0439                    if (userProfile == null)
 440                    {
 0441                        Debug.LogError($"UserProfile is null for {userId}! ... friendshipAction {friendshipAction}");
 0442                        return;
 443                    }
 444
 0445                    var requestSent = friends.ContainsKey(userId)
 446                        ? new FriendRequestEntryModel(friends[userId], string.Empty, false, 0, isQuickActionsForFriendRe
 447                        : new FriendRequestEntryModel { bodyMessage = string.Empty, isReceived = false, timestamp = 0, i
 448
 0449                    requestSent.CopyFrom(userProfile);
 0450                    requestSent.blocked = IsUserBlocked(userId);
 0451                    friends[userId] = requestSent;
 0452                    View.Set(userId, requestSent);
 0453                    userProfile.OnUpdate -= HandleFriendProfileUpdated;
 0454                    userProfile.OnUpdate += HandleFriendProfileUpdated;
 455                    break;
 456            }
 457
 10458            UpdateNotificationsCounter();
 10459            ShowOrHideMoreFriendsToLoadHint();
 10460            ShowOrHideMoreFriendRequestsToLoadHint();
 10461        }
 462
 463        private void RemoveFriendship(string userId)
 464        {
 3465            friends.Remove(userId);
 3466            View.Remove(userId);
 3467            onlineFriends.Remove(userId);
 3468        }
 469
 470        private void HandleFriendProfileUpdated(UserProfile profile)
 471        {
 1472            var userId = profile.userId;
 1473            if (!friends.ContainsKey(userId)) return;
 1474            friends[userId].CopyFrom(profile);
 475
 1476            var status = friendsController.GetUserStatus(profile.userId);
 1477            if (status == null) return;
 478
 1479            UpdateUserStatus(userId, status);
 1480        }
 481
 482        private bool IsUserBlocked(string userId)
 483        {
 17484            if (ownUserProfile != null && ownUserProfile.blocked != null)
 17485                return ownUserProfile.blocked.Contains(userId);
 486
 0487            return false;
 488        }
 489
 490        private void OnFriendNotFound(string name)
 491        {
 1492            View.DisplayFriendUserNotFound();
 1493        }
 494
 495        private void UpdateNotificationsCounter()
 496        {
 30497            if (View.IsActive())
 10498                dataStore.friendNotifications.seenFriends.Set(View.FriendCount);
 499
 30500            dataStore.friendNotifications.pendingFriendRequestCount.Set(friendsController.ReceivedRequestCount);
 30501        }
 502
 503        private void HandleOpenWhisperChat(FriendEntryModel entry) =>
 1504            OnPressWhisper?.Invoke(entry.userId);
 505
 506        private void HandleUnfriend(string userId)
 507        {
 0508            dataStore.notifications.GenericConfirmation.Set(GenericConfirmationNotificationData.CreateUnFriendData(
 509                UserProfileController.userProfilesCatalog.Get(userId)?.userName,
 0510                () => friendsController.RemoveFriend(userId)), true);
 0511        }
 512
 513        private void HandleRequestRejected(FriendRequestEntryModel entry)
 514        {
 0515            HandleRequestRejectedAsync(entry.userId, RestartFriendsOperationsCancellationToken()).Forget();
 0516        }
 517
 518        private async UniTaskVoid HandleRequestRejectedAsync(string userId, CancellationToken cancellationToken)
 519        {
 0520            if (isNewFriendRequestsEnabled)
 521            {
 522                try
 523                {
 0524                    FriendRequest request = await friendsController.RejectFriendshipAsync(userId, cancellationToken);
 525
 0526                    socialAnalytics.SendFriendRequestRejected(request.From, request.To,
 527                        PlayerActionSource.FriendsHUD.ToString(), request.HasBodyMessage);
 528
 0529                    RemoveFriendship(userId);
 0530                }
 0531                catch (Exception e) when (e is not OperationCanceledException)
 532                {
 0533                    e.ReportFriendRequestErrorToAnalyticsByUserId(userId, PlayerActionSource.FriendsHUD.ToString(),
 534                        friendsController, socialAnalytics);
 535
 0536                    throw;
 537                }
 538            }
 539            else
 540            {
 0541                friendsController.RejectFriendship(userId);
 542
 0543                socialAnalytics.SendFriendRequestRejected(ownUserProfile?.userId, userId,
 544                    PlayerActionSource.FriendsHUD.ToString(), false);
 545            }
 546
 0547            UpdateNotificationsCounter();
 0548        }
 549
 550        private async UniTaskVoid HandleRequestCancelledAsync(string userId, CancellationToken cancellationToken)
 551        {
 0552            if (isNewFriendRequestsEnabled)
 553            {
 554                try
 555                {
 0556                    FriendRequest request = await friendsController.CancelRequestByUserIdAsync(userId, cancellationToken
 557
 0558                    socialAnalytics.SendFriendRequestCancelled(request.From, request.To,
 559                        PlayerActionSource.FriendsHUD.ToString());
 560
 0561                    RemoveFriendship(userId);
 0562                }
 0563                catch (Exception e) when (e is not OperationCanceledException)
 564                {
 0565                    e.ReportFriendRequestErrorToAnalyticsByUserId(userId, PlayerActionSource.FriendsHUD.ToString(),
 566                        friendsController, socialAnalytics);
 567
 0568                    throw;
 569                }
 570            }
 571            else
 572            {
 0573                friendsController.CancelRequestByUserId(userId);
 574
 0575                socialAnalytics.SendFriendRequestCancelled(ownUserProfile?.userId, userId,
 576                    PlayerActionSource.FriendsHUD.ToString());
 577            }
 0578        }
 579
 580        private void HandleRequestCancelled(FriendRequestEntryModel entry)
 581        {
 0582            HandleRequestCancelledAsync(entry.userId, RestartFriendsOperationsCancellationToken()).Forget();
 0583        }
 584
 585        private void HandleRequestAccepted(FriendRequestEntryModel entry)
 586        {
 0587            HandleRequestAcceptedAsync(entry.userId, RestartFriendsOperationsCancellationToken()).Forget();
 0588        }
 589
 590        private async UniTaskVoid HandleRequestAcceptedAsync(string userId, CancellationToken cancellationToken)
 591        {
 0592            if (isNewFriendRequestsEnabled)
 593            {
 594                try
 595                {
 0596                    FriendRequest request = friendsController.GetAllocatedFriendRequestByUser(userId);
 0597                    request = await friendsController.AcceptFriendshipAsync(request.FriendRequestId, cancellationToken);
 598
 0599                    socialAnalytics.SendFriendRequestApproved(request.From, request.To,
 600                        PlayerActionSource.FriendsHUD.ToString(),
 601                        request.HasBodyMessage);
 0602                }
 0603                catch (Exception e) when (e is not OperationCanceledException)
 604                {
 0605                    e.ReportFriendRequestErrorToAnalyticsByUserId(userId, PlayerActionSource.FriendsHUD.ToString(),
 606                        friendsController, socialAnalytics);
 607
 0608                    throw;
 609                }
 610            }
 611            else
 612            {
 0613                friendsController.AcceptFriendship(userId);
 614
 0615                socialAnalytics.SendFriendRequestApproved(ownUserProfile?.userId, userId,
 616                    PlayerActionSource.FriendsHUD.ToString(), false);
 617            }
 0618        }
 619
 620        private void DisplayFriendsIfAnyIsLoaded()
 621        {
 1622            if (lastSkipForFriends > 0) return;
 1623            if (!friendsController.IsInitialized) return;
 1624            DisplayMoreFriendsAsync(RestartFriendsOperationsCancellationToken()).Forget();
 1625        }
 626
 627        private void DisplayMoreFriends()
 628        {
 10629            if (!friendsController.IsInitialized) return;
 8630            DisplayMoreFriendsAsync(RestartFriendsOperationsCancellationToken()).Forget();
 8631        }
 632
 633        private async UniTask DisplayMoreFriendsAsync(CancellationToken cancellationToken)
 634        {
 9635            string[] friendsToAdd = await friendsController
 636                                         .GetFriendsAsync(LOAD_FRIENDS_ON_DEMAND_COUNT, lastSkipForFriends, cancellation
 637                                         .Timeout(TimeSpan.FromSeconds(GET_FRIENDS_TIMEOUT));
 638
 18639            for (var i = 0; i < friendsToAdd.Length; i++)
 0640                HandleFriendshipUpdated(friendsToAdd[i], FriendshipAction.APPROVED);
 641
 642            // We are not handling properly the case when the friends are not fetched correctly from server.
 643            // 'lastSkipForFriends' will have an invalid value.
 644            // this may happen only on the old flow.. the task operation should throw an exception if anything goes wron
 9645            lastSkipForFriends += LOAD_FRIENDS_ON_DEMAND_COUNT;
 646
 9647            ShowOrHideMoreFriendsToLoadHint();
 9648        }
 649
 650        private void DisplayMoreFriendRequests()
 651        {
 9652            if (!friendsController.IsInitialized) return;
 9653            if (searchingFriends) return;
 9654            DisplayMoreFriendRequestsAsync(RestartFriendsOperationsCancellationToken()).Forget();
 9655        }
 656
 657        private async UniTask DisplayMoreFriendRequestsAsync(CancellationToken cancellationToken)
 658        {
 10659            if (isNewFriendRequestsEnabled)
 660            {
 10661                var allFriendRequests = await friendsController.GetFriendRequestsAsync(
 662                                                                    LOAD_FRIENDS_ON_DEMAND_COUNT, lastSkipForFriendReque
 663                                                                    LOAD_FRIENDS_ON_DEMAND_COUNT, lastSkipForFriendReque
 664                                                                    cancellationToken);
 665
 10666                AddFriendRequests(allFriendRequests);
 667            }
 668            else
 669            {
 670                // TODO (NEW FRIEND REQUESTS): remove when we don't need to keep the retro-compatibility with the old ve
 0671                friendsController.GetFriendRequests(
 672                    LOAD_FRIENDS_ON_DEMAND_COUNT, lastSkipForFriendRequests,
 673                    LOAD_FRIENDS_ON_DEMAND_COUNT, lastSkipForFriendRequests);
 674            }
 675
 676            // We are not handling properly the case when the friend requests are not fetched correctly from server.
 677            // 'lastSkipForFriendRequests' will have an invalid value.
 678            // this may happen only on the old flow.. the task operation should throw an exception if anything goes wron
 10679            lastSkipForFriendRequests += LOAD_FRIENDS_ON_DEMAND_COUNT;
 680
 10681            ShowOrHideMoreFriendRequestsToLoadHint();
 10682        }
 683
 684        private void AddFriendRequests(List<FriendRequest> friendRequests)
 685        {
 10686            if (friendRequests == null)
 7687                return;
 688
 12689            foreach (var friendRequest in friendRequests)
 3690                ShowFriendRequest(friendRequest);
 3691        }
 692
 693        private void ShowFriendRequest(FriendRequest friendRequest)
 694        {
 7695            bool isReceivedRequest = friendRequest.IsSentTo(ownUserProfile.userId);
 7696            string userId = isReceivedRequest ? friendRequest.From : friendRequest.To;
 7697            var userProfile = userProfileBridge.Get(userId);
 698
 7699            if (userProfile == null)
 700            {
 0701                Debug.LogError($"UserProfile is null for {userId}! ... friendshipAction {(isReceivedRequest ? Friendship
 0702                return;
 703            }
 704
 7705            var request = friends.ContainsKey(userId)
 706                ? new FriendRequestEntryModel(friends[userId], friendRequest.MessageBody, isReceivedRequest, friendReque
 707                : new FriendRequestEntryModel
 708                {
 709                    bodyMessage = friendRequest.MessageBody,
 710                    isReceived = isReceivedRequest,
 711                    timestamp = friendRequest.Timestamp,
 712                    isShortcutButtonsActive = isQuickActionsForFriendRequestsEnabled
 713                };
 714
 7715            request.CopyFrom(userProfile);
 7716            request.blocked = IsUserBlocked(userId);
 7717            friends[userId] = request;
 7718            onlineFriends.Remove(userId);
 7719            View.Set(userId, request);
 7720            userProfile.OnUpdate -= HandleFriendProfileUpdated;
 7721            userProfile.OnUpdate += HandleFriendProfileUpdated;
 7722        }
 723
 724        private void DisplayFriendRequestsIfAnyIsLoaded()
 725        {
 1726            if (lastSkipForFriendRequests > 0) return;
 1727            if (!friendsController.IsInitialized) return;
 1728            if (searchingFriends) return;
 1729            DisplayMoreFriendRequestsAsync(RestartFriendsOperationsCancellationToken()).Forget();
 1730        }
 731
 732        private void ShowOrHideMoreFriendRequestsToLoadHint()
 733        {
 65734            if (lastSkipForFriendRequests >= friendsController.TotalFriendRequestCount)
 64735                View.HideMoreRequestsToLoadHint();
 736            else
 1737                View.ShowMoreRequestsToLoadHint(Mathf.Clamp(friendsController.TotalFriendRequestCount - lastSkipForFrien
 738                    0,
 739                    friendsController.TotalFriendRequestCount));
 1740        }
 741
 742        private void ShowOrHideMoreFriendsToLoadHint()
 743        {
 65744            if (lastSkipForFriends >= friendsController.TotalFriendCount || searchingFriends)
 64745                View.HideMoreFriendsToLoadHint();
 746            else
 1747                View.ShowMoreFriendsToLoadHint(Mathf.Clamp(friendsController.TotalFriendCount - lastSkipForFriends,
 748                    0,
 749                    friendsController.TotalFriendCount));
 1750        }
 751
 752        private void SearchFriends(string search)
 753        {
 3754            SearchFriendsAsync(search, RestartFriendsOperationsCancellationToken()).Forget();
 3755        }
 756
 757        private async UniTask SearchFriendsAsync(string search, CancellationToken cancellationToken)
 758        {
 3759            if (string.IsNullOrEmpty(search))
 760            {
 1761                View.DisableSearchMode();
 1762                searchingFriends = false;
 1763                ShowOrHideMoreFriendsToLoadHint();
 1764                return;
 765            }
 766
 2767            string[] friendsToAdd = await friendsController
 768                                         .GetFriendsAsync(search, MAX_SEARCHED_FRIENDS, cancellationToken)
 769                                         .Timeout(TimeSpan.FromSeconds(GET_FRIENDS_TIMEOUT));
 770
 4771            for (int i = 0; i < friendsToAdd.Length; i++)
 0772                HandleFriendshipUpdated(friendsToAdd[i], FriendshipAction.APPROVED);
 773
 2774            View.EnableSearchMode();
 2775            View.HideMoreFriendsToLoadHint();
 2776            searchingFriends = true;
 3777        }
 778
 779        private void OpenFriendRequestDetails(string userId)
 780        {
 1781            if (!isNewFriendRequestsEnabled) return;
 782
 1783            FriendRequest friendRequest = friendsController.GetAllocatedFriendRequestByUser(userId);
 784
 1785            if (friendRequest == null)
 786            {
 0787                Debug.LogError($"Could not find an allocated friend request for user: {userId}");
 0788                return;
 789            }
 790
 1791            if (friendRequest.IsSentTo(userId))
 1792                dataStore.HUDs.openSentFriendRequestDetail.Set(friendRequest.FriendRequestId, true);
 793            else
 0794                dataStore.HUDs.openReceivedFriendRequestDetail.Set(friendRequest.FriendRequestId, true);
 0795        }
 796
 797        private CancellationToken RestartFriendsOperationsCancellationToken()
 798        {
 25799            friendOperationsCancellationToken = friendOperationsCancellationToken.SafeRestart();
 25800            return friendOperationsCancellationToken.Token;
 801        }
 802    }
 803}

Methods/Properties

FriendsHUDController(DCL.DataStore, DCL.Social.Friends.IFriendsController, IUserProfileBridge, SocialFeaturesAnalytics.ISocialAnalytics, IChatController, DCL.IMouseCatcher)
visibleTaskbarPanels()
isNewFriendRequestsEnabled()
isQuickActionsForFriendRequestsEnabled()
IsVisible()
IsVisible(System.Boolean)
View()
View(IFriendsHUDComponentView)
Initialize(IFriendsHUDComponentView, System.Boolean)
SetVisiblePanelList(System.Boolean)
Dispose()
SetVisibility(System.Boolean)
HandleViewClosed()
HandleFriendsInitialized()
HandleProfileUpdated(UserProfile)
UpdateBlockStatus()
HandleRequestFriendship(System.String)
HandleRequestFriendshipAsync()
AreAlreadyFriends(System.String)
HandleUserStatusUpdated(System.String, UserStatus)
UpdateUserStatus(System.String, UserStatus)
HandleFriendshipUpdated(System.String, DCL.Social.Friends.FriendshipAction)
RemoveFriendship(System.String)
HandleFriendProfileUpdated(UserProfile)
IsUserBlocked(System.String)
OnFriendNotFound(System.String)
UpdateNotificationsCounter()
HandleOpenWhisperChat(FriendEntryModel)
HandleUnfriend(System.String)
HandleRequestRejected(FriendRequestEntryModel)
HandleRequestRejectedAsync()
HandleRequestCancelledAsync()
HandleRequestCancelled(FriendRequestEntryModel)
HandleRequestAccepted(FriendRequestEntryModel)
HandleRequestAcceptedAsync()
DisplayFriendsIfAnyIsLoaded()
DisplayMoreFriends()
DisplayMoreFriendsAsync()
DisplayMoreFriendRequests()
DisplayMoreFriendRequestsAsync()
AddFriendRequests(System.Collections.Generic.List[FriendRequest])
ShowFriendRequest(DCL.Social.Friends.FriendRequest)
DisplayFriendRequestsIfAnyIsLoaded()
ShowOrHideMoreFriendRequestsToLoadHint()
ShowOrHideMoreFriendsToLoadHint()
SearchFriends(System.String)
SearchFriendsAsync()
OpenFriendRequestDetails(System.String)
RestartFriendsOperationsCancellationToken()