Skip to content

Commit a5f3615

Browse files
committed
fix(download): temp dir cleanup, cancellation propagation, Tor proxy auto-set
- Wrap yt-dlp download in try/finally for guaranteed temp dir cleanup - Propagate OperationCanceledException instead of swallowing - Remove duplicate format argument from RunVideoDownload - Auto-set yt-dlp proxy to Tor SOCKS when torEnabled and proxy is empty
1 parent d8b4747 commit a5f3615

1 file changed

Lines changed: 83 additions & 73 deletions

File tree

TelegramBot/MediaGet.cs

Lines changed: 83 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -37,98 +37,108 @@ public class MediaGet
3737

3838
string tempDirPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
3939
Directory.CreateDirectory(tempDirPath);
40-
41-
if (Config.torEnabled)
40+
try
4241
{
43-
var proxy = new WebProxy($"socks5://{Config.torSocksHost}:{Config.torSocksPort}");
44-
var handler = new HttpClientHandler { Proxy = proxy, UseProxy = true };
45-
using var httpClient = new HttpClient(handler);
46-
var result = await httpClient.GetStringAsync("https://check.torproject.org/api/ip");
47-
Log.Debug("Tor IP: " + result);
48-
}
42+
if (Config.torEnabled)
43+
{
44+
var proxy = new WebProxy($"socks5://{Config.torSocksHost}:{Config.torSocksPort}");
45+
var handler = new HttpClientHandler { Proxy = proxy, UseProxy = true };
46+
using var httpClient = new HttpClient(handler);
47+
var result = await httpClient.GetStringAsync("https://check.torproject.org/api/ip");
48+
Log.Debug("Tor IP: " + result);
49+
}
4950

50-
var ytdl = new YoutubeDL
51-
{
52-
YoutubeDLPath = "yt-dlp",
53-
OutputFolder = tempDirPath,
54-
OutputFileTemplate = "video.%(ext)s",
55-
OverwriteFiles = true
56-
};
51+
var ytdl = new YoutubeDL
52+
{
53+
YoutubeDLPath = "yt-dlp",
54+
OutputFolder = tempDirPath,
55+
OutputFileTemplate = "video.%(ext)s",
56+
OverwriteFiles = true
57+
};
5758

58-
var overrideOptions = new OptionSet
59-
{
60-
Format = "mp4",
61-
Verbose = true
62-
};
59+
var overrideOptions = new OptionSet();
6360

64-
if (!string.IsNullOrEmpty(Config.proxy))
65-
{
66-
overrideOptions.Proxy = Config.proxy;
67-
}
61+
string effectiveProxy = Config.proxy;
62+
if (string.IsNullOrEmpty(effectiveProxy) && Config.torEnabled)
63+
effectiveProxy = $"socks5://{Config.torSocksHost}:{Config.torSocksPort}";
6864

69-
DateTime lastProgressUpdate = DateTime.MinValue;
70-
var progress = new Progress<DownloadProgress>(p =>
71-
{
72-
if (DateTime.UtcNow - lastProgressUpdate < TimeSpan.FromMilliseconds(Config.videoGetDelay))
73-
return;
65+
if (!string.IsNullOrEmpty(effectiveProxy))
66+
overrideOptions.Proxy = effectiveProxy;
7467

75-
lastProgressUpdate = DateTime.UtcNow;
76-
int percent = (int)(p.Progress * 100);
77-
string statusText = $"[download] {percent}%";
78-
if (!string.IsNullOrEmpty(p.DownloadSpeed))
79-
statusText += $" at {p.DownloadSpeed}";
80-
if (!string.IsNullOrEmpty(p.ETA))
81-
statusText += $" ETA {p.ETA}";
68+
DateTime lastProgressUpdate = DateTime.MinValue;
69+
var progress = new Progress<DownloadProgress>(p =>
70+
{
71+
if (DateTime.UtcNow - lastProgressUpdate < TimeSpan.FromMilliseconds(Config.videoGetDelay))
72+
return;
8273

83-
if (Config.showVideoDownloadProgress)
84-
Log.Debug($"Video download progress: {statusText}");
74+
lastProgressUpdate = DateTime.UtcNow;
75+
int percent = (int)(p.Progress * 100);
76+
string statusText = $"[download] {percent}%";
77+
if (!string.IsNullOrEmpty(p.DownloadSpeed))
78+
statusText += $" at {p.DownloadSpeed}";
79+
if (!string.IsNullOrEmpty(p.ETA))
80+
statusText += $" ETA {p.ETA}";
8581

86-
_ = Task.Run(async () =>
87-
{
88-
try
89-
{
90-
await botClient.EditMessageText(
91-
statusMessage.Chat.Id,
92-
statusMessage.MessageId,
93-
statusText,
94-
cancellationToken: cancellationToken);
95-
}
96-
catch (Exception ex)
82+
if (Config.showVideoDownloadProgress)
83+
Log.Debug($"Video download progress: {statusText}");
84+
85+
_ = Task.Run(async () =>
9786
{
98-
Log.Debug(ex, "Error editing message.");
99-
}
87+
try
88+
{
89+
await botClient.EditMessageText(
90+
statusMessage.Chat.Id,
91+
statusMessage.MessageId,
92+
statusText,
93+
cancellationToken: cancellationToken);
94+
}
95+
catch (Exception ex)
96+
{
97+
Log.Debug(ex, "Error editing message.");
98+
}
99+
});
100100
});
101-
});
102101

103-
var downloadResult = await ytdl.RunVideoDownload(
104-
videoUrl,
105-
format: "mp4",
106-
ct: cancellationToken,
107-
progress: progress,
108-
overrideOptions: overrideOptions);
102+
var downloadResult = await ytdl.RunVideoDownload(
103+
videoUrl,
104+
ct: cancellationToken,
105+
progress: progress,
106+
overrideOptions: overrideOptions);
109107

110-
if (downloadResult.Success)
111-
{
112-
string filePath = downloadResult.Data;
113-
Log.Debug($"Final file path: {filePath}");
108+
if (downloadResult.Success)
109+
{
110+
string filePath = downloadResult.Data;
111+
Log.Debug($"Final file path: {filePath}");
112+
113+
if (System.IO.File.Exists(filePath))
114+
{
115+
byte[] videoBytes = await System.IO.File.ReadAllBytesAsync(filePath, cancellationToken);
116+
return new List<byte[]> { videoBytes };
117+
}
114118

115-
if (System.IO.File.Exists(filePath))
119+
Log.Error($"Final file does not exist: {filePath}");
120+
}
121+
else
116122
{
117-
byte[] videoBytes = await System.IO.File.ReadAllBytesAsync(filePath, cancellationToken);
118-
Directory.Delete(tempDirPath, recursive: true);
119-
return new List<byte[]> { videoBytes };
123+
string errors = string.Join("\n", downloadResult.ErrorOutput);
124+
Log.Error("Video download failed: " + errors);
120125
}
121126

122-
Log.Error($"Final file does not exist: {filePath}");
127+
return null;
123128
}
124-
else
129+
catch (OperationCanceledException)
125130
{
126-
string errors = string.Join("\n", downloadResult.ErrorOutput);
127-
Log.Error("Video download failed: " + errors);
131+
throw;
128132
}
129-
130-
Directory.Delete(tempDirPath, recursive: true);
131-
return null;
133+
finally
134+
{
135+
if (Directory.Exists(tempDirPath))
136+
Directory.Delete(tempDirPath, recursive: true);
137+
}
138+
}
139+
catch (OperationCanceledException)
140+
{
141+
throw;
132142
}
133143
catch (Exception ex)
134144
{

0 commit comments

Comments
 (0)