Solhee

UserIntefaceAndModeChange

Showing 1 changed file with 187 additions and 146 deletions
...@@ -8,22 +8,14 @@ const TOKEN = 'z5iy5sMU1W4xZAlwvn0/5x4U+4ZsqI0hKO1ZZNFxUGlNzGBjFg2D1u6/Ij5C/Sbkn ...@@ -8,22 +8,14 @@ const TOKEN = 'z5iy5sMU1W4xZAlwvn0/5x4U+4ZsqI0hKO1ZZNFxUGlNzGBjFg2D1u6/Ij5C/Sbkn
8 var ProductCategoryName ; 8 var ProductCategoryName ;
9 var first_url = 'http://apis.data.go.kr/1470000/FoodAdtvInfoService/getFoodAdtvInfoList'; 9 var first_url = 'http://apis.data.go.kr/1470000/FoodAdtvInfoService/getFoodAdtvInfoList';
10 var first_key ='ofY2ppOq5kBqT5jYPaGsW%2BEy7OR5a1bf5Z9PHvqNKvwO5DSCaU2x2qCj%2FoXnuB1YVbMTlErkHWSMEsR5b7isrw%3D%3D'; 10 var first_key ='ofY2ppOq5kBqT5jYPaGsW%2BEy7OR5a1bf5Z9PHvqNKvwO5DSCaU2x2qCj%2FoXnuB1YVbMTlErkHWSMEsR5b7isrw%3D%3D';
11 -/* 11 +
12 -var queryParams1 = '?' + encodeURIComponent('ServiceKey') + '=' +first_key;
13 -//queryParams1 += '&' + encodeURIComponent('prdlst_cd') + '=' + encodeURIComponent('C0118010300000');
14 -queryParams1 += '&' + encodeURIComponent('pc_kor_nm') + '=' + encodeURIComponent(ProductCategoryName);
15 -//queryParams1 += '&' + encodeURIComponent('pageNo') + '=' + encodeURIComponent('213');
16 -//queryParams1 += '&' + encodeURIComponent('numOfRows') + '=' + encodeURIComponent('100');
17 -*/
18 -
19 -var NameOfProduct ; // 제품명 넣는 자리
20 var second_url ='http://openapi.foodsafetykorea.go.kr/api'; 12 var second_url ='http://openapi.foodsafetykorea.go.kr/api';
21 var second_key ='f8ce3271a2dc4decb83b'; 13 var second_key ='f8ce3271a2dc4decb83b';
22 var filetype ='json'; 14 var filetype ='json';
23 var startIndex = 1; 15 var startIndex = 1;
24 var endIndex = 5; 16 var endIndex = 5;
25 -//var fullRequest = encodeURIComponent("http://openapi.foodsafetykorea.go.kr/api/f8ce3271a2dc4decb83b/C002/xml/1/5/PRDLST_REPORT_NO=200101260032"); 17 +var simpleResult = true;
26 -//var fullRequest ='http://openapi.foodsafetykorea.go.kr/api/f8ce3271a2dc4decb83b/C002/json/1/5'; 18 +
27 19
28 const fs = require('fs'); 20 const fs = require('fs');
29 const path = require('path'); 21 const path = require('path');
...@@ -35,15 +27,28 @@ var app = express(); ...@@ -35,15 +27,28 @@ var app = express();
35 app.use(bodyParser.json()); 27 app.use(bodyParser.json());
36 28
37 29
38 -function first(text1){ 30 +function sendOneLineMessage(eventObj, line)
39 - if(text1 == 'y'){ 31 +{
40 - return true; 32 + request.post({
33 + url: TARGET_URL,
34 + headers:{
35 + 'Authorization': `Bearer ${TOKEN}`
36 + },
37 + json:{
38 + "replyToken":eventObj.replyToken,
39 + "messages" :[
40 + {
41 + "type":"text",
42 + "text": line
41 } 43 }
42 - else 44 + ]
43 - return false; 45 + }
46 + },(error,response,body)=>{
47 + console.log(body)
48 + });
44 } 49 }
45 50
46 -function hello(eventObj){ 51 +function helloAndErrorMsg(eventObj){
47 request.post({ 52 request.post({
48 url: TARGET_URL, 53 url: TARGET_URL,
49 headers:{ 54 headers:{
...@@ -58,11 +63,65 @@ function hello(eventObj){ ...@@ -58,11 +63,65 @@ function hello(eventObj){
58 }, 63 },
59 { 64 {
60 "type":"text", 65 "type":"text",
61 - "text": "무엇을 도와드릴까요?" 66 + "text": "정확한 식품명을 기입해주세요.\n안내가 필요하신 경우 '안내'라고 입력해주세요."
67 + }
68 +
69 + ]
70 + }
71 + },(error,response,body)=>{
72 + console.log(body)
73 + });
74 +}
75 +
76 +function prdNameNotFound(eventObj){
77 + request.post({
78 + url: TARGET_URL,
79 + headers:{
80 + 'Authorization': `Bearer ${TOKEN}`
81 + },
82 + json:{
83 + "replyToken":eventObj.replyToken,
84 + "messages" :[
85 + {
86 + "type":"text",
87 + "text": "죄송합니다. \n해당 식품의 정보를 찾을 수 없습니다.\n"
88 + +"정확한 식품명을 기입해주세요.\n"
89 + +"사용 안내가 필요하신 경우 '안내'라고 입력해주세요."
90 + },
91 + {
92 + "type": "sticker",
93 + "packageId": "11537",
94 + "stickerId": "52002770"
95 + }
96 + ]
97 + }
98 + },(error,response,body)=>{
99 + console.log(body)
100 + });
101 +}
102 +
103 +function instruction(eventObj){
104 + request.post({
105 + url: TARGET_URL,
106 + headers:{
107 + 'Authorization': `Bearer ${TOKEN}`
108 + },
109 + json:{
110 + "replyToken":eventObj.replyToken,
111 + "messages" :[
112 + {
113 + "type":"text",
114 + "text": "식품유해정보 알리미 사용 안내입니다."
62 }, 115 },
63 { 116 {
64 "type":"text", 117 "type":"text",
65 - "text": "식품 유해정보가 궁금하시면 y를 입력해주세요" 118 + "text": "사용방법\n"
119 + +"1. 식품명을 '정확하게' 입력해주세요.\n"
120 + +"2. 입력하신 식품명이 식약처 데이터베이스에 존재하는 경우,\n"
121 + +"식품 유형과 첨가물, 첨가물 안전정보에 대해 받아보실 수 있습니다.\n"
122 + +"3. '모드' 명령어를 통해 결과 간단히 보기/자세히 보기 모드를 전환할 수 있습니다.\n"
123 + +"4. 결과 간단히 보기 모드에서는 첨가물과 식품유형을 확인하실 수 있습니다.\n"
124 + +"5. 자세한 결과 보기 모드에서는 위 정보 및 첨가물 안전정보를 확인하실 수 있습니다."
66 } 125 }
67 126
68 ] 127 ]
...@@ -72,162 +131,109 @@ function hello(eventObj){ ...@@ -72,162 +131,109 @@ function hello(eventObj){
72 }); 131 });
73 } 132 }
74 133
134 +
75 app.post('/hook', function (req, res) { 135 app.post('/hook', function (req, res) {
76 136
77 var eventObj = req.body.events[0]; 137 var eventObj = req.body.events[0];
78 var source = eventObj.source; 138 var source = eventObj.source;
79 var message = eventObj.message; 139 var message = eventObj.message;
80 var message_text = message.text; 140 var message_text = message.text;
81 - //var text1;
82 - var text2;
83 141
84 - var findfoods;
85 // request log 142 // request log
86 console.log('======================', new Date() ,'======================'); 143 console.log('======================', new Date() ,'======================');
87 console.log('[request]', req.body); 144 console.log('[request]', req.body);
88 console.log('[request source] ', eventObj.source); 145 console.log('[request source] ', eventObj.source);
89 console.log('[request message]', eventObj.message); 146 console.log('[request message]', eventObj.message);
90 - text = first(message_text);
91 147
92 - if(text == true){ 148 + if(message_text =='안내'){
93 - console.log('Hi',message); 149 + console.log('[안내 출력]');
94 - hello(eventObj); 150 + instruction(eventObj);
151 + }
152 + else if(message_text == '모드')
153 + {
154 + console.log("모드를 변경합니다")
155 + simpleResult = !simpleResult;
156 + if(simpleResult)
157 + {
158 + var msg = "결과 간단히 보기 모드 입니다.";
159 + }
160 + else
161 + {
162 + var msg = "자세한 결과 보기 모드입니다. 첨가물 안전정보를 확인하실 수 있습니다."
163 + }
164 +
165 + sendOneLineMessage(eventObj, msg);
95 } 166 }
96 else{ 167 else{
97 - getfoodinfo(eventObj.replyToken); 168 + getfoodinfoByPdtName(eventObj, message_text);
98 - getfood(eventObj.replyToken);
99 } 169 }
100 170
101 res.sendStatus(200); 171 res.sendStatus(200);
102 }); 172 });
103 173
104 -//rawmaterial 174 +function getfoodinfoByPdtName(eventObj, prdName)
105 -// 식품의약품 안전처 품목제조보고(원재료) API 요청 예시입니다 175 +{
176 + var queryParams = '/' + encodeURIComponent(second_key);
177 + queryParams += '/' + encodeURIComponent('C002');
178 + queryParams += '/' + encodeURIComponent(filetype);
179 + queryParams += '/' + encodeURIComponent(startIndex);
180 + queryParams += '/' + encodeURIComponent(endIndex);
181 + queryParams += '/' + encodeURIComponent('PRDLST_NM') + '=' + encodeURIComponent(prdName);
106 182
107 -console.log("[Input msg] ", NameOfProduct);
108 -
109 -function getfoodinfo(replyToken){
110 - request.post(
111 - {
112 - url: TARGET_URL,
113 - headers:{
114 - 'Authorization': `Bearer ${TOKEN}`
115 - },
116 - json:{
117 - "replyToken": replyToken,
118 - "messages":[
119 - {
120 - "type":"text",
121 - "text": "입력하신 상품은 " + replyToken +"입니다."
122 - }
123 - ]
124 - }
125 - },(error, reponse, body) => {
126 - console.log(body)
127 - });
128 -
129 - var queryParams2 = '/' + encodeURIComponent(second_key);
130 - queryParams2 += '/' + encodeURIComponent('C002');
131 - queryParams2 += '/' + encodeURIComponent(filetype);
132 - queryParams2 += '/' + encodeURIComponent(startIndex);
133 - queryParams2 += '/' + encodeURIComponent(endIndex);
134 - queryParams2 += '/' + encodeURIComponent('PRDLST_NM') + '=' + encodeURIComponent(replyToken);
135 request({ 183 request({
136 - second_url: second_url + queryParams2, 184 + url: second_url + queryParams,
137 - //url : fullRequest,
138 method: 'GET' 185 method: 'GET'
139 }, function (error, response, body) { 186 }, function (error, response, body) {
140 if(error){ 187 if(error){
188 + helloAndErrorMsg(oventObj);
141 console.log('에러입니다.') 189 console.log('에러입니다.')
142 } 190 }
143 else{ 191 else{
144 - if(response.statusCode ==200){ 192 + var result2 =body;
145 - console.log("식품명으로 식품유형과 첨가물 정보를 받아옵니다..."); 193 + var resObj2 = eval("("+result2+")");
146 - var result =body; 194 + var resultCode2 = resObj2.C002.RESULT.CODE;
147 - var resObj = eval("("+result+")");
148 - var ProductCategory = resObj.C002.row[0].PRDLST_DCNM;
149 - // 첨가물정보 API가 입력으로 받을 parameter
150 195
151 - //console.log(result); 196 + console.log("[입력] : ", prdName);
152 - console.log("[처리결과] ",resObj.C002.RESULT.MSG); 197 + console.log("식품명으로 식품유형과 첨가물 정보를 받아옵니다...");
153 - console.log("[유형] ", ProductCategory);
154 - console.log("[첨가물] ",resObj.C002.row[0].RAWMTRL_NM )
155 198
156 - } 199 + if(resultCode2 == "INFO-200")//'유효하지 않은 입력'
157 - request.post({
158 - url:TARGET_URL,
159 - headers: {
160 - 'Authorization': `Bearer ${TOKEN}`
161 - },
162 - json:{
163 - "messages":[
164 - {
165 - "type":"text",
166 - "text":"[처리결과] " + resObj.C002.RESULT.MSG
167 - },
168 - {
169 - "type":"text",
170 - "text":"[유형] " + ProductCategory
171 - },
172 { 200 {
173 - "type":"text", 201 + console.log("존재하지 않는 식품명입니다.");
174 - "text":"[첨가물] " + resObj.C002.row[0].RAWMTRL_NM 202 + prdNameNotFound(eventObj);
175 - }
176 - ]
177 - }
178 - }),(error, response, body) =>{
179 - console.log(body)
180 - }
181 } 203 }
204 + else if(response.statusCode ==200)
205 + { // 유효한 입력
206 + var ProductCategory = resObj2.C002.row[0].PRDLST_DCNM;
207 + // 첨가물정보 API가 입력으로 받을 parameter
182 208
183 - }); 209 + //console.log(result);
184 -} 210 + console.log("성공적으로 정보를 받았습니다.")
211 + console.log("[처리결과] ",resObj2.C002.RESULT.MSG);
212 + console.log("[유형] ", ProductCategory);
213 + console.log("[첨가물] ",resObj2.C002.row[0].RAWMTRL_NM )
185 214
186 215
187 -// 처음에 하던거
188 -function getfood(replyToken){
189 - request.post(
190 - {
191 - url: TARGET_URL,
192 - headers:{
193 - 'Authorization': `Bearer ${TOKEN}`
194 - },
195 - json:{
196 - "replyToken": replyToken,
197 - "messages":[
198 - {
199 - "type":"text",
200 - "text": "입력하신 상품은 " + replyToken +"입니다."
201 - }
202 - ]
203 - }
204 - },(error, reponse, body) => {
205 - console.log(body)
206 - });
207 -
208 - var queryParams1 = '?' + encodeURIComponent('ServiceKey') + '=' +first_key;
209 - //queryParams1 += '&' + encodeURIComponent('prdlst_cd') + '=' + encodeURIComponent('C0118010300000');
210 - queryParams1 += '&' + encodeURIComponent('pc_kor_nm') + '=' + encodeURIComponent(replyToken);
211 - //queryParams1 += '&' + encodeURIComponent('pageNo') + '=' + encodeURIComponent('213');
212 - //queryParams1 += '&' + encodeURIComponent('numOfRows') + '=' + encodeURIComponent('100');
213 216
217 + // 다음 API호출
218 + var queryParams = '?' + encodeURIComponent('ServiceKey') + '=' +first_key;
219 + queryParams += '&' + encodeURIComponent('pc_kor_nm') + '=' + encodeURIComponent(ProductCategory);
214 220
215 request({ 221 request({
216 - first_url: first_url + queryParams1, 222 + url: first_url + queryParams,
217 method: 'GET' 223 method: 'GET'
218 }, function (error, response, body) { 224 }, function (error, response, body) {
219 if(error){ 225 if(error){
220 console.log('에러입니다.') 226 console.log('에러입니다.')
221 } 227 }
222 - else{ 228 + else if(response.statusCode ==200)
223 - if(response.statusCode ==200){ 229 + {
224 - var result =body; 230 + var result1 =body;
225 - var xmltojson = convert.xml2json(result,{compact:true,spaces:4}); 231 + var xmltojson = convert.xml2json(result1,{compact:true,spaces:4});
226 - var resObj = eval("("+xmltojson+")"); 232 + var resObj1 = eval("("+xmltojson+")");
227 - var resultItems = resObj.response.body.items; 233 + var resultItems = resObj1.response.body.items;
228 - var resultLeng = Object.keys(resultItems); 234 +
229 - 235 + if(Object.keys(resultItems).length != 0)
230 - if(Object.keys(resultItems).length != 0){ 236 + {
231 console.log("valid input : 식품 첨가물 정보를 받아옵니다."); 237 console.log("valid input : 식품 첨가물 정보를 받아옵니다.");
232 238
233 var responseMessage ='[ ' + resultItems.item[0].PC_KOR_NM._text + ' ]\n'; 239 var responseMessage ='[ ' + resultItems.item[0].PC_KOR_NM._text + ' ]\n';
...@@ -242,37 +248,72 @@ function getfood(replyToken){ ...@@ -242,37 +248,72 @@ function getfood(replyToken){
242 responseMessage += addictive + ' : ' + specVal + '['+yn+']'+ '\n'; 248 responseMessage += addictive + ' : ' + specVal + '['+yn+']'+ '\n';
243 } 249 }
244 250
245 - }
246 - else
247 - {
248 251
249 - console.log("Invalid Input : 에러 메시지 전송"); 252 + var replyment =
250 - var responseMessage = "잘못 된 입력입니다. 라벨의 식품유형을 확인하고 다시 입력해주세요."; 253 + {
254 + "replyToken":eventObj.replyToken,
255 + "messages":[
256 + {
257 + "type":"text",
258 + "text":prdName +"에 대해 알아볼까요?"
259 + },
260 + {
261 + "type":"text",
262 + "text":"[유형]\n" + ProductCategory
263 + },
264 + {
265 + "type":"text",
266 + "text":"[첨가물]\n" + resObj2.C002.row[0].RAWMTRL_NM
267 + }
268 + ]
269 + }
251 270
271 + if(! simpleResult)
272 + {
273 + var moreInfo =
274 + {
275 + "type":"text",
276 + "text":"더 자세한 첨가물 안전 정보\n" +responseMessage
277 + };
278 + replyment.messages.push(moreInfo);
252 } 279 }
253 - console.log('[responese message]',responseMessage); 280 +
254 - request.post({ 281 + //메시지 전송
282 + request.post(
283 + {
255 url: TARGET_URL, 284 url: TARGET_URL,
256 headers: { 285 headers: {
257 'Authorization': `Bearer ${TOKEN}` 286 'Authorization': `Bearer ${TOKEN}`
258 }, 287 },
259 - json:{ 288 + json: replyment
260 - "messages": [ 289 + },(error, response, body) => {
290 + console.log(body)
291 + });
292 + }
293 + else
261 { 294 {
262 - "type":"text", 295 + console.log("Invalid Input : 에러 메시지 전송");
263 - "text": responseMessage 296 + var responseMessage = "잘못 된 입력입니다. 라벨의 식품유형을 확인하고 다시 입력해주세요.";
264 } 297 }
265 - ] 298 + console.log('[responese message]',responseMessage);
299 +
266 } 300 }
267 - }),(error, response,body) =>{ 301 +
268 - console.log(body) 302 + });
269 } 303 }
304 + else
305 + {
306 + console.log("입력 이외의 오류가 발생하였습니다.");
270 } 307 }
271 } 308 }
272 309
273 }); 310 });
311 +
274 } 312 }
275 313
314 +
315 +
316 +
276 try { 317 try {
277 const option = { 318 const option = {
278 ca: fs.readFileSync('/etc/letsencrypt/live/' + domain +'/fullchain.pem'), 319 ca: fs.readFileSync('/etc/letsencrypt/live/' + domain +'/fullchain.pem'),
......