Solhee

UserIntefaceAndModeChange

Showing 1 changed file with 225 additions and 184 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({
41 - } 33 + url: TARGET_URL,
42 - else 34 + headers:{
43 - return false; 35 + 'Authorization': `Bearer ${TOKEN}`
36 + },
37 + json:{
38 + "replyToken":eventObj.replyToken,
39 + "messages" :[
40 + {
41 + "type":"text",
42 + "text": line
43 + }
44 + ]
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 + +"사용 안내가 필요하신 경우 '안내'라고 입력해주세요."
62 }, 90 },
63 { 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 + {
64 "type":"text", 113 "type":"text",
65 - "text": "식품 유해정보가 궁금하시면 y를 입력해주세요" 114 + "text": "식품유해정보 알리미 사용 안내입니다."
115 + },
116 + {
117 + "type":"text",
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,207 +131,189 @@ function hello(eventObj){ ...@@ -72,207 +131,189 @@ 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 +{
106 - 176 + var queryParams = '/' + encodeURIComponent(second_key);
107 -console.log("[Input msg] ", NameOfProduct); 177 + queryParams += '/' + encodeURIComponent('C002');
178 + queryParams += '/' + encodeURIComponent(filetype);
179 + queryParams += '/' + encodeURIComponent(startIndex);
180 + queryParams += '/' + encodeURIComponent(endIndex);
181 + queryParams += '/' + encodeURIComponent('PRDLST_NM') + '=' + encodeURIComponent(prdName);
108 182
109 -function getfoodinfo(replyToken){ 183 + request({
110 - request.post( 184 + url: second_url + queryParams,
111 - { 185 + method: 'GET'
112 - url: TARGET_URL, 186 + }, function (error, response, body) {
113 - headers:{ 187 + if(error){
114 - 'Authorization': `Bearer ${TOKEN}` 188 + helloAndErrorMsg(oventObj);
115 - }, 189 + console.log('에러입니다.')
116 - json:{
117 - "replyToken": replyToken,
118 - "messages":[
119 - {
120 - "type":"text",
121 - "text": "입력하신 상품은 " + replyToken +"입니다."
122 - }
123 - ]
124 } 190 }
125 - },(error, reponse, body) => { 191 + else{
126 - console.log(body) 192 + var result2 =body;
127 - }); 193 + var resObj2 = eval("("+result2+")");
194 + var resultCode2 = resObj2.C002.RESULT.CODE;
128 195
129 - var queryParams2 = '/' + encodeURIComponent(second_key); 196 + console.log("[입력] : ", prdName);
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({
136 - second_url: second_url + queryParams2,
137 - //url : fullRequest,
138 - method: 'GET'
139 - }, function (error, response, body) {
140 - if(error){
141 - console.log('에러입니다.')
142 - }
143 - else{
144 - if(response.statusCode ==200){
145 console.log("식품명으로 식품유형과 첨가물 정보를 받아옵니다..."); 197 console.log("식품명으로 식품유형과 첨가물 정보를 받아옵니다...");
146 - var result =body;
147 - var resObj = eval("("+result+")");
148 - var ProductCategory = resObj.C002.row[0].PRDLST_DCNM;
149 - // 첨가물정보 API가 입력으로 받을 parameter
150 -
151 - //console.log(result);
152 - console.log("[처리결과] ",resObj.C002.RESULT.MSG);
153 - console.log("[유형] ", ProductCategory);
154 - console.log("[첨가물] ",resObj.C002.row[0].RAWMTRL_NM )
155 -
156 - }
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 - {
173 - "type":"text",
174 - "text":"[첨가물] " + resObj.C002.row[0].RAWMTRL_NM
175 - }
176 - ]
177 - }
178 - }),(error, response, body) =>{
179 - console.log(body)
180 - }
181 - }
182 198
183 - }); 199 + if(resultCode2 == "INFO-200")//'유효하지 않은 입력'
184 -} 200 + {
201 + console.log("존재하지 않는 식품명입니다.");
202 + prdNameNotFound(eventObj);
203 + }
204 + else if(response.statusCode ==200)
205 + { // 유효한 입력
206 + var ProductCategory = resObj2.C002.row[0].PRDLST_DCNM;
207 + // 첨가물정보 API가 입력으로 받을 parameter
208 +
209 + //console.log(result);
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
215 +
186 216
187 -// 처음에 하던거 217 + // 다음 API호출
188 -function getfood(replyToken){ 218 + var queryParams = '?' + encodeURIComponent('ServiceKey') + '=' +first_key;
189 - request.post( 219 + queryParams += '&' + encodeURIComponent('pc_kor_nm') + '=' + encodeURIComponent(ProductCategory);
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 220
208 - var queryParams1 = '?' + encodeURIComponent('ServiceKey') + '=' +first_key; 221 + request({
209 - //queryParams1 += '&' + encodeURIComponent('prdlst_cd') + '=' + encodeURIComponent('C0118010300000'); 222 + url: first_url + queryParams,
210 - queryParams1 += '&' + encodeURIComponent('pc_kor_nm') + '=' + encodeURIComponent(replyToken); 223 + method: 'GET'
211 - //queryParams1 += '&' + encodeURIComponent('pageNo') + '=' + encodeURIComponent('213'); 224 + }, function (error, response, body) {
212 - //queryParams1 += '&' + encodeURIComponent('numOfRows') + '=' + encodeURIComponent('100'); 225 + if(error){
213 - 226 + console.log('에러입니다.')
214 - 227 + }
215 - request({ 228 + else if(response.statusCode ==200)
216 - first_url: first_url + queryParams1, 229 + {
217 - method: 'GET' 230 + var result1 =body;
218 - }, function (error, response, body) { 231 + var xmltojson = convert.xml2json(result1,{compact:true,spaces:4});
219 - if(error){ 232 + var resObj1 = eval("("+xmltojson+")");
220 - console.log('에러입니다.') 233 + var resultItems = resObj1.response.body.items;
221 - } 234 +
222 - else{ 235 + if(Object.keys(resultItems).length != 0)
223 - if(response.statusCode ==200){ 236 + {
224 - var result =body; 237 + console.log("valid input : 식품 첨가물 정보를 받아옵니다.");
225 - var xmltojson = convert.xml2json(result,{compact:true,spaces:4}); 238 +
226 - var resObj = eval("("+xmltojson+")"); 239 + var responseMessage ='[ ' + resultItems.item[0].PC_KOR_NM._text + ' ]\n';
227 - var resultItems = resObj.response.body.items; 240 + //하나의 카테고리에 대한 정보만 받는다고 가정해 반복문 밖으로 뺐습니다.
228 - var resultLeng = Object.keys(resultItems); 241 +
229 - 242 + for(var i=0 ; i < resultItems.item.length; i ++)
230 - if(Object.keys(resultItems).length != 0){ 243 + {
231 - console.log("valid input : 식품 첨가물 정보를 받아옵니다."); 244 + //var responseMessage ='[ ' + resultItems.item[i].PC_KOR_NM._text + ' ]\n';
232 - 245 + var addictive = resultItems.item[i].T_KOR_NM._text;
233 - var responseMessage ='[ ' + resultItems.item[0].PC_KOR_NM._text + ' ]\n'; 246 + var specVal = resultItems.item[i].SPEC_VAL_SUMUP._text;
234 - //하나의 카테고리에 대한 정보만 받는다고 가정해 반복문 밖으로 뺐습니다. 247 + var yn = resultItems.item[i].INJRY_YN._text;
235 - 248 + responseMessage += addictive + ' : ' + specVal + '['+yn+']'+ '\n';
236 - for(var i=0 ; i < resultItems.item.length; i ++) 249 + }
237 - { 250 +
238 - //var responseMessage ='[ ' + resultItems.item[i].PC_KOR_NM._text + ' ]\n';
239 - var addictive = resultItems.item[i].T_KOR_NM._text;
240 - var specVal = resultItems.item[i].SPEC_VAL_SUMUP._text;
241 - var yn = resultItems.item[i].INJRY_YN._text;
242 - responseMessage += addictive + ' : ' + specVal + '['+yn+']'+ '\n';
243 - }
244 251
245 - } 252 + var replyment =
246 - else 253 + {
247 - { 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 + }
248 270
249 - console.log("Invalid Input : 에러 메시지 전송"); 271 + if(! simpleResult)
250 - var responseMessage = "잘못 된 입력입니다. 라벨의 식품유형을 확인하고 다시 입력해주세요."; 272 + {
273 + var moreInfo =
274 + {
275 + "type":"text",
276 + "text":"더 자세한 첨가물 안전 정보\n" +responseMessage
277 + };
278 + replyment.messages.push(moreInfo);
279 + }
251 280
252 - } 281 + //메시지 전송
253 - console.log('[responese message]',responseMessage); 282 + request.post(
254 - 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("입력 이외의 오류가 발생하였습니다.");
307 + }
270 } 308 }
271 - } 309 +
272 - 310 + });
273 - }); 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'),
......