-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.html
541 lines (502 loc) · 21.6 KB
/
index.html
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
<!DOCTYPE html>
<html>
<head>
<title>ImgFind</title>
<style>
.accordion {
transition: 0.4s;
}
.panel {
padding: 0 18px;
background-color: white;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
}
.preview-container {
border: 1px solid #eee;
height: 490px;
width: 100%;
}
</style>
<script src='https://cdn.rawgit.com/naptha/tesseract.js/1.0.10/dist/tesseract.js'></script>
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=Promise"></script>
<script src="https://cdn01.boxcdn.net/platform/preview/1.37.1/en-US/preview.js"></script>
<link rel="stylesheet" href="https://cdn01.boxcdn.net/platform/preview/1.37.1/en-US/preview.css" />
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
var img_extensions = ['png', 'jpg', 'jpeg', 'svg', 'tif', 'bmp', 'pnm'];
function boxOAuth(refresh = false) {
var url = window.location.href;
var code = null
if (url.indexOf('code') > -1) {
code = url.substring(url.indexOf('code=') + 5, url.length);
}
var access_tokens = getLocalAccessTokens();
sessionStorage.service = 'box';
var requestBody = null;
if (access_tokens.hasOwnProperty('box') &&
access_tokens.box.hasOwnProperty('access_token') &&
access_tokens.box.access_token != null) {
authenticationSuccess();
} else if (refresh && access_tokens.hasOwnProperty('box') &&
access_tokens.box.hasOwnProperty('refresh_token') &&
access_tokens.box.refresh_token != null) {
var requestBody = new URLSearchParams();
requestBody.append('grant_type', 'refresh_token');
requestBody.append('refresh_token', access_tokens.box.refresh_token);
} else if (sessionStorage.getItem("box_auth_code") != null) {
var requestBody = new URLSearchParams();
requestBody.append('grant_type', 'authorization_code');
requestBody.append('code', sessionStorage.getItem("box_auth_code"));
sessionStorage.removeItem("box_auth_code");
} else if(code != null) {
sessionStorage.box_auth_code = code;
window.location = window.location.href.split('?')[0];
} else {
authenticationFailure();
}
if (requestBody != null) {
requestBody.append('client_id', '1cf9xjqa83lx77agvkmm7rg635wvuh7t');
requestBody.append('client_secret', 'o0p0xgaRvSooele09STKonmKLJiFzNbv');
//dev-client id
// requestBody.append('client_id', '4v47e213getqp2da9aggsd589r2ui1iz');
// requestBody.append('client_secret', 'opWSY6oXqQd3KaNRcaVm9waczXfe6n2V');
var headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'});
var httpResponse = httpRequest('https://api.box.com/oauth2/token', headers, requestBody, 'POST');
httpResponse.then(function (response) {
if (response.status == 200) {
return response.json();
}
alert("Box OAuth failed");
throw new Error("Box OAuth failed with response code:" + response.statusText);
}).then(function (responseJson) {
access_tokens.box = {
access_token: responseJson.access_token,
refresh_token: responseJson.refresh_token
};
setLocalAccessTokens(access_tokens);
authenticationSuccess();
}).catch(function (error) {
console.log(error);
authenticationFailure();
});
}
}
function authenticationSuccess() {
var button = document.createElement("button");
button.innerHTML = "Index Images!";
button.style.backgroundColor = "#900";
button.style.color = "white";
button.setAttribute("class","btn btn-default btn-lg");
button.addEventListener("click", function () {
fetchAndIndexImagesFromBox();
});
document.getElementById("connect").style.display="none";
document.getElementById("afterConnect").style.display="block";
var div = document.getElementById("success_msg");
// div.innerHTML = "Congratulations! You have successfully connected your Box account! <br><br>" +
// " To make your image files in Box searchable click below! <br>";
div.innerHTML = "To make your image files in Box searchable click below! <br><br>";
div.appendChild(button);
div.style.visibility = "visible"
}
function authenticationFailure() {
document.getElementById("connect").style.display="block";
document.getElementById("afterConnect").style.display="none";
// var div = document.getElementById("success_msg");
// div.innerHTML = "Sorry! Authorization failed! <br>";
// div.style.visibility = "visible"
}
function getLocalAccessTokens() {
if (sessionStorage.access_tokens === undefined || sessionStorage.access_tokens == null) {
return {};
} else {
return JSON.parse(sessionStorage.access_tokens);
}
}
function setLocalAccessTokens(access_tokens) {
if (access_tokens == null) {
sessionStorage.access_tokens = '{}';
} else {
sessionStorage.access_tokens = JSON.stringify(access_tokens);
}
}
function fetchAndIndexImagesFromBox() {
fetchImageIdsFromBox();
indexImages();
}
function refreshBoxToken() {
boxOAuth(true);
}
function fetchImageIdsFromBox() {
var limit = 100;
var offset = 0;
for (var index = 0; index < img_extensions.length; index++) {
fetchAndStoreImageIdsFromBox(img_extensions[index], offset, limit);
}
}
function fetchAndStoreImageIdsFromBox(extension, offset=0, limit=100) {
var url = 'https://api.box.com/2.0/search?query=' + extension + '&fields=id&limit=' + limit +
'&offset=' + offset + '&type=file&file_extensions=' + img_extensions.join(",");
var httpResponse = fetchDataFromBox(url);
var totalEntries = 0;
var apiResponse = httpResponse.then(function (response) {
if (response.status == 200) {
totalEntries = response.responseBody.total_count;
return response.responseBody;
// return response.json(); // To be used with fetch
}
throw new Error("Fetching image ids from Box failed with response code:" + response.statusText);
});
apiResponse.then(saveBoxImageSearchResponse).catch(function (error) {
console.log(error);
});
apiResponse.then(function (response) {
var nextOffset = offset + limit;
if (totalEntries > nextOffset) {
fetchAndStoreImageIdsFromBox(extension, nextOffset, limit);
}
}).catch(function (error) {
console.log(error);
});
}
function saveBoxImageSearchResponse(response) {
var imageIds = JSON.parse('{}');
if (sessionStorage.imageIds) {
imageIds = JSON.parse(sessionStorage.imageIds);
}
for (index = 0; index < response.entries.length; index++) {
img_id = response.entries[index].id;
if (!imageIds.hasOwnProperty(img_id)) {
imageIds[img_id] = false
}
}
sessionStorage.imageIds = JSON.stringify(imageIds);
document.getElementById("img_search_results").textContent = "Processing image(s)!";
}
function indexImages() {
if (sessionStorage.imageIds) {
imageIds = JSON.parse(sessionStorage.imageIds);
var len = Object.keys(imageIds).length
var i = 0;
for (var imageId in imageIds) {
if (imageIds.hasOwnProperty(imageId) && !imageIds[imageId].processed) {
metadata(imageId, i , len);
// To be used with fetch
// fetchImageFromBox(imageId).then(function(response) {
// if (response.status == 200) {
// return response.blob(); // used with fetch
// }
// throw new Error("Fetching image from Box failed with response code:" + response.statusText);
// }).then(parseImage).then(renderImage).catch(function(error) {
// console.log("Indexing image with id: " + imageId + " failed");
// console.log(error);
// });
}
i++;
}
}
}
function metadata(fileId, index, len) {
var access_tokens = getLocalAccessTokens();
// var fileId = data[0].imageId;
var headers = new Headers({
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + access_tokens.box.access_token
});
var httpResponse = httpRequest('https://api.box.com/2.0/files/' + fileId + '/metadata', headers, null, 'GET');
httpResponse.then(function (response) {
if (response.status == 200) {
return response.json();
}
}).then(function (res) {
checkAndUpdate(res, fileId, index, len);
}).catch(function (error) {
console.log(error);
});
}
function checkAndUpdate(res, imageId, index, len) {
if (res && res.entries && res.entries.length != 0 && res.entries[0].imageContent) {
console.log("Metadata already exists");
} else {
var imgFetch = fetchImageFromBox(imageId).then(function (response) {
if (response.status == 200) {
var result = {
"imageBlob": response.responseBody,
"imageId": imageId
}
return result;
}
throw new Error("Fetching image from Box failed with response code:" + response.statusText);
});
var imgParse = imgFetch.then(parseImage);
if (res.entries.length == 0) {
Promise.all([imgFetch, imgParse]).then(addNewMetadata).catch(function (error) {
console.log("Indexing image with id: " + imageId + " failed");
console.log(error);
});
} else {
Promise.all([imgFetch, imgParse]).then(updateMetadata).catch(function (error) {
console.log("Indexing image with id: " + imageId + " failed");
console.log(error);
});
}
}
if(index == len - 1) {
alert("Processing Done");
document.getElementById("success_msg").style.display = "none"
document.getElementById("img_search_results").style.display = "none"
document.getElementById("afterConnect").style.display="flex";
document.getElementById("search_space").style.display = "block";
document.getElementById("file_search_box").value = "";
document.getElementById("file_search_box").placeholder = "Search your files";
}
}
function updateMetadata(data) {
var access_tokens = getLocalAccessTokens();
var metadata = [{
"op": "add",
"path": "/imageContent",
"value": data[1]
}]
var fileId = data[0].imageId;
var xhr = new XMLHttpRequest();
var headers = new Headers({
'Content-Type': 'application/json-patch+json',
'Authorization': 'Bearer ' + access_tokens.box.access_token
});
var httpResponse = httpRequest('https://api.box.com/2.0/files/' + fileId + '/metadata/global/properties',
headers, JSON.stringify(metadata), 'PUT');
httpResponse.then(function (response) {
if (response.status == 200) {
return response.json();
}
}).then(function (res) {
console.log("Metadata Updated");
}).catch(function (error) {
console.log("Some error occured while updating metadata");
});
}
function addNewMetadata(data) {
var access_tokens = getLocalAccessTokens();
var body = {
"imageContent": data[1]
}
var fileId = data[0].imageId;
var headers = new Headers({
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + access_tokens.box.access_token
});
var httpResponse = httpRequest('https://api.box.com/2.0/files/' + fileId + '/metadata/global/properties', headers, JSON.stringify(body), 'POST');
httpResponse.then(function (response) {
if (response.status == 200) {
return response.json();
}
}).then(function (res) {
console.log("Metadata Added");
}).catch(function (error) {
console.log("Some error occured while adding metadata");
});
}
function fetchImageFromBox(imageId) {
return fetchDataFromBox('https://api.box.com/2.0/files/' + imageId + '/content', 'blob');
// With fetch
// return fetchDataFromBox('https://api.box.com/2.0/files/' + imageId + '/content');
}
function fetchDataFromBox(url, responseType = 'json') {
return new Promise(function (resolve, reject) {
access_tokens = getLocalAccessTokens();
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.setRequestHeader('Authorization', 'Bearer ' + access_tokens.box.access_token);
xhr.responseType = responseType;
xhr.onload = function () {
if (xhr.status = 200) {
resolve({
status: xhr.status,
statusText: xhr.statusText,
responseBody: xhr.response
});
} else {
reject({
status: xhr.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function () {
reject({
status: xhr.status,
statusText: xhr.statusText
});
};
xhr.send();
});
// To be used once fetch stops lowercasing headers
// var headers = new Headers({Authorization: 'Bearer ' + access_tokens.box.access_token });
// return httpRequest(url, headers);
}
function parseImage(imageBlob) {
return new Promise(function (resolve, reject) {
Tesseract.recognize(imageBlob.imageBlob)
.then(function (result) {
resolve(result.text);
}).catch(function (error) {
reject("Parsing image failed with: " + error.message);
});
});
}
function httpRequest(url, headers, body, method = 'GET', mode = 'cors') {
if (url == null) {
throw "URL is not specified for the request."
}
request = {
'method': method,
'mode': mode
}
if (body != null) {
request.body = body;
}
if (headers != null) {
request.headers = headers;
}
return fetch(url, request);
}
function searchFilesInBox(url='', offset=0, limit=100) {
if (url == '') {
var searchVal = document.getElementById("file_search_box").value;
if (searchVal != null && searchVal.trim() != '') {
url = 'https://api.box.com/2.0/search?query=' + searchVal.trim() + '&type=file'
}
}
if (url == '') {
return;
}
var httpResponse = fetchDataFromBox(url + '&offset=' + offset + '&limit=' + limit);
var totalEntries = 0;
var apiResponse = httpResponse.then(function (response) {
if (response.status == 200) {
totalEntries = response.responseBody.total_count;
return response.responseBody;
// return response.json(); // To be used with fetch
}
throw new Error("Fetching image ids from Box failed with response code:" + response.statusText);
}).catch(function (error) {
console.log(error);
});
apiResponse.then(handleFileSearchResponse).catch(function (error) {
console.log(error);
});
apiResponse.then(function (response) {
var nextOffset = offset + limit;
if (totalEntries > nextOffset) {
searchFilesInBox(url, nextOffset, limit)
}
}).catch(function (error) {
console.log(error);
});
}
function handleFileSearchResponse(response) {
var access_tokens = getLocalAccessTokens();
var div = document.getElementById("search_results");
div.innerHTML = '';
var results_found = response.total_count;
// div.append(document.createElement("br"));
div.append('\nFound ' + results_found + ' result(s) for your search query!')
div.append(document.createElement("br"));
var imgUl = document.createElement("ol");
for (var index = 0; index < response.entries.length; index++) {
var imgLi = document.createElement("li");
var imgButton = document.createElement('a');
imgButton.setAttribute("href", "#")
imgButton.setAttribute("class", "accordion");
imgButton.append(document.createTextNode(response.entries[index].name));
imgLi.append(imgButton);
var imgCont = document.createElement('div');
imgCont.setAttribute("class", "panel");
var imgText = document.createElement('div');
imgText.setAttribute("class", "preview-container imgpreview" + index);
var preview = new Box.Preview();
preview.show(response.entries[index].id, access_tokens.box.access_token, {
container: '.imgpreview' + index,
showDownload: true
});
imgCont.append(imgText);
imgLi.append(imgCont);
imgUl.append(imgLi);
// var link = document.createElement("a");
// var linkText = document.createTextNode(response.entries[index].name);
// link.appendChild(linkText);
// // link.title = response.entries[index].name;
// link.target = "_blank";
// link.href = "https://app.box.com/file/" + response.entries[index].id;
// div.appendChild(link);
// div.append(document.createElement("br"));
}
div.append(imgUl);
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.maxHeight){
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
});
}
}
function enterPress(e) {
if(e.keyCode == 13)
searchFilesInBox();
}
</script>
</head>
<body onload="boxOAuth()" ;>
<div class="container-fluid">
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container-fluid" style="background-color:black">
<h3 style="color:white">imgFind</h3>
</div>
</nav>
<div id = "connect" style= "display:none; justify-content:center; align-items:center; padding-top: 20%;" align="center">
<button style="background-color:#900; color:white;" class="btn btn-default btn-lg" onclick="location.href = 'https://account.box.com/api/oauth2/authorize?response_type=code&client_id=1cf9xjqa83lx77agvkmm7rg635wvuh7t'"; type="button">
Connect to Box!
</button>
<h4>Login to your Box account to access and search your files</h4>
</div>
<div id = "afterConnect" style = "display:none; justify-content:center; align-items:center; padding-top: 20%;" align="center">
<div id="success_msg">
</div>
<div id="img_search_results">
</div>
<br>
<br>
<div id="image_indexing_progress">
</div>
<div id="search_space" style = "display:none; position:absolute; top:10%; width:95%;">
<h3>File Search</h3>
<div class="row" style="overflow:hidden;">
<div class="col-lg-12">
<div class="input-group">
<input id="file_search_box" type="text" class="form-control" placeholder="Search your files" onkeypress="enterPress(event)">
<span class="input-group-btn">
<button style="background-color:#900; color:white;" class="btn btn-default" type="button" onclick="searchFilesInBox()">Go!</button>
</span>
</div>
</div>
</div>
</div>
<div id="search_results" style="width:95%;">
</div>
</div>
</div>
</body>
</html>