81 lines
1.8 KiB
C#
81 lines
1.8 KiB
C#
using System;
|
|
using System.IO;
|
|
using System.Net.Http;
|
|
using System.Text;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using Newtonsoft.Json;
|
|
namespace Tesses.YouTubeDownloader
|
|
{
|
|
public static class SSEExtensions
|
|
{
|
|
public static async Task<SSEClient> GetSSEClientAsync(this HttpClient clt,string url)
|
|
{
|
|
var strm=await clt.GetStreamAsync(url);
|
|
return new SSEClient(strm);
|
|
}
|
|
}
|
|
|
|
public class SSEEvent : EventArgs
|
|
{
|
|
public SSEEvent(string data)
|
|
{
|
|
Data=data;
|
|
}
|
|
public string Data {get;set;}
|
|
public T ParseJson<T>()
|
|
{
|
|
return JsonConvert.DeserializeObject<T>(Data);
|
|
}
|
|
}
|
|
public class SSEClient
|
|
{
|
|
Stream strm;
|
|
|
|
public SSEClient(Stream strm)
|
|
{
|
|
this.strm=strm;
|
|
}
|
|
public EventHandler<SSEEvent> Event;
|
|
|
|
public async Task ReadEventsAsync(CancellationToken token=default(CancellationToken))
|
|
{
|
|
try{
|
|
using(var sr = new StreamReader(strm)){
|
|
token.Register(()=>{
|
|
sr.Dispose();
|
|
});
|
|
|
|
while(!token.IsCancellationRequested)
|
|
{
|
|
|
|
string text=await sr.ReadLineAsync();
|
|
if(!string.IsNullOrWhiteSpace(text))
|
|
Event?.Invoke(this,new SSEEvent(text.Substring(6)));
|
|
}
|
|
}
|
|
}catch(Exception ex)
|
|
{
|
|
_=ex;
|
|
}
|
|
}
|
|
|
|
}
|
|
public class ProgressItem
|
|
{
|
|
public long Length {get;set;}
|
|
public double Percent {get;set;}
|
|
|
|
public SavedVideo Video {get;set;}
|
|
|
|
public bool StartEvent {get;set;}
|
|
public bool StopEvent {get;set;}
|
|
public bool BellEvent {get;set;}
|
|
|
|
public bool ErrorEvent {get;set;}
|
|
public string Error {get;set;}
|
|
public string Id {get;set;}
|
|
public string Message {get;set;}
|
|
public string ExceptionName {get;set;}
|
|
}
|
|
} |