-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.dart
341 lines (286 loc) · 10.4 KB
/
server.dart
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
import 'dart:io';
import 'dart:convert';
import 'package:excel/excel.dart';
Future<Map<int, List<dynamic>>> processExcelFile(String filePath) async {
try {
var file = File(filePath);
var bytes = await file.readAsBytes();
var excel = Excel.decodeBytes(bytes);
// Assume the first sheet is being processed
var sheet = excel.tables.keys.first;
var rows = excel.tables[sheet]!.rows;
// Convert rows to a Map
var result = <int, List<dynamic>>{};
for (var row in rows) {
var rowList = row.map((cell) => cell?.value).toList();
if (rowList.isNotEmpty) {
var key = int.tryParse(rowList[0]?.toString() ?? '');
var value = rowList.sublist(1);
if (key != null) {
result[key] = value;
}
}
}
return result;
} catch (e) {
print("Error processing Excel file: $e");
return {};
}
}
class UserNumber {
var num;
UserNumber(this.num);
}
void main() async {
var excelFilePath = 'apple.xlsx';
var storeDb = await processExcelFile(excelFilePath);
var usernumber = UserNumber(0);
var userinfoDb = {};
var loginInfo = <dynamic, dynamic>{};
var recentsearchDb = <dynamic,List<dynamic>>{};
var starDb = <dynamic,List<dynamic>>{};
var server = await HttpServer.bind(
InternetAddress.loopbackIPv4, // ip address
4040, // port number
);
printHttpServerActivated(server);
await for (HttpRequest request in server) {
if (request.uri.path.contains('/api/') == true) {
printHttpRequestInfo(request);
try {
switch (request.uri.path) {
case '/api/0001': // Read
readMenuInfo(storeDb, request, recentsearchDb);
break;
case '/api/0002': // Create
createId(userinfoDb, request, usernumber, recentsearchDb);
break;
case '/api/0003': // Read
login(userinfoDb, loginInfo, request, recentsearchDb);
break;
case '/api/0004': // Read
readUserInfo(userinfoDb, request);
break;
case '/api/0005': // Read
readStoreInfo(storeDb, request, recentsearchDb);
break;
case '/api/0006': // Read
recentWord(storeDb, request, recentsearchDb);
break;
case '/api/0007': // Read
getUrl(storeDb, request, recentsearchDb);
break;
case '/api/0008': // Read
clickStar(starDb, request, storeDb);
break;
case '/api/0009': // Read
getStar(starDb, request, storeDb);
break;
default:
print("\$ Unsupported http method");
}
} catch (err) {
print("\$ Exception in http request processing");
}
} else {
print("${request.method} {ERROR: Unsupported API}");
}
}
}
void printHttpServerActivated(HttpServer server) {
var ip = server.address.address;
var port = server.port;
print('\$ Server activated in $ip:$port \n');
}
void printHttpRequestInfo(HttpRequest request) async {
var ip = request.connectionInfo!.remoteAddress.address;
var port = request.connectionInfo!.remotePort;
var method = request.method;
var path = request.uri.path;
print("\$ $method $path from $ip:$port");
if (request.headers.contentLength != -1) {
print("> content-type : ${request.headers.contentType}");
//print("> content-length : ${request.headers.contentLength}");
}
}
void printAndSendHttpResponse(var request, var content) async {
request.response
..headers.contentType = ContentType('text', 'plain', charset: "utf-8")
..statusCode = HttpStatus.ok
..write(content);
await request.response.close();
}
void readMenuInfo(var storeDb, var request, var recentsearchDb) async {
var token = request.headers['authorization']![0];
var content = await utf8.decoder.bind(request).join();
var searchWord = jsonDecode(content);
print("> Find the word '$searchWord' in menu");
Map<int, List<dynamic>> findMenu = {};
storeDb.forEach((key, value) {
if (value.isNotEmpty && value[0].toString().contains(searchWord)) {
findMenu[key] = [value[0], value[1], double.parse(value[2].toStringAsFixed(1)), value[3], double.parse(value[5].toStringAsFixed(1))];
}});
// Map의 값을 첫 번째 요소로 정렬하고, 동일한 경우 두 번째 요소로 정렬
var sortedEntries = findMenu.entries.toList()
..sort((a, b) {
// Compare the first values
int compareFirstValues = b.value[2].compareTo(a.value[2]);
// If the first values are equal, compare the second values
return compareFirstValues == 0 ? b.value[3].compareTo(a.value[3]) : compareFirstValues;
});
// 정렬된 엔트리들을 LinkedHashMap으로 변환
Map<int, List<dynamic>> sortedMap = Map.fromEntries(sortedEntries);
print("> Found \n $sortedMap");
print("> Send to Client \n");
var sendtoClient = "$sortedMap";
if (recentsearchDb[token] == null) {
recentsearchDb[token] = [searchWord];
} else {
recentsearchDb[token].add(searchWord);
}
printAndSendHttpResponse(request, sendtoClient);
}
void readStoreInfo(var storeDb, var request, Map recentsearchDb) async {
var token = request.headers['authorization']![0];
var content = await utf8.decoder.bind(request).join();
var searchWord = jsonDecode(content);
print("> Find the word '$searchWord' in store");
Map<int, List<dynamic>> findMenu = {};
storeDb.forEach((key, value) {
if (value.isNotEmpty && value[1].toString().contains(searchWord)) {
findMenu[key] = [value[0], value[1], double.parse(value[2].toStringAsFixed(1)), value[3], double.parse(value[5].toStringAsFixed(1))];
}});
// Map의 값을 첫 번째 요소로 정렬하고, 동일한 경우 두 번째 요소로 정렬
var sortedEntries = findMenu.entries.toList()
..sort((a, b) {
// Compare the first values
int compareFirstValues = b.value[2].compareTo(a.value[2]);
// If the first values are equal, compare the second values
return compareFirstValues == 0 ? b.value[3].compareTo(a.value[3]) : compareFirstValues;
});
// 정렬된 엔트리들을 LinkedHashMap으로 변환
Map<int, List<dynamic>> sortedMap = Map.fromEntries(sortedEntries);
print("> Found \n $sortedMap");
print("> Send to Client \n");
var sendtoClient = "$sortedMap";
if (recentsearchDb[token] == null) {
recentsearchDb[token] = [searchWord];
} else {
recentsearchDb[token].add(searchWord);
}
printAndSendHttpResponse(request, sendtoClient);
}
void createId(var userinfoDb, var request, UserNumber usernumber, var recentsearchDb) async {
var content = await utf8.decoder.bind(request).join();
var transaction = jsonDecode(content) as List;
print("> user_info \n $content");
bool make = true;
if (userinfoDb.isEmpty) {
usernumber.num++;
int nownum = usernumber.num;
userinfoDb[nownum] = transaction;
content = "Success < $transaction created >";
} else {
var keys = List.from(userinfoDb.keys);
for (var key in keys) {
var value = userinfoDb[key];
if (value.isNotEmpty && value[0] == transaction[0]) {
content = "Fail < ${transaction[0]} already exists >";
make = false;
break;
} else {
continue;
}}
if (make == true) {
usernumber.num++;
int nownum = usernumber.num;
userinfoDb[nownum] = transaction;
content = "Success < $transaction created >";
}
}
print("> Saved user_info $userinfoDb \n");
printAndSendHttpResponse(request, content);
}
void login(var userinfoDb, var loginInfo, var request, var recentsearchDb) async {
var content = await utf8.decoder.bind(request).join();
var transaction = jsonDecode(content) as List;
print("> login_info \n $content \n");
var token;
bool match = false;
if (userinfoDb.isEmpty) {
content = "Please create account";
} else {
var keys = List.from(userinfoDb.keys);
for (var key in keys) {
var value = userinfoDb[key];
if (value.isNotEmpty && value[0] != transaction[0]) {
continue;
} else {
match = true;
token = key;
if(value.isNotEmpty && value[1] == transaction[1]) {
if (recentsearchDb[key] == null){
content = "Login Success!";
break;
} else {
content = "Login Success! \n ${recentsearchDb[key]}";
break;
}
}
else {
content = "Wrong PassWord!";
break;
}
}
}
}
if (match == false) {
token = 0;
content = "Please create account";
}
request.response
..headers.contentType = ContentType('text', 'plain', charset: "utf-8")
..headers.set('Authorization', token)
..statusCode = HttpStatus.ok
..write(content);
await request.response.close();
}
void readUserInfo(var userinfoDb, var request) async {
var token = int.parse(request.headers['authorization']![0]);
print("> user_info \n ${userinfoDb[token]}");
var userInfo = userinfoDb[token];
print("> Send to Client \n");
printAndSendHttpResponse(request, userInfo);
}
void recentWord(var userinfoDb, var request, var recentsearchDb) async {
var token = request.headers['authorization']![0];
print("> recentsearchWord \n ${recentsearchDb[token]}");
print("> Send to Client \n");
printAndSendHttpResponse(request, recentsearchDb[token]);
}
void getUrl(var storeDb, var request, var recentsearchDb) async {
var menutoken = int.parse(request.headers['authorization']![0]);
print("> $menutoken : ${storeDb[menutoken][4]}");
print("> Send to Client \n");
printAndSendHttpResponse(request, storeDb[menutoken][4]);
}
void clickStar(var starDb, var request, var storeDb) async {
var token = int.parse(request.headers['authorization']![0]);
var content = await utf8.decoder.bind(request).join();
var menutoken = int.parse(jsonDecode(content));
Map newDb = {};
newDb[menutoken] = storeDb[menutoken];
if (starDb[token] == null) {
starDb[token] = [newDb];
} else {
starDb[token].add(newDb);
}
print("> Saved star : $starDb");
var content2 = "Star saved";
printAndSendHttpResponse(request, content2);
}
void getStar(var starDb, var request, var storeDb) async {
var token = int.parse(request.headers['authorization']![0]);
print("> Saved star : ${starDb[token]}");
printAndSendHttpResponse(request, starDb[token]);
}