-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFunctions.cs
More file actions
325 lines (281 loc) · 11.4 KB
/
Copy pathFunctions.cs
File metadata and controls
325 lines (281 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using SaemDesk.Scheduler;
using SaemDesk.Models;
using SaemDesk.Services;
namespace SaemDesk
{
/// <summary>
/// Native AOT 호환 Functions 클래스
/// </summary>
internal static class Functions
{
// HttpClient 인스턴스를 한 번만 생성하고 재사용
private static readonly HttpClient _httpClient = new()
{
Timeout = TimeSpan.FromSeconds(15)
};
// 설정값 캐시 (Native AOT를 위한 정적 필드)
private static readonly object _settingsLock = new object();
/// <summary>
/// 급식 정보 가져오기 (Native AOT 최적화)
/// </summary>
public static async Task<List<SchoolMeal>> GetSchoolMealsAsync(
DateTime? startDate = null,
DateTime? endDate = null,
string mmealScCode = "2" )
{
var meals = new List<SchoolMeal>();
try
{
// 네트워크 연결 확인
if (!IsNetworkAvailable())
{
Debug.WriteLine("[Functions] 네트워크 연결 없음 - 급식 조회 취소");
return meals;
}
// API URL 생성
string requestUrl = BuildMealApiUrl(startDate, endDate, mmealScCode);
// HTTP 요청
Debug.WriteLine($"[Functions] 급식 API 요청: {requestUrl}");
using var response = await _httpClient.GetAsync(requestUrl).ConfigureAwait(false);
Debug.WriteLine($"[Functions] 급식 API 응답: {(int)response.StatusCode}, Content-Type: {response.Content.Headers?.ContentType?.MediaType}");
response.EnsureSuccessStatusCode();
// XML 파싱 및 변환
var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
Debug.WriteLine($"[Functions] 급식 응답 본문 앞 200자: {responseBody[..Math.Min(200, responseBody.Length)]}");
var xmlDoc = XDocument.Parse(responseBody);
// NEIS 오류 코드 확인
var resultCode = xmlDoc.Descendants("CODE").FirstOrDefault()?.Value;
var resultMsg = xmlDoc.Descendants("MESSAGE").FirstOrDefault()?.Value;
if (resultCode != null)
{
Debug.WriteLine($"[Functions] NEIS 결과코드: {resultCode} / {resultMsg}");
if (!resultCode.StartsWith("INFO")) return meals; // 오류 응답
}
foreach (var node in xmlDoc.Descendants("row"))
{
var meal = CreateMeal(node);
if (meal != null)
meals.Add(meal);
}
Debug.WriteLine($"[Functions] 급식 파싱 완료: {meals.Count}건");
}
catch (TaskCanceledException)
{
Debug.WriteLine("[Functions] 급식 API 타임아웃 - 네트워크 또는 서버 응답 없음");
}
catch (Exception ex)
{
Debug.WriteLine($"[Functions] 급식 정보 오류: {ex.Message}");
}
return meals;
}
/// <summary>
/// 현재 교시 정보 가져오기 (Native AOT 호환)
/// </summary>
public static Period GetPeriodNow()
{
var now = DateTime.Now;
var dayOfWeek = (int)now.DayOfWeek;
// 주말 체크
if (dayOfWeek == 0 || dayOfWeek == 6)
{
return new Period { Index = 0, Name = "방과후" };
}
var currentTime = new TimeSpan(now.Hour, now.Minute, now.Second);
// 등교 전
if (currentTime < Settings.DayStarting)
{
return new Period { Index = 0, Name = "방과후" };
}
// 조례 시간
if (currentTime < Settings.DayStarting.Value + Settings.AssemblyTime.Value)
{
return new Period
{
Index = 0,
Name = "조례",
Time = Settings.DayStarting,
Duration = Settings.AssemblyTime
};
}
// 교시 계산
TimeSpan firstPeriodStart = Settings.DayStarting.Value + Settings.AssemblyTime.Value + Settings.BreakTime.Value;
int totalPeriods = (dayOfWeek == 1 || dayOfWeek == 3) ? 6 : 7;
var schoolEndTime = firstPeriodStart +
(Settings.OnePeriod.Value * totalPeriods) +
(Settings.BreakTime.Value * (totalPeriods - 2)) +
Settings.LunchTime;
// 1교시 전 휴식
if (currentTime < firstPeriodStart)
{
return new Period
{
Index = 0,
Name = "휴식: 조례~1교시",
Time = firstPeriodStart - Settings.BreakTime,
Duration = Settings.BreakTime
};
}
// 수업 시간대
if (currentTime < schoolEndTime)
{
for (int i = 1; i <= totalPeriods; i++)
{
var periodEnd = CalculatePeriodEnd(i, firstPeriodStart);
var breakEnd = periodEnd + (i == 4 ? Settings.LunchTime : Settings.BreakTime);
if (currentTime < periodEnd)
{
return new Period
{
Index = i,
Name = $"{i}교시",
Time = CalculatePeriodStart(i, firstPeriodStart),
Duration = Settings.OnePeriod
};
}
if (i < totalPeriods && currentTime < breakEnd)
{
var breakName = i == 4 ? "점심 시간" : $"휴식: {i}교시~{i + 1}교시";
return new Period
{
Index = 0,
Name = breakName,
Time = periodEnd,
Duration = i == 4 ? Settings.LunchTime : Settings.BreakTime
};
}
}
}
// 청소 시간
if (currentTime < schoolEndTime + TimeSpan.FromMinutes(10))
{
return new Period
{
Index = 0,
Name = "청소",
Time = schoolEndTime,
Duration = TimeSpan.FromMinutes(10)
};
}
// 종례 시간
if (currentTime < schoolEndTime + TimeSpan.FromMinutes(20))
{
return new Period
{
Index = 0,
Name = "종례",
Time = schoolEndTime + TimeSpan.FromMinutes(10),
Duration = TimeSpan.FromMinutes(10)
};
}
// 방과후
return new Period { Index = 0, Name = "방과후" };
}
#region Helper Methods
private static string BuildMealApiUrl(DateTime? startDate, DateTime? endDate, string mmealScCode)
{
var sb = new StringBuilder(256);
sb.Append("https://open.neis.go.kr/hub/mealServiceDietInfo?Type=xml&KEY=");
sb.Append(Settings.NeisApiKey);
sb.Append("&ATPT_OFCDC_SC_CODE=");
sb.Append(Settings.ProvinceCode);
sb.Append("&SD_SCHUL_CODE=");
sb.Append(Settings.SchoolCode);
if (!string.IsNullOrEmpty(mmealScCode))
{
sb.Append("&MMEAL_SC_CODE=");
sb.Append(mmealScCode);
}
if (startDate.HasValue)
{
if (!endDate.HasValue)
{
sb.AppendFormat("&MLSV_YMD={0:yyyyMMdd}", startDate.Value);
}
else
{
if (startDate > endDate)
{
(startDate, endDate) = (endDate, startDate);
}
sb.AppendFormat("&MLSV_FROM_YMD={0:yyyyMMdd}&MLSV_TO_YMD={1:yyyyMMdd}",
startDate.Value, endDate.Value);
}
}
return sb.ToString();
}
private static SchoolMeal? CreateMeal(XElement node)
{
// 날짜 파싱
if (!DateTime.TryParseExact(
node.Element("MLSV_YMD")?.Value ?? string.Empty,
"yyyyMMdd",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out var mlsvYmd))
{
return null;
}
return new SchoolMeal
{
ATPT_OFCDC_SC_CODE = node.Element("ATPT_OFCDC_SC_CODE")?.Value ?? string.Empty,
ATPT_OFCDC_SC_NM = node.Element("ATPT_OFCDC_SC_NM")?.Value ?? string.Empty,
DDISH_NM = GetMenuStringOptimized(node.Element("DDISH_NM")?.Value ?? string.Empty),
MLSV_YMD = mlsvYmd,
MMEAL_SC_NM = node.Element("MMEAL_SC_NM")?.Value ?? string.Empty,
SCHUL_NM = node.Element("SCHUL_NM")?.Value ?? string.Empty,
SD_SCHUL_CODE = node.Element("SD_SCHUL_CODE")?.Value ?? string.Empty
};
}
private static string GetMenuStringOptimized(string dishName)
{
if (string.IsNullOrWhiteSpace(dishName))
return string.Empty;
var sb = new StringBuilder();
var items = dishName.Split(new[] { "<br/>" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in items)
{
var cleaned = item;
// 특수 문자 제거
var idx = cleaned.IndexOfAny(new[] { '*', ' ', '(' });
if (idx > 0)
{
cleaned = cleaned.Substring(0, idx);
}
if (sb.Length > 0)
{
sb.AppendLine();
}
sb.Append(cleaned);
}
return sb.ToString();
}
private static TimeSpan CalculatePeriodStart(int period, TimeSpan firstPeriodStart)
{
if (period <= 0) return firstPeriodStart;
var elapsedPeriods = period - 1;
var breakCount = period <= 4 ? elapsedPeriods : elapsedPeriods - 1;
var lunchCount = period > 4 ? 1 : 0;
return firstPeriodStart +
(Settings.OnePeriod.Value * elapsedPeriods) +
(Settings.BreakTime.Value * breakCount) +
(Settings.LunchTime.Value * lunchCount);
}
private static TimeSpan CalculatePeriodEnd(int period, TimeSpan firstPeriodStart)
{
return CalculatePeriodStart(period, firstPeriodStart) + Settings.OnePeriod;
}
internal static bool IsNetworkAvailable()
=> System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
#endregion
}
}