using DaJiaoYan.Models; using DaJiaoYan.Utils; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace DaJiaoYan.Services { public static class Api { public delegate void DeleLogin(bool runAfterLoginFn); public static DeleLogin LoginFn; /// /// 枚举类型 /// public static class Enumerates { /// /// 考号类型 /// public enum ExamNumberType { /// /// 系统号(云学情学号) /// System = 1, /// /// 学校学号 /// School = 2, } /// /// 是否获取所有有权限参考学生 /// public enum AllExamStudentType { /// /// 是 /// Yes = 1, /// /// 只获取考试的学生 /// No = 0, } /// /// 搜索名称类型 /// public enum ExamStudentSearchNameType { /// /// 所有 /// All = 0, /// /// 只搜索账号名 /// OnlyUserName = 1, /// /// 用户名跟真实姓名 /// UserNameAndRealName = 2, } } private const int PAGE_SIZE = 999999; private const int PAGE_NO = 1; /// /// 获取试卷划分区域信息 /// /// 试卷ID /// public static async Task GetDividePartitionConfig(int testId, string token = null) { DividePartitionConfig res = null; Dictionary keyValuePairs; var (code, response) = await Fetch(new Http.Request(@"v1/examination/divide-partition", Http.Method.Get, new Dictionary() { {"test_id", testId }, {"page_size", 99 }, {"page_no", 1 }, {"correct_type", 0 }, }), token); if (!string.IsNullOrEmpty(response) && code == 200) { res = Json.Decode(response); keyValuePairs = Json.Decode>(response); keyValuePairs.TryGetValue("template_info", out object templateInfoObj); if (templateInfoObj != null) { Dictionary templateInfo = Json.Decode>(Json.Encode(templateInfoObj)); templateInfo.TryGetValue("temp_rect", out object tempRect); if (tempRect != null) { res.Template.TemplateRect = new TemplateRect(res.Template.ParsedVersion, Json.Encode(tempRect)); } } } return res; } /// /// 获取静态文件流 /// /// /// public static async Task GetStaticFileBytes(string fileName) { byte[] result = null; fileName = Regex.Replace(fileName, @"^[\/\\]*", ""); long begin = Functions.GetTimeStamp(), end; Http.Request request = new Http.Request($"{Variables.Const.HTTP_STATIC_HOST}{fileName}", Http.Method.Get); end = Functions.GetTimeStamp(); Log.WriteLine($"request static file create http: {end - begin}"); begin = end; using (HttpResponseMessage response = await Http.Fetch(request)) { end = Functions.GetTimeStamp(); Log.WriteLine($"request static file fetch http: {end - begin}"); begin = end; if (response != null && response.StatusCode == HttpStatusCode.OK) { result = response.Content.ReadAsByteArrayAsync().Result; end = Functions.GetTimeStamp(); Log.WriteLine($"request static file read byte: {end - begin}"); begin = end; } } return result; } /// /// 获取升级信息 /// /// public static async Task GetUpdateInfo() { UpdateInfo info = new UpdateInfo(); try { string url = Regex.Replace(Variables.Const.HTTP_UPDATE_FILE, "\\.[^.]{2,5}$", ".txt", RegexOptions.IgnoreCase); HttpResponseMessage response = await Http.Fetch(new Http.Request(url, Http.Method.Get)); if (response.IsSuccessStatusCode) { string txt = await response.Content.ReadAsStringAsync(); info = Utils.Json.Decode(txt); } } catch { } return info; } /// /// 获取阿里云OSS STS 权限 /// /// public static async Task GetAliyunAccess(string token = null) { var (_, response) = await Fetch(new Http.Request(@"v1/oss/authorize", Http.Method.Post, null), token); Models.AliyunAccessModel res = null; if (response != null) { res = Json.Decode(response); } return res; } public static async Task<(int, string)> PostExaminationScanResult(Models.ScanResultPost p, string token = null) { var req = new Http.Request(@"v1/examination/scan-result", Http.Method.Post) { data = Json.Decode>(Json.Encode(p)) }; return await Fetch(req, token); } /// /// 获取系统返回的内容 /// /// /// /// /// /// private static async Task GetResponse(string url, Http.Method method, Dictionary data) { T res = default; var (_, response) = await Fetch(new Http.Request(url, method, data)); if (!string.IsNullOrEmpty(response)) { var tmp = Json.Decode>(response); if (tmp != null && tmp.ContainsKey("result")) { res = Json.Decode(tmp["result"].ToString()); } } return res; } #region 私有方法 /// /// 请求 /// /// /// private static async Task<(int, string)> Fetch(Http.Request request, string token = null) { foreach (var item in Variables.Vars.RequestHeaders) { // 添加请求头 request.headers.Add(item.Key, item.Value); } if (!string.IsNullOrEmpty(token)) { request.headers["Authorization"] = $"Bearer {token}"; request.headers["AppName"] = "com.teacherUploadMark.web"; } // 请求地址 #if DEBUG if (request.uri.IndexOf("/oss/") >= 0 && Variables.Const.HTTP_HOST.IndexOf("local") >= 0) { request.uri = string.Concat("http://local.api.dajiaoyan.com/", request.uri); } else { request.uri = string.Concat(Variables.Const.HTTP_HOST, request.uri); } #else // 请求地址 request.uri = string.Concat(Variables.Const.HTTP_HOST, request.uri); #endif string apiResponse = null; int code = 200; Dictionary resp; using (HttpResponseMessage response = await Http.Fetch(request)) { if (response != null) { switch (response.StatusCode) { case HttpStatusCode.OK: // 正常响应 resp = JsonConvert.DeserializeObject>(await response.Content.ReadAsStringAsync()); code = Convert.ToInt32(resp["code"]); switch (code) { case 400: Response400(); apiResponse = resp["errors"] != null ? resp["errors"].ToString() : "接口错误"; break; case 401: Response401(); break; case 4000: Response401(); break; case 404: Response404(); break; case 500: Response500(); apiResponse = resp["errors"].ToString(); break; case 502: Response500(); break; default: apiResponse = resp["data"] != null ? resp["data"].ToString() : ""; break; } break; case HttpStatusCode.NotFound: // 页面不存在 Response404(); break; case HttpStatusCode.Unauthorized: // 无权限 if (string.IsNullOrEmpty(token)) { Response401(); } break; case HttpStatusCode.BadRequest: // 页面错误 Response400(); break; default: // 其它错误 Response500(); break; } } else { // 没有网络 } } return (code, apiResponse); } private static void Response400() { } private static void Response401() { LoginFn?.Invoke(false); } private static void Response404() { } private static void Response500() { } #endregion } }