305 lines
12 KiB
Python
305 lines
12 KiB
Python
import os
|
||
import shutil
|
||
import traceback
|
||
import uuid
|
||
import zipfile
|
||
from datetime import datetime
|
||
|
||
from django import forms
|
||
from django.contrib.auth.decorators import login_required
|
||
from django.contrib.auth.models import User
|
||
from django.core import exceptions
|
||
from django.core.files.uploadedfile import InMemoryUploadedFile
|
||
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
|
||
from django.db.models import Q
|
||
from django.shortcuts import redirect, render
|
||
from django.views.decorators.cache import never_cache
|
||
|
||
from apps.general.models.model_settings import Settings
|
||
from apps.general.views import settingsmodule
|
||
from apps.geoproc.models.model_sector import Sector
|
||
from apps.gto.models.model_type_icons import ModelTypeIcons
|
||
from apps.management.views import views_user
|
||
from apps.util import generalmodule
|
||
from sabron.util import logging
|
||
|
||
|
||
@login_required(login_url="/management?module=eps&catalog=anker&cmd=list")
|
||
@never_cache
|
||
def rtls_save(request):
|
||
try:
|
||
post_param = request.POST.dict()
|
||
if "rtls_server" in post_param:
|
||
rtls_server_link = Settings.objects.filter(name="rtls_server").first()
|
||
if rtls_server_link is None:
|
||
Settings.objects.create(
|
||
name="rtls_server", value=post_param["rtls_server"]
|
||
)
|
||
else:
|
||
rtls_server_link.value = post_param["rtls_server"]
|
||
rtls_server_link.save()
|
||
if "rtls_username" in post_param:
|
||
rtls_username_link = Settings.objects.filter(name="rtls_username").first()
|
||
if rtls_username_link is None:
|
||
Settings.objects.create(
|
||
name="rtls_username", value=post_param["rtls_username"]
|
||
)
|
||
else:
|
||
rtls_username_link.value = post_param["rtls_username"]
|
||
rtls_username_link.save()
|
||
if "rtls_password" in post_param:
|
||
rtls_password_link = Settings.objects.filter(name="rtls_password").first()
|
||
if rtls_password_link is None:
|
||
Settings.objects.create(
|
||
name="rtls_password", value=post_param["rtls_password"]
|
||
)
|
||
else:
|
||
rtls_password_link.value = post_param["rtls_password"]
|
||
rtls_password_link.save()
|
||
return redirect("/management/?module=settings")
|
||
except Exception as err:
|
||
logging.error(traceback.format_exc())
|
||
return redirect("/management/")
|
||
|
||
|
||
@login_required(login_url="/")
|
||
@never_cache
|
||
def oset_save(request):
|
||
try:
|
||
post_param = request.POST.dict()
|
||
for param in post_param:
|
||
if param == "csrfmiddlewaretoken":
|
||
continue
|
||
if param == "geoproc_many_sectors":
|
||
# TODO вынужденный костыль. До переработки системы настроек
|
||
another_sectors_exists = Sector.objects.all().exclude(
|
||
name="Основной участок").exists()
|
||
if another_sectors_exists:
|
||
continue
|
||
element_link = Settings.objects.filter(name=param).first()
|
||
if element_link is None:
|
||
Settings.objects.create(name=param, value=post_param[param])
|
||
else:
|
||
element_link.value = post_param[param]
|
||
element_link.save()
|
||
|
||
return redirect("/management/?module=settings")
|
||
except Exception as err:
|
||
logging.error(traceback.format_exc())
|
||
return redirect("/management/")
|
||
|
||
|
||
@login_required(login_url="/")
|
||
@never_cache
|
||
def file_save(request):
|
||
try:
|
||
for file in request.FILES:
|
||
file_obj = request.FILES[file]
|
||
# Генерация уникального имени файла
|
||
base_name, extension = os.path.splitext(file_obj.name)
|
||
unique_suffix = (
|
||
datetime.now().strftime("%Y%m%d%H%M%S")
|
||
+ "_"
|
||
+ str(uuid.uuid4().hex[:8])
|
||
)
|
||
unique_name = f"{base_name}_{unique_suffix}{extension}"
|
||
|
||
save_path = os.path.join("media/map/", unique_name)
|
||
|
||
# Убедитесь, что директория существует
|
||
os.makedirs(os.path.dirname(save_path), exist_ok=True)
|
||
|
||
# Открываем файл для записи
|
||
with open(save_path, "wb") as destination:
|
||
for chunk in file_obj.chunks():
|
||
destination.write(chunk)
|
||
|
||
setting = Settings.objects.filter(name=file).first()
|
||
if setting is None:
|
||
Settings.objects.create(name=file, value=save_path)
|
||
else:
|
||
setting.value = save_path
|
||
setting.save()
|
||
return redirect("/management/?module=settings")
|
||
except Exception as err:
|
||
logging.error(traceback.format_exc())
|
||
return redirect("/management/")
|
||
|
||
|
||
@login_required(login_url="/")
|
||
@never_cache
|
||
def gto_icon_save(request):
|
||
try:
|
||
for file in request.FILES:
|
||
file_obj = request.FILES[file]
|
||
save_path = os.path.join("media/map/gto", file_obj.name)
|
||
|
||
# Убедитесь, что директория существует
|
||
os.makedirs(os.path.dirname(save_path), exist_ok=True)
|
||
|
||
# Открываем файл для записи
|
||
with open(save_path, "wb") as destination:
|
||
for chunk in file_obj.chunks():
|
||
destination.write(chunk)
|
||
|
||
icon = ModelTypeIcons.objects.filter(model=file).first()
|
||
if icon is None:
|
||
ModelTypeIcons.objects.create(model=file, path=save_path)
|
||
else:
|
||
icon.path = save_path
|
||
icon.save()
|
||
return redirect("/management/?module=settings")
|
||
except Exception as err:
|
||
logging.error(traceback.format_exc())
|
||
return redirect("/management/")
|
||
|
||
|
||
@login_required(login_url="/")
|
||
@never_cache
|
||
def gto_icon_add(request):
|
||
try:
|
||
if request.method == "GET":
|
||
return render(request, "icon_add.html")
|
||
if request.method == "POST":
|
||
file_obj = request.FILES["icon"]
|
||
model = request.POST["model"]
|
||
save_path = os.path.join("media/map/gto", file_obj.name)
|
||
|
||
# Убедитесь, что директория существует
|
||
os.makedirs(os.path.dirname(save_path), exist_ok=True)
|
||
|
||
# Открываем файл для записи
|
||
with open(save_path, "wb") as destination:
|
||
for chunk in file_obj.chunks():
|
||
destination.write(chunk)
|
||
|
||
icon = ModelTypeIcons.objects.filter(model=model).first()
|
||
if icon is None:
|
||
ModelTypeIcons.objects.create(model=model, path=save_path)
|
||
else:
|
||
icon.path = save_path
|
||
icon.save()
|
||
|
||
return redirect("/management/?module=settings")
|
||
except Exception as err:
|
||
logging.error(traceback.format_exc())
|
||
return redirect("/management/")
|
||
|
||
|
||
@login_required(login_url="/")
|
||
@never_cache
|
||
def main_index(request):
|
||
try:
|
||
get_param = request.GET.dict()
|
||
if request.method == "GET":
|
||
return views_user.users_list(request)
|
||
|
||
if request.method == "POST":
|
||
if get_param["cmd"] == "rtls_save":
|
||
return rtls_save(request)
|
||
if get_param["cmd"] == "oset_save":
|
||
return oset_save(request)
|
||
if get_param["cmd"] == "file_save":
|
||
return file_save(request)
|
||
if get_param["cmd"] == "gto_icon_save":
|
||
return gto_icon_save(request)
|
||
context = generalmodule.get_context_template()
|
||
return render(request, "settings.html", context)
|
||
except Exception as err:
|
||
logging.error(traceback.format_exc())
|
||
return redirect("/management/")
|
||
|
||
|
||
@login_required(login_url="/")
|
||
@never_cache
|
||
def add_orthomosaic(request):
|
||
try:
|
||
minLon = settingsmodule.get_settings("orth_minLon", "")
|
||
minLat = settingsmodule.get_settings("orth_minLat", "")
|
||
maxLon = settingsmodule.get_settings("orth_maxLon", "")
|
||
maxLat = settingsmodule.get_settings("orth_maxLat", "")
|
||
|
||
if request.method == "GET":
|
||
context = generalmodule.get_context_template()
|
||
return render(request, "add_orthomosaic.html", context)
|
||
if request.method == "POST":
|
||
settingsmodule.set_settings(
|
||
"orth_minLon", request.POST["min_lon"].replace(",", ".")
|
||
)
|
||
settingsmodule.set_settings(
|
||
"orth_minLat", request.POST["min_lat"].replace(",", ".")
|
||
)
|
||
settingsmodule.set_settings(
|
||
"orth_maxLon", request.POST["max_lon"].replace(",", ".")
|
||
)
|
||
settingsmodule.set_settings(
|
||
"orth_maxLat", request.POST["max_lat"].replace(",", ".")
|
||
)
|
||
|
||
# Получаем архив из запроса
|
||
archive = request.FILES["archive"]
|
||
# Путь для извлечения
|
||
path = "media/map/orth/tiles"
|
||
|
||
# Удаляем целевую директорию, если она существует
|
||
shutil.rmtree(path, ignore_errors=True)
|
||
|
||
# Создаем целевую директорию, если её нет
|
||
os.makedirs(path, exist_ok=True)
|
||
|
||
# Если архив загружен в память (InMemoryUploadedFile), сохраняем его на диск
|
||
if isinstance(archive, InMemoryUploadedFile):
|
||
temp_archive_path = os.path.join(path, "temp_archive.zip")
|
||
with open(temp_archive_path, "wb") as temp_archive:
|
||
for chunk in archive.chunks():
|
||
temp_archive.write(chunk)
|
||
archive_path = temp_archive_path
|
||
else:
|
||
# Если архив уже на диске, используем его путь
|
||
archive_path = archive.temporary_file_path()
|
||
|
||
# Распаковываем архив, игнорируя префикс `tiles/`
|
||
with zipfile.ZipFile(archive_path, "r") as zip_ref:
|
||
# Получаем список всех файлов в архиве
|
||
file_list = zip_ref.namelist()
|
||
|
||
# Выводим список файлов для отладки
|
||
print("Files in archive:")
|
||
for file in file_list:
|
||
print(file)
|
||
|
||
# Префикс, который нужно игнорировать (в вашем случае `tiles/`)
|
||
prefix_to_remove = "tiles/"
|
||
|
||
# Извлекаем все файлы, начиная с префикса `tiles/`
|
||
for file in file_list:
|
||
if file.startswith(prefix_to_remove):
|
||
# Создаем новый путь без префикса `tiles/`
|
||
new_file_path = os.path.join(
|
||
path, os.path.relpath(file, prefix_to_remove)
|
||
)
|
||
|
||
# Если это каталог, создаем его
|
||
if file.endswith("/"):
|
||
print(f"Creating directory: {new_file_path}")
|
||
os.makedirs(new_file_path, exist_ok=True)
|
||
else:
|
||
# Извлекаем файл в нужный путь
|
||
print(f"Extracting: {file} -> {new_file_path}")
|
||
# Создаем родительский каталог, если он не существует
|
||
os.makedirs(os.path.dirname(new_file_path), exist_ok=True)
|
||
# Извлекаем файл
|
||
with zip_ref.open(file) as source_file:
|
||
with open(new_file_path, "wb") as target_file:
|
||
shutil.copyfileobj(source_file, target_file)
|
||
|
||
# Удаляем временный архив, если он был создан
|
||
if isinstance(archive, InMemoryUploadedFile):
|
||
os.remove(archive_path)
|
||
|
||
return redirect("/management/?module=settings")
|
||
|
||
except Exception as err:
|
||
logging.error(traceback.format_exc())
|
||
return redirect("/management/")
|