-
-
Notifications
You must be signed in to change notification settings - Fork 679
Expand file tree
/
Copy pathTopicListViewModel.cs
More file actions
1310 lines (1062 loc) · 43.7 KB
/
Copy pathTopicListViewModel.cs
File metadata and controls
1310 lines (1062 loc) · 43.7 KB
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 (c) Fela Ameghino 2015-2026
//
// 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;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading;
using System.Threading.Tasks;
using Telegram.Collections;
using Telegram.Common;
using Telegram.Navigation;
using Telegram.Services;
using Telegram.Td.Api;
using Telegram.ViewModels.Delegates;
using Telegram.Views.Supergroups.Popups;
using Windows.Foundation;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
namespace Telegram.ViewModels
{
public partial class TopicListViewModel : ViewModelBase, IDelegable<ITopicListDelegate>
{
private readonly INotificationsService _notificationsService;
private readonly bool _chatList;
private readonly bool _forum;
private readonly Dictionary<long, bool> _deletedChats = new();
public ITopicListDelegate Delegate { get; set; }
public bool IsForum => _forum;
public TopicListViewModel(IClientService clientService, ISettingsService settingsService, IEventAggregator aggregator, INotificationsService notificationsService, bool chatList, bool forum)
: base(clientService, settingsService, aggregator)
{
_notificationsService = notificationsService ?? Session.Resolve<INotificationsService>();
_chatList = chatList;
_forum = forum;
if (forum)
{
Items = new ForumTopicsCollection(clientService, aggregator, this, null);
}
else
{
Items = new DirectMessagesChatTopicsCollection(clientService, aggregator, this, null);
}
ChatsMarkCommand = new RelayCommand(ChatsMarkExecute);
ChatsNotifyCommand = new RelayCommand(ChatsNotifyExecute);
ChatsDeleteCommand = new RelayCommand(ChatsDeleteExecute);
ChatsClearCommand = new RelayCommand(ChatsClearExecute);
SelectedItems = new RangeObservableCollection<object>();
}
#region Selection
public MessageTopic LastSelectedItem { get; private set; }
private MessageTopic _selectedItem;
public MessageTopic SelectedItem
{
get => _selectedItem;
set
{
Set(ref _selectedItem, value);
if (value != null)
{
LastSelectedItem = value;
}
}
}
private RangeObservableCollection<object> _selectedItems;
public RangeObservableCollection<object> SelectedItems
{
get => _selectedItems;
set => Set(ref _selectedItems, value);
}
private ListViewSelectionMode _selectionMode = ListViewSelectionMode.None;
public ListViewSelectionMode SelectionMode
{
get => _selectionMode;
set => Set(ref _selectionMode, value);
}
#endregion
public ITopicListCollection Items { get; private set; }
public bool IsLastSliceLoaded { get; set; }
#region Open
public void OpenTopic(ForumTopic topic)
{
NavigationService.NavigateToChat(topic.Info.ChatId, topic: topic.ToId(), createNewWindow: true);
}
#endregion
#region Pin
public void HideTopic(ForumTopic topic)
{
if (Chat is Chat chat)
{
ClientService.Send(new ToggleGeneralForumTopicIsHidden(chat.Id, !topic.Info.IsHidden));
}
}
#endregion
#region Pin
public async void PinTopic(ForumTopic topic)
{
//var position = chat.GetPosition(Items.ChatList);
//if (position == null)
//{
// return;
//}
var response = await ClientService.SendAsync(new ToggleForumTopicIsPinned(topic.Info.ChatId, topic.Info.ForumTopicId, !topic.IsPinned));
if (response is Error error && error.Code == 400)
{
ShowPopup(string.Format(Strings.LimitReachedPinnedTopics, ClientService.Options.PinnedForumTopicCountMax), Strings.LimitReached, Strings.OK);
}
}
#endregion
#region Mark
public void MarkTopicAsRead(ForumTopic topic)
{
if (topic.UnreadCount > 0)
{
if (topic.LastMessage != null)
{
ClientService.ViewMessages(topic.Info.ChatId, topic.ToId(), new[] { topic.LastMessage.Id }, new MessageSourceForumTopicHistory(), true);
}
if (topic.UnreadMentionCount > 0)
{
ClientService.Send(new ReadAllForumTopicMentions(topic.Info.ChatId, topic.Info.ForumTopicId));
}
if (topic.UnreadReactionCount > 0)
{
ClientService.Send(new ReadAllForumTopicReactions(topic.Info.ChatId, topic.Info.ForumTopicId));
}
}
}
#endregion
#region Multiple Mark
public RelayCommand ChatsMarkCommand { get; }
private void ChatsMarkExecute()
{
//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, 0, new[] { chat.LastMessage.Id }, true));
// }
// else if (chat.IsMarkedAsUnread)
// {
// ClientService.Send(new ToggleChatIsMarkedAsUnread(chat.Id, false));
// }
// if (chat.UnreadMentionCount > 0)
// {
// ClientService.Send(new ReadAllChatMentions(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 NotifyTopic(ForumTopic topic)
{
if (Chat is Chat chat)
{
_notificationsService.SetMuteFor(topic, ClientService.Notifications.GetMuteFor(chat, topic) > 0 ? 0 : 632053052, NavigationService.XamlRoot);
}
}
#endregion
#region Notify
public void CloseTopic(ForumTopic topic)
{
if (Chat is Chat chat)
{
ClientService.Send(new ToggleForumTopicIsClosed(chat.Id, topic.Info.ForumTopicId, !topic.Info.IsClosed));
}
}
#endregion
#region Multiple Notify
public RelayCommand ChatsNotifyCommand { get; }
private void ChatsNotifyExecute()
{
//var chats = SelectedItems.ToList();
//var muted = chats.Any(x => ClientService.Notifications.GetMutedFor(x) > 0);
//foreach (var chat in chats)
//{
// if (chat.Type is ChatTypePrivate privata && privata.UserId == ClientService.Options.MyId)
// {
// continue;
// }
// _notificationsService.SetMuteFor(chat, muted ? 0 : 632053052);
//}
//Delegate?.SetSelectionMode(false);
//SelectedItems.Clear();
}
#endregion
#region Delete
public async void DeleteTopic(ForumTopic topic)
{
var message = string.Format(Strings.DeleteSelectedTopic, topic.Info.Name);
var title = Locale.Declension(Strings.R.DeleteTopics, 1);
var confirm = await ShowPopupAsync(message, title, Strings.Delete, Strings.Cancel, destructive: true);
if (confirm == ContentDialogResult.Primary)
{
// TODO: Handle the case where topics can't be deleted because user isn't admin
ClientService.Send(new DeleteForumTopic(Chat.Id, topic.Info.ForumTopicId));
}
}
#endregion
#region Multiple Delete
public RelayCommand ChatsDeleteCommand { get; }
private void ChatsDeleteExecute()
{
//var chats = SelectedItems.ToList();
//var confirm = await ShowPopupAsync(Strings.AreYouSureDeleteFewChats, Locale.Declension("ChatsSelected", chats.Count), Strings.Delete, Strings.Cancel);
//if (confirm == ContentDialogResult.Primary)
//{
// foreach (var chat in chats)
// {
// _deletedChats[chat.Id] = true;
// Items.Handle(chat.Id, 0);
// }
// Delegate?.ShowChatsUndo(chats, UndoType.Delete, items =>
// {
// foreach (var undo in items)
// {
// _deletedChats.Remove(undo.Id);
// Items.Handle(undo.Id, undo.Positions);
// }
// }, async items =>
// {
// foreach (var delete in items)
// {
// if (delete.Type is ChatTypeSecret secret)
// {
// await ClientService.SendAsync(new CloseSecretChat(secret.SecretChatId));
// }
// else if (delete.Type is ChatTypeBasicGroup or ChatTypeSupergroup)
// {
// await ClientService.SendAsync(new LeaveChat(delete.Id));
// }
// ClientService.Send(new DeleteChatHistory(delete.Id, true, false));
// }
// });
//}
//Delegate?.SetSelectionMode(false);
//SelectedItems.Clear();
}
#endregion
#region Clear
public void ClearTopic(ForumTopic chat)
{
//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)
//{
// Delegate?.ShowChatsUndo(new[] { chat }, UndoType.Clear, items =>
// {
// var undo = items.FirstOrDefault();
// if (undo == null)
// {
// return;
// }
// _deletedChats.Remove(undo.Id);
// Items.Handle(undo.Id, undo.Positions);
// }, items =>
// {
// foreach (var delete in items)
// {
// ClientService.Send(new DeleteChatHistory(delete.Id, false, dialog.IsChecked));
// }
// });
//}
}
public async void ClearTopic(DirectMessagesChatTopic topic)
{
var message = string.Format(Strings.AreYouSureClearHistoryWithUser, ClientService.GetTitle(topic.SenderId));
var title = Strings.ClearHistory;
var confirm = await ShowPopupAsync(message, title, Strings.Delete, Strings.Cancel, destructive: true);
if (confirm == ContentDialogResult.Primary)
{
ClientService.Send(new DeleteDirectMessagesChatTopicHistory(ChatId, topic.Id));
}
}
#endregion
#region Multiple Clear
public RelayCommand ChatsClearCommand { get; }
private void ChatsClearExecute()
{
//var chats = SelectedItems.ToList();
//var confirm = await ShowPopupAsync(Strings.AreYouSureClearHistoryFewChats, Locale.Declension("ChatsSelected", chats.Count), Strings.ClearHistory, Strings.Cancel);
//if (confirm == ContentDialogResult.Primary)
//{
// Delegate?.ShowChatsUndo(chats, UndoType.Clear, items =>
// {
// foreach (var undo in items)
// {
// _deletedChats.Remove(undo.Id);
// Items.Handle(undo.Id, undo.Positions);
// }
// }, items =>
// {
// var clear = items.FirstOrDefault();
// if (clear == null)
// {
// return;
// }
// ClientService.Send(new DeleteChatHistory(clear.Id, false, false));
// });
//}
//Delegate?.SetSelectionMode(false);
//SelectedItems.Clear();
}
#endregion
#region Select
public void SelectTopic(ForumTopic chat)
{
//SelectedItems.ReplaceWith(new[] { chat });
//SelectionMode = ListViewSelectionMode.Multiple;
//Delegate?.SetSelectedItems(_selectedItems);
}
#endregion
public Chat Chat => Items.Chat;
public long ChatId => Items.Chat?.Id ?? 0;
public void SetChat(Chat chat)
{
if (chat?.Id != Items.Chat?.Id)
{
_ = Items.ReloadAsync(chat);
LastSelectedItem = null;
SelectedItem = null;
SelectedItems.Clear();
if (_forum)
{
Aggregator.Subscribe<UpdateForumTopicInfo>(this, Handle)
.Subscribe<UpdateForumTopicReadInbox>(Handle)
.Subscribe<UpdateForumTopicReadOutbox>(Handle)
.Subscribe<UpdateForumTopicUnreadMentionCount>(Handle)
.Subscribe<UpdateForumTopicUnreadReactionCount>(Handle)
.Subscribe<UpdateForumTopicNotificationSettings>(Handle)
.Subscribe<UpdateChatAction>(Handle);
}
else
{
Aggregator.Subscribe<UpdateDirectMessagesChatTopicReadInbox>(this, Handle)
.Subscribe<UpdateDirectMessagesChatTopicReadOutbox>(Handle)
.Subscribe<UpdateDirectMessagesChatTopicUnreadMentionCount>(Handle)
.Subscribe<UpdateDirectMessagesChatTopicUnreadReactionCount>(Handle);
}
}
else if (chat == null)
{
LastSelectedItem = null;
SelectedItem = null;
SelectedItems.Clear();
Aggregator.Unsubscribe(this);
}
}
#region ForumTopic
private void Handle(UpdateChatAction update)
{
if (update.ChatId == Chat?.Id && update.TopicId is MessageTopicForum topicForum)
{
BeginOnUIThread(() => Delegate?.HandleForumTopic(topicForum.ForumTopicId, (cell, topic) => cell.UpdateForumTopicActions(topic, ClientService.GetChatActions(update.ChatId, update.TopicId))));
}
}
private void Handle(UpdateForumTopicInfo update)
{
if (update.Info.ChatId == Chat?.Id)
{
BeginOnUIThread(() => Delegate?.HandleForumTopic(update.Info.ForumTopicId, (cell, topic) => cell.UpdateForumTopicInfo(topic)));
}
}
private void Handle(UpdateForumTopicReadInbox update)
{
if (update.ChatId == Chat?.Id)
{
BeginOnUIThread(() => Delegate?.HandleForumTopic(update.ForumTopicId, (cell, topic) => cell.UpdateForumTopicReadInbox(topic)));
}
}
private void Handle(UpdateForumTopicReadOutbox update)
{
if (update.ChatId == Chat?.Id)
{
BeginOnUIThread(() => Delegate?.HandleForumTopic(update.ForumTopicId, (cell, topic) => cell.UpdateForumTopicReadOutbox(topic)));
}
}
private void Handle(UpdateForumTopicUnreadMentionCount update)
{
if (update.ChatId == Chat?.Id)
{
BeginOnUIThread(() => Delegate?.HandleForumTopic(update.ForumTopicId, (cell, topic) => cell.UpdateForumTopicUnreadMentionCount(topic)));
}
}
private void Handle(UpdateForumTopicUnreadReactionCount update)
{
if (update.ChatId == Chat?.Id)
{
BeginOnUIThread(() => Delegate?.HandleForumTopic(update.ForumTopicId, (cell, topic) => cell.UpdateForumTopicUnreadMentionCount(topic)));
}
}
public void Handle(UpdateForumTopicNotificationSettings update)
{
if (update.ChatId == Chat?.Id)
{
BeginOnUIThread(() => Delegate?.HandleForumTopic(update.ForumTopicId, (cell, topic) => cell.UpdateForumTopicNotificationSettings(topic)));
}
}
#endregion
#region ForumTopic
private void Handle(UpdateDirectMessagesChatTopicReadInbox update)
{
if (update.ChatId == Chat?.Id)
{
BeginOnUIThread(() => Delegate?.HandleDirectMessagesChatTopic(update.TopicId, (cell, topic) => cell.UpdateDirectMessagesChatTopicReadInbox(topic)));
}
}
private void Handle(UpdateDirectMessagesChatTopicReadOutbox update)
{
if (update.ChatId == Chat?.Id)
{
BeginOnUIThread(() => Delegate?.HandleDirectMessagesChatTopic(update.TopicId, (cell, topic) => cell.UpdateDirectMessagesChatTopicReadOutbox(topic)));
}
}
private void Handle(UpdateDirectMessagesChatTopicUnreadMentionCount update)
{
if (update.ChatId == Chat?.Id)
{
BeginOnUIThread(() => Delegate?.HandleDirectMessagesChatTopic(update.TopicId, (cell, topic) => cell.UpdateDirectMessagesChatTopicUnreadMentionCount(topic)));
}
}
private void Handle(UpdateDirectMessagesChatTopicUnreadReactionCount update)
{
if (update.ChatId == Chat?.Id)
{
BeginOnUIThread(() => Delegate?.HandleDirectMessagesChatTopic(update.TopicId, (cell, topic) => cell.UpdateDirectMessagesChatTopicUnreadMentionCount(topic)));
}
}
#endregion
public async void ViewAsMessages()
{
if (Chat is not Chat chat)
{
return;
}
await ClientService.SendAsync(new ToggleChatViewAsTopics(chat.Id, false));
NavigationService.NavigateToChat(chat, force: false, clearBackStack: true);
}
public async void CreateTopic()
{
if (Chat is not Chat chat)
{
return;
}
var popup = new SupergroupTopicPopup(ClientService, null);
var confirm = await ShowPopupAsync(popup);
if (confirm == ContentDialogResult.Primary)
{
var response = await ClientService.SendAsync(new CreateForumTopic(chat.Id, popup.SelectedName, false, popup.SelectedIcon));
if (response is ForumTopicInfo info)
{
NavigationService.NavigateToChat(chat, topic: new MessageTopicForum(info.ForumTopicId), force: false, clearBackStack: true);
}
}
}
public interface ITopicListCollection : IList, ICollectionWithTotalCount
{
Chat Chat { get; }
Task ReloadAsync(Chat chat);
object GetItem(MessageTopic topic);
}
public partial class ForumTopicsCollection : ObservableCollection<ForumTopic>, ISupportIncrementalLoading, ITopicListCollection
{
private readonly IClientService _clientService;
private readonly IEventAggregator _aggregator;
private CancellationTokenSource _token = new();
private readonly HashSet<int> _topics = new();
private readonly TopicListViewModel _viewModel;
private Chat _chat;
private bool _hasMoreItems = true;
private int _lastTopicId;
private long _lastOrder;
public Chat Chat => _chat;
public ForumTopicsCollection(IClientService clientService, IEventAggregator aggregator, TopicListViewModel viewModel, Chat chat)
{
_clientService = clientService;
_aggregator = aggregator;
_viewModel = viewModel;
_chat = chat;
//_ = LoadMoreItemsAsync(0);
}
public Task ReloadAsync(Chat chat)
{
if (_chat != null)
{
_clientService.Send(new CloseChat(_chat.Id));
}
_token?.Cancel();
_token = new CancellationTokenSource();
_aggregator.Unsubscribe(this);
_hasMoreItems = false;
_lastTopicId = 0;
_lastOrder = 0;
_chat = chat;
_topics.Clear();
Clear();
if (_chat != null)
{
_clientService.Send(new OpenChat(chat.Id));
return LoadMoreItemsAsync();
}
return Task.CompletedTask;
}
public IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
{
return IncrementalLoading.Run(token => LoadMoreItemsAsync());
}
private async Task<LoadMoreItemsResult> LoadMoreItemsAsync()
{
Logger.Info(Count);
var token = _token;
var totalCount = 0u;
await Task.Yield();
if (_chat == null)
{
_hasMoreItems = false;
return new LoadMoreItemsResult
{
Count = totalCount
};
}
var response = await _clientService.GetForumTopicsAsync(_chat.Id, Count, 20);
if (response is ForumTopics2 topics && !token.IsCancellationRequested)
{
if (_viewModel != null && !_viewModel._chatList && Count == 0)
{
topics.TopicIds = new List<int>(topics.TopicIds);
topics.TopicIds.Insert(0, int.MaxValue);
}
foreach (var topic in _clientService.GetForumTopics(_chat.Id, topics.TopicIds))
{
var order = topic.Order;
if (order != 0)
{
// TODO: is this redundant?
var next = NextIndexOf(topic, order);
if (next >= 0)
{
if (_topics.Contains(topic.Info.ForumTopicId))
{
Remove(topic);
}
_topics.Add(topic.Info.ForumTopicId);
Insert(Math.Min(Count, next), topic);
if ((_viewModel?.SelectedItem == null && topic.Info.ForumTopicId == 0) || _viewModel?.SelectedItem?.IsForum(topic.Info.ForumTopicId) is true)
{
_viewModel?.Delegate?.SetSelectedItem(topic);
}
totalCount++;
}
_lastTopicId = topic.Info.ForumTopicId;
_lastOrder = order;
}
}
Logger.Info(string.Format("Received {0} items, added {1}", topics.TopicIds.Count, totalCount));
IsEmpty = Count == 0;
_hasMoreItems = topics.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<UpdateForumTopicLastMessage>(Handle)
.Subscribe<UpdateForumTopicPosition>(Handle);
}
public bool HasMoreItems => _hasMoreItems;
#region Handle
public void Handle(UpdateAuthorizationState update)
{
if (update.AuthorizationState is AuthorizationStateReady)
{
_viewModel.BeginOnUIThread(() => _ = ReloadAsync(_chat));
}
}
public void Handle(UpdateForumTopicPosition update)
{
if (update.ChatId == _chat.Id)
{
Handle(update.ForumTopicId, update.Order);
}
}
public void Handle(UpdateForumTopicLastMessage update)
{
if (update.ChatId == _chat.Id)
{
Handle(update.ForumTopicId, update.Order, true);
}
}
//public void Handle(UpdateChatDraftMessage update)
//{
// Handle(update.ChatId, update.Positions, true);
//}
public void Handle(int forumTopicId, long order, bool lastMessage = false)
{
var topic = GetTopic(forumTopicId);
Handle(topic, order, lastMessage);
}
public void Handle(int forumTopicId, long order)
{
var chat = GetTopic(forumTopicId);
if (chat != null)
{
Handle(chat, order, false);
}
}
private void Handle(ForumTopic topic, long order, bool lastMessage)
{
//var chat = GetChat(chatId);
if (topic != null /*&& _chatList.ListEquals(chat.ChatList)*/)
{
_viewModel?.BeginOnUIThread(() => UpdateForumTopicOrder(topic, order, lastMessage));
}
}
private void UpdateForumTopicOrder(ForumTopic topic, long order, bool lastMessage)
{
if (order > 0 && (order > _lastOrder || (order == _lastOrder && topic.Info.ForumTopicId >= _lastTopicId)))
{
var next = NextIndexOf(topic, order);
if (next >= 0)
{
if (_topics.Contains(topic.Info.ForumTopicId))
{
Remove(topic);
}
else
{
_topics.Add(topic.Info.ForumTopicId);
}
Insert(Math.Min(Count, next), topic);
if (next == Count - 1)
{
_lastTopicId = topic.Info.ForumTopicId;
_lastOrder = order;
}
if (_viewModel.SelectedItem.IsForum(topic.Info.ForumTopicId))
{
_viewModel.Delegate?.SetSelectedItem(topic);
}
if (_viewModel.SelectedItems.Contains(topic))
{
_viewModel.Delegate?.SetSelectedItems(_viewModel.SelectedItems);
}
IsEmpty = Count == 0;
}
else if (lastMessage)
{
_viewModel.Delegate?.UpdateForumTopicLastMessage(topic);
}
}
else if (_topics.Contains(topic.Info.ForumTopicId))
{
_topics.Remove(topic.Info.ForumTopicId);
Remove(topic);
if (_viewModel.SelectedItems.Contains(topic))
{
_viewModel.SelectedItems.Remove(topic);
_viewModel.Delegate?.SetSelectedItems(_viewModel.SelectedItems);
}
IsEmpty = Count == 0;
//if (!_hasMoreItems)
//{
// await LoadMoreItemsAsync(0);
//}
}
}
private int NextIndexOf(ForumTopic topic, long order)
{
var prev = -1;
var next = 0;
for (int i = 0; i < Count; i++)
{
var item = this[i];
if (item.Info.ForumTopicId == topic.Info.ForumTopicId)
{
prev = i;
continue;
}
if (order > item.Order || order == item.Order && topic.Info.ForumTopicId >= item.Info.ForumTopicId)
{
return next == prev ? -1 : next;
}
next++;
}
return Count;
}
public ForumTopic GetTopic(int forumTopicId)
{
//if (_viewModels.ContainsKey(chatId))
//{
// return _viewModels[chatId];
//}
//else
//{
// var chat = ClientService.GetChat(chatId);
// var item = _viewModels[chatId] = new ChatViewModel(ClientService, chat);
// return item;
//}
if (forumTopicId == 0 && _viewModel != null && !_viewModel._chatList && Items.Count > 0)
{
return Items[0];
}
return _clientService.GetForumTopic(_chat.Id, forumTopicId);
}
public object GetItem(MessageTopic topic)
{
if (topic == null && _viewModel != null && !_viewModel._chatList && Items.Count > 0)
{
return Items[0];
}
if (topic is MessageTopicForum forum && _topics.Contains(forum.ForumTopicId))
{
return _clientService.GetForumTopic(_chat.Id, forum.ForumTopicId);
}
return null;
}
#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 int _totalCount;
public int TotalCount
{
get => _totalCount;
set
{
if (_totalCount != value)
{
_totalCount = value;
OnPropertyChanged(new PropertyChangedEventArgs(nameof(TotalCount)));
}
}
}
private void NotifyChanged()
{
OnPropertyChanged(new PropertyChangedEventArgs(nameof(IsEmpty)));
}
}
public partial class DirectMessagesChatTopicsCollection : ObservableCollection<DirectMessagesChatTopic>, ISupportIncrementalLoading, ITopicListCollection
{
private readonly IClientService _clientService;
private readonly IEventAggregator _aggregator;
private CancellationTokenSource _token = new();
private readonly HashSet<long> _topics = new();
private readonly TopicListViewModel _viewModel;
private Chat _chat;
private bool _hasMoreItems = true;
private long _lastTopicId;
private long _lastOrder;
public Chat Chat => _chat;
public DirectMessagesChatTopicsCollection(IClientService clientService, IEventAggregator aggregator, TopicListViewModel viewModel, Chat chat)
{
_clientService = clientService;
_aggregator = aggregator;
_viewModel = viewModel;
_chat = chat;
_ = LoadMoreItemsAsync(0);
}
public Task ReloadAsync(Chat chat)
{
if (_chat != null)
{
_clientService.Send(new CloseChat(_chat.Id));
}
_token?.Cancel();
_token = new CancellationTokenSource();
_aggregator.Unsubscribe(this);
_hasMoreItems = false;
_lastTopicId = 0;
_lastOrder = 0;