|
- using log4net;
- using Newtonsoft.Json.Linq;
- using Newtonsoft.Json;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Sockets;
- using System.Reflection;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Web.UI;
- using static THUploadOss.Common;
- using System.Net.Http;
- using System.Runtime.Remoting.Contexts;
- using uPLibrary.Networking.M2Mqtt.Messages;
- using uPLibrary.Networking.M2Mqtt;
-
- namespace THUploadOss
- {
- internal class THHttpServe
- {
- public string m_listenerUrl;
- private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
- public string m_callback;
- public HttpListener httpListener;
- public bool StartListener()
- {
- try
- {
- httpListener = new HttpListener();
- httpListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
- httpListener.Prefixes.Add(m_listenerUrl);
- httpListener.Start();
- httpListener.BeginGetContext(ListenerHandle, httpListener); //开始监听
- return true;
- }
- catch (Exception e)
- {
- Logger.WriteError("THHttpServe: StartListener-ERROR:" + $"服务器启动失败!{e.Message}");
- return false;
- }
- }
-
- public void ListenerHandle(IAsyncResult result)
- {
- try
- {
- httpListener = result.AsyncState as HttpListener;
- if (httpListener == null) return;
- if (httpListener.IsListening)
- {
- httpListener.BeginGetContext(ListenerHandle, httpListener); //继续监听
- HttpListenerContext context = httpListener.EndGetContext(result);
- HttpListenerRequest request = context.Request;
- Stream stream = context.Request.InputStream;
- StreamReader reader = new StreamReader(stream, Encoding.UTF8);
- string content = reader.ReadToEnd();
- Logger.WriteInfo("THHttpServe: ListenerHandle()-收到消息:" + content);
- switch (request.RawUrl)
- {
- case "/upload/start":
- {
- dynamic jsonObj = JsonConvert.DeserializeObject(content);
- if (StsrtDownload != -1)
- {
- UploadResponse(context, (int)UPLOAD.UPLOAD_START_FAIL);
- return;
- }
- lock (lockFileList)
- {
- for (int i = FileList.Count - 1; i >= 0; i--)
- {
- FileList.Remove(FileList[i]);
- }
- }
- RequestId = jsonObj.requestId;
- m_callback = jsonObj.callbackUrl;
- DownloadFinsh = 0;
- StsrtDownload = 1;
- Status = (int)UPLOAD_STATUS.Preparation;
- UploadResponse(context, (int)UPLOAD.UPLOAD_OK);
- }
- break;
- case "/upload/stop":
- {
- if (StsrtDownload == -1)
- {
- UploadResponse(context,(int)UPLOAD.UPLOAD_STOP_FAIL);
- return;
- }
- DownloadFinsh = -1;
- StsrtDownload = -1;
- //Status = (int)UPLOAD_STATUS.Ccancellation;
- UploadResponse(context, (int)UPLOAD.UPLOAD_OK);
- }
- break;
- case "/upload/callback":
- {
- UploadStatusResponse(context);
- }
- break;
- }
- }
- }
- catch (Exception ex)
- {
- Logger.WriteError("THHttpServe: ListenerHandle" + $"异常:{ex.StackTrace}");
- }
- }
- public void UploadStatus()
- {
- Logger.WriteError("Http UploadStatus: StsrtDownload:" + StsrtDownload + "Status:" + Status);
- if (StsrtDownload != -1 || Status != (int)UPLOAD_STATUS.Preparation)
- {
- JObject data = new JObject
- {
- { "requestId", RequestId },
- { "errorCode", "" },
- { "errorMsg", "" },
- { "status", Status },// 状态:待执行 5 执行中 10 完成 15 超时 20 失败 25
- { "currentTime", DateTime.Now.ToString() }
- };
- JArray imgjArray = new JArray();
- JArray videojArray = new JArray();
- lock (lockFileList)
- {
- foreach (FileStates file in FileList)
- {
- if (file.fileType == "pic")
- {
- JObject img = new JObject
- {
- { "fileName", file.fileName},
- { "imageUrl",file.url },
- { "status",file.status },
- { "progress",file.progress}
- };
- imgjArray.Add(img);
- }
- if (file.fileType == "video")
- {
- JObject video = new JObject
- {
- { "fileName", file.fileName},
- { "videoUrl",file.url },
- { "status",file.status },
- { "progress",file.progress }
- };
- videojArray.Add(video);
- }
- }
- }
- data.Add("imageList", new JArray(imgjArray));
- data.Add("videoList", new JArray(videojArray));
- // 将对象序列化为 JSON 字符串
- string json = JsonConvert.SerializeObject(data);
- Logger.WriteInfo("THHttpServe: UploadStatus-交互日志:" + json);
- try
- {
- HttpClient client = new HttpClient();
- HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");
- HttpResponseMessage response = client.PostAsync(m_callback, content).Result;
-
- // 检查响应状态码
- if (response.IsSuccessStatusCode)
- {
- string responseBody = response.Content.ReadAsStringAsync().Result;
- }
- else
- {
- Logger.WriteError("THHttpServe: UploadStatus-Error sending GET request: " + response.StatusCode);
- }
- }
- catch (Exception ex)
- {
- Logger.WriteError("THHttpServe: UploadStatus-An error occurred: " + ex.Message);
- }
- if (Status == (int)UPLOAD_STATUS.Complete)
- Status = (int)UPLOAD_STATUS.Preparation;
- if (Status == (int)UPLOAD_STATUS.Fail)
- Status = (int)UPLOAD_STATUS.Preparation;
- if (Status == (int)UPLOAD_STATUS.Ccancellation)
- Status = (int)UPLOAD_STATUS.Preparation;
- }
- System.Threading.Thread.Sleep(5000);
- }
- public void UploadStatusResponse(HttpListenerContext context)
- {
- //构造Response响应
- HttpListenerResponse response = context.Response;
- response.StatusCode = 200;
- response.ContentType = "text/html;";
- response.ContentEncoding = Encoding.UTF8;
-
- using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
- {
- JObject data = new JObject
- {
- { "requestId", RequestId },
- { "errorCode", "" },
- { "errorMsg", "" },
- { "status", Status },// 状态:待执行 5 执行中 10 完成 15 超时 20 失败 25
- { "currentTime", DateTime.Now.ToString() }
- };
- JArray imgjArray = new JArray();
- JArray videojArray = new JArray();
- lock (lockFileList)
- {
- foreach (FileStates file in FileList)
- {
- if (file.fileType == "pic")
- {
- JObject img = new JObject
- {
- { "fileName", file.fileName},
- { "imageUrl",file.url },
- { "status",file.status },
- { "progress",file.progress}
- };
- imgjArray.Add(img);
- }
- if (file.fileType == "video")
- {
- JObject video = new JObject
- {
- { "fileName", file.fileName},
- { "videoUrl",file.url },
- { "status",file.status },
- { "progress",file.progress }
- };
- videojArray.Add(video);
- }
- }
- }
- data.Add("imageList", new JArray(imgjArray));
- data.Add("videoList", new JArray(videojArray));
- // 将对象序列化为 JSON 字符串
- string json = JsonConvert.SerializeObject(data);
-
- Logger.WriteInfo("THHttpServe: UploadStatusResponse-交互日志:" + json);
- writer.Write(json);
- writer.Close();
- response.Close();
- }
- }
- public void RtmpResponse(HttpListenerContext context, int code)
- {
- //构造Response响应
- HttpListenerResponse response = context.Response;
- response.StatusCode = 200;
- response.ContentType = "text/html;";
- response.ContentEncoding = Encoding.UTF8;
-
- using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
- {
- string jsonret = $"{{\"code\":{code},\"msg\":\"{UPLOAD_RESULT[code]}\",\"data\":\"{null}\",\"class\":\"{null}\"}}";
- Logger.WriteInfo("THHttpServe: RtmpResponse-交互日志:" + jsonret);
- writer.Write(jsonret);
- writer.Close();
- response.Close();
- }
- }
-
- public void UploadResponse(HttpListenerContext context,int code)
- {
- //构造Response响应
- HttpListenerResponse response = context.Response;
- response.StatusCode = 200;
- response.ContentType = "text/html;";
- response.ContentEncoding = Encoding.UTF8;
-
- using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
- {
- string jsonret = $"{{\"code\":{code},\"msg\":\"{UPLOAD_RESULT[code]}\",\"data\":\"{null}\",\"class\":\"{null}\"}}";
- Logger.WriteInfo("THHttpServe: UploadResponse-交互日志:" + jsonret);
- writer.Write(jsonret);
- writer.Close();
- response.Close();
- }
- }
-
- public bool CloseRtmpChannel()
- {
- // 创建HttpClient实例
- HttpClient client = new HttpClient();
- try
- {
- // 发送GET请求并获取响应
- HttpResponseMessage response = client.GetAsync("http://localhost:19610/api/v1/getChannelList?offset=0&row=50").Result;
- // 检查响应是否成功
- if (response.IsSuccessStatusCode)
- {
- // 读取响应内容
- string content = response.Content.ReadAsStringAsync().Result;
- Logger.WriteInfo("CloseRtmpChannel" + content);
-
- dynamic jsonObj = JsonConvert.DeserializeObject(content);
- string srcURL = jsonObj.ChannelList[0].srcURL;
- srcURL = WebUtility.UrlEncode(srcURL).Replace("%3A", ":");
- string dstURL = jsonObj.ChannelList[0].dstURL;
- dstURL = WebUtility.UrlEncode(dstURL).Replace("%3A", ":");
-
- string closeUrl = "http://127.0.0.1:19610/api/v1/updateChannel?indexCode=" + jsonObj.ChannelList[0].indexcode + "&name=" + jsonObj.ChannelList[0].name + "&srcURL=%22" + srcURL + "%22&connectType=" + jsonObj.ChannelList[0].connectType + "&timeout=" + jsonObj.ChannelList[0].connectTimeout + "&mediaType=video" + "&dstURL=" + dstURL + "&dstFormat=rtmp&enable=false";
-
- // 输出响应内容
- HttpResponseMessage closeResponse = client.GetAsync(closeUrl).Result;
- if (closeResponse.IsSuccessStatusCode)
- {
- string closeContent = closeResponse.Content.ReadAsStringAsync().Result;
- Logger.WriteInfo("CloseRtmpChannel" + closeContent);
- if (closeContent == "OK")
- return true;
- else
- return false;
- }
- }
- else
- {
- Logger.WriteError("THHttpServe: CloseRtmpChannel-请求失败,状态码:" + response.StatusCode);
- return false;
- }
- }
- catch (Exception e)
- {
- Logger.WriteError($"THHttpServe: CloseRtmpChannel-其他错误发生: {e.Message}");
- return false;
- }
- return false;
- }
- public bool OpenRtmpChannel()
- {
- // 创建HttpClient实例
- HttpClient client = new HttpClient();
- try
- {
- // 发送GET请求并获取响应
- HttpResponseMessage response = client.GetAsync("http://localhost:19610/api/v1/getChannelList?offset=0&row=50").Result;
-
- // 检查响应是否成功
- if (response.IsSuccessStatusCode)
- {
- // 读取响应内容
- string content = response.Content.ReadAsStringAsync().Result;
- // 输出响应内容
- Logger.WriteInfo("OpenRtmpChannel: "+content);
- dynamic jsonObj = JsonConvert.DeserializeObject(content);
- string srcURL = jsonObj.ChannelList[0].srcURL;
- srcURL = WebUtility.UrlEncode(srcURL).Replace("%3A", ":");
- string dstURL = jsonObj.ChannelList[0].dstURL;
- dstURL = WebUtility.UrlEncode(dstURL).Replace("%3A", ":");
-
- string openUrl = "http://127.0.0.1:19610/api/v1/updateChannel?indexCode=" + jsonObj.ChannelList[0].indexcode + "&name=" + jsonObj.ChannelList[0].name + "&srcURL=%22" + srcURL + "%22&connectType=" + jsonObj.ChannelList[0].connectType + "&timeout=" + jsonObj.ChannelList[0].connectTimeout + "&mediaType=video" + "&dstURL=" + dstURL + "&dstFormat=rtmp&enable=true";
- // 输出响应内容
- HttpResponseMessage openResponse = client.GetAsync(openUrl).Result;
- if (openResponse.IsSuccessStatusCode)
- {
- string closeContent = openResponse.Content.ReadAsStringAsync().Result;
- Logger.WriteInfo("OpenRtmpChannel: "+closeContent);
- if (closeContent == "OK")
- return true;
- else
- return false;
- }
- }
- else
- {
- Logger.WriteError("THHttpServe: OpenRtmpChannel-请求失败,状态码:" + response.StatusCode);
- return false;
- }
- }
- catch (Exception e)
- {
- Logger.WriteError($"THHttpServe: OpenRtmpChannel-其他错误发生: {e.Message}");
- return false;
- }
- return false;
- }
-
- //停止HTTP请求监听
- private void StopListener()
- {
- if (httpListener != null)
- {
- httpListener.Close();
- Logger.WriteError("THHttpServe: StopListener-ERROR:" + "停止数据监听");
- }
- }
- public bool InitHttpServer()
- {
- if (!getMqttConfig())
- return false;
- if(!StartListener())
- return false;
- return true;
- }
- public bool getMqttConfig()
- {
- if (System.IO.File.Exists(ConfigPath))
- {
- try
- {
- StringBuilder listenerUrl = new StringBuilder(20);
- GetPrivateProfileString("HTTP", "listenerUrl", "配置文件存在,读取未成功!", listenerUrl, 255, ConfigPath);
- m_listenerUrl = listenerUrl.ToString();
- return true;
- }
- catch (Exception ex)
- {
- Logger.WriteError("THHttpServe: getMqttConfig" + ex.Message.ToString());
- return false;
- }
- }
- return false;
- }
- }
- }
- //case "/easy/rtmp/start":
- // {
- // if(OpenRtmpChannel())
- // RtmpResponse(context, (int)TRMP.RTMP_OK);
- // else
- // RtmpResponse(context, (int)TRMP.RTMP_START_ACTION_FAIL);
-
- // }
- // break;
- //case "/easy/rtmp/stop":
- // {
- // if(CloseRtmpChannel())
- // RtmpResponse(context, (int)TRMP.RTMP_OK);
- // else
- // RtmpResponse(context, (int)TRMP.RTMP_STOP_ACTION_FAIL);
- // }
- // break;
|