-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSuccessForm.cs
More file actions
607 lines (524 loc) · 23 KB
/
Copy pathSuccessForm.cs
File metadata and controls
607 lines (524 loc) · 23 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
using System;
using System.Collections.Generic;
using System.Drawing.Text;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using TL;
using TLSharp.Core.Network.Exceptions;
using WTelegram;
namespace Telegram_File_downloader
{
public partial class Telepop : Form
{
private Client client;
private List<string> _allChannels; // Store all channels for easy searching
private string _downloadFolderPath;
private int _downloadedFilesCounter = 0; // Counter for downloaded files
private CancellationTokenSource _cancellationTokenSource; // Source for the cancellation token
private const string SelectionFilePath = "selected_channels.txt"; // Path to the file where selections are saved
public Telepop(Client client)
{
InitializeComponent();
this.client = client;
lblprogressshow.Text = "";
// Redirect console output
Console.SetOut(new TextBoxWriter(txtConsoleOutput));
// Load channels initially when the form is created
LoadChannelsAsync();
// Example console output
Console.WriteLine("Console output redirected to TextBox.");
}
// Event handler for the Sort button
private void btnSortChannels_Click(object sender, EventArgs e)
{
if (_allChannels != null)
{
// Sort channels alphabetically
var sortedChannels = _allChannels.OrderBy(channel => channel).ToList();
// Clear and repopulate the CheckedListBox with sorted channels
channelCheckedListBox.Items.Clear();
channelCheckedListBox.Items.AddRange(sortedChannels.ToArray());
}
else
{
MessageBox.Show("No channels available to sort.");
}
}
private void Telepop_FormClosing(object sender, FormClosingEventArgs e)
{
// Log out by disposing of the client
if (client != null)
{
client.Dispose();
client = null;
Console.WriteLine("Logged out successfully.");
}
}
private void BtnLogout_Click(object sender, EventArgs e)
{
// Dispose of the client to log out
client?.Dispose();
client = null;
// Show the LoginForm
LoginForm loginForm = new LoginForm();
loginForm.Show();
// Close the current form
this.Close();
}
private void BtnSaveSelection_Click(object sender, EventArgs e)
{
SaveSelectedChannels();
}
private void BtnLoadSelection_Click(object sender, EventArgs e)
{
LoadSelectedChannels();
}
private void SaveSelectedChannels()
{
try
{
var selectedChannels = channelCheckedListBox.CheckedItems.Cast<string>().ToList();
File.WriteAllLines(SelectionFilePath, selectedChannels);
MessageBox.Show("Channel selection saved successfully.");
}
catch (Exception ex)
{
MessageBox.Show($"Error saving channel selection: {ex.Message}");
}
}
private void LoadSelectedChannels()
{
try
{
if (File.Exists(SelectionFilePath))
{
var savedChannels = File.ReadAllLines(SelectionFilePath).ToList();
for (int i = 0; i < channelCheckedListBox.Items.Count; i++)
{
var channel = channelCheckedListBox.Items[i].ToString();
channelCheckedListBox.SetItemChecked(i, savedChannels.Contains(channel));
}
}
else
{
MessageBox.Show("No saved selection found.");
}
}
catch (Exception ex)
{
MessageBox.Show($"Error loading channel selection: {ex.Message}");
}
}
private async Task<List<string>> FetchChannelsAsync()
{
var dialogs = await client.Messages_GetAllDialogs(); // Retrieve all dialogs
var channels = new List<string>();
foreach (var chat in dialogs.chats.Values)
{
if (chat is Channel channel)
{
channels.Add(channel.title); // Add channel titles to the list
}
}
return channels;
}
private async void LoadChannelsAsync()
{
try
{
channelCheckedListBox.Items.Clear(); // Clear the existing items
_allChannels = await FetchChannelsAsync(); // Fetch all channels
channelCheckedListBox.Items.AddRange(_allChannels.ToArray()); // Add new items
}
catch (Exception ex)
{
MessageBox.Show("Error loading channels: " + ex.Message);
}
}
private void BtnUpdate_Click(object sender, EventArgs e)
{
LoadChannelsAsync(); // Reload channels when update button is clicked
}
private void btnSearchChannels_Click(object sender, EventArgs e)
{
SearchChannels(txtSearchChannels.Text);
SaveSelectedChannels();
}
private void TxtSearchChannels_TextChanged(object sender, EventArgs e)
{
SearchChannels(txtSearchChannels.Text);
SaveSelectedChannels();
}
private void SearchChannels(string searchText)
{
if (string.IsNullOrWhiteSpace(searchText))
{
// If search text is empty, display all channels
channelCheckedListBox.Items.Clear();
channelCheckedListBox.Items.AddRange(_allChannels.ToArray());
}
else
{
// Filter channels based on search text
var filteredChannels = _allChannels
.Where(channel => channel.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0)
.ToArray();
// Update CheckedListBox with filtered channels
channelCheckedListBox.Items.Clear();
channelCheckedListBox.Items.AddRange(filteredChannels);
}
}
private void BtnChooseFolder_Click(object sender, EventArgs e)
{
using (var folderBrowserDialog = new FolderBrowserDialog())
{
// Show the folder browser dialog
DialogResult result = folderBrowserDialog.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(folderBrowserDialog.SelectedPath))
{
_downloadFolderPath = folderBrowserDialog.SelectedPath; // Store the chosen folder path
lblDownloadFolder.Text = $"{_downloadFolderPath}"; // Update label with path
}
}
}
private async void BtnDownload_Click(object sender, EventArgs e)
{
try
{
// Disable buttons while downloading
SetControlsEnabled(false);
if (!ValidateInputs()) return;
_cancellationTokenSource = new CancellationTokenSource();
DateTime fromDate = dtpFromDate.Value.Date.ToUniversalTime();
DateTime toDate = dtpToDate.Value.Date.AddDays(1).AddTicks(-1).ToUniversalTime(); // End of the day in UTC
var selectedFileTypes = GetSelectedFileTypes();
var selectedChannels = channelCheckedListBox.CheckedItems.Cast<string>().ToList();
foreach (var channelTitle in selectedChannels)
{
await DownloadFilesFromChannel(channelTitle, fromDate, toDate, selectedFileTypes, _cancellationTokenSource.Token);
}
MessageBox.Show("Download complete!");
}
catch (OperationCanceledException)
{
// Catch the OperationCanceledException and suppress further exceptions
if (_cancellationTokenSource.IsCancellationRequested)
{
Console.WriteLine("Download canceled!");
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred during download: {ex.Message}");
}
finally
{
// Re-enable buttons when done
SetControlsEnabled(true);
}
}
private void SetControlsEnabled(bool enabled)
{
btnDownload.Enabled = enabled;
btnLogout.Enabled = enabled;
btnSaveSelection.Enabled = enabled;
btnLoadSelection.Enabled = enabled;
btnChooseFolder.Enabled = enabled;
BtnUpdate.Enabled = enabled;
txtSearchChannels.Enabled = enabled;
dtpFromDate.Enabled = enabled;
dtpToDate.Enabled = enabled;
numMinSize.Enabled = enabled;
numMaxSize.Enabled = enabled;
chkTxt.Enabled = enabled;
chkRar.Enabled = enabled;
chkZip.Enabled = enabled;
chk7z.Enabled = enabled;
channelCheckedListBox.Enabled = enabled;
btnSortChannels.Enabled = enabled;
}
private bool ValidateInputs()
{
// Validate date selection
if (dtpFromDate.Value >= dtpToDate.Value)
{
MessageBox.Show("The 'From' date must be earlier than the 'To' date.");
return false;
}
// Validate download folder
if (string.IsNullOrEmpty(_downloadFolderPath))
{
MessageBox.Show("Please select a download folder.");
return false;
}
// Validate channel selection
if (channelCheckedListBox.CheckedItems.Count == 0)
{
MessageBox.Show("Please select at least one channel.");
return false;
}
return true;
}
private List<string> GetSelectedFileTypes()
{
var fileTypes = new List<string>();
if (chkTxt.Checked) fileTypes.Add(".txt");
if (chkTxt.Checked) fileTypes.Add(".rtf");
if (chkRar.Checked) fileTypes.Add(".rar");
if (chkZip.Checked) fileTypes.Add(".zip");
if (chk7z.Checked) fileTypes.Add(".7z");
// If no file type is selected, consider downloading all types
if (!fileTypes.Any())
{
fileTypes.Add(".txt");
fileTypes.Add(".rtf");
fileTypes.Add(".rar");
fileTypes.Add(".zip");
fileTypes.Add(".7z");
}
return fileTypes;
}
private async Task DownloadFilesFromChannel(string channelTitle, DateTime fromDate, DateTime toDate, List<string> selectedFileTypes, CancellationToken cancellationToken)
{
try
{
var dialogs = await client.Messages_GetAllDialogs();
var channel = dialogs.chats.Values.OfType<Channel>().FirstOrDefault(c => c.title == channelTitle);
if (channel == null)
{
MessageBox.Show($"Channel {channelTitle} not found.");
return;
}
// Initialize date filter
var offsetDate = toDate;
// Fetch messages in the specified date range
var allMessages = new List<TL.Message>();
const int limit = 100; // Adjust the limit as needed
bool hasMoreMessages = true;
while (hasMoreMessages)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
var messageHistory = await client.Messages_GetHistory(channel, limit: limit, offset_date: offsetDate);
var messagesInRange = messageHistory.Messages
.OfType<TL.Message>()
.Where(msg => msg.date >= fromDate && msg.date <= toDate)
.ToList();
allMessages.AddRange(messagesInRange);
var lastMessage = messageHistory.Messages.OfType<TL.Message>().LastOrDefault();
if (lastMessage == null || lastMessage.date < fromDate)
{
hasMoreMessages = false;
}
else
{
offsetDate = lastMessage.date;
}
if (!messagesInRange.Any())
{
break;
}
}
catch (FloodException ex) when (ex.Message.Contains("FLOOD_WAIT"))
{
int waitTime = int.Parse(ex.Message.Split('_').Last());
MessageBox.Show($"Flood wait error. Retrying after {waitTime} seconds...");
await Task.Delay(waitTime * 1000, cancellationToken);
}
}
foreach (var msg in allMessages)
{
// Check for cancellation before processing each message
cancellationToken.ThrowIfCancellationRequested();
if (msg.media is TL.MessageMediaDocument mediaDoc)
{
var doc = mediaDoc.document as TL.Document;
if (doc != null && doc.mime_type != null)
{
cancellationToken.ThrowIfCancellationRequested();
var fileSizeMB = doc.size / (1024.0 * 1024); // Convert bytes to MB
// Convert NumericUpDown values to double for comparison
double minSizeMB = (double)numMinSize.Value;
double maxSizeMB = (double)numMaxSize.Value;
if (fileSizeMB < minSizeMB || fileSizeMB > maxSizeMB)
{
continue; // Skip files that do not meet the size criteria
}
// Check file extension against selected file types
string extension = Path.GetExtension(doc.Filename).ToLower();
// Only download if the extension is in the selected file types
if (selectedFileTypes.Contains(extension))
{
await DownloadFile(doc, channelTitle, cancellationToken);
}
}
}
}
}
catch (OperationCanceledException)
{
lblprogressshow.Text = "";
Console.WriteLine("Download Cancelled!.....");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred during download: {ex.Message}");
}
}
private async Task DownloadFile(Document document, string channelTitle, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
// Get the original filename from the document
string originalFilename = document.Filename;
// Define invalid characters typically not allowed in filenames
char[] invalidChars = Path.GetInvalidFileNameChars();
// Sanitize filename using the SanitizeName method
string sanitizedFilename = SanitizeName(originalFilename, invalidChars, "default_filename");
string extension = Path.GetExtension(originalFilename);
// Ensure the extension is appended only once to avoid duplication
if (!sanitizedFilename.EndsWith(extension, StringComparison.OrdinalIgnoreCase))
{
sanitizedFilename += extension;
}
// Determine the file path in the download folder
string filePath = Path.Combine(_downloadFolderPath, sanitizedFilename);
// Check if the file already exists and has the same size
if (File.Exists(filePath))
{
long existingFileSize = new FileInfo(filePath).Length;
if (existingFileSize == document.size)
{
return; // File already exists and sizes match, skip downloading
}
// If sizes differ, create a new file with an incremented index
int fileIndex = 1;
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(sanitizedFilename);
while (File.Exists(filePath))
{
filePath = Path.Combine(_downloadFolderPath, $"{fileNameWithoutExtension} ({fileIndex++}){extension}");
}
}
// Download the file
using (var cts = new CancellationTokenSource())
{
await DownloadDocumentLineByLineAsync(document, filePath, cts.Token);
}
// Update the downloaded files counter and UI label
_downloadedFilesCounter++;
lblDownloadedCounter.Text = $"Downloaded Files: {_downloadedFilesCounter}";
}
catch (OperationCanceledException)
{
// Handle cancellation gracefully
if (cancellationToken.IsCancellationRequested)
{
lblprogressshow.Text = "";
}
}
catch (Exception ex)
{
// Handle other exceptions and log errors
Console.WriteLine($"An error occurred in file download: {ex.Message}");
}
}
private async Task DownloadDocumentLineByLineAsync(Document document, string filePath, CancellationToken cancellationToken)
{
// Reset progress to zero
long totalBytes = document.size; // The total size of the document
long bytesReceived = 0; // To track the number of bytes received so far
int mbtotalBytes = (int)(totalBytes / 1024 / 1024);
lblfilesize.Text = $"Recent File Size: {mbtotalBytes} MB";
using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
using (var streamWriter = new StreamWriter(fileStream))
{
using (var memoryStream = new MemoryStream())
{
await client.DownloadFileAsync(document, memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
using (var streamReader = new StreamReader(memoryStream))
{
// Check for cancellation at the start of each loop iteration
cancellationToken.ThrowIfCancellationRequested();
string line;
while ((line = await streamReader.ReadLineAsync()) != null)
{
// Calculate bytes received
bytesReceived += Encoding.UTF8.GetByteCount(line + Environment.NewLine);
// Report progress
double percentComplete = (double)bytesReceived / totalBytes * 100;
percentComplete = Math.Min(percentComplete, 100.0); // Clamp to 100%
Console.WriteLine($"{percentComplete:F2}%"); // For debugging purposes
// Write each line to the file
await streamWriter.WriteLineAsync(line);
}
}
}
}
}
// Method to sanitize filenames by removing invalid characters
private string SanitizeName(string name, char[] invalidChars, string defaultName)
{
// Replace invalid characters with underscores
foreach (char invalidChar in invalidChars)
{
name = name.Replace(invalidChar, '_');
}
// Additional sanitization for known problematic characters
string[] additionalInvalidChars = { "@", "#", " ", ":", "/", "\\", "*", "?", "\"", "<", ">", "|", "⚡️", "👍", "🐍", "💸", "🦅", "⛅️", "🌩️", "🌓" };
foreach (string invalidChar in additionalInvalidChars)
{
name = name.Replace(invalidChar, "_");
}
// Limit name length to prevent path length issues
if (name.Length > 100)
{
name = name.Substring(0, 100);
}
// If name is empty after sanitization, assign a default name
if (string.IsNullOrWhiteSpace(name))
{
name = defaultName;
}
return name;
}
private void txt_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
// Call the button click event or the download logic directly
BtnDownload_Click(sender, e);
// Suppress the default beep sound on Enter key press
e.SuppressKeyPress = true;
}
}
private string SanitizeFilename(string filename)
{
return SanitizeName(filename, Path.GetInvalidFileNameChars(), "unnamed_file");
}
private string SanitizeFolderName(string folderName)
{
return SanitizeName(folderName, Path.GetInvalidPathChars(), "unnamed_folder");
}
// Add this method for the Stop button click event
private void btnCancel_Click(object sender, EventArgs e)
{
if (_cancellationTokenSource != null && !_cancellationTokenSource.IsCancellationRequested)
{
var result = MessageBox.Show("Are you sure you want to cancel the download?", "Confirm Cancel", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
lblprogressshow.Text = "Please wait for the recent file to be downloaded.....";
_cancellationTokenSource.Cancel();
_downloadedFilesCounter = 0;
}
}
}
}
}