97 lines
3.2 KiB
Python
97 lines
3.2 KiB
Python
# Standard library imports.
|
|
from pathlib import Path
|
|
from math import ceil
|
|
|
|
# External library imports.
|
|
import filetype
|
|
|
|
# Django imports.
|
|
from django.http import HttpResponseNotFound
|
|
from django.conf import settings
|
|
from django.shortcuts import (render,
|
|
redirect)
|
|
|
|
# Project imports.
|
|
from .utils import make_thumbnail
|
|
|
|
###########################################################################################
|
|
# CONSTANTS. #
|
|
###########################################################################################
|
|
|
|
CELLS_PER_ROW = 7
|
|
ROWS_PER_PAGE = 4
|
|
IMAGES_PER_PAGE = CELLS_PER_ROW * ROWS_PER_PAGE
|
|
|
|
###########################################################################################
|
|
# View functions. #
|
|
###########################################################################################
|
|
|
|
def gallery_view(request, path = None):
|
|
"""
|
|
Shows a list of subdirectories and image files inside the given path.
|
|
The path should be inside the GALLERY_ROOT path, otherwise a 404 error will be thrown.
|
|
"""
|
|
|
|
def list2rows(lst, cells = CELLS_PER_ROW):
|
|
rows = []
|
|
i = 0
|
|
while i < len(lst):
|
|
row = []
|
|
for c in range(cells):
|
|
try:
|
|
row.append(lst[i + c])
|
|
except:
|
|
pass
|
|
rows.append(row)
|
|
i += cells
|
|
return rows
|
|
|
|
full_path = settings.GALLERY_ROOT.joinpath(path) if path is not None else settings.GALLERY_ROOT
|
|
|
|
if full_path.exists():
|
|
if full_path.is_dir():
|
|
subdirs = sorted([i for i in full_path.iterdir() if i.is_dir()])
|
|
images = sorted([i for i in full_path.iterdir() if i.is_file() and filetype.is_image(str(i))])
|
|
img_data = []
|
|
num_pages = ceil((len(images) / CELLS_PER_ROW) / ROWS_PER_PAGE)
|
|
|
|
try:
|
|
page = int(request.GET.get('page', 1))
|
|
except ValueError:
|
|
page = 1
|
|
|
|
page_base = IMAGES_PER_PAGE * (page - 1)
|
|
|
|
for image in images[page_base : page_base + IMAGES_PER_PAGE]:
|
|
make_thumbnail(image)
|
|
|
|
img_context = {
|
|
'path': image.name,
|
|
'name': image.name,
|
|
'thumbnail': '/thumbs/' + path + '/' + image.name if path is not None else '/thumbs/' + image.name
|
|
}
|
|
|
|
img_data.append(img_context)
|
|
|
|
print(page)
|
|
|
|
context = {
|
|
'path': path,
|
|
'subdirs': list2rows(subdirs),
|
|
'images': list2rows(img_data),
|
|
'pages': range(1, num_pages + 1),
|
|
'num_files': len(images),
|
|
'page': page,
|
|
'prev_page': page - 1,
|
|
'next_page': page + 1,
|
|
'num_pages': num_pages
|
|
}
|
|
|
|
return render(request, 'gallery_view.html', context)
|
|
|
|
else:
|
|
return render(request, 'image_view.html', {'image_path': Path('/imgs/').joinpath(path)})
|
|
|
|
else:
|
|
return HttpResponseNotFound('Not found')
|