1
0

Compare commits

...

3 Commits

7 changed files with 159 additions and 169 deletions

View File

@@ -9,7 +9,7 @@ import utils
import database
def GetUsernamePassword():
def GetUsernamePassword() -> tuple[str, str]:
print("What is the first username of this calendar system?")
cache = input()
while not utils.IsValidUsername(cache):
@@ -27,14 +27,19 @@ def GetUsernamePassword():
return (username, password)
def SetLoggingStyle(level: int) -> None:
logging.basicConfig(format="[%(levelname)s] %(message)s", level=level)
if __name__ == "__main__":
print("Coconut-leaf")
print("A self-host, multi-account calendar system.")
print("Project: https://github.com/yyc12345/coconut-leaf")
print("===================")
# Set as INFO level in default first,
# and we will change it once we load the configuration file.
SetLoggingStyle(logging.INFO)
# Receive arguments
parser = ArgumentParser(description="Coconut-leaf")
parser = ArgumentParser(
description="The server of light, self-host and multi-account calendar system."
)
parser.add_argument(
"-c",
"--config",
@@ -54,16 +59,22 @@ if __name__ == "__main__":
)
args = parser.parse_args()
# Show splash
logging.info("Coconut-leaf")
logging.info("A light, self-host and multi-account calendar system")
logging.info("Project: https://github.com/yyc12345/coconut-leaf")
logging.info("===================")
# Load config file
try:
config.setup_config(cast(Path, args.config))
except Exception as e:
print(f"Error loading config file: {e}")
logging.critical(f"Error loading config file: {e}")
sys.exit(1)
# Setup logging level
# Change logging level again according to whether enable debug mode
logging_level = logging.DEBUG if config.get_config().others.debug else logging.INFO
logging.basicConfig(format='[%(levelname)s] %(message)s', level=logging_level)
SetLoggingStyle(logging_level)
# Initialize the calendar system if needed
if cast(bool, args.init):

View File

@@ -15,7 +15,7 @@ path = "coconut-leaf.db"
# database = "coconut_leaf"
[web]
port = 8888
port = 8848
[others]
auto-token-clean-duration = 86400

View File

@@ -1,14 +0,0 @@
{
"database-type": "sqlite",
"database-config": {
"user": "",
"password": "",
"db": "",
"url": "",
"port": 3306
},
"web": {
"port": 8888
},
"debug": true
}

View File

