-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgallery.js
737 lines (647 loc) · 18.1 KB
/
gallery.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
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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
function Gallery(wrapper, api) {
var self = this;
/// Gallery version
this.version = 0;
var $configuration; // Client configuration
/// Gallery wrapping element
var $wrapper = $(wrapper);
var $gallery = null;
var $listing = null;
var $viewer = null;
var $viewerWeb = null;
var $viewerFull = null;
var $viewerButtons = {
exit: null,
next: null,
prev: null,
download: null,
original: null,
save: null
};
var $login = null;
var $topbar = null;
/// Gallery API URL
var api = api;
/// Path to current directory
var path = null;
/// Current directory content
var items = null;
/// Current directory images
var images = null;
/// Current open image index relative to images
var currentImage = null;
/// Connection speed (B/s)
var connection_speed = 0;
var gallerytemplate = '\
<div class="gallery">\
<div class="top-bar">\
<div class="path">Loading...</div>\
<div class="actions">\
<div class="break"><div class="action downloadall">Download all</div></div>\
<div class="break"><div class="action logout">Logout</div></div>\
</div>\
</div>\
<div class="listing">Loading...</div>\
<div class="viewer" style="display:none;" data-zoom="1" data-pos-x="0" data-pos-y="0">\
<div class="web"></div>\
<div class="full"></div>\
<div class="prev">\
<div class="inner" style="display: none;">\
<span class="nav" title="previous image"><</span>\
</div>\
</div>\
<div class="next">\
<div class="inner" style="display: none;">\
<span class="nav" title="next image">></span>\
</div>\
</div>\
<div class="top-menu">\
<div class="inner" style="display: none;">\
<div class="info"></div>\
<div class="name"></div>\
<div class="link"><a href="http://seznam.cz"></a></div>\
<div class="exit button" title="exit">x</div>\
</div>\
</div>\
<div class="bottom-menu">\
<div class="inner" style="display: none;">\
<div class="original button" title="full resolution">▒</div>\
<div class="save button" title="download full resolution image">⇩</div>\
</div>\
</div>\
</div>\
<div class="login" style="display: none;">\
<div class="restricted">\
<h1>RESTRICTED ACCESS</h1>\
<p class="enter-pass">enter passphrase</p>\
<form>\
<p><input type="password" name="passphrase"/></p>\
</form>\
</div>\
</div>\
</div>'
var itemImageTemplate = '\
<div class="images">\
{{#.}}<div class="item {{type}}" data-name="{{name}}">\
<div class="thumb" style="background-image: url(\'{{thumb}}\');"></div>\
<span class="name">{{name}}</span>\
</div>{{/.}}\
</div>';
var itemDirectoryTemplate = '\
<div class="item {{type}}" data-name="{{name}}" data-path="{{path}}">\
<span class="name">{{name}}</span>\
</div>';
var itemDirectoryListTemplate = '\
<div class="dirs noncategorized">\
{{#.}}\
' + itemDirectoryTemplate + '\
{{/.}}\
</div>';
var itemCategorizedListTemplate = '\
<div class="dirs categorized"> \
{{#.}}\
<div class="category">\
<span class="label">{{category}}</span>\
<div class="dirs">\
{{#dirs}}' + itemDirectoryTemplate + '{{/dirs}}\
</div>\
</div>\
{{/.}}\
</div>';
var pathPartTemplate = '\
{{#.}}<span class="path-part" data-path="{{path}}">{{name}}</span>{{/.}}';
var imageInfoTemplate = '\
<table class="info-table">\
{{#.}}\
<tr>\
<td class="name">{{name}}</td>\
<td class="value">{{value}}</td>\
</tr>\
{{/.}}\
</table>';
var videoPlayerTemplate = '\
<video width="100%" height="100%" controls>\
<source src="{{url}}" consols="true" autoplay="true">\
Your browser does not support the video tag.\
</video>';
/** Gallery initialization */
init = function() {
// Render gallery and viewer element
$wrapper.empty();
$gallery = $(gallerytemplate).appendTo($wrapper);
// Resolve gallery element references
$listing = $gallery.find('.listing');
$path = $gallery.find('.path');
$viewer = $gallery.find('.viewer');
$viewerWeb = $viewer.find('.web');
$viewerFull = $viewer.find('.full');
$viewerButtons.exit = $viewer.find('.exit')
$viewerButtons.next = $viewer.find('.next')
$viewerButtons.prev = $viewer.find('.prev')
$viewerButtons.download = $viewer.find('.download')
$viewerButtons.original = $viewer.find('.original')
$viewerButtons.save = $viewer.find('.save')
$login = $gallery.find('.login');
$logout = $gallery.find('.action.logout');
$downloadall = $gallery.find('.action.downloadall');
$topbar = $gallery.find('.top-bar');
// Show viewer controls on hover
$('.prev, .next, .top-menu, .bottom-menu', $viewer).hover(
function () { $('.inner', this).fadeIn(50); },
function () { $('.inner', this).fadeOut(); }
);
// Bind viewer actions
$viewerButtons.exit.click(closeViewer);
$viewerButtons.prev.click(prevImg);
$viewerButtons.next.click(nextImg);
$viewerButtons.save.click(downloadSourceImage);
$viewerButtons.original.click(displayOriginal);
$('body').keydown(function(event) {
switch(event.which) {
case 27:
closeViewer();
break;
case 39:
event.preventDefault();
nextImg();
break;
case 37:
event.preventDefault();
prevImg();
break;
}
});
$(document).on("webkitfullscreenchange", function() {
if(!document.webkitIsFullScreen)
closeViewer();
});
$(document).on("mozfullscreenchange", function() {
// if(!document.mozIsFullScreen)
// closeViewer();
});
// Download all images in a directory
$downloadall.click(function() {
self.items.forEach(function(item) {
if(item.type != "image" && item.type != "video")
return;
var a = $('<a />');
a.attr('href', item.src);
a.attr('download', item.name);
a.appendTo('body');
a[0].click();
a.remove();
});
});
// Prevent unwanted actions
$viewer.dblclick(function(event) {
event.preventDefault();
event.stopPropagation();
});
// Hide logout when not logged in (passwordless gallery)
if(document.cookie.match(/ticket/) == null)
$logout.hide();
// Login action
$('form', $login).submit(function(event) {
event.preventDefault();
var passphrase = $('input', $login).val();
// Get challange
$.ajax({
url: api,
data: { fn: "login-challenge" }
}).done(function(challenge) {
// Respond to challenge
var response = pidCrypt.SHA512(challenge.concat(passphrase));
// Send response
$.ajax({
url: api,
data: { fn: "login-response", response: response }
}).done(function(data) {
location.reload();
});
});
});
// Logout action
$logout.click(function() {
// Logout
$.ajax({
url: api,
data: { fn: "logout" }
}).done(function() {
location.reload();
});
});
// Check session and render root directory
$.ajax({
url: api,
data: { fn: "session" }
}).done(function(result) {
if(result == "logged") {
updateView();
} else {
showLogin();
}
});
// Benchmark connection
var start = new Date().getTime();
var size = 10240;
$.ajax({
url: api,
data: { fn: "speedtest", size: size }
}).done(function(result) {
var elapsed = new Date().getTime() - start;
connection_speed = size / elapsed * 1000;
console.log("Connection speed " + connection_speed + " B/s");
});
};
var readURL = function() {
var searchParams = new URLSearchParams(window.location.search);
p = searchParams.get("gallery_path")
if(p == null) {
p = "";
}
return {
path: p,
image: searchParams.get("gallery_image")
};
}
var writeURL = function(path, image) {
var searchParams = new URLSearchParams(window.location.search);
searchParams.set("gallery_path", path);
if(image != null) {
searchParams.set("gallery_image", image);
} else {
searchParams.delete("gallery_image");
}
history.pushState({}, "title", "?" + searchParams.toString());
}
var showLogin = function() {
$login.show();
}
/** Change directory */
var cd = function(path) {
writeURL(path, null);
updateView()
}
/** Update view */
var updateView = function() {
url = readURL();
// Set path
renderPath(url.path);
// Load listing
$.ajax({
url: api,
data: {
fn: 'ls',
folder: url.path,
subdirs: $config.categories == "name"
}
}).done(function(items) {
// Open path
renderDir(items, url.path=='');
// Open image if set and found
$(items).each(function(index) {
if(self.items[index].name == url.image) {
openViewer(index);
}
})
});
};
var renderPath = function(path) {
// Get path parts
parts = path==""?path.split('/'):[""].concat(path.split('/'));
var path = "";
var partObjs = [];
$(parts).each(function() {
if(path != "")
path += "/";
path += this;
var name = this;
if(name == '')
name = "Gallery";
partObjs.push({name: name, path: path});
});
// Render path content
var content = Mustache.render(pathPartTemplate, partObjs);
$path.html(content);
// Register path click events
$('.path-part', $path).click(function() {
var path = $(this).data('path');
cd(path);
});
}
/** Sort items, directories first
*
* @param items Items to sort
* @return Sorted items
*/
var sortItems = function(items) {
return items.sort(function(a, b) {
return a.name.localeCompare(b.name, navigator.language, {numeric: true});
});
}
var containsFiles = function(files) {
for(index in files) {
file = files[index];
if(file.type != "directory"){
return true;
}
};
return false;
}
var renderDirFlat = function(dirs) {
dirs = sortItems(dirs);
return Mustache.render(itemDirectoryListTemplate, dirs);
}
var renderDirCategorized = function(dirs) {
switch($config.categories){
case "year":
// Categorize items by year contained in name
dirs = sortItems(dirs);
var categ = {};
$(dirs).each(function() {
var test = this.name.match(/19[0-9][0-9]|2[0-9][0-9][0-9]/);
cat = "Other";
if(test)
cat = test[0];
if(typeof categ[cat] == "undefined")
categ[cat] = [];
categ[cat].push(this);
});
break;
case "name":
// Categorize items by top folder
dirs = sortItems(dirs);
var categ = {};
for(index in dirs) {
var dir = dirs[index];
files = sortItems(dir.subdirs);
cat = "Other";
if(!containsFiles(files)){
cat = dir.name;
}
if(typeof categ[cat] == "undefined"){
categ[cat] = [];
}
if(cat == "Other"){
categ[cat].push(dir);
}
else {
for(i in files){
file = files[i];
categ[cat].push(file);
}
}
}
break;
default:
console.log("Error: bad configuration parameter categories = " + $config.categories);
}
var data = [];
for(cat in categ) {
data.push({category: cat, dirs: categ[cat]});
}
return Mustache.render(itemCategorizedListTemplate, data);
}
var renderImages = function(images) {
images = sortItems(images);
return Mustache.render(itemImageTemplate, images);
}
var renderDir = function(items, categorize) {
// Set current directory content
items = sortItems(items);
self.items = items;
path = readURL().path;
// Add data to items
$(items).each(function() {
var img = encodeURIComponent(path + "/" + this.name)
this.thumb = api + "?fn=thumb&img=" + img;
this.web = api + "?fn=web&img=" + img;
this.src = api + "?fn=img&img=" + img;
this.video = api + "?fn=video&img=" + img;
});
// Render elements
var content = "";
// Split items by type
self.images = [];
var dirs = [];
$(items).each(function() {
if(this.type == "directory")
dirs.push(this);
else
self.images.push(this);
});
// Render content
if(categorize == true)
content += renderDirCategorized(dirs);
else
content += renderDirFlat(dirs);
content += renderImages(self.images);
$listing.html(content);
// Register directory click events
$('.item.directory', $listing).click(function() {
var path = $(this).data('path');
cd(path);
});
// Register image click events
$('.item.image, .item.video', $listing).click(function() {
var name = $(this).data('name');
// Find index for name
var index = 0;
$(self.images).each(function(i) {
if(this.name == name)
index = i;
});
openViewer(index);
});
// Handle zooming the image by mouse wheel
$viewer.bind("mousewheel", function(event) {
var img = new Image();
img.src = $viewer.css('background-image').replace(/url\(|\)$|"/ig, '');
// Update zoom value
var oldZoom = $viewer.data("zoom");
var zoom = oldZoom;
var zoomStep = 1.05;
if(event.originalEvent.wheelDelta > 0)
zoom *= zoomStep;
else
zoom /= zoomStep;
if(zoom < 1)
zoom = 1;
$viewer.data("zoom", zoom);
// Zoom image
var scale = Math.min($viewer.height() / img.height, $viewer.width() / img.width);
$viewer.css('background-size', scale * zoom * img.width + "px " + scale * zoom * img.height + "px");
});
/// Handle drag and drop image shifting
$viewer.bind("mousedown", function(event) {
$viewer.mouseStart = {
x:event.clientX,
y:event.clientY
};
});
$viewer.bind("mouseup", function(event) {
delete $viewer.mouseStart;
});
$viewer.bind("mousemove", function(event) {
// Do nothing when mouse is not down
if(typeof $viewer.mouseStart == 'undefined')
return;
$viewer.shift.x += event.clientX - $viewer.mouseStart.x;
$viewer.shift.y += event.clientY - $viewer.mouseStart.y;
$viewer.mouseStart = {
x:event.clientX,
y:event.clientY
};
$viewer.css("background-position", "calc(50% + " + $viewer.shift.x + "px) calc(50% + " + $viewer.shift.y + "px)");
});
};
var openViewer = function(index) {
// Show viewer and hide gallery
$viewer.show();
$listing.hide();
$topbar.hide();
// Go fullscreen
if (document.documentElement.requestFullScreen) {
document.documentElement.requestFullScreen();
} else if (document.documentElement.mozRequestFullScreen) {
document.documentElement.mozRequestFullScreen();
} else if (document.documentElement.webkitRequestFullScreen) {
document.documentElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
}
display(index);
}
var closeViewer = function() {
// Update URL to remove image
writeURL(readURL().path, null);
// Hide viewer show listing
$listing.show();
$viewer.hide();
$topbar.show();
resetViewer();
// Stop fullscreen
if (document.cancelFullScreen) {
document.cancelFullScreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitCancelFullScreen) {
document.webkitCancelFullScreen();
}
// Scroll to image in image listing
var $target = $('.image[data-name="' + self.images[self.currentImage].name + '"]');
$("body").scrollTop($target.offset().top - $(window).height() / 2 + $target.height() / 2);
}
var getNext = function(index) {
if(index + 1 < self.images.length)
return index + 1;
else
return 0;
}
var getPrev = function(index) {
if(index - 1 >= 0)
return index - 1;
else
return self.images.length - 1;
}
var nextImg = function() {
display(getNext(self.currentImage));
}
var prevImg = function() {
display(getPrev(self.currentImage));
}
var resetViewer = function() {
// Remove old content
$viewer.find('video').remove();
$viewer.find('img').remove();
$viewerWeb.css("background-image", '');
$viewerFull.css("background-image", '');
// Reset zoom
$viewerWeb.data("zoom", 1);
$viewerFull.data("zoom", 1);
$viewerWeb.css('background-size', 'contain');
$viewerFull.css('background-size', 'contain');
// Reset shift
$viewer.css("background-position", "50% 50%");
$viewer.shift = {
x:0,
y:0
};
// Reset full quality switch
$viewerButtons.original.show();
}
var display = function(index) {
// Set current index
self.currentImage = index;
resetViewer();
writeURL(readURL().path, self.images[index].name);
if(self.images[index].type == 'image')
displayImage(index);
if(self.images[index].type == 'video')
displayVideo(index);
}
var displayVideo = function(index) {
var content = Mustache.render(videoPlayerTemplate, {url: self.images[index].video});
$(content).prependTo($viewer);
}
var displayImage = function(index) {
// Get next expected image
var nextIndex = getNext(index);
if(self.currentImage > index)
nextIndex = getPrev(index);
// Set current index
self.currentImage = index;
// Set image and preloaders
$viewerWeb.css("background-image", 'url(\'' + self.images[index].web + '\')');
$viewerWeb.ready(function() {
if(self.currentImage == index) {
console.log("Web image loaded: " + self.images[index].name);
var next = new Image();
next.src = self.images[nextIndex].web;
next.onload = function() {
console.log("Prealoaded web image: " + self.images[nextIndex].name);
};
}
});
// Show source automaticaly if connection is fast
if(connection_speed > $config.speed_limit) {
displayOriginal();
}
// Set image name
$('.name', $viewer).text(self.images[index].name);
$link = $('.link a', $viewer);
$link.text(location.href);
$link.attr('href', location.href);
// Load image info
$('.info', $viewer).empty();
$.ajax({
url: api,
data: { fn: 'info', img: readURL().path + "/" + self.images[index].name }
}).done(function(info) {
var data = [];
for(key in info)
data.push({name: key, value: info[key]});
$('.info', $viewer).html(Mustache.render(imageInfoTemplate, data));
});
}
/**
* Downloads current image source
*/
var downloadSourceImage = function() {
window.location.href = self.images[self.currentImage].src;
}
/**
* Displays original image version in the viewer
*/
var displayOriginal = function() {
console.log("Showing original: ", self.images[self.currentImage].name);
$viewerFull.css("background-image", 'url(\'' + self.images[self.currentImage].src + '\')');
$viewerButtons.original.hide();
}
// Load configuration and initialize gallery
$.ajax({
url: api,
data: { fn: 'config' },
}).done(function(cat) {
$config = cat;
init();
});
}