-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMainForm.cs
1267 lines (1042 loc) · 58.3 KB
/
MainForm.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Media = System.Media;
using Td = Telegram.Td;
using TdApi = Telegram.Td.Api;
using Tulpep.NotificationWindow;
using System.IO;
using Vlc.DotNet.Forms.TypeEditors;
using convertion = GroupDocs.Conversion;
using GroupDocs.Conversion.Options.Convert;
namespace TelegramClient {
public delegate void DelegateChat(long id);
public partial class MainForm : Form {
#region Обработчики
//обработчик авторизации
public class AuthorizationRequestHandler : Td.ClientResultHandler {
void Td.ClientResultHandler.OnResult(TdApi.BaseObject @object) {
if (@object is TdApi.Error) {
OnAuthorizationStateUpdated(null); // repeat last action
}
else {
// result is already received through UpdateAuthorizationState, nothing to do
}
}
}
//обработчик, который передаётся при создании клиента и не только
public class DefaultHandler : Td.ClientResultHandler {
public MainForm mainForm;
public DefaultHandler(MainForm mainForm) {
this.mainForm = mainForm;
}
void Td.ClientResultHandler.OnResult(TdApi.BaseObject @object) {
//Console.WriteLine(@object.GetType());
if (@object is Td.Api.Ok) {
//Console.WriteLine(@object.ToString());
//MessageBox.Show("ura");
}
if (@object is TdApi.Error) {
//Console.WriteLine((@object as TdApi.Error).Message);
}
//? может для отправки
if (@object is TdApi.File) {
//Console.WriteLine((@object as TdApi.File).Local.Path);
}
//id чатов
if (@object is TdApi.Chats) {
//long[] reverse = (@object as TdApi.Chats).ChatIds.Reverse<long>().ToArray();
listsIndexChats = (@object as TdApi.Chats).ChatIds;
//foreach (var item in reverse) {
// MainForm.DictChatID_listMessages.Add(item, new List<long>());
// //MainForm.Chat_IDs.Enqueue(item);
// PanelChat panelChat = new PanelChat();
// ChatsUserControl chatsUserControl = new ChatsUserControl();
// panelChat.messagesPanel = chatsUserControl;
// mainForm.BeginInvoke(new Action(delegate { mainForm.panel5.Controls.Add(chatsUserControl); }));
// mainForm.BeginInvoke(new Action(delegate { mainForm.panel15.Controls.Add(panelChat); }));
// ChatsPanels.Add(item, panelChat);
//}
autoReset.Set();
}
//конкретный чат
if (@object is TdApi.Chat) {
if ((@object as TdApi.Chat).Type is TdApi.ChatTypePrivate) {
MainForm.listChats.Add((@object as TdApi.Chat));
}
CountChats++;
//long id = (@object as TdApi.Chat).Id;
//mainForm.BeginInvoke(new Action(delegate {
// ChatsPanels[id].ID = (@object as TdApi.Chat).Id;
// ChatsPanels[id].label1.Text = (@object as TdApi.Chat).Title;
// ChatsPanels[id].Dock = DockStyle.Top;
// ChatsPanels[id].Location = new Point(0, PanelChat.CurentHeight);
// PanelChat.CurentHeight += 46;
//}));
//if ((@object as TdApi.Chat).Photo != null) {
// _client.Send(new TdApi.DownloadFile((@object as TdApi.Chat).Photo.Big.Id, 1, 0, 0, true), _defaultHandler);
// ChatsPanels[id].pictureBox1.ImageLocation = (@object as TdApi.Chat).Photo.Big.Local.Path;
// ChatsPanels[id].pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
//}
//else
// ChatsPanels[id].pictureBox1.ImageLocation = @"D:\2. Учёба\4 семестр\4. Сети ЭВМ\Курсовая работа\TelegramClient\Images\person.png";
////mainForm.LoadPanelChat(panelChat);
//mainForm.BeginInvoke(new Action(delegate {
// ChatsPanels[id].messagesPanel.Location = new Point(0, 60);
// ChatsPanels[id].messagesPanel.SendToBack();
// ChatsPanels[id].messagesPanel.Dock = DockStyle.Fill;
//}));
//mainForm.BeginInvoke(new Action(delegate {
// mainForm.panel5.Controls.Add(chatsUserControl);
// chatsUserControl.SendToBack();
//}));
//if (!Dictionary_ChatID_Success.Keys.Contains<long>((@object as TdApi.Chat).Id)) {
// MainForm.Dictionary_ChatID_Success.Add((@object as TdApi.Chat).Id, (true, 0));
//}
//else {
// Dictionary_ChatID_Success[(@object as TdApi.Chat).Id] = true;
//}
//new Task(() => {
//do {
//_client.Send(new TdApi.GetChatHistory((@object as TdApi.Chat).Id, Dictionary_ChatID_Success[(@object as TdApi.Chat).Id].Item2, 0, 100, false), _defaultHandler);
//} while (Dictionary_ChatID_Success[(@object as TdApi.Chat).Id].Item1);
//});
}
//контент чата
if (@object is TdApi.Messages) {
//int last_index = (@object as TdApi.Messages).MessagesValue.Length;
long last_id = lastMessageID;
for (int i = 0; i < (@object as TdApi.Messages).MessagesValue.Length; i++) {
if ((@object as TdApi.Messages).MessagesValue[i].Content is TdApi.MessageText || (@object as TdApi.Messages).MessagesValue[i].Content is TdApi.MessageSticker) {
listMessages.Add((@object as TdApi.Messages).MessagesValue[i]);
}
//MainForm.Tuple_chatID.Add(((@object as TdApi.Messages).MessagesValue[0].ChatId,
// (@object as TdApi.Messages).MessagesValue[i].Id,
// ((@object as TdApi.Messages).MessagesValue[i].Content as TdApi.MessageText).Text.Text));
//Label label = new Label();
//label.AutoSize = true;
//label.BackColor = Color.FromArgb(255, 112, 133, 153);
//label.MaximumSize = new Size(300, int.MaxValue);
//if (((@object as TdApi.Messages).MessagesValue[i].SenderId as TdApi.MessageSenderUser).UserId == MainForm.IDuser) {
// label.Location = new Point(50, 500 * i + 100);
//}
//else {
// label.Location = new Point(700, 500 * i + 100);
//}
//MainForm.Tuple_chatID.Add((CurChatID, (@object as TdApi.Messages).MessagesValue[i].Id,((@object as TdApi.Messages).MessagesValue[i].Content as TdApi.MessageText).Text.Text));
last_id = (@object as TdApi.Messages).MessagesValue[i].Id;
}
if (last_id == lastMessageID) {
flagMessages = false;
}
lastMessageID = last_id;
autoReset.Set();
//chat_id = (@object as TdApi.Messages).MessagesValue[0].ChatId;
//if (last_id == MainForm.Dictionary_ChatID_Success[chat_id].Item2) {
// MainForm.Dictionary_ChatID_Success[chat_id] = (false, MainForm.Dictionary_ChatID_Success[chat_id].Item2);
//}
//MainForm.Dictionary_ChatID_Success[chat_id] = (MainForm.Dictionary_ChatID_Success[chat_id].Item1, last_id);
//if (Dictionary_ChatID_Success[chat_id].Item1) {
// _client.Send(new TdApi.GetChatHistory(chat_id, Dictionary_ChatID_Success[chat_id].Item2, 0, 100, false), _defaultHandler);
//}
#region
//if ((@object as TdApi.Messages).MessagesValue[i].Content is TdApi.MessagePhoto) {
// //Console.WriteLine(((@object as TdApi.Messages).MessagesValue[0].Content as TdApi.MessagePhoto).Photo.Sizes[0].Photo.Id);
// _client.Send(new TdApi.DownloadFile(((@object as TdApi.Messages).MessagesValue[i].Content as TdApi.MessagePhoto).Photo.Sizes[i].Photo.Id, 1, 0, 0, true), _defaultHandler);
//}
//if ((@object as TdApi.Messages).MessagesValue[i].Content is TdApi.MessageSticker) {
// //Console.WriteLine(((@object as TdApi.Messages).MessagesValue[0].Content as TdApi.MessageSticker).Sticker.Thumbnail);
// _client.Send(new TdApi.DownloadFile(((@object as TdApi.Messages).MessagesValue[i].Content as TdApi.MessageSticker).Sticker.StickerValue.Id, 1, 0, 0, true), _defaultHandler);
//}
//if ((@object as TdApi.Messages).MessagesValue[i].Content is TdApi.MessageVoiceNote) {
// //Console.WriteLine(((@object as TdApi.Messages).MessagesValue[0].Content as TdApi.MessageVoiceNote).VoiceNote.Voice.Id);
// _client.Send(new TdApi.DownloadFile(((@object as TdApi.Messages).MessagesValue[i].Content as TdApi.MessageVoiceNote).VoiceNote.Voice.Id, 1, 0, 0, true), _defaultHandler);
// #region Media
// //using (var vorbisStream = new NAudio.Vorbis.VorbisWaveReader("path/to/file.ogg"))
// //using (var waveOut = new NAudio.Wave.WaveOutEvent()) {
// // waveOut.Init(vorbisStream);
// // waveOut.Play();
// // // wait here until playback stops or should stop
// //}
// //var filePath = $@"C:\Users\blabla\foo\bar\";
// //var fileOgg = "testAudio.ogg";
// //var fileWav = "testAudio.wav";
// //using (FileStream fileIn = new FileStream($"{filePath}{fileOgg}", FileMode.Open))
// //using (MemoryStream pcmStream = new MemoryStream()) {
// // OpusDecoder decoder = OpusDecoder.Create(48000, 1);
// // OpusOggReadStream oggIn = new OpusOggReadStream(decoder, fileIn);
// // while (oggIn.HasNextPacket) {
// // short[] packet = oggIn.DecodeNextPacket();
// // if (packet != null) {
// // for (int i = 0; i < packet.Length; i++) {
// // var bytes = BitConverter.GetBytes(packet[i]);
// // pcmStream.Write(bytes, 0, bytes.Length);
// // }
// // }
// // }
// // pcmStream.Position = 0;
// // var wavStream = new RawSourceWaveStream(pcmStream, new WaveFormat(48000, 1));
// // var sampleProvider = wavStream.ToSampleProvider();
// // WaveFileWriter.CreateWaveFile16($"{filePath}{fileWav}", sampleProvider);
// #endregion
//}
//if ((@object as TdApi.Messages).MessagesValue[i].Content is TdApi.MessageVideo) {
//}
//if ((@object as TdApi.Messages).MessagesValue[i].Content is TdApi.MessageAnimation) {
//}
//if ((@object as TdApi.Messages).MessagesValue[i].Content is TdApi.MessageAnimatedEmoji) {
//}
//if ((@object as TdApi.Messages).MessagesValue[i].Content is TdApi.MessageDocument) {
//}
//lastMessageIndex = (@object as TdApi.Messages).MessagesValue[i].Id;
//if((@object as TdApi.Messages).MessagesValue.Length == (int)MainForm.HashTable_ChatID_LastMessageID[0])
//_client.Send(new TdApi.GetChatHistory((@object as TdApi.Messages).MessagesValue[(@object as TdApi.Messages).MessagesValue.Length - 1].ChatId, (@object as TdApi.Messages).MessagesValue[(@object as TdApi.Messages).MessagesValue.Length - 1].Id, 100, int.MaxValue, false), _defaultHandler);
//if (lastMessageIndex == lastMessageID) {
//flagMessages = false;
//}
//else {
// lastMessageID = lastMessageIndex;
// _client.Send(new TdApi.GetChatHistory(MainForm.CurChatID, MainForm.lastMessageID, 0, 100, false), _defaultHandler);
//}
#endregion
}
//информация о пользователе
if (@object is TdApi.User) {
mainForm.BeginInvoke(new Action(delegate {
mainForm.label2.Text = (@object as TdApi.User).FirstName + (@object as TdApi.User).LastName;
mainForm.label4.Text = "+" + (@object as TdApi.User).PhoneNumber;
mainForm.label12.Text = (@object as TdApi.User).Id.ToString();
mainForm.label14.Text = (@object as TdApi.User).Username;
if ((@object as TdApi.User).ProfilePhoto != null) {
_client.Send(new TdApi.DownloadFile((@object as TdApi.User).ProfilePhoto.Big.Id, 1, 0, 0, true), _defaultHandler);
mainForm.pictureBox1.ImageLocation = (@object as TdApi.User).ProfilePhoto.Big.Local.Path;
mainForm.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
}
else
mainForm.pictureBox1.ImageLocation = @"D:\2. Учёба\4 семестр\4. Сети ЭВМ\Курсовая работа\TelegramClient\Images\person.png";
}));
MainForm.IDuser = (@object as TdApi.User).Id;
}
//информация о телефонном номере
if (@object is TdApi.PhoneNumberInfo) {
//User.mainForm.maskedTextBox1.Text = (@object as TdApi.PhoneNumberInfo).FormattedPhoneNumber;
}
//?
if (@object is TdApi.NetworkStatistics) {
//Console.WriteLine((@object as TdApi.NetworkStatistics).ToString());
}
//информация о регионе
if (@object is TdApi.CountryInfo) {
//Console.WriteLine((@object as TdApi.CountryInfo).CountryCode
}
//?
if (@object is TdApi.Count) {
//Console.WriteLine(@object.ToString
}
//? текстовые объекты
if (@object is TdApi.TextEntities) {
//Console.WriteLine(@object.ToString());
}
}
}
//Обновление данных
public class UpdateHandler : Td.ClientResultHandler {
public MainForm main;
public UpdateHandler() {
}
//public UpdateHandler(MainForm main) {
// this.main = main;
//}
void Td.ClientResultHandler.OnResult(TdApi.BaseObject @object) {
if (@object is TdApi.UpdateAuthorizationState) {
OnAuthorizationStateUpdated((@object as TdApi.UpdateAuthorizationState).AuthorizationState);
}
else {
if (@object is TdApi.UpdateOption) {
}
if (@object is TdApi.UpdateNewMessage) {
if (((@object as TdApi.UpdateNewMessage)?.Message.SenderId as TdApi.MessageSenderUser)?.UserId != IDuser) {
MainForm.flagNotifer = true;
MainForm.titleNotifer = "Новое сообщение";
MainForm.textNotifer = ((@object as TdApi.UpdateNewMessage)?.Message?.Content as TdApi.MessageText)?.Text.Text;
}
MainForm.updateMessage = (@object as TdApi.UpdateNewMessage);
MainForm.updateMessageFlag = true;
}
if (@object is TdApi.UpdateFile) {
if (!(@object as TdApi.UpdateFile).File.Local.IsDownloadingActive) {
//downloadReset.Set();
}
}
#region
//if (@object is TdApi.UpdateUser) {
//}
//if (@object is TdApi.UpdateUserStatus) {
//}
//if (@object is TdApi.UpdateBasicGroup) {
//}
//if (@object is TdApi.UpdateSupergroup) {
//}
//if (@object is TdApi.UpdateSecretChat) {
//}
//if (@object is TdApi.UpdateNewChat) {
//}
//if (@object is TdApi.UpdateChatTitle) {
//}
//if (@object is TdApi.UpdateChatLastMessage) {
//}
//if (@object is TdApi.UpdateChatPosition) {
//}
//if (@object is TdApi.UpdateChatReadInbox) {
//}
//if (@object is TdApi.UpdateChatUnreadMentionCount) {
//}
//if (@object is TdApi.UpdateMessageMentionRead) {
//}
//if (@object is TdApi.UpdateChatReplyMarkup) {
//}
//if (@object is TdApi.UpdateChatDraftMessage) {
//}
//if (@object is TdApi.UpdateChatPermissions) {
//}
//if (@object is TdApi.UpdateChatNotificationSettings) {
//}
//if (@object is TdApi.UpdateChatDefaultDisableNotification) {
//}
//if (@object is TdApi.UpdateChatIsMarkedAsUnread) {
//}
//if (@object is TdApi.UpdateChatIsBlocked) {
//}
//if (@object is TdApi.UpdateChatHasScheduledMessages) {
//}
//if (@object is TdApi.UpdateUserFullInfo) {
//}
//if (@object is TdApi.UpdateBasicGroupFullInfo) {
//}
//if (@object is TdApi.UpdateSupergroupFullInfo) {
//}
//if (@object is TdApi.UpdateFile) {
//}
#endregion
}
}
}
//public async void LoadMessagesChats() {
// await new Task(() => {
// autoReset.Reset();
// autoReset.WaitOne();
// });
//}
#endregion
#region Клиент
//Телеграмм клиент
public static Td.Client _client = null;
//Обработчик ответа(получает ответ). Обработка в OnResult()
public static Td.ClientResultHandler _defaultHandler;
//состояние авторизации
public static TdApi.AuthorizationState _authorizationState = null;
//авторизация флаг
public static volatile bool _haveAuthorization = false;
//флаги для закрытия
public static volatile bool _needQuit = false;
public static volatile bool _canQuit = false;
//ожидание авторизации?
public static volatile AutoResetEvent _gotAuthorization = new AutoResetEvent(false);
public static volatile AutoResetEvent autoReset = new AutoResetEvent(true);
public static volatile AutoResetEvent downloadReset = new AutoResetEvent(true);
//текущая платформа
public static readonly string _newLine = Environment.NewLine;
//public Command command = Command.NotCommand;
public static string command { get; set; } = "";
public static volatile string _currentPrompt = null;
private static UpdateHandler updateHandler = new UpdateHandler();
public static bool FLAG_AUTHORIZATION = false;
public static MainForm mainForm;
public static string titleNotifer;
public static string textNotifer;
public static string senderID;
public static bool flagNotifer = false;
public void LoadClient() {
MainForm._defaultHandler = new DefaultHandler(this);
//User.mainForm = mainForm;
// disable TDLib log
Td.Client.Execute(new TdApi.SetLogVerbosityLevel(0));
if (Td.Client.Execute(new TdApi.SetLogStream(new TdApi.LogStreamFile("tdlib.log", 1 << 27, false))) is TdApi.Error) {
throw new System.IO.IOException("Write access to the current directory is required");
}
new Thread(() => {
Thread.CurrentThread.IsBackground = true;
Td.Client.Run();
}).Start();
//инициализация клиента
// create Td.Client
_client = CreateTdClient();
//ЧТО-ТО ДЕЛАЕТ С ПОЛУЧЕННЫМ РЕЗУЛЬТАТОМ | ДЕЛАЕТ ЗАПРОС
// test Client.Execute
_defaultHandler.OnResult(Td.Client.Execute(new TdApi.GetTextEntities("@telegram /test_command https://telegram.org telegram.me @gif @test")));
//new Task(() => {
// CheckState();
//}).Start();
//CheckState();
new Task(() => {
while (!_needQuit) {
//ожидание ответа после _defaultHandler.OnResult(Td.Client.Execute(...))
// await authorization
//_gotAuthorization.Reset();
//_gotAuthorization.WaitOne();
_client.Send(new TdApi.GetAuthorizationState(), updateHandler);
// preload main chat list
_client.Send(new TdApi.LoadChats(null, 1000), _defaultHandler);
while (_haveAuthorization) {
_client.Send(new TdApi.GetAuthorizationState(), updateHandler);
//GetCommand();
}
}
while (!_canQuit) {
Thread.Sleep(1);
}
});
}
public async void CheckState() {
await new Task(() => {
while (!_needQuit) {
//ожидание ответа после _defaultHandler.OnResult(Td.Client.Execute(...))
// await authorization
//_gotAuthorization.Reset();
//_gotAuthorization.WaitOne();
_client.Send(new TdApi.GetAuthorizationState(), updateHandler);
// preload main chat list
_client.Send(new TdApi.LoadChats(null, 1000), _defaultHandler);
while (_haveAuthorization) {
_client.Send(new TdApi.GetAuthorizationState(), updateHandler);
//GetCommand();
}
}
while (!_canQuit) {
Thread.Sleep(1);
}
});
}
//инициализация клиента
public static Td.Client CreateTdClient() {
return Td.Client.Create(new UpdateHandler());
}
//проверка состояния
public static void OnAuthorizationStateUpdated(TdApi.AuthorizationState authorizationState) {
if (authorizationState != null) {
_authorizationState = authorizationState;
}
if (_authorizationState is TdApi.AuthorizationStateWaitTdlibParameters) {
TdApi.TdlibParameters parameters = new TdApi.TdlibParameters();
parameters.DatabaseDirectory = "tdlib";
parameters.UseMessageDatabase = true;
parameters.UseSecretChats = true;
parameters.ApiId = 10523607;
parameters.ApiHash = "bac30fa36fc132b5994a050c16d1e12f";
parameters.SystemLanguageCode = "en";
parameters.DeviceModel = "Desktop";
parameters.ApplicationVersion = "1.0";
parameters.EnableStorageOptimizer = true;
_client.Send(new TdApi.SetTdlibParameters(parameters), new AuthorizationRequestHandler());
}
else if (_authorizationState is TdApi.AuthorizationStateWaitEncryptionKey) {
_client.Send(new TdApi.CheckDatabaseEncryptionKey(), new AuthorizationRequestHandler());
//_gotAuthorization.Reset();
//_gotAuthorization.WaitOne();
}
else if (_authorizationState is TdApi.AuthorizationStateWaitPhoneNumber) {
//MessageBox.Show("number");
_client.Send(new TdApi.SetAuthenticationPhoneNumber(/*"+79206021338"*/mainForm.maskedTextBox1.Text, null), new AuthorizationRequestHandler());
_gotAuthorization.Reset();
_gotAuthorization.WaitOne();
//mainForm.maskedTextBox1.Enabled = false;
//mainForm.textBox2.Enabled = true;
//mainForm.textBox3.Enabled = true;
//_client.Send(new TdApi.GetPhoneNumberInfo(), _defaultHandler);
}
else if (_authorizationState is TdApi.AuthorizationStateWaitOtherDeviceConfirmation state) {
//Console.WriteLine("Please confirm this login link on another device: " + state.Link);
}
else if (_authorizationState is TdApi.AuthorizationStateWaitCode) {
//MessageBox.Show("maked code");
//_client.Send(new TdApi.CheckAuthenticationCode(""), new AuthorizationRequestHandler());
//mainForm.maskedTextBox1.Enabled = false;
// mainForm.textBox2.Enabled = false;
// mainForm.textBox3.Enabled = true;
}
else if (_authorizationState is TdApi.AuthorizationStateWaitRegistration) {
//string firstName = ReadLine("Please enter your first name: ");
//string lastName = ReadLine("Please enter your last name: ");
_client.Send(new TdApi.RegisterUser(/*firstName*/"", /*lastName*/""), new AuthorizationRequestHandler());
//_client.Send(new TdApi.SetAuthenticationPhoneNumber("+79206021338", null), new AuthorizationRequestHandler());
}
else if (_authorizationState is TdApi.AuthorizationStateWaitPassword) {
_client.Send(new TdApi.CheckAuthenticationPassword(""), new AuthorizationRequestHandler());
}
else if (_authorizationState is TdApi.AuthorizationStateReady) {
_haveAuthorization = true;
_gotAuthorization.Set();
FLAG_AUTHORIZATION = true;
mainForm.BeginInvoke(new Action(delegate { mainForm.panel10.BringToFront(); }));
//MainForm.LoadTelegram();
}
else if (_authorizationState is TdApi.AuthorizationStateLoggingOut) {
_haveAuthorization = false;
//Print("Logging out");
}
else if (_authorizationState is TdApi.AuthorizationStateClosing) {
_haveAuthorization = false;
//Print("Closing");
}
else if (_authorizationState is TdApi.AuthorizationStateClosed) {
//Print("Closed");
if (!_needQuit) {
_client = CreateTdClient(); // recreate _client after previous has closed
}
else {
_canQuit = true;
}
}
else {
//mainForm.panel10.BringToFront();
//Print("Unsupported authorization state:" + _newLine + _authorizationState);
}
}
//преобразование строки id в число
public static long GetChatId(string arg) {
long chatId = 0;
try {
chatId = Convert.ToInt64(arg);
}
catch (FormatException) {
}
catch (OverflowException) {
}
return chatId;
}
//выполнение определенной команды
//public static void GetCommand() {
// //string command = Console.ReadLine();
// string[] commands = command.Split(new char[] { ' ' }, 3);
// try {
// switch (commands[0]) {
// case "gcs":
// _client.Send(new TdApi.GetChats(null, int.MaxValue), _defaultHandler);
// break;
// case "gc":
// _client.Send(new TdApi.GetChat(GetChatId(commands[1])), _defaultHandler);
// break;
// case "me":
// _client.Send(new TdApi.GetMe(), _defaultHandler);
// break;
// case "sm":
// string[] args = commands[1].Split(new char[] { ' ' }, 2);
// sendMessage(GetChatId(args[0]), args[1]);
// break;
// case "lo":
// _haveAuthorization = false;
// _client.Send(new TdApi.LogOut(), _defaultHandler);
// break;
// case "r":
// _haveAuthorization = false;
// _client.Send(new TdApi.Close(), _defaultHandler);
// break;
// case "q":
// _needQuit = true;
// _haveAuthorization = false;
// _client.Send(new TdApi.Close(), _defaultHandler);
// break;
// case "get_chat_history":
// _client.Send(new TdApi.GetChatHistory(GetChatId(commands[1]), long.Parse(commands[2]), 0, 100, false), _defaultHandler);
// break;
// case "get_message_count":
// _client.Send(new TdApi.GetChatMessageCount(long.Parse(commands[1]), null, false), _defaultHandler);
// break;
// case "get_messages":
// _client.Send(new TdApi.GetMessages(GetChatId(commands[1]), new long[] { long.Parse(commands[2]) }), _defaultHandler);
// break;
// case "get_country_code":
// _client.Send(new TdApi.GetCountryCode(), _defaultHandler);
// break;
// case "load_chats":
// _client.Send(new TdApi.LoadChats(null, 1000), _defaultHandler);
// break;
// case "get_json_string":
// _client.Send(new TdApi.GetJsonString(), _defaultHandler);
// break;
// case "get_json_value":
// _client.Send(new TdApi.GetJsonValue(), _defaultHandler);
// break;
// case "download_file":
// _client.Send(new TdApi.DownloadFile(), _defaultHandler);
// break;
// case "get_message_filetype":
// _client.Send(new TdApi.GetMessageFileType(), _defaultHandler);
// break;
// case "upload_file":
// _client.Send(new TdApi.UploadFile(), _defaultHandler);
// break;
// case "upload_sticker_file":
// _client.Send(new TdApi.UploadStickerFile(), _defaultHandler);
// break;
// case "e":
// _client.Send(new TdApi.GetMessageFileType(), _defaultHandler);
// break;
// case "m":
// _client.Send(new TdApi.GetMessageFileType(), _defaultHandler);
// break;
// case "n":
// _client.Send(new TdApi.GetMessageFileType(), _defaultHandler);
// break;
// case "o":
// _client.Send(new TdApi.GetMessageFileType(), _defaultHandler);
// break;
// default:
// //Print("Unsupported command: " + command);
// break;
// }
// }
// catch (IndexOutOfRangeException) {
// //Print("Not enough arguments");
// }
//}
//ОТПРАВКА СООБЩЕНИЯ
public static void sendMessage(long chatId, string message) {
// initialize reply markup just for testing
TdApi.InlineKeyboardButton[] row = {
new TdApi.InlineKeyboardButton("https://telegram.org?1", new TdApi.InlineKeyboardButtonTypeUrl()),
new TdApi.InlineKeyboardButton("https://telegram.org?2", new TdApi.InlineKeyboardButtonTypeUrl()),
new TdApi.InlineKeyboardButton("https://telegram.org?3", new TdApi.InlineKeyboardButtonTypeUrl())
};
TdApi.ReplyMarkup replyMarkup = new TdApi.ReplyMarkupInlineKeyboard(new TdApi.InlineKeyboardButton[][] { row, row, row });
TdApi.InputMessageContent content = new TdApi.InputMessageText(new TdApi.FormattedText(message, null), false, true);
_client.Send(new TdApi.SendMessage(chatId, 0, 0, null, replyMarkup, content), _defaultHandler);
}
#endregion
#region MainForm
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HTCAPTION = 0x2;
[DllImport("User32.dll")]
public static extern bool ReleaseCapture();
[DllImport("User32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
//public static List<ChatsUserControl> ChatsUserControls = new List<ChatsUserControl>();
//public static Queue<long> Chat_IDs { get; set; }
//public static Queue<long> Messages_ID { get; set; }
//public static Queue<(long,TdApi.MessageContent)> Chat_MessagePairs{ get; set; }
//public static Dictionary<long, (bool, long)> Dictionary_ChatID_Success = new Dictionary<long, (bool, long)>();
//public static Dictionary<long, long> Dictionary_chatID = new Dictionary<long, long>();
//public static int CurrentindexChat;
//public static Dictionary<long, List<long>> DictChatID_listMessages = new Dictionary<long, List<long>>();
//public static Dictionary<long, PanelChat> ChatsPanels = new Dictionary<long, PanelChat>();
public static long[] listsIndexChats;
public static List<TdApi.Chat> listChats = new List<TdApi.Chat>();
public static List<TdApi.Message> listMessages = new List<TdApi.Message>();
//public static List<long> Chat_IDs { get; set; }
//public static List<long> Messages_ID { get; set; }
public static int CountChats;
public static long lastMessageID; //для GetChatHistory()
public static long CurChatID; //текущий id чата (для сообщений)
public static long IDuser; //ID пользователя
public static bool flagChat { get; set; } = false;
public static bool flagMessages { get; set; } = false;
public static bool updateMessageFlag;
public static TdApi.UpdateNewMessage updateMessage;
public DelegateChat delegateChat;
public static string fileName;
public MainForm() {
InitializeComponent();
delegateChat += ChangeChat;
LoadClient();
mainForm = this;
//pictureBox2.Image = Properties.Resources.back_picture4;
//pictureBox2.BackgroundImageLayout = ImageLayout.Stretch;
//panel13.BringToFront();
timer1.Start();
//Chat_IDs = new List<long>();
//Messages_ID = new List<long>();
textBox3.Enabled = false;
button8.Enabled = false;
}
public void ChangeChat(long ID) {
foreach (var item in panel15.Controls) {
if (item is PanelChat)
(item as PanelChat).BackColor = Color.FromArgb(255, 30, 41, 55);
(item as PanelChat).label1.BackColor = Color.FromArgb(255, 30, 41, 55);
(item as PanelChat).pictureBox1.BackColor = Color.FromArgb(255, 30, 41, 55);
}
foreach (var item in panel15.Controls) {
if (item is PanelChat)
if (ID == (item as PanelChat).ID) {
(item as PanelChat).color = Color.FromArgb(255, 50, 61, 75);
(item as PanelChat).color1 = Color.FromArgb(255, 50, 61, 75);
(item as PanelChat).color2 = Color.FromArgb(255, 50, 61, 75);
(item as PanelChat).BackColor = Color.FromArgb(255, 50, 61, 75);
(item as PanelChat).label1.BackColor = Color.FromArgb(255, 50, 61, 75);
(item as PanelChat).pictureBox1.BackColor = Color.FromArgb(255, 50, 61, 75);
label7.Text = (item as PanelChat).label1.Text;
}
}
}
public void LoadData() {
//_client.Send(new TdApi.LogOut(), _defaultHandler);
//this.Close();
_client.Send(new TdApi.GetMe(), _defaultHandler);
_client.Send(new TdApi.GetChats(null, int.MaxValue), _defaultHandler);
autoReset.Reset();
autoReset.WaitOne();
CountChats = 0;
foreach (var i in listsIndexChats) {
_client.Send(new TdApi.GetChat(i), _defaultHandler);
}
while (CountChats != listsIndexChats.Length) { }
int a = 0;
for (; a < listChats.Count; a++) {
lastMessageID = 0;
flagMessages = true;
while (flagMessages) {
_client.Send(new TdApi.GetChatHistory(/*listsIndexChats[a]*/listChats[a].Id, lastMessageID, 0, 100, false), _defaultHandler);
autoReset.Reset();
autoReset.WaitOne();
}
}
while (flagChat && a != listsIndexChats.Length - 1) { }
listChats.Reverse();
//listMessages.Reverse();
foreach (var item in listChats) {
PanelChat panel = new PanelChat(delegateChat);
panel.ID = item.Id;
panel.label1.Text = item.Title;
panel.Dock = DockStyle.Top;
panel.Location = new Point(0, panel.CurentHeight);
panel.CurentHeight += 46;
if (item.Photo != null) {
_client.Send(new TdApi.DownloadFile(item.Photo.Big.Id, 1, 0, 0, true), _defaultHandler);
panel.pictureBox1.ImageLocation = item.Photo.Big.Local.Path;
panel.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
}
else
panel.pictureBox1.ImageLocation = @"D:\2. Учёба\4 семестр\4. Сети ЭВМ\Курсовая работа\TelegramClient\Images\person.png";
int k = 0;
foreach (var item1 in listMessages) {
if (item1.ChatId == item.Id) {
if (item1.Content is TdApi.MessageText) {
Label label = new Label();
label.TextAlign = ContentAlignment.MiddleLeft;
label.AutoSize = true;
label.BackColor = Color.FromArgb(255, 112, 133, 153);
label.ForeColor = Color.White;
label.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
label.Size = new Size(300, 50);
label.MaximumSize = new Size(300, label.MaximumSize.Height);
label.MinimumSize = new Size(300, 50);
label.Text = (item1.Content as TdApi.MessageText).Text.Text;
label.BorderStyle = BorderStyle.FixedSingle;
label.Location = new Point(0, 0);
label.BorderStyle = BorderStyle.FixedSingle;
label.TextAlign = ContentAlignment.MiddleLeft;
Panel p = new Panel();
p.AutoSize = true;
p.MaximumSize = new Size(1030, int.MaxValue);
p.MinimumSize = new Size(1030, 50);
//for (int i = 0; i < panel15.Controls.Count; i++) {
// if ((panel15.Controls[i] as PanelChat).ID == item.Id) {
// if ((panel15.Controls[i] as PanelChat).messagesPanel.Controls.Count > 0)
// p.Location = new Point(0, ((panel15.Controls[i] as PanelChat).messagesPanel.Controls[(panel15.Controls[i] as PanelChat).messagesPanel.Controls.Count - 1] as Panel).Location.Y + 10);
// else
// p.Location = new Point(0, 10);
// }
// p.Location = new Point(0, int.MaxValue);
//}
p.Dock = DockStyle.Top;
if ((item1.SenderId as TdApi.MessageSenderUser).UserId == IDuser) {
label.Location = new Point(15, 15);
}
else {
label.Location = new Point(700, 15);
}
p.Controls.Add(label);
panel.messagesPanel.Controls.Add(p);
}
else if (item1.Content is TdApi.MessageSticker) {
_client.Send(new TdApi.DownloadFile((item1.Content as TdApi.MessageSticker).Sticker.Thumbnail.File.Id, 1, 0, 0, true), _defaultHandler);
//downloadReset.Reset();
//downloadReset.WaitOne();
if ((item1.Content as TdApi.MessageSticker).Sticker.Thumbnail.File.Local.Path != "") {
PictureBox pictureBox = new PictureBox();
pictureBox.Size = new Size(250, 250);
pictureBox.MaximumSize = new Size(250, 250);
pictureBox.MinimumSize = new Size(250, 250);
pictureBox.BackgroundImageLayout = ImageLayout.Stretch;
using (convertion.Converter converter = new convertion.Converter((item1.Content as TdApi.MessageSticker).Sticker.Thumbnail.File.Local.Path)) {
ImageConvertOptions options = new ImageConvertOptions { Format = convertion.FileTypes.ImageFileType.Jpg };
converter.Convert(/*(item1.Content as TdApi.MessageSticker).Sticker.Thumbnail.File.Local.Path.Split('.')[0] + ".jpg"*/Path.GetFileNameWithoutExtension((item1.Content as TdApi.MessageSticker).Sticker.Thumbnail.File.Local.Path) + ".jpg", options);
}
pictureBox.ImageLocation = /*(item1.Content as TdApi.MessageSticker).Sticker.Thumbnail.File.Local.Path.Split('.')[0] + ".jpg"*/Path.GetFileNameWithoutExtension((item1.Content as TdApi.MessageSticker).Sticker.Thumbnail.File.Local.Path) + ".jpg";
Panel p = new Panel();
p.AutoSize = true;
p.MaximumSize = new Size(1030, int.MaxValue);
p.MinimumSize = new Size(1030, 50);
p.Dock = DockStyle.Top;
if ((item1.SenderId as TdApi.MessageSenderUser).UserId == IDuser) {
pictureBox.Location = new Point(15, 15);
}
else {
pictureBox.Location = new Point(750, 15);
}
p.Controls.Add(pictureBox);
panel.messagesPanel.Controls.Add(p);
}
}
}
k++;
}
this.panel15.Controls.Add(panel);
this.panel5.Controls.Add(panel.messagesPanel);
}
//_client.Send(new TdApi.LoadChats(null, int.MaxValue), _defaultHandler);
//new Task(() => {
//while (listsChats.Length > 0) {
// autoReset.Reset();
// autoReset.WaitOne();
// _client.Send(new TdApi.GetChatHistory(listsChats[listsChats.Length - 1], Dictionary_chatID_lastMessageID[listsChats[listsChats.Length - 1]], 1, 0, true), _defaultHandler);
//}
//});
//LoadCHats();
//t.Start();
}
//public void LoadPanelChat(PanelChat panelChat) {
//}
//public async void LoadCHats() {
// await Task.Run(() => {
// //flagChat = true;
// //while (flagChat) {
// //while (Chat_IDs.Count > 0) {
// //CurChatID = Chat_IDs.Dequeue();
// _client.Send(new TdApi.GetChat(CurChatID), _defaultHandler);
// //autoReset.Reset();