-
-
Notifications
You must be signed in to change notification settings - Fork 492
/
Copy pathChatListViewModel.cs
1055 lines (859 loc) · 32.8 KB
/
ChatListViewModel.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright Fela Ameghino 2015-2025
//
// Distributed under the GNU General Public License v3.0. (See accompanying
// file LICENSE or copy at https://www.gnu.org/licenses/gpl-3.0.txt)
//
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading;
using System.Threading.Tasks;
using Telegram.Collections;
using Telegram.Common;
using Telegram.Controls;
using Telegram.Navigation;
using Telegram.Services;
using Telegram.Td.Api;
using Telegram.ViewModels.Delegates;
using Telegram.Views.Folders;
using Telegram.Views.Popups;
using Windows.Foundation;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
namespace Telegram.ViewModels
{
public partial class ChatListViewModel : ViewModelBase, IDelegable<IChatListDelegate>
{
private readonly INotificationsService _notificationsService;
private readonly Dictionary<long, bool> _deletedChats = new Dictionary<long, bool>();
public IChatListDelegate Delegate { get; set; }
public ChatListViewModel(IClientService clientService, ISettingsService settingsService, IEventAggregator aggregator, INotificationsService notificationsService, ChatList chatList)
: base(clientService, settingsService, aggregator)
{
_notificationsService = notificationsService;
Items = new ItemsCollection(clientService, aggregator, this, chatList);
#if MOCKUP
Items.AddRange(clientService.GetChats(null));
#endif
SelectedItems = new MvxObservableCollection<Chat>();
}
#region Selection
public long LastSelectedItem { get; private set; }
private long? _selectedItem;
public long? SelectedItem
{
get => _selectedItem;
set
{
Set(ref _selectedItem, value);
if (value.HasValue)
{
LastSelectedItem = value.Value;
}
}
}
public MvxObservableCollection<Chat> SelectedItems { get; }
private ListViewSelectionMode _selectionMode = ListViewSelectionMode.None;
public ListViewSelectionMode SelectionMode
{
get => _selectionMode;
set => Set(ref _selectionMode, value);
}
#endregion
public ItemsCollection Items { get; private set; }
public bool IsLastSliceLoaded { get; set; }
#region Open
public void OpenChat(Chat chat)
{
NavigationService.NavigateToChat(chat, createNewWindow: true);
}
#endregion
#region Pin
public async void PinChat(Chat chat)
{
var position = chat.GetPosition(Items.ChatList);
if (position == null)
{
return;
}
var response = await ClientService.SendAsync(new ToggleChatIsPinned(Items.ChatList, chat.Id, !position.IsPinned));
if (response is Error error && error.Code == 400)
{
// This is not the right way
NavigationService.ShowLimitReached(new PremiumLimitTypePinnedChatCount());
}
}
#endregion
#region Archive
public async void ArchiveChat(Chat chat)
{
var archived = chat.Positions.Any(x => x.List is ChatListArchive);
if (archived)
{
ClientService.Send(new AddChatToList(chat.Id, new ChatListMain()));
return;
}
else
{
ClientService.Send(new AddChatToList(chat.Id, new ChatListArchive()));
}
var confirm = await ToastPopup.ShowActionAsync(XamlRoot, Strings.ChatArchived, Strings.Undo, ToastPopupIcon.Archived);
if (confirm == ContentDialogResult.Primary)
{
ClientService.Send(new AddChatToList(chat.Id, new ChatListMain()));
}
}
#endregion
#region Multiple Archive
public async void ArchiveSelectedChats()
{
var chats = SelectedItems.ToList();
foreach (var chat in chats)
{
ClientService.Send(new AddChatToList(chat.Id, new ChatListArchive()));
}
Delegate?.SetSelectionMode(false);
SelectedItems.Clear();
var confirm = await ToastPopup.ShowActionAsync(XamlRoot, Strings.ChatsArchived, Strings.Undo, ToastPopupIcon.Archived);
if (confirm == ContentDialogResult.Primary)
{
foreach (var undo in chats)
{
ClientService.Send(new AddChatToList(undo.Id, new ChatListMain()));
}
}
}
#endregion
#region Mark
public void MarkChatAsRead(Chat chat)
{
if (chat.UnreadCount > 0 || chat.UnreadMentionCount > 0 || chat.UnreadReactionCount > 0)
{
if (chat.UnreadCount > 0 && chat.LastMessage != null)
{
ClientService.Send(new ViewMessages(chat.Id, new[] { chat.LastMessage.Id }, new MessageSourceChatList(), true));
}
if (chat.UnreadMentionCount > 0)
{
ClientService.Send(new ReadAllChatMentions(chat.Id));
}
if (chat.UnreadReactionCount > 0)
{
ClientService.Send(new ReadAllChatReactions(chat.Id));
}
}
else
{
ClientService.Send(new ToggleChatIsMarkedAsUnread(chat.Id, !chat.IsMarkedAsUnread));
}
}
#endregion
#region Multiple Mark
public void MarkSelectedChatsAsRead()
{
var chats = SelectedItems.ToList();
var unread = chats.Any(x => x.IsUnread());
foreach (var chat in chats)
{
if (unread)
{
if (chat.UnreadCount > 0 && chat.LastMessage != null)
{
ClientService.Send(new ViewMessages(chat.Id, new[] { chat.LastMessage.Id }, new MessageSourceChatList(), true));
}
else if (chat.IsMarkedAsUnread)
{
ClientService.Send(new ToggleChatIsMarkedAsUnread(chat.Id, false));
}
if (chat.UnreadMentionCount > 0)
{
ClientService.Send(new ReadAllChatMentions(chat.Id));
}
if (chat.UnreadReactionCount > 0)
{
ClientService.Send(new ReadAllChatReactions(chat.Id));
}
}
else if (chat.UnreadCount == 0 && !chat.IsMarkedAsUnread)
{
ClientService.Send(new ToggleChatIsMarkedAsUnread(chat.Id, true));
}
}
Delegate?.SetSelectionMode(false);
SelectedItems.Clear();
}
#endregion
#region Notify
public void NotifyChat(Chat chat)
{
_notificationsService.SetMuteFor(chat, ClientService.Notifications.IsMuted(chat) ? 0 : 632053052, XamlRoot);
}
#endregion
#region Mute for
public async void MuteChatFor(Tuple<Chat, int?> value)
{
var chat = value.Item1;
if (chat == null)
{
return;
}
if (value.Item2 is int update)
{
_notificationsService.SetMuteFor(chat, update, XamlRoot);
}
else
{
var muteFor = Settings.Notifications.GetMuteFor(chat);
var popup = new ChatMutePopup(muteFor);
var confirm = await ShowPopupAsync(popup);
if (confirm != ContentDialogResult.Primary)
{
return;
}
if (muteFor != popup.Value)
{
_notificationsService.SetMuteFor(chat, popup.Value, XamlRoot);
}
}
}
#endregion
#region Multiple Notify
public void NotifySelectedChats()
{
var chats = SelectedItems.ToList();
var muted = chats.Any(x => ClientService.Notifications.IsMuted(x));
foreach (var chat in chats)
{
if (chat.Type is ChatTypePrivate privata && privata.UserId == ClientService.Options.MyId)
{
continue;
}
_notificationsService.SetMuteFor(chat, muted ? 0 : 632053052, XamlRoot);
}
Delegate?.SetSelectionMode(false);
SelectedItems.Clear();
}
#endregion
#region Delete
public async void DeleteChat(Chat chat)
{
Logger.Info(chat.Type);
var updated = await ClientService.SendAsync(new GetChat(chat.Id)) as Chat ?? chat;
var popup = new DeleteChatPopup(ClientService, updated, Items.ChatList, false);
var confirm = await ShowPopupAsync(popup);
if (confirm == ContentDialogResult.Primary)
{
var check = popup.IsChecked == true;
_deletedChats[chat.Id] = true;
Items.Handle(chat.Id, 0);
string title;
if (chat.Type is ChatTypeSupergroup super)
{
title = super.IsChannel ? Strings.ChannelDeletedUndo : Strings.GroupDeletedUndo;
}
else
{
title = chat.Type is ChatTypeBasicGroup ? Strings.GroupDeletedUndo : Strings.ChatDeletedUndo;
}
var undo = await ToastPopup.ShowCountdownAsync(XamlRoot, title, Strings.Undo, TimeSpan.FromSeconds(5));
if (undo == ContentDialogResult.Primary)
{
_deletedChats.Remove(chat.Id);
Items.Handle(chat.Id, chat.Positions);
}
else
{
if (chat.Type is ChatTypeBasicGroup or ChatTypeSupergroup)
{
await ClientService.SendAsync(new LeaveChat(chat.Id));
await ClientService.SendAsync(new DeleteChatHistory(chat.Id, true, false));
}
else if (chat.Type is ChatTypeSecret)
{
await ClientService.SendAsync(new DeleteChat(chat.Id));
}
else
{
var user = ClientService.GetUser(chat);
if (user?.Type is UserTypeRegular)
{
await ClientService.SendAsync(new DeleteChatHistory(chat.Id, true, check));
}
else
{
if (user?.Type is UserTypeBot && check)
{
await ClientService.SendAsync(new SetMessageSenderBlockList(new MessageSenderUser(user.Id), new BlockListMain()));
}
await ClientService.SendAsync(new DeleteChatHistory(chat.Id, true, false));
}
}
}
}
}
#endregion
#region Multiple Delete
public async void DeleteSelectedChats()
{
var chats = SelectedItems.ToList();
var confirm = await ShowPopupAsync(Strings.AreYouSureDeleteFewChats, Locale.Declension(Strings.R.ChatsSelected, chats.Count), Strings.Delete, Strings.Cancel, destructive: true);
if (confirm == ContentDialogResult.Primary)
{
foreach (var chat in chats)
{
_deletedChats[chat.Id] = true;
Items.Handle(chat.Id, 0);
}
var undo = await ToastPopup.ShowCountdownAsync(XamlRoot, Strings.ChatDeletedUndo, Strings.Undo, TimeSpan.FromSeconds(5));
if (undo == ContentDialogResult.Primary)
{
foreach (var chat in chats)
{
_deletedChats.Remove(chat.Id);
Items.Handle(chat.Id, chat.Positions);
}
}
else
{
foreach (var chat in chats)
{
if (chat.Type is ChatTypeBasicGroup or ChatTypeSupergroup)
{
await ClientService.SendAsync(new LeaveChat(chat.Id));
await ClientService.SendAsync(new DeleteChatHistory(chat.Id, true, false));
}
else if (chat.Type is ChatTypeSecret secret)
{
await ClientService.SendAsync(new DeleteChat(chat.Id));
await ClientService.SendAsync(new CloseSecretChat(secret.SecretChatId));
}
else
{
await ClientService.SendAsync(new DeleteChatHistory(chat.Id, true, false));
}
}
}
}
Delegate?.SetSelectionMode(false);
SelectedItems.Clear();
}
#endregion
#region Clear
public async void ClearChat(Chat chat)
{
Logger.Info(chat.Type);
var updated = await ClientService.SendAsync(new GetChat(chat.Id)) as Chat ?? chat;
var dialog = new DeleteChatPopup(ClientService, updated, Items.ChatList, true);
var confirm = await ShowPopupAsync(dialog);
if (confirm == ContentDialogResult.Primary)
{
var undo = await ToastPopup.ShowCountdownAsync(XamlRoot, Strings.HistoryClearedUndo, Strings.Undo, TimeSpan.FromSeconds(5));
if (undo == ContentDialogResult.Primary)
{
_deletedChats.Remove(chat.Id);
Items.Handle(chat.Id, chat.Positions);
}
else
{
ClientService.Send(new DeleteChatHistory(chat.Id, false, dialog.IsChecked));
}
}
}
#endregion
#region Multiple Clear
public async void ClearSelectedChats()
{
var chats = SelectedItems.ToList();
var confirm = await ShowPopupAsync(Strings.AreYouSureClearHistoryFewChats, Locale.Declension(Strings.R.ChatsSelected, chats.Count), Strings.ClearHistory, Strings.Cancel);
if (confirm == ContentDialogResult.Primary)
{
var undo = await ToastPopup.ShowCountdownAsync(XamlRoot, Strings.HistoryClearedUndo, Strings.Undo, TimeSpan.FromSeconds(5));
if (undo == ContentDialogResult.Primary)
{
foreach (var chat in chats)
{
_deletedChats.Remove(chat.Id);
Items.Handle(chat.Id, chat.Positions);
}
}
else
{
foreach (var chat in chats)
{
ClientService.Send(new DeleteChatHistory(chat.Id, false, false));
}
}
}
Delegate?.SetSelectionMode(false);
SelectedItems.Clear();
}
#endregion
#region Select
public void SelectChat(Chat chat)
{
SelectedItems.ReplaceWith(new[] { chat });
SelectionMode = ListViewSelectionMode.Multiple;
Delegate?.SetSelectedItems(SelectedItems);
}
#endregion
#region Folder add
public async void AddToFolder((int ChatFolderId, Chat Chat) data)
{
var folder = await ClientService.SendAsync(new GetChatFolder(data.ChatFolderId)) as ChatFolder;
if (folder == null)
{
return;
}
var total = folder.IncludedChatIds.Count + folder.PinnedChatIds.Count + 1;
if (total > 99)
{
await ShowPopupAsync(Strings.FilterAddToAlertFullText, Strings.FilterAddToAlertFullTitle, Strings.OK);
return;
}
if (folder.IncludedChatIds.Contains(data.Chat.Id))
{
// Warn user about chat being already in the folder?
return;
}
folder.ExcludedChatIds.Remove(data.Chat.Id);
folder.IncludedChatIds.Add(data.Chat.Id);
ClientService.Send(new EditChatFolder(data.ChatFolderId, folder));
}
#endregion
#region Folder remove
public async void RemoveFromFolder((int ChatFolderId, Chat Chat) data)
{
var folder = await ClientService.SendAsync(new GetChatFolder(data.ChatFolderId)) as ChatFolder;
if (folder == null)
{
return;
}
if (folder.IsShareable)
{
folder.IncludedChatIds.Remove(data.Chat.Id);
}
else
{
var total = folder.ExcludedChatIds.Count + 1;
if (total > 99)
{
await ShowPopupAsync(Strings.FilterRemoveFromAlertFullText, Strings.AppName, Strings.OK);
return;
}
if (folder.ExcludedChatIds.Contains(data.Chat.Id))
{
// TODO: Warn user about chat being already in the folder?
return;
}
folder.IncludedChatIds.Remove(data.Chat.Id);
folder.ExcludedChatIds.Add(data.Chat.Id);
}
if (folder.Empty())
{
// TODO: Warn user about chat being already in the folder?
return;
}
ClientService.Send(new EditChatFolder(data.ChatFolderId, folder));
}
#endregion
#region Folder create
public void CreateFolder(Chat chat)
{
NavigationService.Navigate(typeof(FolderPage), new FolderPageCreateArgs(chat.Id));
}
#endregion
public void SetChatList(ChatList chatList)
{
_ = Items.ReloadAsync(chatList);
}
public partial class ItemsCollection : ObservableCollection<Chat>, ISupportIncrementalLoading
{
private readonly IClientService _clientService;
private readonly IEventAggregator _aggregator;
private CancellationTokenSource _token = new();
private readonly HashSet<long> _chats = new();
private readonly ChatListViewModel _viewModel;
private ChatList _chatList;
private bool _hasMoreItems = true;
private long _lastChatId;
private long _lastOrder;
public ChatList ChatList => _chatList;
public ItemsCollection(IClientService clientService, IEventAggregator aggregator, ChatListViewModel viewModel, ChatList chatList)
{
_clientService = clientService;
_aggregator = aggregator;
_viewModel = viewModel;
_chatList = chatList;
#if MOCKUP
_hasMoreItems = false;
#endif
_ = LoadMoreItemsAsync(0);
}
public Task ReloadAsync(ChatList chatList)
{
_token?.Cancel();
_token = new CancellationTokenSource();
_aggregator.Unsubscribe(this);
_hasMoreItems = false;
_lastChatId = 0;
_lastOrder = 0;
_chatList = chatList;
_chats.Clear();
Clear();
return LoadMoreItemsAsync();
}
public IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
{
return AsyncInfo.Run(token => LoadMoreItemsAsync());
}
private async Task<LoadMoreItemsResult> LoadMoreItemsAsync()
{
Logger.Info(Count);
var token = _token;
var totalCount = 0u;
await Task.Yield();
var response = await _clientService.GetChatListAsync(_chatList, Count, 20);
if (response is Telegram.Td.Api.Chats chats && !token.IsCancellationRequested)
{
foreach (var chat in _clientService.GetChats(chats.ChatIds))
{
var order = chat.GetOrder(_chatList);
if (order != 0)
{
// TODO: is this redundant?
var next = NextIndexOf(chat, order);
if (next >= 0)
{
if (_chats.Contains(chat.Id))
{
Remove(chat);
}
_chats.Add(chat.Id);
Insert(Math.Min(Count, next), chat);
if (chat.Id == _viewModel.SelectedItem)
{
_viewModel.Delegate?.SetSelectedItem(chat);
}
totalCount++;
}
_lastChatId = chat.Id;
_lastOrder = order;
}
}
Logger.Info(string.Format("Received {0} items, added {1}", chats.ChatIds.Count, totalCount));
IsEmpty = Count == 0;
_hasMoreItems = chats.TotalCount >= 0;
Subscribe();
_viewModel.Delegate?.SetSelectedItems(_viewModel.SelectedItems);
}
return new LoadMoreItemsResult
{
Count = totalCount
};
}
private void Subscribe()
{
_aggregator.Subscribe<UpdateAuthorizationState>(this, Handle)
.Subscribe<UpdateChatDraftMessage>(Handle)
.Subscribe<UpdateChatLastMessage>(Handle)
.Subscribe<UpdateChatPosition>(Handle);
}
public bool HasMoreItems => _hasMoreItems;
#region Handle
public void Handle(UpdateAuthorizationState update)
{
if (update.AuthorizationState is AuthorizationStateReady)
{
_viewModel.BeginOnUIThread(() => _ = ReloadAsync(_chatList));
}
}
public void Handle(UpdateChatPosition update)
{
if (update.Position.List.AreTheSame(_chatList))
{
Handle(update.ChatId, update.Position.Order);
}
// Can't be else otherwise cell won't update while archive is open
if (update.Position.List is ChatListArchive)
{
_viewModel.Delegate?.UpdateChatListArchive();
}
}
public void Handle(UpdateChatLastMessage update)
{
Handle(update.ChatId, update.Positions, true);
}
public void Handle(UpdateChatDraftMessage update)
{
Handle(update.ChatId, update.Positions, true);
}
public void Handle(long chatId, IList<ChatPosition> positions, bool lastMessage = false)
{
var chat = GetChat(chatId);
var order = 0L;
for (int i = 0; i < positions.Count; i++)
{
var position = positions[i];
if (position.List.AreTheSame(_chatList))
{
order = position.Order;
}
// Can't be else otherwise cell won't update while archive is open
if (position.List is ChatListArchive)
{
_viewModel.Delegate?.UpdateChatListArchive();
}
}
Handle(chat, order, lastMessage);
}
public void Handle(long chatId, long order)
{
var chat = GetChat(chatId);
if (chat != null)
{
Handle(chat, order, false);
}
}
private void Handle(Chat chat, long order, bool lastMessage)
{
if (_viewModel._deletedChats.ContainsKey(chat.Id))
{
if (order == 0)
{
_viewModel._deletedChats.Remove(chat.Id);
}
else
{
return;
}
}
//var chat = GetChat(chatId);
if (chat != null /*&& _chatList.ListEquals(chat.ChatList)*/)
{
_viewModel.BeginOnUIThread(() => UpdateChatOrder(chat, order, lastMessage));
}
}
private void UpdateChatOrder(Chat chat, long order, bool lastMessage)
{
if (order > 0 && (order > _lastOrder || (order == _lastOrder && chat.Id >= _lastChatId)))
{
var next = NextIndexOf(chat, order);
if (next >= 0)
{
if (_chats.Contains(chat.Id))
{
Remove(chat);
}
else
{
_chats.Add(chat.Id);
}
Insert(Math.Min(Count, next), chat);
if (next == Count - 1)
{
_lastChatId = chat.Id;
_lastOrder = order;
}
if (chat.Id == _viewModel.SelectedItem)
{
_viewModel.Delegate?.SetSelectedItem(chat);
}
if (_viewModel.SelectedItems.Contains(chat))
{
_viewModel.Delegate?.SetSelectedItems(_viewModel.SelectedItems);
}
IsEmpty = Count == 0;
}
else if (lastMessage)
{
_viewModel.Delegate?.UpdateChatLastMessage(chat);
}
}
else if (_chats.Contains(chat.Id))
{
_chats.Remove(chat.Id);
Remove(chat);
if (_viewModel.SelectedItems.Contains(chat))
{
_viewModel.SelectedItems.Remove(chat);
_viewModel.Delegate?.SetSelectedItems(_viewModel.SelectedItems);
}
IsEmpty = Count == 0;
//if (!_hasMoreItems)
//{
// await LoadMoreItemsAsync(0);
//}
}
}
private int NextIndexOf(Chat chat, long order)
{
var prev = -1;
var next = 0;
for (int i = 0; i < Count; i++)
{
var item = this[i];
if (item.Id == chat.Id)
{
prev = i;
continue;
}
var itemOrder = item.GetOrder(_chatList);
if (order > itemOrder || order == itemOrder && chat.Id >= item.Id)
{
return next == prev ? -1 : next;
}
next++;
}
return Count;
}
private Chat GetChat(long chatId)
{
//if (_viewModels.ContainsKey(chatId))
//{
// return _viewModels[chatId];
//}
//else
//{
// var chat = ClientService.GetChat(chatId);
// var item = _viewModels[chatId] = new ChatViewModel(ClientService, chat);
// return item;
//}
return _clientService.GetChat(chatId);
}
#endregion
private bool _isEmpty;
public bool IsEmpty
{
get
{
return _isEmpty;
}
set
{
if (_isEmpty != value)
{
_isEmpty = value;
_viewModel.Dispatcher?.Dispatch(NotifyChanged, Windows.System.DispatcherQueuePriority.Low);
}
}
}
private void NotifyChanged()
{
OnPropertyChanged(new PropertyChangedEventArgs(nameof(IsEmpty)));
}
}
}
public enum SearchResultType
{
Recent,
Chats,
ChatsOnServer,
Contacts,
PublicChats,
Ads,
RecentWebApps,
WebApps,
ChatMembers,
None
}
// TODO: always load User when creating by Chat
public partial class SearchResult : BindableBase
{
private readonly IClientService _clientService;
private readonly bool _canSendMessageToUser;
public Chat Chat { get; set; }
public User User { get; set; }
public ForumTopic Topic { get; set; }
public string Query { get; set; }
public SearchResultType Type { get; }
public bool IsPublic => Type == SearchResultType.PublicChats;
public SearchResult(IClientService clientService, Chat chat, string query, SearchResultType type, bool canSendMessageToUser)
{
_clientService = clientService;
Chat = chat;
Query = query;
Type = type;
}
public SearchResult(IClientService clientService, Chat chat, bool canSendMessageToUser)
{
_clientService = clientService;
Chat = chat;
Query = string.Empty;
Type = SearchResultType.None;
}
public SearchResult(IClientService clientService, User user, string query, SearchResultType type, bool canSendMessageToUser)
{
_clientService = clientService;
User = user;
Query = query;
Type = type;
}
public SearchResult(ForumTopic topic, string query, SearchResultType type)
{
Topic = topic;
Query = query;
Type = type;
}
private bool? _restrictsNewChats;
public bool? RestrictsNewChats
{
get => _restrictsNewChats;
set => Set(ref _restrictsNewChats, value);
}
public void CanSendMessageToUser()
{
long? userId;
if (Chat?.Type is ChatTypePrivate privata)