228 lines
7.9 KiB
Python
228 lines
7.9 KiB
Python
import json
|
|
import os
|
|
from werkzeug.utils import secure_filename
|
|
from app.forms import *
|
|
from PIL import Image
|
|
from pathlib import Path, PurePath, PurePosixPath
|
|
from shutil import rmtree, copytree
|
|
import subprocess
|
|
|
|
class DataSite:
|
|
user_folder = None
|
|
username = str()
|
|
datas = str()
|
|
static_path = None
|
|
trash = list()
|
|
filej= None
|
|
|
|
def __init__(self, username :str , users_folder :str ):
|
|
self.username = username
|
|
self.user_folder = PurePosixPath(users_folder).joinpath(username)
|
|
self.filej = Path(PurePosixPath(self.user_folder).joinpath('ident.json'))
|
|
|
|
|
|
with self.filej.open(newline='', mode='r', encoding='utf-8') as f:
|
|
self.datas = json.load(f)
|
|
self.static_path = Path(PurePosixPath(self.user_folder.joinpath('public')))
|
|
self.static_path.mkdir(parents=True, exist_ok=True)
|
|
|
|
def load_file(self):
|
|
if not self.filej.isfile():
|
|
raise FileNotFoundError(f"Le fichier ident.json n'existe pas : {self.filej}")
|
|
|
|
with self.filej.open(newline='', mode='r', encoding='utf-8') as f:
|
|
self.datas = json.load(f)
|
|
|
|
|
|
|
|
|
|
def get_blocs(self, page: str):
|
|
|
|
if page != '':
|
|
page = Path(self.user_folder.joinpath(page, 'page.json'))
|
|
datas = ""
|
|
if not page.exists():
|
|
raise FileNotFoundError(f"Le fichier page.json n'existe pas : {page}")
|
|
|
|
datas = json.loads(page.read_text())
|
|
else:
|
|
datas = self.datas
|
|
|
|
return datas
|
|
|
|
|
|
def update_bloc(self, bloc, form, files=None):
|
|
print (form)
|
|
for field in form():
|
|
print(field)
|
|
|
|
if files != None:
|
|
f = files['image']
|
|
filename = secure_filename(f.filename)
|
|
extension = filename.rsplit('.', 1)[1].lower()
|
|
bg_custom = 'bg_custom_'+bloc['name']+'.'+extension
|
|
f.save(PurePath.joinpath(
|
|
self.static_path, 'img', bg_custom))
|
|
|
|
bloc['bg_img'] = bg_custom
|
|
|
|
return bloc
|
|
|
|
def update_img(self, image, form):
|
|
img = dict()
|
|
img['title'] = form.title.data
|
|
img['subtitle'] = form.subtitle.data
|
|
img['description'] = form.description.data
|
|
img['category'] = form.category.data
|
|
img['file'] = image
|
|
return img
|
|
|
|
def add_img(self, image_uploaded):
|
|
img = dict()
|
|
|
|
img['title'] = ""
|
|
img['subtitle']=""
|
|
img['text'] = ""
|
|
img['category'] = ""
|
|
img['file'] = image_uploaded
|
|
|
|
return img
|
|
|
|
|
|
def del_img(self, bloc, img):
|
|
|
|
if bloc['type'] == 'gallery':
|
|
img_file = Path(PurePosixPath(self.user_folder).joinpath('public', 'img', bloc[img]['file'] ))
|
|
img_thumb_file = Path(PurePosixPath(self.user_folder).joinpath('public','img', 'thumbnails', bloc[img]['file']))
|
|
if img_file.exists():
|
|
img_file.unlink()
|
|
|
|
if img_thumb_file.exists():
|
|
img_thumb_file.unlink()
|
|
|
|
bloc.pop(img)
|
|
else:
|
|
img_file = Path(PurePosixPath(self.user_folder).joinpath('public', 'img', img ))
|
|
|
|
return bloc
|
|
|
|
|
|
def save_menu(self, menu:dict):
|
|
self.datas['menu'] = menu
|
|
self.filej.write_text(json.dumps(self.datas, indent=5))
|
|
|
|
|
|
def save_blocs(self, page='', blocs=dict()):
|
|
if page != '':
|
|
datas = dict()
|
|
datas['blocs'] = blocs
|
|
|
|
page_info = Path(PurePosixPath(self.user_folder).joinpath(page, 'page.json'))
|
|
|
|
if not page_info.exists():
|
|
raise FileNotFoundError(f"Le fichier page.json n'existe pas : {page}")
|
|
|
|
page_info.write_text(json.dumps(datas, indent=3))
|
|
else:
|
|
self.datas['blocs']= blocs
|
|
self.filej.write_text(json.dumps(self.datas, indent=5))
|
|
|
|
|
|
def get_theme(self):
|
|
return self.datas['config']['theme']
|
|
|
|
def get_pages(self):
|
|
mypages = list()
|
|
folders = Path(self.user_folder)
|
|
for folder in folders.iterdir():
|
|
if folder.name != 'public' and folder.is_dir():
|
|
mypages.append(folder.name)
|
|
|
|
return mypages
|
|
|
|
def new_page(self, pageName:str, pageType:str):
|
|
page_folder = Path(PurePosixPath(self.user_folder).joinpath(pageName))
|
|
page = Path(PurePosixPath(self.user_folder).joinpath(pageName, 'page.json'))
|
|
page_type = Path('./app/templates/themes/'+self.datas['config']['theme']+'/pages/'+pageType+'.json')
|
|
|
|
if not page_type.exists():
|
|
raise FileNotFoundError(f"Le type de page n'existe pas : {page_type}")
|
|
else:
|
|
page_folder.mkdir()
|
|
page.write_text(page_type.read_text())
|
|
|
|
if not page.exists():
|
|
raise FileNotFoundError(f"La page n'a pas pu etre créé : {page}")
|
|
|
|
return True
|
|
|
|
def rm_page(self, pageName :str):
|
|
page_folder = Path(PurePosixPath(self.user_folder).joinpath(pageName))
|
|
page = Path(PurePosixPath(self.user_folder).joinpath(pageName, 'page.json'))
|
|
|
|
#First delete the json page
|
|
try:
|
|
page.unlink()
|
|
print(f"Successfully deleted: {page}")
|
|
except FileNotFoundError:
|
|
print(f"File not found: {page}. Nothing to delete.")
|
|
# Delete the empty directory
|
|
if page_folder.is_dir():
|
|
try:
|
|
page_folder.rmdir()
|
|
print(f"Successfully removed empty directory: {page_folder}")
|
|
except OSError as e:
|
|
print(f"Error removing directory (might not be empty): {e}")
|
|
|
|
|
|
def writeHTML(self, theme:str, pageName :str, htmlExport :str):
|
|
publicFolder = Path(PurePosixPath(self.user_folder).joinpath('public'))
|
|
themesFolder = Path(PurePosixPath('app').joinpath('templates','themes', self.datas['config']['theme'],'static'))
|
|
|
|
if pageName == '/':
|
|
pageIndex = publicFolder / 'index.html'
|
|
pageIndex.write_text(htmlExport)
|
|
else:
|
|
pageFolder = Path(PurePosixPath(self.user_folder).joinpath('public', pageName))
|
|
pageFolder.mkdir(exist_ok=True)
|
|
pageIndex = pageFolder / 'index.html'
|
|
pageIndex.write_text(htmlExport)
|
|
|
|
def copy_static_files(self):
|
|
themesStaticFolder = Path(PurePosixPath('app').joinpath('static','themes', self.datas['config']['theme']))
|
|
publicStaticFolder = Path(PurePosixPath(self.user_folder).joinpath('public', 'static', 'themes', self.datas['config']['theme']))
|
|
|
|
rmtree (publicStaticFolder, ignore_errors=True)
|
|
|
|
copytree(themesStaticFolder, publicStaticFolder)
|
|
|
|
|
|
def publish(self, user:str, password:str, serverAddress:str, serverPort:int, folder:str):
|
|
remote_directory = "/remote/dir"
|
|
userDir = Path(PurePosixPath(self.user_folder))
|
|
|
|
command = "lftp -u \"{}\",\"{}\" -p {} {} -e ' mirror -R public {}; chmod -R o+rx ./; bye;'".format(user,
|
|
password,
|
|
serverPort,
|
|
serverAddress,
|
|
folder)
|
|
try:
|
|
subprocess.call(command, shell=True, cwd=str(userDir))
|
|
except ChildProcessError:
|
|
return False
|
|
|
|
return True
|
|
|
|
def emptyTrash(self):
|
|
for file in self.trash:
|
|
try:
|
|
remove(self.static_path+'img/portfolio/fullsize/'+file)
|
|
except FileNotFoundError:
|
|
print (f'Le fichier {file} n\'existe pas')
|
|
if path.exists((self.static_path+'img/portfolio/thumbnails/'+file)):
|
|
remove(self.static_path+'img/portfolio/thumbnails/'+file)
|
|
self.trash.clear()
|
|
|
|
|
|
|