THupload-Oss
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

436 行
18KB

  1. using log4net;
  2. using Newtonsoft.Json.Linq;
  3. using Newtonsoft.Json;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Net.Sockets;
  10. using System.Reflection;
  11. using System.Text;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using System.Web.UI;
  15. using static THUploadOss.Common;
  16. using System.Net.Http;
  17. using System.Runtime.Remoting.Contexts;
  18. using uPLibrary.Networking.M2Mqtt.Messages;
  19. using uPLibrary.Networking.M2Mqtt;
  20. namespace THUploadOss
  21. {
  22. internal class THHttpServe
  23. {
  24. public string m_listenerUrl;
  25. private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  26. public string m_callback;
  27. public HttpListener httpListener;
  28. public bool StartListener()
  29. {
  30. try
  31. {
  32. httpListener = new HttpListener();
  33. httpListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
  34. httpListener.Prefixes.Add(m_listenerUrl);
  35. httpListener.Start();
  36. httpListener.BeginGetContext(ListenerHandle, httpListener); //开始监听
  37. return true;
  38. }
  39. catch (Exception e)
  40. {
  41. Logger.WriteError("THHttpServe: StartListener-ERROR:" + $"服务器启动失败!{e.Message}");
  42. return false;
  43. }
  44. }
  45. public void ListenerHandle(IAsyncResult result)
  46. {
  47. try
  48. {
  49. httpListener = result.AsyncState as HttpListener;
  50. if (httpListener == null) return;
  51. if (httpListener.IsListening)
  52. {
  53. httpListener.BeginGetContext(ListenerHandle, httpListener); //继续监听
  54. HttpListenerContext context = httpListener.EndGetContext(result);
  55. HttpListenerRequest request = context.Request;
  56. Stream stream = context.Request.InputStream;
  57. StreamReader reader = new StreamReader(stream, Encoding.UTF8);
  58. string content = reader.ReadToEnd();
  59. Logger.WriteInfo("THHttpServe: ListenerHandle()-收到消息:" + content);
  60. switch (request.RawUrl)
  61. {
  62. case "/upload/start":
  63. {
  64. dynamic jsonObj = JsonConvert.DeserializeObject(content);
  65. if (StsrtDownload != -1)
  66. {
  67. UploadResponse(context, (int)UPLOAD.UPLOAD_START_FAIL);
  68. return;
  69. }
  70. lock (lockFileList)
  71. {
  72. for (int i = FileList.Count - 1; i >= 0; i--)
  73. {
  74. FileList.Remove(FileList[i]);
  75. }
  76. }
  77. RequestId = jsonObj.requestId;
  78. m_callback = jsonObj.callbackUrl;
  79. DownloadFinsh = 0;
  80. StsrtDownload = 1;
  81. Status = (int)UPLOAD_STATUS.Preparation;
  82. UploadResponse(context, (int)UPLOAD.UPLOAD_OK);
  83. }
  84. break;
  85. case "/upload/stop":
  86. {
  87. if (StsrtDownload == -1)
  88. {
  89. UploadResponse(context,(int)UPLOAD.UPLOAD_STOP_FAIL);
  90. return;
  91. }
  92. DownloadFinsh = -1;
  93. StsrtDownload = -1;
  94. //Status = (int)UPLOAD_STATUS.Ccancellation;
  95. UploadResponse(context, (int)UPLOAD.UPLOAD_OK);
  96. }
  97. break;
  98. case "/upload/callback":
  99. {
  100. UploadStatusResponse(context);
  101. }
  102. break;
  103. }
  104. }
  105. }
  106. catch (Exception ex)
  107. {
  108. Logger.WriteError("THHttpServe: ListenerHandle" + $"异常:{ex.StackTrace}");
  109. }
  110. }
  111. public void UploadStatus()
  112. {
  113. Logger.WriteError("Http UploadStatus: StsrtDownload:" + StsrtDownload + "Status:" + Status);
  114. if (StsrtDownload != -1 || Status != (int)UPLOAD_STATUS.Preparation)
  115. {
  116. JObject data = new JObject
  117. {
  118. { "requestId", RequestId },
  119. { "errorCode", "" },
  120. { "errorMsg", "" },
  121. { "status", Status },// 状态:待执行 5 执行中 10 完成 15 超时 20 失败 25
  122. { "currentTime", DateTime.Now.ToString() }
  123. };
  124. JArray imgjArray = new JArray();
  125. JArray videojArray = new JArray();
  126. lock (lockFileList)
  127. {
  128. foreach (FileStates file in FileList)
  129. {
  130. if (file.fileType == "pic")
  131. {
  132. JObject img = new JObject
  133. {
  134. { "fileName", file.fileName},
  135. { "imageUrl",file.url },
  136. { "status",file.status },
  137. { "progress",file.progress}
  138. };
  139. imgjArray.Add(img);
  140. }
  141. if (file.fileType == "video")
  142. {
  143. JObject video = new JObject
  144. {
  145. { "fileName", file.fileName},
  146. { "videoUrl",file.url },
  147. { "status",file.status },
  148. { "progress",file.progress }
  149. };
  150. videojArray.Add(video);
  151. }
  152. }
  153. }
  154. data.Add("imageList", new JArray(imgjArray));
  155. data.Add("videoList", new JArray(videojArray));
  156. // 将对象序列化为 JSON 字符串
  157. string json = JsonConvert.SerializeObject(data);
  158. Logger.WriteInfo("THHttpServe: UploadStatus-交互日志:" + json);
  159. try
  160. {
  161. HttpClient client = new HttpClient();
  162. HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");
  163. HttpResponseMessage response = client.PostAsync(m_callback, content).Result;
  164. // 检查响应状态码
  165. if (response.IsSuccessStatusCode)
  166. {
  167. string responseBody = response.Content.ReadAsStringAsync().Result;
  168. }
  169. else
  170. {
  171. Logger.WriteError("THHttpServe: UploadStatus-Error sending GET request: " + response.StatusCode);
  172. }
  173. }
  174. catch (Exception ex)
  175. {
  176. Logger.WriteError("THHttpServe: UploadStatus-An error occurred: " + ex.Message);
  177. }
  178. if (Status == (int)UPLOAD_STATUS.Complete)
  179. Status = (int)UPLOAD_STATUS.Preparation;
  180. if (Status == (int)UPLOAD_STATUS.Fail)
  181. Status = (int)UPLOAD_STATUS.Preparation;
  182. if (Status == (int)UPLOAD_STATUS.Ccancellation)
  183. Status = (int)UPLOAD_STATUS.Preparation;
  184. }
  185. System.Threading.Thread.Sleep(5000);
  186. }
  187. public void UploadStatusResponse(HttpListenerContext context)
  188. {
  189. //构造Response响应
  190. HttpListenerResponse response = context.Response;
  191. response.StatusCode = 200;
  192. response.ContentType = "text/html;";
  193. response.ContentEncoding = Encoding.UTF8;
  194. using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
  195. {
  196. JObject data = new JObject
  197. {
  198. { "requestId", RequestId },
  199. { "errorCode", "" },
  200. { "errorMsg", "" },
  201. { "status", Status },// 状态:待执行 5 执行中 10 完成 15 超时 20 失败 25
  202. { "currentTime", DateTime.Now.ToString() }
  203. };
  204. JArray imgjArray = new JArray();
  205. JArray videojArray = new JArray();
  206. lock (lockFileList)
  207. {
  208. foreach (FileStates file in FileList)
  209. {
  210. if (file.fileType == "pic")
  211. {
  212. JObject img = new JObject
  213. {
  214. { "fileName", file.fileName},
  215. { "imageUrl",file.url },
  216. { "status",file.status },
  217. { "progress",file.progress}
  218. };
  219. imgjArray.Add(img);
  220. }
  221. if (file.fileType == "video")
  222. {
  223. JObject video = new JObject
  224. {
  225. { "fileName", file.fileName},
  226. { "videoUrl",file.url },
  227. { "status",file.status },
  228. { "progress",file.progress }
  229. };
  230. videojArray.Add(video);
  231. }
  232. }
  233. }
  234. data.Add("imageList", new JArray(imgjArray));
  235. data.Add("videoList", new JArray(videojArray));
  236. // 将对象序列化为 JSON 字符串
  237. string json = JsonConvert.SerializeObject(data);
  238. Logger.WriteInfo("THHttpServe: UploadStatusResponse-交互日志:" + json);
  239. writer.Write(json);
  240. writer.Close();
  241. response.Close();
  242. }
  243. }
  244. public void RtmpResponse(HttpListenerContext context, int code)
  245. {
  246. //构造Response响应
  247. HttpListenerResponse response = context.Response;
  248. response.StatusCode = 200;
  249. response.ContentType = "text/html;";
  250. response.ContentEncoding = Encoding.UTF8;
  251. using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
  252. {
  253. string jsonret = $"{{\"code\":{code},\"msg\":\"{UPLOAD_RESULT[code]}\",\"data\":\"{null}\",\"class\":\"{null}\"}}";
  254. Logger.WriteInfo("THHttpServe: RtmpResponse-交互日志:" + jsonret);
  255. writer.Write(jsonret);
  256. writer.Close();
  257. response.Close();
  258. }
  259. }
  260. public void UploadResponse(HttpListenerContext context,int code)
  261. {
  262. //构造Response响应
  263. HttpListenerResponse response = context.Response;
  264. response.StatusCode = 200;
  265. response.ContentType = "text/html;";
  266. response.ContentEncoding = Encoding.UTF8;
  267. using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
  268. {
  269. string jsonret = $"{{\"code\":{code},\"msg\":\"{UPLOAD_RESULT[code]}\",\"data\":\"{null}\",\"class\":\"{null}\"}}";
  270. Logger.WriteInfo("THHttpServe: UploadResponse-交互日志:" + jsonret);
  271. writer.Write(jsonret);
  272. writer.Close();
  273. response.Close();
  274. }
  275. }
  276. public bool CloseRtmpChannel()
  277. {
  278. // 创建HttpClient实例
  279. HttpClient client = new HttpClient();
  280. try
  281. {
  282. // 发送GET请求并获取响应
  283. HttpResponseMessage response = client.GetAsync("http://localhost:19610/api/v1/getChannelList?offset=0&row=50").Result;
  284. // 检查响应是否成功
  285. if (response.IsSuccessStatusCode)
  286. {
  287. // 读取响应内容
  288. string content = response.Content.ReadAsStringAsync().Result;
  289. Logger.WriteInfo("CloseRtmpChannel" + content);
  290. dynamic jsonObj = JsonConvert.DeserializeObject(content);
  291. string srcURL = jsonObj.ChannelList[0].srcURL;
  292. srcURL = WebUtility.UrlEncode(srcURL).Replace("%3A", ":");
  293. string dstURL = jsonObj.ChannelList[0].dstURL;
  294. dstURL = WebUtility.UrlEncode(dstURL).Replace("%3A", ":");
  295. 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";
  296. // 输出响应内容
  297. HttpResponseMessage closeResponse = client.GetAsync(closeUrl).Result;
  298. if (closeResponse.IsSuccessStatusCode)
  299. {
  300. string closeContent = closeResponse.Content.ReadAsStringAsync().Result;
  301. Logger.WriteInfo("CloseRtmpChannel" + closeContent);
  302. if (closeContent == "OK")
  303. return true;
  304. else
  305. return false;
  306. }
  307. }
  308. else
  309. {
  310. Logger.WriteError("THHttpServe: CloseRtmpChannel-请求失败,状态码:" + response.StatusCode);
  311. return false;
  312. }
  313. }
  314. catch (Exception e)
  315. {
  316. Logger.WriteError($"THHttpServe: CloseRtmpChannel-其他错误发生: {e.Message}");
  317. return false;
  318. }
  319. return false;
  320. }
  321. public bool OpenRtmpChannel()
  322. {
  323. // 创建HttpClient实例
  324. HttpClient client = new HttpClient();
  325. try
  326. {
  327. // 发送GET请求并获取响应
  328. HttpResponseMessage response = client.GetAsync("http://localhost:19610/api/v1/getChannelList?offset=0&row=50").Result;
  329. // 检查响应是否成功
  330. if (response.IsSuccessStatusCode)
  331. {
  332. // 读取响应内容
  333. string content = response.Content.ReadAsStringAsync().Result;
  334. // 输出响应内容
  335. Logger.WriteInfo("OpenRtmpChannel: "+content);
  336. dynamic jsonObj = JsonConvert.DeserializeObject(content);
  337. string srcURL = jsonObj.ChannelList[0].srcURL;
  338. srcURL = WebUtility.UrlEncode(srcURL).Replace("%3A", ":");
  339. string dstURL = jsonObj.ChannelList[0].dstURL;
  340. dstURL = WebUtility.UrlEncode(dstURL).Replace("%3A", ":");
  341. 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";
  342. // 输出响应内容
  343. HttpResponseMessage openResponse = client.GetAsync(openUrl).Result;
  344. if (openResponse.IsSuccessStatusCode)
  345. {
  346. string closeContent = openResponse.Content.ReadAsStringAsync().Result;
  347. Logger.WriteInfo("OpenRtmpChannel: "+closeContent);
  348. if (closeContent == "OK")
  349. return true;
  350. else
  351. return false;
  352. }
  353. }
  354. else
  355. {
  356. Logger.WriteError("THHttpServe: OpenRtmpChannel-请求失败,状态码:" + response.StatusCode);
  357. return false;
  358. }
  359. }
  360. catch (Exception e)
  361. {
  362. Logger.WriteError($"THHttpServe: OpenRtmpChannel-其他错误发生: {e.Message}");
  363. return false;
  364. }
  365. return false;
  366. }
  367. //停止HTTP请求监听
  368. private void StopListener()
  369. {
  370. if (httpListener != null)
  371. {
  372. httpListener.Close();
  373. Logger.WriteError("THHttpServe: StopListener-ERROR:" + "停止数据监听");
  374. }
  375. }
  376. public bool InitHttpServer()
  377. {
  378. if (!getMqttConfig())
  379. return false;
  380. if(!StartListener())
  381. return false;
  382. return true;
  383. }
  384. public bool getMqttConfig()
  385. {
  386. if (System.IO.File.Exists(ConfigPath))
  387. {
  388. try
  389. {
  390. StringBuilder listenerUrl = new StringBuilder(20);
  391. GetPrivateProfileString("HTTP", "listenerUrl", "配置文件存在,读取未成功!", listenerUrl, 255, ConfigPath);
  392. m_listenerUrl = listenerUrl.ToString();
  393. return true;
  394. }
  395. catch (Exception ex)
  396. {
  397. Logger.WriteError("THHttpServe: getMqttConfig" + ex.Message.ToString());
  398. return false;
  399. }
  400. }
  401. return false;
  402. }
  403. }
  404. }
  405. //case "/easy/rtmp/start":
  406. // {
  407. // if(OpenRtmpChannel())
  408. // RtmpResponse(context, (int)TRMP.RTMP_OK);
  409. // else
  410. // RtmpResponse(context, (int)TRMP.RTMP_START_ACTION_FAIL);
  411. // }
  412. // break;
  413. //case "/easy/rtmp/stop":
  414. // {
  415. // if(CloseRtmpChannel())
  416. // RtmpResponse(context, (int)TRMP.RTMP_OK);
  417. // else
  418. // RtmpResponse(context, (int)TRMP.RTMP_STOP_ACTION_FAIL);
  419. // }
  420. // break;