-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathscript.js
418 lines (356 loc) · 12.6 KB
/
script.js
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
var fileUrl = '';
var bytes = 0;
var fileArray = new Array();
var toggle = true; // 토글 버튼 초기 상태
var many = true; // 인물 여러명 감지시 알림 여부 상태
var flag2 = null; // 이미지 주소에 확장자가 없는 경우 확장자를 저장할 변수
//이미지 주소에 확장자가 없는 경우 확장자를 저장
function getImageInfoHandler(item, callback) {
return function() {
var imageinfo = ImageInfo.getAllFields(item.srcUrl);
file_type = imageinfo['format'];
callback(item, file_type);
};
};
function duple_callback(item,file_type){
duple_check(item, file_type, "temp");
}
//파일 이름 확인
function validCheck(obj){
if(obj == null ) {
alert('유효하지 않은 이름입니다.');
return false;
}
if(obj.length==0){
alert('유효하지 않은 이름입니다.');
return false;
}
var special_pattern = /[:|?<>*"\\\/\s]/gi;
if(special_pattern.test(obj) == true){
alert('유효하지 않은 이름입니다.');
return false;
}
return true;
}
//콘텍스트 메뉴 클릭시 실행 - 토글 상태 확인, 중복 체크
function ctmClick(item) {
var img_url= item.srcUrl;
var file_type = img_url.split('.');
var file_name = img_url.split('/');
//원본 파일 이름
file_name = file_name[file_name.length-1];
file_name = (file_name.split('.'))[0];
//toggle 상태 확인
if(!toggle) {
alert('어덕편덕 OFF 상태입니다. ');
return;
}
//맨 뒤 확장자 추출
switch(file_type[file_type.length-1]) {
case 'gif':
file_type = ".gif";
break;
case 'png':
file_type = ".png";
break;
case 'jpeg':
file_type = ".jpg";
break;
case 'jpg':
file_type = ".jpg";
break;
case 'bmp':
file_type = ".bmp";
break;
case 'webp':
file_type = ".webp";
break;
case 'icon':
file_type = ".ico";
break;
default:
//이미지 주소에 확장자 있는 경우
if(img_url.toLowerCase().includes('jpg') || img_url.toLowerCase().includes('jpeg') )
file_type = ".jpg";
else if(img_url.toLowerCase().includes('gif'))
file_type = ".gif";
else if(img_url.toLowerCase().includes('png'))
file_type = ".png";
else if(img_url.toLowerCase().includes('bmp'))
file_type = ".bmp";
else if(img_url.toLowerCase().includes('webp'))
file_type = ".webp";
else if(img_url.toLowerCase().includes('ico'))
file_type = ".ico";
//이미지 주소에 확장자 없는 경우
else {
//이미지를 분석해 확장자 알아냄
file_type=null;
ImageInfo.loadInfo(img_url, getImageInfoHandler(item, duple_callback));
}
break;
}
//중복체크
if(file_type!=null)
duple_check(item, file_type, file_name);
}
function duple_check(item, file_type, file_name) {
var img_url = item.srcUrl;
var flag = false;
whale.downloads.search({
orderBy: ['-startTime'],
exists: true,
url: img_url
}, downloadedItems => {
downloadedItems.some(item => {
if((item.filename).length!=0) {
flag = true;
return true;
}
});
//콜백함수 whale.downloads.search 완료 후 실행
//중복일 때
if(flag == true) {
var duple_confirm = confirm("중복된 이미지입니다. 계속 저장하겠습니까?");
if(duple_confirm) {
img_recognition(img_url, file_type, file_name);
}
else
return;
}
//중복이 아닐때
else {
img_recognition(img_url, file_type, file_name);
}
});
}
//이미지 얼굴인식
function img_recognition(file_url, filetype, file_name) {
var url = file_url; // 다운로드 url
var file_type = filetype; // 파일 종류 => 파일 확장자
var filename = file_name;
var newDownload = false; // 원본이름으로 저장(false), 새로운 이름으로 저장(true)
$.ajax({
method: "POST",
async: false, // 동기식으로 통신
url: "http://ec2-52-79-137-54.ap-northeast-2.compute.amazonaws.com/duckduck/cfr_v2.py", // 파이썬 모듈 호출 (http://localhost/whale/python-server/cfr_v2.py)
beforeSend: function() {
whale.sidebarAction.setBadgeBackgroundColor({ color: [255, 187, 0, 255] });// 로딩중 배지 색상 변경 (주황), 알림창
},
complete: function() {whale.sidebarAction.setBadgeBackgroundColor({ color: [29, 219 ,22, 255] });}, // 완료후 배지 색상 (초록)
data: {img_url : url, file_type: file_type }, // 원본 url, 확장자
error: function() {alert("서버와의 통신에 실패했습니다. 다시 시도해주세요.");}
}).done(function( data ) {
data = data.toString();
data = data.replace(/\n/g, "");//행바꿈제거
data = data.replace(/\r/g, "");//엔터제거
data = data.replace(/'/g, '"');// 작은따옴표를 큰따옴표로 변경 (json 객체 생성시 에러 방지)
console.log("data(script.js): " + data); // 문자열
try {
var celObj = JSON.parse(data); // json 객체 생성
// json 객체에서 정보 추출
var count = celObj.info.faceCount; // 인물 수
var faces = celObj.faces; // 인물 정보가 담긴 json Array
var people = new Array(count); // 인물의 수만큼 배열 (인물이름)
var confidences = new Array(count); // 신뢰도
// 인물을 찾지 못한 경우
if(count <= 0) {
var fail_confirm = confirm("인물을 찾지 못했어요. :(\n원본 이름으로 저장할까요?");
// 원본 이름으로 저장
if(!fail_confirm) {
// 파일 이름 수정
filename = prompt("어떤 이름으로 저장할까요?", "");
if(validCheck(filename)) {
fullname = filename+filetype;
img_download(url, filename+filetype);
return;
}
}
img_download_original(url);
return;
// 인물을 찾은 경우
} else {
var message = ""; // 인식된 인물 이름과 신뢰도 메시지
// 인물 정보 배열에 저장하기
for(var i = 0; i < faces.length; i++) {
people[i] = faces[i].celebrity.value;
confidences[i] = faces[i].celebrity.confidence;
}
// 신뢰도 높은 순으로 정렬
var temp;
for(var i=confidences.length; i>0; i--) {
for (var j=0; j<i-1; j++) {
if(confidences[j] < confidences[j+1]) {
temp = confidences[j];
confidences[j] = confidences[j+1];
confidences[j+1] = temp;
temp = people[j];
people[j] = people[j+1];
people[j+1] = temp;
}
}
}
for(var i = 0; i < people.length; i++) {
message = message + (i+1) + ". " + people[i] + " (" + (confidences[i] * 100).toFixed(2) + "%)\n";
}
// 신뢰도가 최고값인 인물의 이름
filename = people[0];
var conf = (confidences[0]*100).toFixed(2);
// 분석 결과 알림창
var mess = "분석결과\n" + filename + " (" + conf + "%)";
var opt = {
type: "basic",
title: "어덕편덕",
message: mess,
iconUrl: "icon/duck.PNG"
};
if(count == 1) {
whale.notifications.create(opt);
}
// '인물 여럿 인식시 알림' 체크되어있는 경우
if(many) {
if(count > 1) {
filename = prompt("인물이 여러명 인식되었어요.\n" + message + "어떤 이름으로 저장할까요?", filename);
if(validCheck(filename))
newDownload = true;
} else if(count == 1) {
if(conf <= 60.0) {
var fail_confirm = confirm("인물 신뢰도가 낮아요.:(\n결과: " + filename + "(" + conf + "%)\n이대로 저장하시겠어요?");
// 파일 이름 수정
if(!fail_confirm) {
filename = prompt("어떤 이름으로 저장할까요?", "");
if(validCheck(filename))
newDownload = true;
// 지정한 파일 이름
} else
newDownload = true;
} else { // 60% 이상이면 파일 이름 자동 수정
newDownload = true;
}
}
} else {
// 신뢰도가 60%이하인 경우 인식 실패 알림
if(conf <= 60.0) {
var fail_confirm = confirm("인물 신뢰도가 낮아요.:(\n결과: " + filename + "(" + conf + "%)\n이대로 저장하시겠어요?");
if(!fail_confirm) { // 파일 이름 수정
filename = prompt("어떤 이름으로 저장할까요?", "");
if(validCheck(filename))
newDownload = true;
} else {
newDownload = true;
}
} else {
newDownload = true;
}
}
// 최종 경로: .../download/인물이름/인물이름(n).xxx
try {
//새로운 이름으로 저장
if(newDownload)
img_download(url, filename + "/" +filename+file_type);
//원본 이름으로 저장
else
img_download_original(url);
} catch(e) {
img_download_original(url);
}
}
}
catch(exception){
var fail_confirm = confirm("인물을 찾지 못했어요. :(\n원본 이름으로 저장할까요?");
// 원본 이름으로 저장
if(fail_confirm) {
img_download_original(url);
} else { // 파일 이름 수정
filename = prompt("어떤 이름으로 저장할까요?", "");
if(validCheck(filename))
img_download(url, filename + "/" +filename+file_type);
else
img_download_original(url);
}
} finally {
console.log("filename(script.js): " + filename);
}
});
}
//새로운 이름으로 이미지 다운로드
function img_download(file_url, file_name) {
whale.downloads.download({
url: file_url,
filename: file_name });
}
//원본 이름으로 이미지 다운로드
function img_download_original(file_url) {
whale.downloads.download({
url: file_url });
}
//콘텍스트 메뉴 생성
whale.contextMenus.create({
title: '이미지 저장하기',
contexts: ['image'],
onclick: ctmClick //콘텍스트 메뉴 클릭시 ctmClick 메소드 실행
});
// toggle: 최초 다운로드시에 true / many: 최초 다운로드시에 true
whale.runtime.onInstalled.addListener(function (details) {
whale.storage.sync.set({'toggle': true});
whale.storage.sync.set({'many': true});
});
// 웨일 브라우저 실행할 때 아이콘 설정
whale.storage.sync.get(['toggle'], function(result) {
console.log("toggle(storage): " + result.toggle);
if(result.toggle == true) {
whale.sidebarAction.setBadgeText({text: "O"});
whale.sidebarAction.setBadgeBackgroundColor({ color: [29, 219 ,22, 255] });
} else {
whale.sidebarAction.setBadgeText({text: ""});
}
});
// toggle, many 변화되면 스토리지에 상태 저장
whale.storage.onChanged.addListener(function (changes, namespace) {
for (key in changes) {
var storageChange = changes[key];
if (key == "toggle") {
toggle = storageChange.newValue;
console.log("toggle: " + toggle);
if(toggle) {
whale.sidebarAction.setBadgeText({text: "O"});
whale.sidebarAction.setBadgeBackgroundColor({ color: [29, 219 ,22, 255] });
} else {
whale.sidebarAction.setBadgeText({text: ""});
}
} else if (key == "many") {
many = storageChange.newValue;
console.log("many: " + many);
}
}
});
// 사이드바 열려있는지 체크
var is_open = false;
whale.sidebarAction.onClicked.addListener(function(result) {
if(result.opened) {
is_open = true;
} else {
is_open = false;
}
});
// 단축키
whale.commands.onCommand.addListener(function (command) {
// 서비스 on/off 단축키
if (command === "toggle") {
if(toggle) {
whale.storage.sync.set({'toggle': false}); // 서비스 끄기
} else {
whale.storage.sync.set({'toggle': true}); // 서비스 켜기
}
}
// 사이드바 on/off 단축키
if(command === "side-page") {
if(is_open) {
whale.sidebarAction.hide();
is_open = false;
} else {
whale.sidebarAction.show();
is_open = true;
}
}
});