@@ -1,107 +1,23 @@
from flask import Flask
# from flask import g
from flask import render_template
from flask import url_for
from flask import request
# from flask import abort
from flask import redirect
# from functools import reduce
# import json
# import os
import config
import database
import utils
from pathlib import Path
_FRONTEND_PATH = Path(__file__).resolve().parent.parent / "frontend"
app = Flask(
__name__,
static_folder=_FRONTEND_PATH / "static",
template_folder=_FRONTEND_PATH / "templates",
)
app = Flask(__name__)
calendar_db = database.CalendarDatabase()
# render_static_resources = None
# region: API Route
# =============================================database
# region: Common
# def get_database():
# db = getattr(g, '_database', None)
# if db is None:
# db = database.CalendarDatabase()
# db.open()
# return db
# @app.teardown_appcontext
# def close_database(exception):
# db = getattr(g, '_database', None)
# if db is not None:
# db.close()
# ============================================= static page route
@app.route('/', methods=['GET'])
def nospecHandle():
return redirect(url_for('web_homeHandle'))
@app.route('/web/home', methods=['GET'])
def web_homeHandle():
# UpdateStaticResources()
return render_template("home.html")
@app.route('/web/calendar', methods=['GET'])
def web_calendarHandle():
# UpdateStaticResources()
return render_template("calendar.html")
@app.route('/web/todo', methods=['GET'])
def web_todoHandle():
# UpdateStaticResources()
return render_template("todo.html")
@app.route('/web/admin', methods=['GET'])
def web_adminHandle():
# UpdateStaticResources()
return render_template("admin.html")
@app.route('/web/login', methods=['GET'])
def web_loginHandle():
# UpdateStaticResources()
return render_template("login.html")
@app.route('/web/collection', methods=['GET'])
def web_collectionHandle():
# UpdateStaticResources()
return render_template("collection.html")
@app.route('/web/eventAdd', methods=['GET'])
def web_eventAddHandle():
# UpdateStaticResources()
return render_template("event.html",
uuidPath=''
)
@app.route('/web/eventUpdate/<path:uuidPath>', methods=['GET'])
def web_eventUpdateHandle(uuidPath):
# UpdateStaticResources()
return render_template("event.html",
uuidPath = uuidPath
)
# ============================================= query page route
# ================================ common
@app.route('/api/common/salt', methods=['POST'])
@app.route('/common/salt', methods=['POST'])
def api_common_saltHandle():
return SmartDbCaller(calendar_db.common_salt,
(('username', str, False), ),
None)
@app.route('/api/common/login', methods=['POST'])
@app.route('/common/login', methods=['POST'])
def api_common_loginHandle():
# construct client data first
clientUa = request.user_agent.string
@@ -120,7 +36,7 @@ def api_common_loginHandle():
'clientIp': clientIp
})
@app.route('/api/common/webLogin', methods=['POST'])
@app.route('/common/webLogin', methods=['POST'])
def api_common_webLoginHandle():
# construct client data first
clientUa = request.user_agent.string
@@ -139,21 +55,23 @@ def api_common_webLoginHandle():
'clientIp': clientIp
})
@app.route('/api/common/logout', methods=['POST'])
@app.route('/common/logout', methods=['POST'])
def api_common_logoutHandle():
return SmartDbCaller(calendar_db.common_logout,
(('token', str, False), ),
None)
@app.route('/api/common/tokenValid', methods=['POST'])
@app.route('/common/tokenValid', methods=['POST'])
def api_common_tokenValidHandle():
return SmartDbCaller(calendar_db.common_tokenValid,
(('token', str, False), ),
None)
# ================================ calendar
# endregion
@app.route('/api/calendar/getFull', methods=['POST'])
# region: Calendar
@app.route('/calendar/getFull', methods=['POST'])
def api_calendar_getFullHandle():
return SmartDbCaller(calendar_db.calendar_getFull,
(('token', str, False),
@@ -161,7 +79,7 @@ def api_calendar_getFullHandle():
('endDateTime', int, False)),
None)
@app.route('/api/calendar/getList', methods=['POST'])
@app.route('/calendar/getList', methods=['POST'])
def api_calendar_getListHandle():
return SmartDbCaller(calendar_db.calendar_getList,
(('token', str, False),
@@ -169,14 +87,14 @@ def api_calendar_getListHandle():
('endDateTime', int, False)),
None)
@app.route('/api/calendar/getDetail', methods=['POST'])
@app.route('/calendar/getDetail', methods=['POST'])
def api_calendar_getDetailHandle():
return SmartDbCaller(calendar_db.calendar_getDetail,
(('token', str, False),
('uuid', str, False)),
None)
@app.route('/api/calendar/update', methods=['POST'])
@app.route('/calendar/update', methods=['POST'])
def api_calendar_updateHandle():
return SmartDbCaller(calendar_db.calendar_update,
(('token', str, False),
@@ -191,7 +109,7 @@ def api_calendar_updateHandle():
('lastChange', str, False)),
None)
@app.route('/api/calendar/add', methods=['POST'])
@app.route('/calendar/add', methods=['POST'])
def api_calendar_addHandle():
return SmartDbCaller(calendar_db.calendar_add,
(('token', str, False),
@@ -204,7 +122,7 @@ def api_calendar_addHandle():
('timezoneOffset', int, False)),
None)
@app.route('/api/calendar/delete', methods=['POST'])
@app.route('/calendar/delete', methods=['POST'])
def api_calendar_deleteHandle():
return SmartDbCaller(calendar_db.calendar_delete,
(('token', str, False),
@@ -212,35 +130,37 @@ def api_calendar_deleteHandle():
('lastChange', str, False)),
None)
# ================================ collection
# endregion
@app.route('/api/collection/getFullOwn', methods=['POST'])
# region: Collection
@app.route('/collection/getFullOwn', methods=['POST'])
def api_collection_getFullOwnHandle():
return SmartDbCaller(calendar_db.collection_getFullOwn,
(('token', str, False), ),
None)
@app.route('/api/collection/getListOwn', methods=['POST'])
@app.route('/collection/getListOwn', methods=['POST'])
def api_collection_getListOwnHandle():
return SmartDbCaller(calendar_db.collection_getListOwn,
(('token', str, False), ),
None)
@app.route('/api/collection/getDetailOwn', methods=['POST'])
@app.route('/collection/getDetailOwn', methods=['POST'])
def api_collection_getDetailOwnHandle():
return SmartDbCaller(calendar_db.collection_getDetailOwn,
(('token', str, False),
('uuid', str, False)),
None)
@app.route('/api/collection/addOwn', methods=['POST'])
@app.route('/collection/addOwn', methods=['POST'])
def api_collection_addOwnHandle():
return SmartDbCaller(calendar_db.collection_addOwn,
(('token', str, False),
('name', str, False)),
None)
@app.route('/api/collection/updateOwn', methods=['POST'])
@app.route('/collection/updateOwn', methods=['POST'])
def api_collection_updateOwnHandle():
return SmartDbCaller(calendar_db.collection_updateOwn,
(('token', str, False),
@@ -249,7 +169,7 @@ def api_collection_updateOwnHandle():
('lastChange', str, False)),
None)
@app.route('/api/collection/deleteOwn', methods=['POST'])
@app.route('/collection/deleteOwn', methods=['POST'])
def api_collection_deleteOwnHandle():
return SmartDbCaller(calendar_db.collection_deleteOwn,
(('token', str, False),
@@ -258,14 +178,14 @@ def api_collection_deleteOwnHandle():
None)
@app.route('/api/collection/getSharing', methods=['POST'])
@app.route('/collection/getSharing', methods=['POST'])
def api_collection_getSharingHandle():
return SmartDbCaller(calendar_db.collection_getSharing,
(('token', str, False),
('uuid', str, False)),
None)
@app.route('/api/collection/deleteSharing', methods=['POST'])
@app.route('/collection/deleteSharing', methods=['POST'])
def api_collection_deleteSharingHandle():
return SmartDbCaller(calendar_db.collection_deleteSharing,
(('token', str, False),
@@ -274,7 +194,7 @@ def api_collection_deleteSharingHandle():
('lastChange', str, False)),
None)
@app.route('/api/collection/addSharing', methods=['POST'])
@app.route('/collection/addSharing', methods=['POST'])
def api_collection_addSharingHandle():
return SmartDbCaller(calendar_db.collection_addSharing,
(('token', str, False),
@@ -284,40 +204,42 @@ def api_collection_addSharingHandle():
None)
@app.route('/api/collection/getShared', methods=['POST'])
@app.route('/collection/getShared', methods=['POST'])
def api_collection_getSharedHandle():
return SmartDbCaller(calendar_db.collection_getShared,
(('token', str, False), ),
None)
# ================================ todo
# endregion
@app.route('/api/todo/getFull', methods=['POST'])
# region: Todo
@app.route('/todo/getFull', methods=['POST'])
def api_todo_getFullHandle():
return SmartDbCaller(calendar_db.todo_getFull,
(('token', str, False), ),
None)
@app.route('/api/todo/getList', methods=['POST'])
@app.route('/todo/getList', methods=['POST'])
def api_todo_getListHandle():
return SmartDbCaller(calendar_db.todo_getList,
(('token', str, False), ),
None)
@app.route('/api/todo/getDetail', methods=['POST'])
@app.route('/todo/getDetail', methods=['POST'])
def api_todo_getDetailHandle():
return SmartDbCaller(calendar_db.todo_getDetail,
(('token', str, False),
('uuid', str, False)),
None)
@app.route('/api/todo/add', methods=['POST'])
@app.route('/todo/add', methods=['POST'])
def api_todo_addHandle():
return SmartDbCaller(calendar_db.todo_add,
(('token', str, False), ),
None)
@app.route('/api/todo/update', methods=['POST'])
@app.route('/todo/update', methods=['POST'])
def api_todo_updateHandle():
return SmartDbCaller(calendar_db.todo_update,
(('token', str, False),
@@ -326,7 +248,7 @@ def api_todo_updateHandle():
('lastChange', str, False)),
None)
@app.route('/api/todo/delete', methods=['POST'])
@app.route('/todo/delete', methods=['POST'])
def api_todo_deleteHandle():
return SmartDbCaller(calendar_db.todo_delete,
(('token', str, False),
@@ -334,22 +256,24 @@ def api_todo_deleteHandle():
('lastChange', str, False)),
None)
# ================================ admin
# endregion
@app.route('/api/admin/get', methods=['POST'])
# region: Admin
@app.route('/admin/get', methods=['POST'])
def api_admin_getHandle():
return SmartDbCaller(calendar_db.admin_get,
(('token', str, False), ),
None)
@app.route('/api/admin/add', methods=['POST'])
@app.route('/admin/add', methods=['POST'])
def api_admin_addHandle():
return SmartDbCaller(calendar_db.admin_add,
(('token', str, False),
('username', str, False)),
None)
@app.route('/api/admin/update', methods=['POST'])
@app.route('/admin/update', methods=['POST'])
def api_admin_updateHandle():
return SmartDbCaller(calendar_db.admin_update,
(('token', str, False),
@@ -358,60 +282,48 @@ def api_admin_updateHandle():
('isAdmin', utils.Str2Bool, True)),
None)
@app.route('/api/admin/delete', methods=['POST'])
@app.route('/admin/delete', methods=['POST'])
def api_admin_deleteHandle():
return SmartDbCaller(calendar_db.admin_delete,
(('token', str, False),
('username', str, False)),
None)
# ================================ profile
# endregion
@app.route('/api/profile/isAdmin', methods=['POST'])
# region: Profile
@app.route('/profile/isAdmin', methods=['POST'])
def api_profile_isAdminHandle():
return SmartDbCaller(calendar_db.profile_isAdmin,
(('token', str, False), ),
None)
@app.route('/api/profile/changePassword', methods=['POST'])
@app.route('/profile/changePassword', methods=['POST'])
def api_profile_changePasswordHandle():
return SmartDbCaller(calendar_db.profile_changePassword,
(('token', str, False),
('password', str, False)),
None)
@app.route('/api/profile/getToken', methods=['POST'])
@app.route('/profile/getToken', methods=['POST'])
def api_profile_getTokenHandle():
return SmartDbCaller(calendar_db.profile_getToken,
(('token', str, False), ),
None)
@app.route('/api/profile/deleteToken', methods=['POST'])
@app.route('/profile/deleteToken', methods=['POST'])
def api_profile_deleteTokenHandle():
return SmartDbCaller(calendar_db.profile_deleteToken,
(('token', str, False),
('deleteToken', str, False)),
None)
# =============================================main run
# endregion
'''
def UpdateStaticResources():
global render_static_resources
if render_static_resources is not None:
return
# endregion
render_static_resources = {
'url_js_localStorageAssist': url_for('static', filename='js/localStorageAssist.js'),
'url_js_i18n': url_for('static', filename='js/i18n.js'),
'url_js_api': url_for('static', filename='js/api.js'),
'url_js_headerNav': url_for('static', filename='js/headerNav.js'),
'url_tmpl_headerNac': url_for('static', filename='tmpl/headerNav.tmpl'),
'url_js_pageHome': url_for('static', filename='js/page/home.js')
}
'''
# region: Misc Functions
def SmartDbCaller(dbMethod, paramTuple, extraDict):
result = (False, 'Invalid parameter', None)
@@ -455,3 +367,4 @@ def run():
app.run(port=config.get_config().web.port)
calendar_db.close()
# endregion

View File

@@ -15,4 +15,23 @@ export default defineConfig({
'@': fileURLToPath(new URL('./src', import.meta.url))
},
},
// 项目基础路径(对应 Nginx 路由到的 /web 前缀)
base: '/web/',
server: {
port: 5173, // 开发服务器默认端口
open: '/web/', // 启动时自动打开 /web 路径
// 核心:代理配置(对应 Nginx 的 /api -> Go 服务)
proxy: {
// 精细控制路由,对齐生产环境
'^/api/(.*)$': {
target: 'http://127.0.0.1:8848',
changeOrigin: true,
// 路径重写/api/user -> /user
rewrite: (path) => path.replace(/^\/api\//, '/'),
}
},
})

61
tools/.nginx.conf Normal file
View File

@@ -0,0 +1,61 @@
# ============================
# 路由 1: /web -> 静态文件
# ============================
location /web {
# 使用 alias 精确映射
# 请求 /web/index.html -> /var/www/static/index.html
alias /var/www/static;
# 静态文件优化
expires 7d;
add_header Cache-Control "public, max-age=604800";
# 尝试返回文件不存在则返回404避免落入其他location
try_files $uri $uri/ =404;
# 可选:启用 gzip 压缩
gzip_static on;
}
# ============================
# 路由 2: /api -> Go 程序 (8848端口)
# ============================
location /api {
# 反向代理到本地 Go 服务
proxy_pass http://127.0.0.1:8848;
# 重要:保留原始请求头
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# WebSocket 支持(如果 Go 程序需要)
# proxy_http_version 1.1;
# proxy_set_header Upgrade $http_upgrade;
# proxy_set_header Connection "upgrade";
# 超时设置(根据业务调整)
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# 缓冲设置(可选,大文件上传时注意调整)
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
}
# ============================
# 可选:根路径处理
# ============================
location = / {
# 重定向到 /web
return 302 /web/;
}
# 禁止访问隐藏文件
location ~ /\. {
deny all;
return 404;
}