-
-
Notifications
You must be signed in to change notification settings - Fork 492
/
Copy pathTopicListViewModel.cs
766 lines (618 loc) · 24.7 KB
/
TopicListViewModel.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
//
// 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.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<IChatListDelegate>
{
private readonly INotificationsService _notificationsService;
private readonly Dictionary<long, bool> _deletedChats = new Dictionary<long, bool>();
public IChatListDelegate Delegate { get; set; }
public TopicListViewModel(IClientService clientService, ISettingsService settingsService, IEventAggregator aggregator, INotificationsService notificationsService, long chatId)
: base(clientService, settingsService, aggregator)
{
_notificationsService = notificationsService;
Items = new ItemsCollection(clientService, aggregator, this, null);
SearchFilters = new MvxObservableCollection<ISearchChatsFilter>();
ChatsMarkCommand = new RelayCommand(ChatsMarkExecute);
ChatsNotifyCommand = new RelayCommand(ChatsNotifyExecute);
ChatsDeleteCommand = new RelayCommand(ChatsDeleteExecute);
ChatsClearCommand = new RelayCommand(ChatsClearExecute);
#if MOCKUP
Items.AddRange(clientService.GetChats(null));
#endif
SelectedItems = new MvxObservableCollection<ForumTopic>();
}
#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;
}
}
}
private MvxObservableCollection<ForumTopic> _selectedItems;
public MvxObservableCollection<ForumTopic> 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 ItemsCollection Items { get; private set; }
public bool IsLastSliceLoaded { get; set; }
public MvxObservableCollection<ISearchChatsFilter> SearchFilters { get; private set; }
#region Open
public void OpenTopic(ForumTopic topic)
{
NavigationService.NavigateToChat(topic.Info.ChatId, thread: topic.Info.MessageThreadId, 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.MessageThreadId, !topic.IsPinned));
if (response is Error error && error.Code == 400)
{
// This is not the right way
NavigationService.ShowLimitReached(new PremiumLimitTypePinnedChatCount());
}
}
#endregion
#region Mark
public void MarkTopicAsRead(ForumTopic topic)
{
if (topic.UnreadCount > 0)
{
if (topic.LastMessage != null)
{
ClientService.ViewMessages(topic.Info.ChatId, topic.Info.MessageThreadId, new[] { topic.LastMessage.Id }, new MessageSourceForumTopicHistory(), true);
}
if (topic.UnreadMentionCount > 0)
{
ClientService.Send(new ReadAllMessageThreadMentions(topic.Info.ChatId, topic.Info.MessageThreadId));
}
if (topic.UnreadReactionCount > 0)
{
ClientService.Send(new ReadAllMessageThreadReactions(topic.Info.ChatId, topic.Info.MessageThreadId));
}
}
}
#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(chat, 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.MessageThreadId, !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.MessageThreadId));
}
}
#endregion
#region Multiple Delete
public RelayCommand ChatsDeleteCommand { get; }
private async 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
private async 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));
// }
// });
//}
}
#endregion
#region Multiple Clear
public RelayCommand ChatsClearCommand { get; }
private async 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 void SetChat(Chat chat)
{
if (chat?.Id != Items.Chat?.Id)
{
_ = Items.ReloadAsync(chat);
}
else
{
LastSelectedItem = 0;
SelectedItem = 0;
SelectedItems.Clear();
}
}
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, popup.SelectedIcon));
if (response is ForumTopicInfo info)
{
NavigationService.NavigateToChat(chat, thread: info.MessageThreadId, force: false, clearBackStack: true);
}
}
}
public partial class ItemsCollection : ObservableCollection<ForumTopic>, ISupportIncrementalLoading
{
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 ItemsCollection(IClientService clientService, IEventAggregator aggregator, TopicListViewModel viewModel, Chat chat)
{
_clientService = clientService;
_aggregator = aggregator;
_viewModel = viewModel;
_chat = chat;
#if MOCKUP
_hasMoreItems = false;
#endif
_ = 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 AsyncInfo.Run(token => LoadMoreItemsAsync());
}
private async Task<LoadMoreItemsResult> LoadMoreItemsAsync()
{
Logger.Info(Count);
var token = _token;
var totalCount = 0u;
await Task.Yield();
if (_chat == null)
{
return new LoadMoreItemsResult
{
Count = totalCount
};
}
var response = await _clientService.GetForumTopicsAsync(_chat.Id, Count, 20);
if (response is ForuminoTopicinos topics && !token.IsCancellationRequested)
{
foreach (var topic in _clientService.GetTopics(_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.MessageThreadId))
{
Remove(topic);
}
_topics.Add(topic.Info.MessageThreadId);
Insert(Math.Min(Count, next), topic);
if (topic.Info.MessageThreadId == _viewModel?.SelectedItem)
{
_viewModel?.Delegate?.SetSelectedItem(topic);
}
totalCount++;
}
_lastTopicId = topic.Info.MessageThreadId;
_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.MessageThreadId, update.Order);
}
}
public void Handle(UpdateForumTopicLastMessage update)
{
if (update.ChatId == _chat.Id)
{
Handle(update.MessageThreadId, update.Order, true);
}
}
//public void Handle(UpdateChatDraftMessage update)
//{
// Handle(update.ChatId, update.Positions, true);
//}
public void Handle(long chatId, long order, bool lastMessage = false)
{
var topic = GetTopic(chatId);
Handle(topic, order, lastMessage);
}
public void Handle(long chatId, long order)
{
var chat = GetTopic(chatId);
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.MessageThreadId >= _lastTopicId)))
{
var next = NextIndexOf(topic, order);
if (next >= 0)
{
if (_topics.Contains(topic.Info.MessageThreadId))
{
Remove(topic);
}
else
{
_topics.Add(topic.Info.MessageThreadId);
}
Insert(Math.Min(Count, next), topic);
if (next == Count - 1)
{
_lastTopicId = topic.Info.MessageThreadId;
_lastOrder = order;
}
if (topic.Info.MessageThreadId == _viewModel.SelectedItem)
{
_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.MessageThreadId))
{
_topics.Remove(topic.Info.MessageThreadId);
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.MessageThreadId == topic.Info.MessageThreadId)
{
prev = i;
continue;
}
if (order > item.Order || order == item.Order && topic.Info.MessageThreadId >= item.Info.MessageThreadId)
{
return next == prev ? -1 : next;
}
next++;
}
return Count;
}
private ForumTopic GetTopic(long messageThreadId)
{
//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.GetTopic(_chat.Id, messageThreadId);
}
#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)));
}
}
}
}