Files
hDM/src/DownloadManager.BrowserBridge/Program.cs
2026-05-04 01:19:04 +03:00

103 lines
3.4 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.IO;
using System.IO.Pipes;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace DownloadManager.BrowserBridge;
public class BridgeMessage
{
[JsonProperty("action")]
public string Action { get; set; } = string.Empty;
[JsonProperty("url")]
public string Url { get; set; } = string.Empty;
[JsonProperty("filename")]
public string? FileName { get; set; }
[JsonProperty("referrer")]
public string? Referrer { get; set; }
}
class Program
{
static async Task Main(string[] args)
{
var stdin = Console.OpenStandardInput();
var stdout = Console.OpenStandardOutput();
while (true)
{
// Chrome protokolü: 4 byte (little-endian uint32) = mesaj uzunluğu
var lenBuf = new byte[4];
int read = await stdin.ReadAsync(lenBuf, 0, 4);
if (read < 4) break;
var length = BitConverter.ToUInt32(lenBuf, 0);
var msgBuf = new byte[length];
int msgRead = 0;
while (msgRead < length)
{
int r = await stdin.ReadAsync(msgBuf, msgRead, (int)length - msgRead);
if (r <= 0) break;
msgRead += r;
}
var json = Encoding.UTF8.GetString(msgBuf);
var msg = JsonConvert.DeserializeObject<BridgeMessage>(json);
if (msg != null)
{
await SendToMainAppAsync(msg);
// Mesaj gönderildikten sonra çık (Native messaging her mesaj için yeni process açabiliyor)
break;
}
}
}
static async Task SendToMainAppAsync(BridgeMessage msg)
{
try
{
// Ana uygulamanın çalışıp çalışmadığını kontrol et
var processes = System.Diagnostics.Process.GetProcessesByName("DownloadManager.WPF");
if (processes.Length == 0)
{
// Uygulama çalışmıyorsa başlat (Yolu bulmaya çalışalım)
string appPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DownloadManager.WPF.exe");
// Geliştirme ortamı için alternatif yollar
if (!File.Exists(appPath))
appPath = @"D:\Calismalar\AI\hDM\DownloadManager\src\DownloadManager.WPF\bin\Release\net8.0-windows\DownloadManager.WPF.exe";
if (File.Exists(appPath))
{
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(appPath) { UseShellExecute = true });
// Uygulamanın açılması ve pipe'ı başlatması için biraz bekleyelim
await Task.Delay(3000);
}
}
using var pipe = new NamedPipeClientStream(".", "DownloadManagerPipe",
PipeDirection.Out, PipeOptions.Asynchronous);
// Timeout'u 10 saniyeye çıkaralım (Uygulama yeni açılıyorsa gerekebilir)
await pipe.ConnectAsync(10000);
var json = JsonConvert.SerializeObject(msg);
var data = Encoding.UTF8.GetBytes(json);
await pipe.WriteAsync(data);
await pipe.FlushAsync();
}
catch (Exception ex)
{
File.AppendAllText("bridge_error.log", $"{DateTime.Now}: Bağlantı hatası ({msg.Url}): {ex.Message}\n");
}
}
}