Compare commits
32
Commits
v1.1
...
20bf3a0c34
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
20bf3a0c34 | ||
|
|
14350f84c5 | ||
|
|
7e335c51c6 | ||
|
|
9f7fd6e5e7 | ||
|
|
1cc6b7b1ba | ||
|
|
a8de650a5a | ||
|
|
b3efb196ed | ||
|
|
26dce7ce80 | ||
|
|
0f674d0483 | ||
|
|
e6fc06c0f9 | ||
|
|
91317c9eb7 | ||
|
|
b1b42ab2fb | ||
|
|
18f73b3084 | ||
|
|
fcc022d070 | ||
|
|
fda2fe9ec9 | ||
|
|
ebe7ea5f56 | ||
|
|
c4b68400b3 | ||
|
|
d7df194a12 | ||
|
|
35fee0f473 | ||
|
|
e484ded5be | ||
|
|
2a280dcba0 | ||
|
|
6337ae432d | ||
|
|
826cbf18b1 | ||
|
|
167c83f7d4 | ||
|
|
078e61e993 | ||
|
|
bdee3b3efa | ||
|
|
37b08927a7 | ||
|
|
46f2d69800 | ||
|
|
24790d8e69 | ||
|
|
07205396c8 | ||
|
|
433c6cf2f8 | ||
|
|
37435eeb66 |
No files matched your search
+10
@@ -0,0 +1,10 @@
|
||||
# Roadmap
|
||||
|
||||
1. 前后端分离,将前端静态文件和后端Python分装到两个文件夹中。同时辅助类文件夹改换位置。
|
||||
1. 后端使用Astral UV重构,使得项目可以跑起来。
|
||||
1. 定为1.1版本。1.0版本也要打tag然后提交。然后分叉v1-maintain分支。后续在master上开发v2。
|
||||
1. 后端数据库字段重命名。
|
||||
1. 前后端通信API命名格式修改。
|
||||
1. 使用Vue重写前端
|
||||
1. 使用Tailwind重写前端CSS
|
||||
1. 使用Go重写后端。
|
||||
@@ -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;
|
||||
}
|
||||
File renamed without changes.
@@ -0,0 +1,101 @@
|
||||
import icalendar
|
||||
|
||||
def DumpComponentHeader(file, component):
|
||||
fields = []
|
||||
inclusiveUnitCounter = 0
|
||||
fields += map(lambda x: x + ' - required', component.required)
|
||||
fields += map(lambda x: x + ' - singletons', component.singletons)
|
||||
for units in component.inclusive:
|
||||
fields += map(lambda x: x + ' - inclusive{}'.format(inclusiveUnitCounter), units)
|
||||
inclusiveUnitCounter += 1
|
||||
fields += ('exclusive - name', 'exclusive - data')
|
||||
fields += ('multiple', )
|
||||
file.write(','.join(fields))
|
||||
file.write('\n')
|
||||
|
||||
def DumpComponentData(file, component):
|
||||
data = []
|
||||
gotten_instance = None
|
||||
|
||||
for item in component.required:
|
||||
gotten_instance = component.get(item)
|
||||
if gotten_instance is not None:
|
||||
data.append(AdvancedFormater(gotten_instance))
|
||||
else:
|
||||
data.append('')
|
||||
for item in component.singletons:
|
||||
gotten_instance = component.get(item)
|
||||
if gotten_instance is not None:
|
||||
data.append(AdvancedFormater(gotten_instance))
|
||||
else:
|
||||
data.append('')
|
||||
for units in component.inclusive:
|
||||
for item in units:
|
||||
gotten_instance = component.get(item)
|
||||
if gotten_instance is not None:
|
||||
data.append(AdvancedFormater(gotten_instance))
|
||||
else:
|
||||
data.append('')
|
||||
|
||||
gotten_name = ""
|
||||
gotten_data = ""
|
||||
for item in component.exclusive:
|
||||
gotten_instance = component.get(item)
|
||||
if gotten_instance is not None:
|
||||
gotten_name = item
|
||||
gotten_data = AdvancedFormater(gotten_instance)
|
||||
break
|
||||
data.append(gotten_name)
|
||||
data.append(gotten_data)
|
||||
|
||||
for item in component.multiple:
|
||||
gotten_instance = component.get(item)
|
||||
if gotten_instance is not None:
|
||||
data.append('- {} -'.format(item))
|
||||
data.append(AdvancedFormater(gotten_instance))
|
||||
else:
|
||||
data.append('')
|
||||
|
||||
file.write(','.join(data))
|
||||
file.write('\n')
|
||||
|
||||
def AdvancedFormater(data):
|
||||
if isinstance(data, icalendar.prop.vDDDTypes):
|
||||
return str(data.dt)
|
||||
else:
|
||||
return str(data)
|
||||
|
||||
# read file
|
||||
icsFile = open('test.ics', 'rb')
|
||||
cal = icalendar.Calendar.from_ical(icsFile.read())
|
||||
icsFile.close()
|
||||
|
||||
# analyse file
|
||||
csvEvent = open('event.csv', 'w')
|
||||
csvEventHeader = False
|
||||
csvAlarm = open('alarm.csv', 'w')
|
||||
csvAlarmHeader = False
|
||||
|
||||
eventCount = 0
|
||||
alarmCount = 0
|
||||
miscCount = 0
|
||||
for component in cal.walk():
|
||||
if component.name == 'VEVENT':
|
||||
eventCount += 1
|
||||
if not csvEventHeader:
|
||||
DumpComponentHeader(csvEvent, component)
|
||||
csvEventHeader = True
|
||||
DumpComponentData(csvEvent, component)
|
||||
elif component.name == 'VALARM':
|
||||
alarmCount += 1
|
||||
if not csvAlarmHeader:
|
||||
DumpComponentHeader(csvAlarm, component)
|
||||
csvAlarmHeader = True
|
||||
DumpComponentData(csvAlarm, component)
|
||||
else:
|
||||
miscCount += 1
|
||||
|
||||
|
||||
csvEvent.close()
|
||||
csvAlarm.close()
|
||||
print('Event count: {}\nAlarm count: {}\nMisc count: {}'.format(eventCount, alarmCount, miscCount))
|
||||
@@ -0,0 +1,156 @@
|
||||
import icalendar
|
||||
import sys
|
||||
import os
|
||||
import database
|
||||
import json
|
||||
import datetime
|
||||
import dt as localdt
|
||||
|
||||
def AdvancedDatetTimeGet(dt, isStartDateTime):
|
||||
if isinstance(dt, datetime.datetime):
|
||||
gottenDatetime = int(dt.timestamp() / 60)
|
||||
elif isinstance(dt, datetime.date):
|
||||
gottenDatetime = int(datetime.datetime(
|
||||
dt.year,
|
||||
dt.month,
|
||||
dt.day,
|
||||
0 if isStartDateTime else 23,
|
||||
0 if isStartDateTime else 59,
|
||||
0 if isStartDateTime else 59,
|
||||
0, tzinfo=LOCAL_TZ
|
||||
).timestamp() / 60)
|
||||
else:
|
||||
raise Exception('Unexpected data')
|
||||
|
||||
timezoneOffset = LOCAL_UTC_OFFSET
|
||||
return (gottenDatetime, timezoneOffset)
|
||||
|
||||
def AdvancedDateTimeAnalyser(component):
|
||||
startDatetimeRef = component.get('DTSTART').dt
|
||||
(startDatetime, timezoneOffset) = AdvancedDatetTimeGet(startDatetimeRef, True)
|
||||
|
||||
if component.get('DTEND') is not None:
|
||||
(endDatetime, _) = AdvancedDatetTimeGet(startDatetimeRef, False)
|
||||
elif component.get('DURATION') is not None:
|
||||
endDurationRef = component.get('DURATION').dt
|
||||
if isinstance(endDurationRef, datetime.timedelta):
|
||||
endDatetime = startDatetime + int(endDurationRef.total_seconds() / 60)
|
||||
else:
|
||||
raise Exception('Unexpected data')
|
||||
else:
|
||||
raise Exception('Unexpected data')
|
||||
|
||||
return (startDatetime, endDatetime, timezoneOffset)
|
||||
|
||||
def LoopRulesConverter(component):
|
||||
jsonData = component.get('RRULE')
|
||||
if jsonData is None:
|
||||
return ""
|
||||
|
||||
loopRules = ""
|
||||
loopStopRules = ""
|
||||
freq = jsonData.get('FREQ')[0]
|
||||
if freq == 'MONTHLY':
|
||||
loopRules = 'MSA{}'.format(str(jsonData.get('INTERVAL')[0]))
|
||||
elif freq == 'WEEKLY':
|
||||
occupiedWeek = [False, ] * 7
|
||||
for item in jsonData.get('BYDAY'):
|
||||
occupiedWeek[WEEK_DICT[item]] = True
|
||||
loopRules = 'W{}{}'.format(
|
||||
''.join(map(lambda x: 'T' if x else 'F', occupiedWeek)),
|
||||
str(jsonData.get('INTERVAL')[0])
|
||||
)
|
||||
elif freq == 'YEARLY':
|
||||
loopRules = 'YS{}'.format(str(jsonData.get('INTERVAL')[0]))
|
||||
else:
|
||||
raise Exception('Unexpected data')
|
||||
|
||||
if jsonData.get('COUNT') is not None:
|
||||
loopStopRules = 'T{}'.format(str(jsonData.get('COUNT')[0]))
|
||||
else:
|
||||
loopStopRules = 'F'
|
||||
|
||||
return loopRules + '-' + loopStopRules
|
||||
|
||||
# ============================ read args
|
||||
icsFilePath = sys.argv[1]
|
||||
if not os.path.isfile(icsFilePath):
|
||||
print('Fail to load ics file')
|
||||
sys.exit(1)
|
||||
|
||||
# read file
|
||||
icsFile = open(icsFilePath, 'rb')
|
||||
cal = icalendar.Calendar.from_ical(icsFile.read())
|
||||
icsFile.close()
|
||||
|
||||
# ============================ init const
|
||||
utfOffset = float(input('Input this ics file\'s utc offset (time unit: hour)>'))
|
||||
LOCAL_UTC_OFFSET = int(utfOffset * 60)
|
||||
LOCAL_TZ = localdt.UTCTimezone(LOCAL_UTC_OFFSET)
|
||||
WEEK_DICT = {
|
||||
"SU": 6, "MO": 0, "TU": 1, "WE": 2, "TH": 3, "FR": 4, "SA": 5,
|
||||
}
|
||||
|
||||
# ============================ pick database
|
||||
|
||||
db = database.CalendarDatabase()
|
||||
db.open()
|
||||
username = input('Input username >')
|
||||
password = input('Input password >')
|
||||
(status, error, token) = db.common_webLogin(username, password, 'Python backend', '127.0.0.1')
|
||||
if not status:
|
||||
print('Fail to login.')
|
||||
sys.exit(1)
|
||||
(status, error, collectionList) = db.collection_getFullOwn(token)
|
||||
if not status:
|
||||
print('Database return an error')
|
||||
sys.exit(1)
|
||||
print('Pick a collection to insert imported events')
|
||||
counter = 0
|
||||
for i in collectionList:
|
||||
print('{}\t{}'.format(counter, i[1]))
|
||||
counter += 1
|
||||
pickedIndex = int(input())
|
||||
collectionUuid = collectionList[pickedIndex][0]
|
||||
|
||||
# ============================ analyse file
|
||||
eventCount = 0
|
||||
allCount = 0
|
||||
for component in cal.walk():
|
||||
allCount += 1
|
||||
# only import event chunk
|
||||
if component.name == 'VEVENT':
|
||||
eventCount += 1
|
||||
title = str(component.get('SUMMARY'))
|
||||
descriptionPrototype = {
|
||||
'color': '#1e90ff',
|
||||
'description': None
|
||||
}
|
||||
descriptionList = []
|
||||
if component.get('DESCRIPTION') is not None and str(component.get('DESCRIPTION')) != '':
|
||||
descriptionList.append(component.get('DESCRIPTION'))
|
||||
if component.get('LOCATION') is not None and str(component.get('LOCATION')) != '':
|
||||
descriptionList.append(component.get('LOCATION'))
|
||||
descriptionPrototype['description'] = '\n'.join(descriptionList)
|
||||
description = json.dumps(descriptionPrototype)
|
||||
|
||||
(eventDateTimeStart, eventDateTimeEnd, timezoneOffset) = AdvancedDateTimeAnalyser(component)
|
||||
loopRules = LoopRulesConverter(component)
|
||||
|
||||
(status, _, _) = db.calendar_add(
|
||||
token,
|
||||
collectionUuid,
|
||||
title,
|
||||
description,
|
||||
eventDateTimeStart,
|
||||
eventDateTimeEnd,
|
||||
loopRules,
|
||||
timezoneOffset
|
||||
)
|
||||
if not status:
|
||||
print('Database return an error')
|
||||
sys.exit(1)
|
||||
|
||||
db.common_logout(token)
|
||||
db.close()
|
||||
print('All chunk: {}\nEvent count: {}'.format(allCount, eventCount))
|
||||
@@ -0,0 +1,3 @@
|
||||
# Migration
|
||||
|
||||
This directory contains the migration scripts for the database.
|
||||
@@ -0,0 +1,49 @@
|
||||
-- Migration script for coconut-leaf database v1 to v2
|
||||
-- This script updates field names by:
|
||||
-- 1. Removing 'ccn_' prefix from all fields
|
||||
-- 2. Converting camelCase to snake_case
|
||||
|
||||
-- Step 1: Rename user table columns
|
||||
ALTER TABLE user RENAME COLUMN ccn_name TO name;
|
||||
ALTER TABLE user RENAME COLUMN ccn_password TO password;
|
||||
ALTER TABLE user RENAME COLUMN ccn_isAdmin TO is_admin;
|
||||
ALTER TABLE user RENAME COLUMN ccn_salt TO salt;
|
||||
|
||||
-- Step 2: Rename token table columns
|
||||
ALTER TABLE token RENAME COLUMN ccn_user TO user;
|
||||
ALTER TABLE token RENAME COLUMN ccn_token TO token;
|
||||
ALTER TABLE token RENAME COLUMN ccn_tokenExpireOn TO token_expire_on;
|
||||
ALTER TABLE token RENAME COLUMN ccn_ua TO ua;
|
||||
ALTER TABLE token RENAME COLUMN ccn_ip TO ip;
|
||||
|
||||
-- Step 3: Rename collection table columns
|
||||
ALTER TABLE collection RENAME COLUMN ccn_uuid TO uuid;
|
||||
ALTER TABLE collection RENAME COLUMN ccn_name TO name;
|
||||
ALTER TABLE collection RENAME COLUMN ccn_user TO user;
|
||||
ALTER TABLE collection RENAME COLUMN ccn_lastChange TO last_change;
|
||||
|
||||
-- Step 4: Rename share table columns
|
||||
ALTER TABLE share RENAME COLUMN ccn_uuid TO uuid;
|
||||
ALTER TABLE share RENAME COLUMN ccn_target TO target;
|
||||
|
||||
-- Step 5: Rename calendar table columns
|
||||
ALTER TABLE calendar RENAME COLUMN ccn_uuid TO uuid;
|
||||
ALTER TABLE calendar RENAME COLUMN ccn_belongTo TO belong_to;
|
||||
ALTER TABLE calendar RENAME COLUMN ccn_title TO title;
|
||||
ALTER TABLE calendar RENAME COLUMN ccn_description TO description;
|
||||
ALTER TABLE calendar RENAME COLUMN ccn_lastChange TO last_change;
|
||||
ALTER TABLE calendar RENAME COLUMN ccn_eventDateTimeStart TO event_date_time_start;
|
||||
ALTER TABLE calendar RENAME COLUMN ccn_eventDateTimeEnd TO event_date_time_end;
|
||||
ALTER TABLE calendar RENAME COLUMN ccn_timezoneOffset TO timezone_offset;
|
||||
ALTER TABLE calendar RENAME COLUMN ccn_loopRules TO loop_rules;
|
||||
ALTER TABLE calendar RENAME COLUMN ccn_loopDateTimeStart TO loop_date_time_start;
|
||||
ALTER TABLE calendar RENAME COLUMN ccn_loopDateTimeEnd TO loop_date_time_end;
|
||||
|
||||
-- Step 6: Rename todo table columns
|
||||
ALTER TABLE todo RENAME COLUMN ccn_uuid TO uuid;
|
||||
ALTER TABLE todo RENAME COLUMN ccn_belongTo TO belong_to;
|
||||
ALTER TABLE todo RENAME COLUMN ccn_data TO data;
|
||||
ALTER TABLE todo RENAME COLUMN ccn_lastChange TO last_change;
|
||||
|
||||
-- Note: Foreign key constraints will be automatically updated by SQLite when renaming columns
|
||||
-- No additional steps needed for foreign keys
|
||||
@@ -0,0 +1,19 @@
|
||||
## ======== Personal ========
|
||||
# Database file
|
||||
*.db
|
||||
|
||||
# Ignore setting file
|
||||
coconut-leaf.toml
|
||||
|
||||
## ======== Python ========
|
||||
# Python-generated files
|
||||
__pycache__/
|
||||
*.py[oc]
|
||||
build/
|
||||
dist/
|
||||
wheels/
|
||||
*.egg-info
|
||||
|
||||
# Virtual environments
|
||||
.venv
|
||||
|
||||
File renamed without changes.
File renamed without changes.
@@ -1,15 +1,17 @@
|
||||
import sys
|
||||
import logging
|
||||
from argparse import ArgumentParser
|
||||
from typing import cast
|
||||
from pathlib import Path
|
||||
|
||||
import server
|
||||
import config
|
||||
import utils
|
||||
import database
|
||||
import logger
|
||||
from logger import LOGGER, LoggerLevel
|
||||
|
||||
|
||||
def GetUsernamePassword():
|
||||
def GetUsernamePassword() -> tuple[str, str]:
|
||||
print("What is the first username of this calendar system?")
|
||||
cache = input()
|
||||
while not utils.IsValidUsername(cache):
|
||||
@@ -26,15 +28,15 @@ def GetUsernamePassword():
|
||||
|
||||
return (username, password)
|
||||
|
||||
|
||||
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.
|
||||
logger.set_level(LoggerLevel.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 +56,22 @@ if __name__ == "__main__":
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
# Show splash
|
||||
LOGGER.info("Coconut-leaf")
|
||||
LOGGER.info("A light, self-host and multi-account calendar system")
|
||||
LOGGER.info("Project: https://github.com/yyc12345/coconut-leaf")
|
||||
LOGGER.info("===================")
|
||||
|
||||
# Load config file
|
||||
try:
|
||||
config.setup_config(cast(Path, args.config))
|
||||
except Exception as e:
|
||||
print(f"Error loading config file: {e}")
|
||||
LOGGER.critical(f"Error loading config file: {e}")
|
||||
sys.exit(1)
|
||||
|
||||
# Setup logging level
|
||||
logging_level = logging.DEBUG if config.get_config().others.debug else logging.INFO
|
||||
logging.basicConfig(format='[%(levelname)s] %(message)s', level=logging_level)
|
||||
# Change logging level again according to whether enable debug mode
|
||||
logging_level = LoggerLevel.DEBUG if config.get_config().others.debug else LoggerLevel.INFO
|
||||
logger.set_level(logging_level)
|
||||
|
||||
# Initialize the calendar system if needed
|
||||
if cast(bool, args.init):
|
||||
@@ -72,5 +80,5 @@ if __name__ == "__main__":
|
||||
calendar.init(*gotten_data)
|
||||
calendar.close()
|
||||
|
||||
logging.info("Staring server...")
|
||||
LOGGER.info("Staring server...")
|
||||
server.run()
|
||||
@@ -15,7 +15,7 @@ path = "coconut-leaf.db"
|
||||
# database = "coconut_leaf"
|
||||
|
||||
[web]
|
||||
port = 8888
|
||||
port = 8848
|
||||
|
||||
[others]
|
||||
auto-token-clean-duration = 86400
|
||||
File renamed without changes.
@@ -1,54 +1,81 @@
|
||||
import config
|
||||
import sqlite3
|
||||
import utils
|
||||
import threading
|
||||
import logging
|
||||
import dt
|
||||
from typing import cast
|
||||
from pathlib import Path
|
||||
from dataclasses import dataclass
|
||||
from typing import Callable, ParamSpec, TypeVar, Generic
|
||||
|
||||
def SafeDatabaseOperation(func):
|
||||
def wrapper(self: 'CalendarDatabase', *args, **kwargs):
|
||||
import dt
|
||||
import utils
|
||||
import config
|
||||
from logger import LOGGER
|
||||
|
||||
|
||||
T = TypeVar('T')
|
||||
P = ParamSpec('P')
|
||||
R = TypeVar('R')
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ResponseBody(Generic[T]):
|
||||
"""The generic response body for API return."""
|
||||
|
||||
success: bool
|
||||
"""True if this operation is successful, otherwise false."""
|
||||
error: str
|
||||
"""The error message provided when operation failed."""
|
||||
data: T | None
|
||||
"""The payload provided when operation successed."""
|
||||
|
||||
|
||||
class DbException(Exception):
|
||||
"""Error occurs when manipulating with database."""
|
||||
pass
|
||||
|
||||
|
||||
def SafeDatabaseOperation(inner: Callable[P, R]) -> Callable[P, ResponseBody[R]]:
|
||||
def wrapper(*args, **kwargs) -> ResponseBody[R]:
|
||||
# extract self from args
|
||||
self: 'CalendarDatabase' = args[0]
|
||||
# get config
|
||||
cfg = config.get_config()
|
||||
|
||||
with self.mutex:
|
||||
# check database and acquire cursor
|
||||
# try to fetching database and allocate database cursor
|
||||
try:
|
||||
self.check_database()
|
||||
self.cursor = self.db.cursor()
|
||||
db = self._get_db()
|
||||
self._allocate_cursor()
|
||||
except Exception as e:
|
||||
self.cursor = None
|
||||
self._free_cursor()
|
||||
if cfg.others.debug:
|
||||
logging.exception(e)
|
||||
return (False, str(e), None)
|
||||
LOGGER.exception(e)
|
||||
return ResponseBody(False, str(e), None)
|
||||
|
||||
# do real data work
|
||||
try:
|
||||
currentTime = utils.GetCurrentTimestamp()
|
||||
if currentTime - self.latestClean > cfg.others.auto_token_clean_duration:
|
||||
self.latestClean = currentTime
|
||||
logging.info('Cleaning outdated token...')
|
||||
LOGGER.info('Cleaning outdated token...')
|
||||
self.tokenOper_clean()
|
||||
|
||||
result = (True, '', func(self, *args, **kwargs))
|
||||
self.cursor.close()
|
||||
self.cursor = None
|
||||
self.db.commit()
|
||||
result = ResponseBody(True, '', inner(*args, **kwargs))
|
||||
self._free_cursor()
|
||||
db.commit()
|
||||
return result
|
||||
except Exception as e:
|
||||
self.cursor.close()
|
||||
self.cursor = None
|
||||
self.db.rollback()
|
||||
self._free_cursor()
|
||||
db.rollback()
|
||||
if cfg.others.debug:
|
||||
logging.exception(e)
|
||||
return (False, str(e), None)
|
||||
LOGGER.exception(e)
|
||||
return ResponseBody(False, str(e), None)
|
||||
|
||||
return wrapper
|
||||
|
||||
class CalendarDatabase:
|
||||
|
||||
db: sqlite3.Connection
|
||||
cursor: sqlite3.Cursor
|
||||
db: sqlite3.Connection | None
|
||||
cursor: sqlite3.Cursor | None
|
||||
mutex: threading.Lock
|
||||
latestClean: int
|
||||
|
||||
@@ -59,8 +86,8 @@ class CalendarDatabase:
|
||||
self.latestClean = 0
|
||||
|
||||
def open(self):
|
||||
if (self.is_database_valid()):
|
||||
raise Exception('Databade is opened')
|
||||
if (self.db is not None):
|
||||
raise DbException('Database is already opened')
|
||||
|
||||
cfg = config.get_config()
|
||||
match cfg.database.driver:
|
||||
@@ -69,13 +96,13 @@ class CalendarDatabase:
|
||||
self.db.execute('PRAGMA encoding = "UTF-8";')
|
||||
self.db.execute('PRAGMA foreign_keys = ON;')
|
||||
case config.DatabaseDriver.MYSQL:
|
||||
raise Exception('Not implemented database')
|
||||
raise DbException('Not implemented database')
|
||||
case _:
|
||||
raise Exception('Unknow database type')
|
||||
raise DbException('Unknow database type')
|
||||
|
||||
def init(self, username, password):
|
||||
if (self.is_database_valid()):
|
||||
raise Exception('Database is opened')
|
||||
def init(self, username: str, password: str):
|
||||
if (self.db is not None):
|
||||
raise DbException('Database is already opened')
|
||||
|
||||
# establish tables
|
||||
cfg = config.get_config()
|
||||
@@ -85,44 +112,74 @@ class CalendarDatabase:
|
||||
case config.DatabaseDriver.SQLITE:
|
||||
sql_file = backend_sql_path / 'sqlite.sql'
|
||||
case config.DatabaseDriver.MYSQL:
|
||||
raise Exception('Not implemented database')
|
||||
raise DbException('Not implemented database')
|
||||
case _:
|
||||
raise Exception('Unknow database type')
|
||||
raise DbException('Unknow database type')
|
||||
|
||||
self.open()
|
||||
cursor = self.db.cursor()
|
||||
db = self._get_db()
|
||||
|
||||
self._allocate_cursor()
|
||||
cursor = self._get_cursor()
|
||||
|
||||
# execute script for creating tables
|
||||
with open(sql_file, 'r', encoding='utf-8') as fsql:
|
||||
cursor.executescript(fsql.read())
|
||||
|
||||
# finish init
|
||||
# add default user in user table
|
||||
cursor.execute('INSERT INTO user VALUES (?, ?, ?, ?);', (
|
||||
username,
|
||||
utils.ComputePasswordHash(password),
|
||||
1,
|
||||
utils.GenerateSalt()
|
||||
))
|
||||
cursor.close()
|
||||
self.db.commit()
|
||||
|
||||
self._free_cursor()
|
||||
|
||||
# commit to database
|
||||
db.commit()
|
||||
|
||||
def close(self):
|
||||
self.check_database()
|
||||
self.db.close()
|
||||
self.db = None
|
||||
if (self.db is None):
|
||||
LOGGER.warning('Try to close null database.')
|
||||
else:
|
||||
self._free_cursor()
|
||||
self.db.close()
|
||||
self.db = None
|
||||
|
||||
def check_database(self):
|
||||
if (not self.is_database_valid()):
|
||||
raise Exception('Databade is None')
|
||||
def _get_db(self) -> sqlite3.Connection:
|
||||
if (self.db is None):
|
||||
raise DbException('There is no opened database')
|
||||
else:
|
||||
return self.db
|
||||
|
||||
def is_database_valid(self):
|
||||
return not (self.db == None)
|
||||
def _allocate_cursor(self) -> None:
|
||||
if (self.cursor is not None):
|
||||
raise DbException('There is already opened database cursor')
|
||||
else:
|
||||
self.cursor = self._get_db().cursor()
|
||||
|
||||
def _get_cursor(self) -> sqlite3.Cursor:
|
||||
if (self.cursor is None):
|
||||
raise DbException('There is no opened database cursor')
|
||||
else:
|
||||
return self.cursor
|
||||
|
||||
def _free_cursor(self) -> None:
|
||||
if (self.cursor is None):
|
||||
LOGGER.warning('Try to free null databse cursor.')
|
||||
else:
|
||||
self.cursor.close()
|
||||
self.cursor = None
|
||||
|
||||
# ======================= token related internal operation
|
||||
def tokenOper_clean(self):
|
||||
# remove outdated token
|
||||
self.cursor.execute('DELETE FROM token WHERE [ccn_tokenExpireOn] <= ?',(utils.GetCurrentTimestamp(), ))
|
||||
cursor = self._get_cursor()
|
||||
cursor.execute('DELETE FROM token WHERE [token_expire_on] <= ?',(utils.GetCurrentTimestamp(), ))
|
||||
|
||||
def tokenOper_postpone_expireOn(self, token):
|
||||
self.cursor.execute('UPDATE token SET [ccn_tokenExpireOn] = ? WHERE [ccn_token] = ?;', (
|
||||
cursor = self._get_cursor()
|
||||
cursor.execute('UPDATE token SET [token_expire_on] = ? WHERE [token] = ?;', (
|
||||
utils.GetTokenExpireOn(),
|
||||
token
|
||||
))
|
||||
@@ -131,16 +188,18 @@ class CalendarDatabase:
|
||||
self.tokenOper_get_username(token)
|
||||
|
||||
def tokenOper_is_admin(self, username):
|
||||
self.cursor.execute('SELECT [ccn_isAdmin] FROM user WHERE [ccn_name] = ?;',(username, ))
|
||||
cache = self.cursor.fetchone()[0]
|
||||
cursor = self._get_cursor()
|
||||
cursor.execute('SELECT [is_admin] FROM user WHERE [name] = ?;',(username, ))
|
||||
cache = cursor.fetchone()[0]
|
||||
return cache == 1
|
||||
|
||||
def tokenOper_get_username(self, token):
|
||||
self.cursor.execute('SELECT [ccn_user] FROM token WHERE [ccn_token] = ? AND [ccn_tokenExpireOn] > ?;',(
|
||||
cursor = self._get_cursor()
|
||||
cursor.execute('SELECT [user] FROM token WHERE [token] = ? AND [token_expire_on] > ?;',(
|
||||
token,
|
||||
utils.GetCurrentTimestamp()
|
||||
))
|
||||
result = self.cursor.fetchone()[0]
|
||||
result = cursor.fetchone()[0]
|
||||
# need postpone expire on time
|
||||
self.tokenOper_postpone_expireOn(token)
|
||||
return result
|
||||
@@ -150,8 +209,9 @@ class CalendarDatabase:
|
||||
|
||||
@SafeDatabaseOperation
|
||||
def common_salt(self, username):
|
||||
cursor = self._get_cursor()
|
||||
salt = utils.GenerateSalt()
|
||||
self.cursor.execute('UPDATE user SET [ccn_salt] = ? WHERE [ccn_name] = ?;', (
|
||||
cursor.execute('UPDATE user SET [salt] = ? WHERE [name] = ?;', (
|
||||
salt,
|
||||
username
|
||||
))
|
||||
@@ -159,16 +219,17 @@ class CalendarDatabase:
|
||||
|
||||
@SafeDatabaseOperation
|
||||
def common_login(self, username, password, clientUa, clientIp):
|
||||
self.cursor.execute('SELECT [ccn_password], [ccn_salt] FROM user WHERE [ccn_name] = ?;', (username, ))
|
||||
(gotten_salt, gotten_password) = self.cursor.fetchone()
|
||||
cursor = self._get_cursor()
|
||||
cursor.execute('SELECT [password], [salt] FROM user WHERE [name] = ?;', (username, ))
|
||||
(gotten_salt, gotten_password) = cursor.fetchone()
|
||||
|
||||
if password == utils.ComputePasswordHashWithSalt(gotten_password, gotten_salt):
|
||||
token = utils.GenerateToken(username)
|
||||
self.cursor.execute('UPDATE user SET [ccn_salt] = ? WHERE [ccn_name] = ?;', (
|
||||
cursor.execute('UPDATE user SET [salt] = ? WHERE [name] = ?;', (
|
||||
utils.GenerateSalt(), # regenerate a new slat to prevent re-login try
|
||||
username
|
||||
))
|
||||
self.cursor.execute('INSERT INTO token VALUES (?, ?, ?, ?, ?);', (
|
||||
cursor.execute('INSERT INTO token VALUES (?, ?, ?, ?, ?);', (
|
||||
username,
|
||||
token,
|
||||
utils.GetTokenExpireOn(), # add 2 day from now
|
||||
@@ -178,15 +239,21 @@ class CalendarDatabase:
|
||||
return token
|
||||
else:
|
||||
# throw a exception to indicate fail to login
|
||||
raise Exception('Login authentication failed')
|
||||
raise DbException('Login authentication failed')
|
||||
|
||||
@SafeDatabaseOperation
|
||||
def common_webLogin(self, username, password, clientUa, clientIp):
|
||||
self.cursor.execute('SELECT [ccn_name] FROM user WHERE [ccn_name] = ? AND [ccn_password] = ?;', (username, utils.ComputePasswordHash(password)))
|
||||
cursor = self._get_cursor()
|
||||
LOGGER.debug(f'WebLogin Username: {username}')
|
||||
LOGGER.debug(f'WebLogin Password: {password}')
|
||||
passwordHash = utils.ComputePasswordHash(password)
|
||||
LOGGER.debug(f'WebLogin Password Hash: {passwordHash}')
|
||||
|
||||
if len(self.cursor.fetchall()) != 0:
|
||||
cursor.execute('SELECT [name] FROM user WHERE [name] = ? AND [password] = ?;', (username, passwordHash))
|
||||
|
||||
if len(cursor.fetchall()) != 0:
|
||||
token = utils.GenerateToken(username)
|
||||
self.cursor.execute('INSERT INTO token VALUES (?, ?, ?, ?, ?);', (
|
||||
cursor.execute('INSERT INTO token VALUES (?, ?, ?, ?, ?);', (
|
||||
username,
|
||||
token,
|
||||
utils.GetTokenExpireOn(), # add 2 day from now
|
||||
@@ -196,12 +263,13 @@ class CalendarDatabase:
|
||||
return token
|
||||
else:
|
||||
# throw a exception to indicate fail to login
|
||||
raise Exception('Login authentication failed')
|
||||
raise DbException('Login authentication failed')
|
||||
|
||||
@SafeDatabaseOperation
|
||||
def common_logout(self, token):
|
||||
cursor = self._get_cursor()
|
||||
self.tokenOper_check_valid(token)
|
||||
self.cursor.execute('DELETE FROM token WHERE [ccn_token] = ?;', (token, ))
|
||||
cursor.execute('DELETE FROM token WHERE [token] = ?;', (token, ))
|
||||
return True
|
||||
|
||||
@SafeDatabaseOperation
|
||||
@@ -212,40 +280,44 @@ class CalendarDatabase:
|
||||
# =============================== calendar
|
||||
@SafeDatabaseOperation
|
||||
def calendar_getFull(self, token, startDateTime, endDateTime):
|
||||
cursor = self._get_cursor()
|
||||
username = self.tokenOper_get_username(token)
|
||||
self.cursor.execute('SELECT calendar.* FROM calendar INNER JOIN collection \
|
||||
ON collection.ccn_uuid = calendar.ccn_belongTo \
|
||||
WHERE (collection.ccn_user = ? AND calendar.ccn_loopDateTimeEnd >= ? AND calendar.ccn_loopDateTimeStart - (calendar.ccn_eventDateTimeEnd - calendar.ccn_eventDateTimeStart) <= ?);',
|
||||
cursor.execute('SELECT calendar.* FROM calendar INNER JOIN collection \
|
||||
ON collection.uuid = calendar.belong_to \
|
||||
WHERE (collection.user = ? AND calendar.loop_date_time_end >= ? AND calendar.loop_date_time_start - (calendar.event_date_time_end - calendar.event_date_time_start) <= ?);',
|
||||
(username, startDateTime, endDateTime))
|
||||
return self.cursor.fetchall()
|
||||
return cursor.fetchall()
|
||||
|
||||
@SafeDatabaseOperation
|
||||
def calendar_getList(self, token, startDateTime, endDateTime):
|
||||
cursor = self._get_cursor()
|
||||
username = self.tokenOper_get_username(token)
|
||||
self.cursor.execute('SELECT calendar.ccn_uuid FROM calendar INNER JOIN collection \
|
||||
ON collection.ccn_uuid = calendar.ccn_belongTo \
|
||||
WHERE (collection.ccn_user = ? AND calendar.ccn_loopDateTimeEnd >= ? AND calendar.ccn_loopDateTimeStart - (calendar.ccn_eventDateTimeEnd - calendar.ccn_eventDateTimeStart) <= ?);',
|
||||
cursor.execute('SELECT calendar.uuid FROM calendar INNER JOIN collection \
|
||||
ON collection.uuid = calendar.belong_to \
|
||||
WHERE (collection.user = ? AND calendar.loop_date_time_end >= ? AND calendar.loop_date_time_start - (calendar.event_date_time_end - calendar.event_date_time_start) <= ?);',
|
||||
(username, startDateTime, endDateTime))
|
||||
return tuple(map(lambda x: x[0], self.cursor.fetchall()))
|
||||
return tuple(map(lambda x: x[0], cursor.fetchall()))
|
||||
|
||||
@SafeDatabaseOperation
|
||||
def calendar_getDetail(self, token, uuid):
|
||||
cursor = self._get_cursor()
|
||||
self.tokenOper_check_valid(token)
|
||||
self.cursor.execute('SELECT * FROM calendar WHERE [ccn_uuid] = ?;', (uuid, ))
|
||||
return self.cursor.fetchone()
|
||||
cursor.execute('SELECT * FROM calendar WHERE [uuid] = ?;', (uuid, ))
|
||||
return cursor.fetchone()
|
||||
|
||||
@SafeDatabaseOperation
|
||||
def calendar_update(self, token, uuid, lastChange, **optArgs):
|
||||
cursor = self._get_cursor()
|
||||
self.tokenOper_check_valid(token)
|
||||
|
||||
# get prev data
|
||||
self.cursor.execute('SELECT * FROM calendar WHERE [ccn_uuid] = ? AND [ccn_lastChange] = ?;', (uuid, lastChange))
|
||||
analyseData = list(self.cursor.fetchone())
|
||||
cursor.execute('SELECT * FROM calendar WHERE [uuid] = ? AND [last_change] = ?;', (uuid, lastChange))
|
||||
analyseData = list(cursor.fetchone())
|
||||
|
||||
# construct update data
|
||||
lastupdate = utils.GenerateUUID()
|
||||
sqlList = [
|
||||
'[ccn_lastChange] = ?',
|
||||
'[last_change] = ?',
|
||||
]
|
||||
argumentsList = [
|
||||
lastupdate,
|
||||
@@ -256,44 +328,44 @@ class CalendarDatabase:
|
||||
|
||||
cache = optArgs.get('belongTo', None)
|
||||
if cache is not None:
|
||||
sqlList.append('[ccn_belongTo] = ?')
|
||||
sqlList.append('[belong_to] = ?')
|
||||
argumentsList.append(cache)
|
||||
cache = optArgs.get('title', None)
|
||||
if cache is not None:
|
||||
sqlList.append('[ccn_title] = ?')
|
||||
sqlList.append('[title] = ?')
|
||||
argumentsList.append(cache)
|
||||
cache = optArgs.get('description', None)
|
||||
if cache is not None:
|
||||
sqlList.append('[ccn_description] = ?')
|
||||
sqlList.append('[description] = ?')
|
||||
argumentsList.append(cache)
|
||||
cache = optArgs.get('eventDateTimeStart', None)
|
||||
if cache is not None:
|
||||
sqlList.append('[ccn_eventDateTimeStart] = ?')
|
||||
sqlList.append('[event_date_time_start] = ?')
|
||||
argumentsList.append(cache)
|
||||
reAnalyseLoop = True
|
||||
analyseData[5] = cache
|
||||
cache = optArgs.get('eventDateTimeEnd', None)
|
||||
if cache is not None:
|
||||
sqlList.append('[ccn_eventDateTimeEnd] = ?')
|
||||
sqlList.append('[event_date_time_end] = ?')
|
||||
argumentsList.append(cache)
|
||||
cache = optArgs.get('loopRules', None)
|
||||
if cache is not None:
|
||||
sqlList.append('[ccn_loopRules] = ?')
|
||||
sqlList.append('[loop_rules] = ?')
|
||||
argumentsList.append(cache)
|
||||
reAnalyseLoop = True
|
||||
analyseData[8] = cache
|
||||
cache = optArgs.get('timezoneOffset', None)
|
||||
if cache is not None:
|
||||
sqlList.append('[ccn_timezoneOffset] = ?')
|
||||
sqlList.append('[timezone_offset] = ?')
|
||||
argumentsList.append(cache)
|
||||
reAnalyseLoop = True
|
||||
analyseData[7] = cache
|
||||
|
||||
if reAnalyseLoop:
|
||||
# re-compute loop data and upload it into list
|
||||
sqlList.append('[ccn_loopDateTimeStart] = ?')
|
||||
sqlList.append('[loop_date_time_start] = ?')
|
||||
argumentsList.append(analyseData[5])
|
||||
sqlList.append('[ccn_loopDateTimeEnd] = ?')
|
||||
sqlList.append('[loop_date_time_end] = ?')
|
||||
argumentsList.append(str(dt.ResolveLoopStr(
|
||||
analyseData[8],
|
||||
analyseData[5],
|
||||
@@ -302,14 +374,15 @@ class CalendarDatabase:
|
||||
|
||||
# execute
|
||||
argumentsList.append(uuid)
|
||||
self.cursor.execute('UPDATE calendar SET {} WHERE [ccn_uuid] = ?;'.format(', '.join(sqlList)),
|
||||
cursor.execute('UPDATE calendar SET {} WHERE [uuid] = ?;'.format(', '.join(sqlList)),
|
||||
tuple(argumentsList))
|
||||
if self.cursor.rowcount != 1:
|
||||
raise Exception('Fail to update due to no matched rows or too much rows.')
|
||||
if cursor.rowcount != 1:
|
||||
raise DbException('Fail to update due to no matched rows or too much rows.')
|
||||
return lastupdate
|
||||
|
||||
@SafeDatabaseOperation
|
||||
def calendar_add(self, token, belongTo, title, description, eventDateTimeStart, eventDateTimeEnd, loopRules, timezoneOffset):
|
||||
cursor = self._get_cursor()
|
||||
self.tokenOper_check_valid(token)
|
||||
|
||||
newuuid = utils.GenerateUUID()
|
||||
@@ -319,7 +392,7 @@ class CalendarDatabase:
|
||||
loopDateTimeStart = eventDateTimeStart
|
||||
loopDateTimeEnd = dt.ResolveLoopStr(loopRules, eventDateTimeStart, timezoneOffset)
|
||||
|
||||
self.cursor.execute('INSERT INTO calendar VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);',
|
||||
cursor.execute('INSERT INTO calendar VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);',
|
||||
(newuuid,
|
||||
belongTo,
|
||||
title,
|
||||
@@ -335,134 +408,149 @@ class CalendarDatabase:
|
||||
|
||||
@SafeDatabaseOperation
|
||||
def calendar_delete(self, token, uuid, lastChange):
|
||||
cursor = self._get_cursor()
|
||||
self.tokenOper_check_valid(token)
|
||||
self.cursor.execute('DELETE FROM calendar WHERE [ccn_uuid] = ? AND [ccn_lastChange] = ?;', (uuid, lastChange))
|
||||
if self.cursor.rowcount != 1:
|
||||
raise Exception('Fail to delete due to no matched rows or too much rows.')
|
||||
cursor.execute('DELETE FROM calendar WHERE [uuid] = ? AND [last_change] = ?;', (uuid, lastChange))
|
||||
if cursor.rowcount != 1:
|
||||
raise DbException('Fail to delete due to no matched rows or too much rows.')
|
||||
return True
|
||||
|
||||
# =============================== collection
|
||||
@SafeDatabaseOperation
|
||||
def collection_getFullOwn(self, token):
|
||||
cursor = self._get_cursor()
|
||||
username = self.tokenOper_get_username(token)
|
||||
self.cursor.execute('SELECT [ccn_uuid], [ccn_name], [ccn_lastChange] FROM collection WHERE [ccn_user] = ?;', (username, ))
|
||||
return self.cursor.fetchall()
|
||||
cursor.execute('SELECT [uuid], [name], [last_change] FROM collection WHERE [user] = ?;', (username, ))
|
||||
return cursor.fetchall()
|
||||
|
||||
@SafeDatabaseOperation
|
||||
def collection_getListOwn(self, token):
|
||||
cursor = self._get_cursor()
|
||||
username = self.tokenOper_get_username(token)
|
||||
self.cursor.execute('SELECT [ccn_uuid] FROM collection WHERE [ccn_user] = ?;', (username, ))
|
||||
return tuple(map(lambda x: x[0], self.cursor.fetchall()))
|
||||
cursor.execute('SELECT [uuid] FROM collection WHERE [user] = ?;', (username, ))
|
||||
return tuple(map(lambda x: x[0], cursor.fetchall()))
|
||||
|
||||
@SafeDatabaseOperation
|
||||
def collection_getDetailOwn(self, token, uuid):
|
||||
cursor = self._get_cursor()
|
||||
username = self.tokenOper_get_username(token)
|
||||
self.cursor.execute('SELECT [ccn_uuid], [ccn_name], [ccn_lastChange] FROM collection WHERE [ccn_user] = ? AND [ccn_uuid] = ?;', (username, uuid))
|
||||
return self.cursor.fetchone()
|
||||
cursor.execute('SELECT [uuid], [name], [last_change] FROM collection WHERE [user] = ? AND [uuid] = ?;', (username, uuid))
|
||||
return cursor.fetchone()
|
||||
|
||||
@SafeDatabaseOperation
|
||||
def collection_addOwn(self, token, newname):
|
||||
cursor = self._get_cursor()
|
||||
username = self.tokenOper_get_username(token)
|
||||
newuuid = utils.GenerateUUID()
|
||||
lastupdate = utils.GenerateUUID()
|
||||
self.cursor.execute('INSERT INTO collection VALUES (?, ?, ?, ?);',
|
||||
cursor.execute('INSERT INTO collection VALUES (?, ?, ?, ?);',
|
||||
(newuuid, newname, username, lastupdate))
|
||||
return newuuid
|
||||
|
||||
@SafeDatabaseOperation
|
||||
def collection_updateOwn(self, token, uuid, newname, lastChange):
|
||||
cursor = self._get_cursor()
|
||||
self.tokenOper_check_valid(token)
|
||||
|
||||
lastupdate = utils.GenerateUUID()
|
||||
self.cursor.execute('UPDATE collection SET [ccn_name] = ?, [ccn_lastChange] = ? WHERE [ccn_uuid] = ? AND [ccn_lastChange] = ?;', (
|
||||
cursor.execute('UPDATE collection SET [name] = ?, [last_change] = ? WHERE [uuid] = ? AND [last_change] = ?;', (
|
||||
newname,
|
||||
lastupdate,
|
||||
uuid,
|
||||
lastChange
|
||||
))
|
||||
if self.cursor.rowcount != 1:
|
||||
raise Exception('Fail to update due to no matched rows or too much rows.')
|
||||
if cursor.rowcount != 1:
|
||||
raise DbException('Fail to update due to no matched rows or too much rows.')
|
||||
return lastupdate
|
||||
|
||||
@SafeDatabaseOperation
|
||||
def collection_deleteOwn(self, token, uuid, lastChange):
|
||||
cursor = self._get_cursor()
|
||||
self.tokenOper_check_valid(token)
|
||||
|
||||
self.cursor.execute('DELETE FROM collection WHERE [ccn_uuid] = ? AND [ccn_lastChange] = ?;', (
|
||||
cursor.execute('DELETE FROM collection WHERE [uuid] = ? AND [last_change] = ?;', (
|
||||
uuid,
|
||||
lastChange
|
||||
))
|
||||
if self.cursor.rowcount != 1:
|
||||
raise Exception('Fail to delete due to no matched rows or too much rows.')
|
||||
if cursor.rowcount != 1:
|
||||
raise DbException('Fail to delete due to no matched rows or too much rows.')
|
||||
return True
|
||||
|
||||
@SafeDatabaseOperation
|
||||
def collection_getSharing(self, token, uuid):
|
||||
cursor = self._get_cursor()
|
||||
self.tokenOper_check_valid(token)
|
||||
self.cursor.execute('SELECT [ccn_target] FROM share WHERE [ccn_uuid] = ?;', (uuid, ))
|
||||
return tuple(map(lambda x: x[0], self.cursor.fetchall()))
|
||||
cursor.execute('SELECT [target] FROM share WHERE [uuid] = ?;', (uuid, ))
|
||||
return tuple(map(lambda x: x[0], cursor.fetchall()))
|
||||
|
||||
@SafeDatabaseOperation
|
||||
def collection_deleteSharing(self, token, uuid, target, lastChange):
|
||||
cursor = self._get_cursor()
|
||||
self.tokenOper_check_valid(token)
|
||||
|
||||
lastupdate = utils.GenerateUUID()
|
||||
self.cursor.execute('UPDATE collection SET [ccn_lastChange] = ?, WHERE [ccn_uuid] = ? AND [ccn_lastChange] = ?;', (lastupdate, uuid, lastChange))
|
||||
if self.cursor.rowcount != 1:
|
||||
raise Exception('Fail to delete due to no matched rows or too much rows.')
|
||||
cursor.execute('UPDATE collection SET [last_change] = ?, WHERE [uuid] = ? AND [last_change] = ?;', (lastupdate, uuid, lastChange))
|
||||
if cursor.rowcount != 1:
|
||||
raise DbException('Fail to delete due to no matched rows or too much rows.')
|
||||
|
||||
self.cursor.execute('DELETE FROM share WHERE [ccn_uuid] = ? AND [ccn_target] = ?;', (uuid, target))
|
||||
if self.cursor.rowcount != 1:
|
||||
raise Exception('Fail to delete due to no matched rows or too much rows.')
|
||||
cursor.execute('DELETE FROM share WHERE [uuid] = ? AND [target] = ?;', (uuid, target))
|
||||
if cursor.rowcount != 1:
|
||||
raise DbException('Fail to delete due to no matched rows or too much rows.')
|
||||
|
||||
return lastupdate
|
||||
|
||||
@SafeDatabaseOperation
|
||||
def collection_addSharing(self, token, uuid, target, lastChange):
|
||||
cursor = self._get_cursor()
|
||||
self.tokenOper_check_valid(token)
|
||||
|
||||
lastupdate = utils.GenerateUUID()
|
||||
self.cursor.execute('UPDATE collection SET [ccn_lastChange] = ? WHERE [ccn_uuid] = ? AND [ccn_lastChange] = ?;', (lastupdate, uuid, lastChange))
|
||||
if self.cursor.rowcount != 1:
|
||||
raise Exception('Fail to delete due to no matched rows or too much rows.')
|
||||
cursor.execute('UPDATE collection SET [last_change] = ? WHERE [uuid] = ? AND [last_change] = ?;', (lastupdate, uuid, lastChange))
|
||||
if cursor.rowcount != 1:
|
||||
raise DbException('Fail to delete due to no matched rows or too much rows.')
|
||||
|
||||
self.cursor.execute('SELECT * FROM share WHERE [ccn_uuid] = ? AND [ccn_target] = ?;', (uuid, target))
|
||||
if len(self.cursor.fetchall()) != 0:
|
||||
raise Exception('Fail to insert duplicated item.')
|
||||
self.cursor.execute('INSERT INTO share VALUES (?, ?);', (uuid, target))
|
||||
cursor.execute('SELECT * FROM share WHERE [uuid] = ? AND [target] = ?;', (uuid, target))
|
||||
if len(cursor.fetchall()) != 0:
|
||||
raise DbException('Fail to insert duplicated item.')
|
||||
cursor.execute('INSERT INTO share VALUES (?, ?);', (uuid, target))
|
||||
|
||||
return lastupdate
|
||||
|
||||
@SafeDatabaseOperation
|
||||
def collection_getShared(self, token):
|
||||
cursor = self._get_cursor()
|
||||
username = self.tokenOper_get_username(token)
|
||||
self.cursor.execute('SELECT collection.ccn_uuid, collection.ccn_name, collection.ccn_user \
|
||||
cursor.execute('SELECT collection.uuid, collection.name, collection.user \
|
||||
FROM share INNER JOIN collection \
|
||||
ON share.ccn_uuid = collection.ccn_uuid \
|
||||
WHERE share.ccn_target = ?;', (username, ))
|
||||
return self.cursor.fetchall()
|
||||
ON share.uuid = collection.uuid \
|
||||
WHERE share.target = ?;', (username, ))
|
||||
return cursor.fetchall()
|
||||
|
||||
# =============================== todo
|
||||
@SafeDatabaseOperation
|
||||
def todo_getFull(self, token):
|
||||
cursor = self._get_cursor()
|
||||
username = self.tokenOper_get_username(token)
|
||||
self.cursor.execute('SELECT * FROM todo WHERE [ccn_belongTo] = ?;', (username, ))
|
||||
return self.cursor.fetchall()
|
||||
cursor.execute('SELECT * FROM todo WHERE [belong_to] = ?;', (username, ))
|
||||
return cursor.fetchall()
|
||||
|
||||
@SafeDatabaseOperation
|
||||
def todo_getList(self, token):
|
||||
cursor = self._get_cursor()
|
||||
username = self.tokenOper_get_username(token)
|
||||
self.cursor.execute('SELECT [ccn_uuid] FROM todo WHERE [ccn_belongTo] = ?;', (username, ))
|
||||
return tuple(map(lambda x: x[0], self.cursor.fetchall()))
|
||||
cursor.execute('SELECT [uuid] FROM todo WHERE [belong_to] = ?;', (username, ))
|
||||
return tuple(map(lambda x: x[0], cursor.fetchall()))
|
||||
|
||||
@SafeDatabaseOperation
|
||||
def todo_getDetail(self, token, uuid):
|
||||
cursor = self._get_cursor()
|
||||
username = self.tokenOper_get_username(token)
|
||||
self.cursor.execute('SELECT * FROM todo WHERE [ccn_belongTo] = ? AND [ccn_uuid] = ?;', (username, uuid))
|
||||
return self.cursor.fetchone()
|
||||
cursor.execute('SELECT * FROM todo WHERE [belong_to] = ? AND [uuid] = ?;', (username, uuid))
|
||||
return cursor.fetchone()
|
||||
|
||||
@SafeDatabaseOperation
|
||||
def todo_add(self, token):
|
||||
cursor = self._get_cursor()
|
||||
username = self.tokenOper_get_username(token)
|
||||
newuuid = utils.GenerateUUID()
|
||||
lastupdate = utils.GenerateUUID()
|
||||
@@ -472,56 +560,60 @@ class CalendarDatabase:
|
||||
'',
|
||||
lastupdate,
|
||||
)
|
||||
self.cursor.execute('INSERT INTO todo VALUES (?, ?, ?, ?);', returnedData)
|
||||
cursor.execute('INSERT INTO todo VALUES (?, ?, ?, ?);', returnedData)
|
||||
return returnedData
|
||||
|
||||
@SafeDatabaseOperation
|
||||
def todo_update(self, token, uuid, data, lastChange):
|
||||
cursor = self._get_cursor()
|
||||
# check valid token
|
||||
self.tokenOper_check_valid(token)
|
||||
|
||||
# update
|
||||
newLastChange = utils.GenerateUUID()
|
||||
self.cursor.execute('UPDATE todo SET [ccn_data] = ?, [ccn_lastChange] = ? WHERE [ccn_uuid] = ? AND [ccn_lastChange] = ?;', (
|
||||
cursor.execute('UPDATE todo SET [data] = ?, [last_change] = ? WHERE [uuid] = ? AND [last_change] = ?;', (
|
||||
data,
|
||||
newLastChange,
|
||||
uuid,
|
||||
lastChange
|
||||
))
|
||||
if self.cursor.rowcount != 1:
|
||||
raise Exception('Fail to update due to no matched rows or too much rows.')
|
||||
if cursor.rowcount != 1:
|
||||
raise DbException('Fail to update due to no matched rows or too much rows.')
|
||||
return newLastChange
|
||||
|
||||
@SafeDatabaseOperation
|
||||
def todo_delete(self, token, uuid, lastChange):
|
||||
cursor = self._get_cursor()
|
||||
# check valid token
|
||||
self.tokenOper_check_valid(token)
|
||||
|
||||
# delete
|
||||
self.cursor.execute('DELETE FROM todo WHERE [ccn_uuid] = ? AND [ccn_lastChange] = ?;', (uuid, lastChange))
|
||||
if self.cursor.rowcount != 1:
|
||||
raise Exception('Fail to delete due to no matched rows or too much rows.')
|
||||
cursor.execute('DELETE FROM todo WHERE [uuid] = ? AND [last_change] = ?;', (uuid, lastChange))
|
||||
if cursor.rowcount != 1:
|
||||
raise DbException('Fail to delete due to no matched rows or too much rows.')
|
||||
return True
|
||||
|
||||
|
||||
# =============================== admin
|
||||
@SafeDatabaseOperation
|
||||
def admin_get(self, token):
|
||||
cursor = self._get_cursor()
|
||||
username = self.tokenOper_get_username(token)
|
||||
if not self.tokenOper_is_admin(username):
|
||||
raise Exception('Permission denied.')
|
||||
raise DbException('Permission denied.')
|
||||
|
||||
self.cursor.execute('SELECT [ccn_name], [ccn_isAdmin] FROM user;')
|
||||
return tuple(map(lambda x: (x[0], x[1] == 1), self.cursor.fetchall()))
|
||||
cursor.execute('SELECT [name], [is_admin] FROM user;')
|
||||
return tuple(map(lambda x: (x[0], x[1] == 1), cursor.fetchall()))
|
||||
|
||||
@SafeDatabaseOperation
|
||||
def admin_add(self, token, newname):
|
||||
cursor = self._get_cursor()
|
||||
username = self.tokenOper_get_username(token)
|
||||
if not self.tokenOper_is_admin(username):
|
||||
raise Exception('Permission denied.')
|
||||
raise DbException('Permission denied.')
|
||||
|
||||
newpassword = utils.ComputePasswordHash(utils.GenerateUUID())
|
||||
self.cursor.execute('INSERT INTO user VALUES (?, ?, ?, ?);', (
|
||||
cursor.execute('INSERT INTO user VALUES (?, ?, ?, ?);', (
|
||||
newname,
|
||||
newpassword,
|
||||
0,
|
||||
@@ -531,9 +623,10 @@ class CalendarDatabase:
|
||||
|
||||
@SafeDatabaseOperation
|
||||
def admin_update(self, token, _username, **optArgs):
|
||||
cursor = self._get_cursor()
|
||||
username = self.tokenOper_get_username(token)
|
||||
if not self.tokenOper_is_admin(username):
|
||||
raise Exception('Permission denied.')
|
||||
raise DbException('Permission denied.')
|
||||
|
||||
# construct data
|
||||
sqlList = []
|
||||
@@ -542,45 +635,48 @@ class CalendarDatabase:
|
||||
# analyse opt arg
|
||||
cache = optArgs.get('password', None)
|
||||
if cache is not None:
|
||||
sqlList.append('[ccn_password] = ?')
|
||||
sqlList.append('[password] = ?')
|
||||
argumentsList.append(utils.ComputePasswordHash(cache))
|
||||
cache = optArgs.get('isAdmin', None)
|
||||
if cache is not None:
|
||||
sqlList.append('[ccn_isAdmin] = ?')
|
||||
sqlList.append('[is_admin] = ?')
|
||||
argumentsList.append(1 if cache else 0)
|
||||
|
||||
# execute
|
||||
argumentsList.append(_username)
|
||||
self.cursor.execute('UPDATE user SET {} WHERE [ccn_name] = ?;'.format(', '.join(sqlList)),
|
||||
cursor.execute('UPDATE user SET {} WHERE [name] = ?;'.format(', '.join(sqlList)),
|
||||
tuple(argumentsList))
|
||||
logging.debug(cache)
|
||||
logging.debug(tuple(argumentsList))
|
||||
if self.cursor.rowcount != 1:
|
||||
raise Exception('Fail to update due to no matched rows or too much rows.')
|
||||
LOGGER.debug(cache)
|
||||
LOGGER.debug(tuple(argumentsList))
|
||||
if cursor.rowcount != 1:
|
||||
raise DbException('Fail to update due to no matched rows or too much rows.')
|
||||
return True
|
||||
|
||||
@SafeDatabaseOperation
|
||||
def admin_delete(self, token, username):
|
||||
cursor = self._get_cursor()
|
||||
_username = self.tokenOper_get_username(token)
|
||||
if not self.tokenOper_is_admin(_username):
|
||||
raise Exception('Permission denied.')
|
||||
raise DbException('Permission denied.')
|
||||
|
||||
# delete
|
||||
self.cursor.execute('DELETE FROM user WHERE [ccn_name] = ?;', (username, ))
|
||||
if self.cursor.rowcount != 1:
|
||||
raise Exception('Fail to delete due to no matched rows or too much rows.')
|
||||
cursor.execute('DELETE FROM user WHERE [name] = ?;', (username, ))
|
||||
if cursor.rowcount != 1:
|
||||
raise DbException('Fail to delete due to no matched rows or too much rows.')
|
||||
return True
|
||||
|
||||
# =============================== profile
|
||||
@SafeDatabaseOperation
|
||||
def profile_isAdmin(self, token):
|
||||
cursor = self._get_cursor()
|
||||
username = self.tokenOper_get_username(token)
|
||||
return self.tokenOper_is_admin(username)
|
||||
|
||||
@SafeDatabaseOperation
|
||||
def profile_changePassword(self, token, newpassword):
|
||||
cursor = self._get_cursor()
|
||||
username = self.tokenOper_get_username(token)
|
||||
self.cursor.execute('UPDATE user SET [ccn_password] = ? WHERE [ccn_name] = ?;', (
|
||||
cursor.execute('UPDATE user SET [password] = ? WHERE [name] = ?;', (
|
||||
utils.ComputePasswordHash(newpassword),
|
||||
username
|
||||
))
|
||||
@@ -588,23 +684,25 @@ class CalendarDatabase:
|
||||
|
||||
@SafeDatabaseOperation
|
||||
def profile_getToken(self, token):
|
||||
cursor = self._get_cursor()
|
||||
username = self.tokenOper_get_username(token)
|
||||
|
||||
self.cursor.execute('SELECT * FROM token WHERE [ccn_user] = ?;', (
|
||||
cursor.execute('SELECT * FROM token WHERE [user] = ?;', (
|
||||
username,
|
||||
))
|
||||
return self.cursor.fetchall()
|
||||
return cursor.fetchall()
|
||||
|
||||
@SafeDatabaseOperation
|
||||
def profile_deleteToken(self, token, deleteToken):
|
||||
cursor = self._get_cursor()
|
||||
_username = self.tokenOper_get_username(token)
|
||||
|
||||
# delete
|
||||
self.cursor.execute('DELETE FROM token WHERE [ccn_user] = ? AND [ccn_token] = ?;', (
|
||||
cursor.execute('DELETE FROM token WHERE [user] = ? AND [token] = ?;', (
|
||||
_username,
|
||||
deleteToken
|
||||
))
|
||||
if self.cursor.rowcount != 1:
|
||||
raise Exception('Fail to delete due to no matched rows or too much rows.')
|
||||
if cursor.rowcount != 1:
|
||||
raise DbException('Fail to delete due to no matched rows or too much rows.')
|
||||
return True
|
||||
|
||||
File renamed without changes.
@@ -0,0 +1,42 @@
|
||||
import logging
|
||||
import enum
|
||||
|
||||
|
||||
def _build_logger() -> tuple[logging.Logger, logging.Handler]:
|
||||
# Create a new logger which is independent with Flask
|
||||
logger = logging.getLogger("my_console_logger")
|
||||
# Avoid message was propagated to root logger or captured by Flask logger.
|
||||
logger.propagate = False
|
||||
# Set initial level.
|
||||
logger.setLevel(logging.INFO)
|
||||
|
||||
# Create StreamHandler to output into stderr.
|
||||
console_handler = logging.StreamHandler()
|
||||
console_handler.setLevel(logging.DEBUG)
|
||||
# Set format for it.
|
||||
formatter = logging.Formatter("[%(levelname)s] %(message)s")
|
||||
console_handler.setFormatter(formatter)
|
||||
# Add handler
|
||||
logger.addHandler(console_handler)
|
||||
|
||||
return (logger, console_handler)
|
||||
|
||||
|
||||
(LOGGER, CONSOLE_HANDLER) = _build_logger()
|
||||
|
||||
|
||||
class LoggerLevel(enum.IntEnum):
|
||||
DEBUG = enum.auto()
|
||||
INFO = enum.auto()
|
||||
|
||||
|
||||
def set_level(level: LoggerLevel) -> None:
|
||||
logging_level: int = logging.INFO
|
||||
match level:
|
||||
case LoggerLevel.DEBUG:
|
||||
logging_level = logging.DEBUG
|
||||
case LoggerLevel.INFO:
|
||||
logging_level = logging.INFO
|
||||
|
||||
LOGGER.setLevel(logging_level)
|
||||
CONSOLE_HANDLER.setLevel(logging_level)
|
||||
File renamed without changes.
@@ -0,0 +1,513 @@
|
||||
from flask import Flask
|
||||
from flask import request
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Callable, ParamSpec, TypeVar, Generic
|
||||
|
||||
import config
|
||||
import database
|
||||
import utils
|
||||
from logger import LOGGER
|
||||
from database import ResponseBody
|
||||
|
||||
app = Flask(__name__)
|
||||
calendar_db = database.CalendarDatabase()
|
||||
|
||||
# region: API Route
|
||||
|
||||
# region: Common
|
||||
|
||||
|
||||
@app.route("/common/salt", methods=["POST"])
|
||||
def api_common_saltHandle():
|
||||
return SmartDbCaller(
|
||||
calendar_db.common_salt, (FormField("username", str, False),), None
|
||||
)
|
||||
|
||||
|
||||
@app.route("/common/login", methods=["POST"])
|
||||
def api_common_loginHandle():
|
||||
clientInfo = FetchClientNetworkInfo()
|
||||
|
||||
return SmartDbCaller(
|
||||
calendar_db.common_login,
|
||||
(
|
||||
FormField("username", str, False),
|
||||
FormField("password", str, False),
|
||||
FormField("clientUa", str, False),
|
||||
FormField("clientIp", str, False),
|
||||
),
|
||||
{"clientUa": clientInfo.user_agent, "clientIp": clientInfo.ip_addr},
|
||||
)
|
||||
|
||||
|
||||
@app.route("/common/webLogin", methods=["POST"])
|
||||
def api_common_webLoginHandle():
|
||||
clientInfo = FetchClientNetworkInfo()
|
||||
|
||||
return SmartDbCaller(
|
||||
calendar_db.common_webLogin,
|
||||
(
|
||||
FormField("username", str, False),
|
||||
FormField("password", str, False),
|
||||
FormField("clientUa", str, False),
|
||||
FormField("clientIp", str, False),
|
||||
),
|
||||
{"clientUa": clientInfo.user_agent, "clientIp": clientInfo.ip_addr},
|
||||
)
|
||||
|
||||
|
||||
@app.route("/common/logout", methods=["POST"])
|
||||
def api_common_logoutHandle():
|
||||
return SmartDbCaller(
|
||||
calendar_db.common_logout, (FormField("token", str, False),), None
|
||||
)
|
||||
|
||||
|
||||
@app.route("/common/tokenValid", methods=["POST"])
|
||||
def api_common_tokenValidHandle():
|
||||
return SmartDbCaller(
|
||||
calendar_db.common_tokenValid, (FormField("token", str, False),), None
|
||||
)
|
||||
|
||||
|
||||
# endregion
|
||||
|
||||
# region: Calendar
|
||||
|
||||
|
||||
@app.route("/calendar/getFull", methods=["POST"])
|
||||
def api_calendar_getFullHandle():
|
||||
return SmartDbCaller(
|
||||
calendar_db.calendar_getFull,
|
||||
(
|
||||
FormField("token", str, False),
|
||||
FormField("startDateTime", int, False),
|
||||
FormField("endDateTime", int, False),
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
@app.route("/calendar/getList", methods=["POST"])
|
||||
def api_calendar_getListHandle():
|
||||
return SmartDbCaller(
|
||||
calendar_db.calendar_getList,
|
||||
(
|
||||
FormField("token", str, False),
|
||||
FormField("startDateTime", int, False),
|
||||
FormField("endDateTime", int, False),
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
@app.route("/calendar/getDetail", methods=["POST"])
|
||||
def api_calendar_getDetailHandle():
|
||||
return SmartDbCaller(
|
||||
calendar_db.calendar_getDetail,
|
||||
(FormField("token", str, False), FormField("uuid", str, False)),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
@app.route("/calendar/update", methods=["POST"])
|
||||
def api_calendar_updateHandle():
|
||||
return SmartDbCaller(
|
||||
calendar_db.calendar_update,
|
||||
(
|
||||
FormField("token", str, False),
|
||||
FormField("uuid", str, False),
|
||||
FormField("belongTo", str, True),
|
||||
FormField("title", str, True),
|
||||
FormField("description", str, True),
|
||||
FormField("eventDateTimeStart", int, True),
|
||||
FormField("eventDateTimeEnd", int, True),
|
||||
FormField("loopRules", str, True),
|
||||
FormField("timezoneOffset", int, True),
|
||||
FormField("lastChange", str, False),
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
@app.route("/calendar/add", methods=["POST"])
|
||||
def api_calendar_addHandle():
|
||||
return SmartDbCaller(
|
||||
calendar_db.calendar_add,
|
||||
(
|
||||
FormField("token", str, False),
|
||||
FormField("belongTo", str, False),
|
||||
FormField("title", str, False),
|
||||
FormField("description", str, False),
|
||||
FormField("eventDateTimeStart", int, False),
|
||||
FormField("eventDateTimeEnd", int, False),
|
||||
FormField("loopRules", str, False),
|
||||
FormField("timezoneOffset", int, False),
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
@app.route("/calendar/delete", methods=["POST"])
|
||||
def api_calendar_deleteHandle():
|
||||
return SmartDbCaller(
|
||||
calendar_db.calendar_delete,
|
||||
(
|
||||
FormField("token", str, False),
|
||||
FormField("uuid", str, False),
|
||||
FormField("lastChange", str, False),
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
# endregion
|
||||
|
||||
# region: Collection
|
||||
|
||||
|
||||
@app.route("/collection/getFullOwn", methods=["POST"])
|
||||
def api_collection_getFullOwnHandle():
|
||||
return SmartDbCaller(
|
||||
calendar_db.collection_getFullOwn, (FormField("token", str, False),), None
|
||||
)
|
||||
|
||||
|
||||
@app.route("/collection/getListOwn", methods=["POST"])
|
||||
def api_collection_getListOwnHandle():
|
||||
return SmartDbCaller(
|
||||
calendar_db.collection_getListOwn, (FormField("token", str, False),), None
|
||||
)
|
||||
|
||||
|
||||
@app.route("/collection/getDetailOwn", methods=["POST"])
|
||||
def api_collection_getDetailOwnHandle():
|
||||
return SmartDbCaller(
|
||||
calendar_db.collection_getDetailOwn,
|
||||
(FormField("token", str, False), FormField("uuid", str, False)),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
@app.route("/collection/addOwn", methods=["POST"])
|
||||
def api_collection_addOwnHandle():
|
||||
return SmartDbCaller(
|
||||
calendar_db.collection_addOwn,
|
||||
(FormField("token", str, False), FormField("name", str, False)),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
@app.route("/collection/updateOwn", methods=["POST"])
|
||||
def api_collection_updateOwnHandle():
|
||||
return SmartDbCaller(
|
||||
calendar_db.collection_updateOwn,
|
||||
(
|
||||
FormField("token", str, False),
|
||||
FormField("uuid", str, False),
|
||||
FormField("name", str, False),
|
||||
FormField("lastChange", str, False),
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
@app.route("/collection/deleteOwn", methods=["POST"])
|
||||
def api_collection_deleteOwnHandle():
|
||||
return SmartDbCaller(
|
||||
calendar_db.collection_deleteOwn,
|
||||
(
|
||||
FormField("token", str, False),
|
||||
FormField("uuid", str, False),
|
||||
FormField("lastChange", str, False),
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
@app.route("/collection/getSharing", methods=["POST"])
|
||||
def api_collection_getSharingHandle():
|
||||
return SmartDbCaller(
|
||||
calendar_db.collection_getSharing,
|
||||
(FormField("token", str, False), FormField("uuid", str, False)),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
@app.route("/collection/deleteSharing", methods=["POST"])
|
||||
def api_collection_deleteSharingHandle():
|
||||
return SmartDbCaller(
|
||||
calendar_db.collection_deleteSharing,
|
||||
(
|
||||
FormField("token", str, False),
|
||||
FormField("uuid", str, False),
|
||||
FormField("target", str, False),
|
||||
FormField("lastChange", str, False),
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
@app.route("/collection/addSharing", methods=["POST"])
|
||||
def api_collection_addSharingHandle():
|
||||
return SmartDbCaller(
|
||||
calendar_db.collection_addSharing,
|
||||
(
|
||||
FormField("token", str, False),
|
||||
FormField("uuid", str, False),
|
||||
FormField("target", str, False),
|
||||
FormField("lastChange", str, False),
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
@app.route("/collection/getShared", methods=["POST"])
|
||||
def api_collection_getSharedHandle():
|
||||
return SmartDbCaller(
|
||||
calendar_db.collection_getShared, (FormField("token", str, False),), None
|
||||
)
|
||||
|
||||
|
||||
# endregion
|
||||
|
||||
# region: Todo
|
||||
|
||||
|
||||
@app.route("/todo/getFull", methods=["POST"])
|
||||
def api_todo_getFullHandle():
|
||||
return SmartDbCaller(
|
||||
calendar_db.todo_getFull, (FormField("token", str, False),), None
|
||||
)
|
||||
|
||||
|
||||
@app.route("/todo/getList", methods=["POST"])
|
||||
def api_todo_getListHandle():
|
||||
return SmartDbCaller(
|
||||
calendar_db.todo_getList, (FormField("token", str, False),), None
|
||||
)
|
||||
|
||||
|
||||
@app.route("/todo/getDetail", methods=["POST"])
|
||||
def api_todo_getDetailHandle():
|
||||
return SmartDbCaller(
|
||||
calendar_db.todo_getDetail,
|
||||
(FormField("token", str, False), FormField("uuid", str, False)),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
@app.route("/todo/add", methods=["POST"])
|
||||
def api_todo_addHandle():
|
||||
return SmartDbCaller(calendar_db.todo_add, (FormField("token", str, False),), None)
|
||||
|
||||
|
||||
@app.route("/todo/update", methods=["POST"])
|
||||
def api_todo_updateHandle():
|
||||
return SmartDbCaller(
|
||||
calendar_db.todo_update,
|
||||
(
|
||||
FormField("token", str, False),
|
||||
FormField("uuid", str, False),
|
||||
FormField("data", str, False),
|
||||
FormField("lastChange", str, False),
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
@app.route("/todo/delete", methods=["POST"])
|
||||
def api_todo_deleteHandle():
|
||||
return SmartDbCaller(
|
||||
calendar_db.todo_delete,
|
||||
(
|
||||
FormField("token", str, False),
|
||||
FormField("uuid", str, False),
|
||||
FormField("lastChange", str, False),
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
# endregion
|
||||
|
||||
# region: Admin
|
||||
|
||||
|
||||
@app.route("/admin/get", methods=["POST"])
|
||||
def api_admin_getHandle():
|
||||
return SmartDbCaller(calendar_db.admin_get, (FormField("token", str, False),), None)
|
||||
|
||||
|
||||
@app.route("/admin/add", methods=["POST"])
|
||||
def api_admin_addHandle():
|
||||
return SmartDbCaller(
|
||||
calendar_db.admin_add,
|
||||
(FormField("token", str, False), FormField("username", str, False)),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
@app.route("/admin/update", methods=["POST"])
|
||||
def api_admin_updateHandle():
|
||||
return SmartDbCaller(
|
||||
calendar_db.admin_update,
|
||||
(
|
||||
FormField("token", str, False),
|
||||
FormField("username", str, False),
|
||||
FormField("password", str, True),
|
||||
FormField("isAdmin", utils.Str2Bool, True),
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
@app.route("/admin/delete", methods=["POST"])
|
||||
def api_admin_deleteHandle():
|
||||
return SmartDbCaller(
|
||||
calendar_db.admin_delete,
|
||||
(FormField("token", str, False), FormField("username", str, False)),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
# endregion
|
||||
|
||||
# region: Profile
|
||||
|
||||
|
||||
@app.route("/profile/isAdmin", methods=["POST"])
|
||||
def api_profile_isAdminHandle():
|
||||
return SmartDbCaller(
|
||||
calendar_db.profile_isAdmin, (FormField("token", str, False),), None
|
||||
)
|
||||
|
||||
|
||||
@app.route("/profile/changePassword", methods=["POST"])
|
||||
def api_profile_changePasswordHandle():
|
||||
return SmartDbCaller(
|
||||
calendar_db.profile_changePassword,
|
||||
(FormField("token", str, False), FormField("password", str, False)),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
@app.route("/profile/getToken", methods=["POST"])
|
||||
def api_profile_getTokenHandle():
|
||||
return SmartDbCaller(
|
||||
calendar_db.profile_getToken, (FormField("token", str, False),), None
|
||||
)
|
||||
|
||||
|
||||
@app.route("/profile/deleteToken", methods=["POST"])
|
||||
def api_profile_deleteTokenHandle():
|
||||
return SmartDbCaller(
|
||||
calendar_db.profile_deleteToken,
|
||||
(FormField("token", str, False), FormField("deleteToken", str, False)),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
# endregion
|
||||
|
||||
# endregion
|
||||
|
||||
# region: Utilities
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ClientNetworkInfo:
|
||||
user_agent: str
|
||||
"""The user agent of client."""
|
||||
ip_addr: str
|
||||
"""The IP address of client."""
|
||||
|
||||
|
||||
def FetchClientNetworkInfo() -> ClientNetworkInfo:
|
||||
clientUa = request.user_agent.string
|
||||
forwardIpList = request.headers.getlist("X-Forwarded-For")
|
||||
if forwardIpList:
|
||||
clientIp = forwardIpList[0]
|
||||
else:
|
||||
directIp = request.remote_addr
|
||||
if directIp is not None:
|
||||
clientIp = directIp
|
||||
else:
|
||||
clientIp = "0.0.0.0"
|
||||
|
||||
return ClientNetworkInfo(clientUa, clientIp)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FormField:
|
||||
name: str
|
||||
"""The name of form field."""
|
||||
ty: Callable[[str], Any]
|
||||
"""The type of form field."""
|
||||
is_optional: bool
|
||||
"""True if this form field is optional, otherwise false."""
|
||||
|
||||
|
||||
def SmartDbCaller(
|
||||
db_method: Callable[..., ResponseBody[Any]],
|
||||
fields: tuple[FormField, ...],
|
||||
padding_form: dict[str, str] | None,
|
||||
) -> dict[str, Any]:
|
||||
opt_param_counter = 0
|
||||
lost_required: bool = False
|
||||
param_list: list[Any] = []
|
||||
opt_param_dict: dict[str, Any] = {}
|
||||
|
||||
# fetch user passed form
|
||||
user_form: dict[str, str] = request.form.to_dict()
|
||||
LOGGER.debug(f"User Form: {user_form}")
|
||||
# overwrite user form by our padding form
|
||||
if padding_form is not None:
|
||||
user_form.update(padding_form)
|
||||
LOGGER.debug(f"Padded User Form: {user_form}")
|
||||
|
||||
# check fields one by one
|
||||
for field in fields:
|
||||
value = user_form.get(field.name, None)
|
||||
if value is not None:
|
||||
value = field.ty(value)
|
||||
|
||||
if field.is_optional:
|
||||
# optional param
|
||||
if value is not None:
|
||||
opt_param_dict[field.name] = value
|
||||
opt_param_counter += 1
|
||||
else:
|
||||
# required param
|
||||
if value is None:
|
||||
lost_required = True
|
||||
else:
|
||||
param_list.append(value)
|
||||
|
||||
# Only execute database function if there is no lost required fields.
|
||||
# And fulfill one of following requirements:
|
||||
# 1. There are all required fields (optional parameter count is zero).
|
||||
# 1. Or, there is some optional parameter.
|
||||
LOGGER.debug(f"Has Lost Required Parameter: {lost_required}")
|
||||
LOGGER.debug(f"All Optional Parameter Count: {opt_param_counter}")
|
||||
LOGGER.debug(f"Available Optional Parameter Count: {len(opt_param_dict)}")
|
||||
result: ResponseBody[Any]
|
||||
if lost_required == False and (opt_param_counter == 0 or len(opt_param_dict) != 0):
|
||||
result = db_method(*param_list, **opt_param_dict)
|
||||
else:
|
||||
result = ResponseBody(False, "Invalid parameter", None)
|
||||
|
||||
return ConstructResponseBody(result)
|
||||
|
||||
|
||||
def ConstructResponseBody(body: ResponseBody[Any]) -> dict[str, Any]:
|
||||
return {"success": body.success, "error": body.error, "data": body.data}
|
||||
|
||||
|
||||
# endregion
|
||||
|
||||
|
||||
def run():
|
||||
calendar_db.open()
|
||||
app.run(port=config.get_config().web.port)
|
||||
calendar_db.close()
|
||||
File renamed without changes.
@@ -0,0 +1,67 @@
|
||||
CREATE TABLE user(
|
||||
[name] TEXT NOT NULL,
|
||||
[password] TEXT NOT NULL,
|
||||
[is_admin] TINYINT NOT NULL CHECK(is_admin = 1 OR is_admin = 0),
|
||||
[salt] INTEGER NOT NULL,
|
||||
|
||||
PRIMARY KEY (name)
|
||||
);
|
||||
|
||||
CREATE TABLE token(
|
||||
[user] TEXT NOT NULL,
|
||||
[token] TEXT UNIQUE NOT NULL,
|
||||
[token_expire_on] BIGINT NOT NULL,
|
||||
[ua] TEXT NOT NULL,
|
||||
[ip] TEXT NOT NULL,
|
||||
|
||||
FOREIGN KEY (user) REFERENCES user(name) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE collection(
|
||||
[uuid] TEXT NOT NULL,
|
||||
[name] TEXT NOT NULL,
|
||||
[user] TEXT NOT NULL,
|
||||
[last_change] TEXT NOT NULL,
|
||||
|
||||
PRIMARY KEY (uuid),
|
||||
FOREIGN KEY (user) REFERENCES user(name) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE share(
|
||||
[uuid] TEXT NOT NULL,
|
||||
[target] TEXT NOT NULL,
|
||||
|
||||
FOREIGN KEY (uuid) REFERENCES collection(uuid) ON DELETE CASCADE
|
||||
FOREIGN KEY (target) REFERENCES user(name) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE calendar(
|
||||
[uuid] TEXT NOT NULL,
|
||||
[belong_to] TEXT NOT NULL,
|
||||
|
||||
[title] TEXT NOT NULL,
|
||||
[description] TEXT NOT NULL,
|
||||
[last_change] TEXT NOT NULL,
|
||||
|
||||
[event_date_time_start] BIGINT NOT NULL,
|
||||
[event_date_time_end] BIGINT NOT NULL,
|
||||
[timezone_offset] INT NOT NULL,
|
||||
|
||||
[loop_rules] TEXT NOT NULL,
|
||||
[loop_date_time_start] BIGINT NOT NULL,
|
||||
[loop_date_time_end] BIGINT NOT NULL,
|
||||
|
||||
PRIMARY KEY (uuid),
|
||||
FOREIGN KEY (belong_to) REFERENCES collection(uuid) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE todo(
|
||||
[uuid] TEXT NOT NULL,
|
||||
[belong_to] TEXT NOT NULL,
|
||||
|
||||
[data] TEXT NOT NULL,
|
||||
[last_change] TEXT NOT NULL,
|
||||
|
||||
PRIMARY KEY (uuid),
|
||||
FOREIGN KEY (belong_to) REFERENCES user(name) ON DELETE CASCADE
|
||||
);
|
||||
@@ -0,0 +1,64 @@
|
||||
import hashlib
|
||||
import random
|
||||
import uuid
|
||||
import time
|
||||
import math
|
||||
import re
|
||||
|
||||
USERNAME_PATTERN: re.Pattern = re.compile("^[0-9A-Za-z]+$")
|
||||
PASSWORD_PATTERN: re.Pattern = re.compile("^[!-~]+$")
|
||||
|
||||
|
||||
def IsValidUsername(strl: str) -> bool:
|
||||
return USERNAME_PATTERN.match(strl) is not None
|
||||
|
||||
|
||||
def IsValidPassword(strl: str) -> bool:
|
||||
return PASSWORD_PATTERN.match(strl) is not None
|
||||
|
||||
|
||||
def ComputePasswordHash(password: str) -> str:
|
||||
s = hashlib.sha256()
|
||||
s.update(password.encode("utf-8"))
|
||||
return s.hexdigest()
|
||||
|
||||
|
||||
def GenerateUUID() -> str:
|
||||
return str(uuid.uuid1())
|
||||
|
||||
|
||||
def GenerateToken(username: str) -> str:
|
||||
s = hashlib.sha256()
|
||||
s.update(username.encode("utf-8"))
|
||||
s.update(GenerateUUID().encode("utf-8"))
|
||||
return s.hexdigest()
|
||||
|
||||
|
||||
def GenerateSalt() -> int:
|
||||
return random.randint(0, 6172748)
|
||||
|
||||
|
||||
def ComputePasswordHashWithSalt(passwordHashed: str, salt: int) -> str:
|
||||
s = hashlib.sha256()
|
||||
s.update((passwordHashed + str(salt)).encode("utf-8"))
|
||||
return s.hexdigest()
|
||||
|
||||
|
||||
def GetCurrentTimestamp() -> int:
|
||||
return int(time.time())
|
||||
|
||||
|
||||
def GetTokenExpireOn() -> int:
|
||||
return GetCurrentTimestamp() + 60 * 60 * 24 * 2 # add 2 day from now
|
||||
|
||||
|
||||
def Str2Bool(strl: str) -> bool:
|
||||
return strl.lower() == "true"
|
||||
|
||||
|
||||
def GCD(a: int, b: int) -> int:
|
||||
return math.gcd(a, b)
|
||||
|
||||
|
||||
def LCM(a: int, b: int) -> int:
|
||||
return (a * b) // GCD(a, b)
|
||||
File renamed without changes.
+28
-15
@@ -1,19 +1,32 @@
|
||||
## ======== Personal ========
|
||||
# Database file
|
||||
*.db
|
||||
# If you prefer the allow list template instead of the deny list, see community template:
|
||||
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
|
||||
#
|
||||
# Binaries for programs and plugins
|
||||
*.exe
|
||||
*.exe~
|
||||
*.dll
|
||||
*.so
|
||||
*.dylib
|
||||
|
||||
# Ignore setting file
|
||||
coconut-leaf.toml
|
||||
# Test binary, built with `go test -c`
|
||||
*.test
|
||||
|
||||
## ======== Python ========
|
||||
# Python-generated files
|
||||
__pycache__/
|
||||
*.py[oc]
|
||||
build/
|
||||
dist/
|
||||
wheels/
|
||||
*.egg-info
|
||||
# Code coverage profiles and other test artifacts
|
||||
*.out
|
||||
coverage.*
|
||||
*.coverprofile
|
||||
profile.cov
|
||||
|
||||
# Virtual environments
|
||||
.venv
|
||||
# Dependency directories (remove the comment below to include it)
|
||||
# vendor/
|
||||
|
||||
# Go workspace file
|
||||
go.work
|
||||
go.work.sum
|
||||
|
||||
# env file
|
||||
.env
|
||||
|
||||
# Editor/IDE
|
||||
# .idea/
|
||||
# .vscode/
|
||||
@@ -0,0 +1,47 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
// CLIArgs holds the arguments parsed from the command line, mirroring the
|
||||
// argparse result in the legacy coconut-leaf.py.
|
||||
type CLIArgs struct {
|
||||
// Config is the path to the configuration file (the legacy CONFIG_TOML).
|
||||
Config string
|
||||
// Init indicates whether to initialize the calendar system before running.
|
||||
Init bool
|
||||
}
|
||||
|
||||
// Parse parses the command-line arguments via the standard flag package and
|
||||
// returns a *CLIArgs. When the required --config flag is missing, it prints the
|
||||
// usage and exits with status 2 (matching argparse's exit code).
|
||||
func Parse() *CLIArgs {
|
||||
args := &CLIArgs{}
|
||||
|
||||
// Custom usage output mirroring the legacy ArgumentParser description banner.
|
||||
flag.Usage = func() {
|
||||
out := flag.CommandLine.Output()
|
||||
fmt.Fprintln(out, "The server of light, self-host and multi-account calendar system.")
|
||||
fmt.Fprintln(out)
|
||||
fmt.Fprintf(out, "Usage of %s:\n", os.Args[0])
|
||||
flag.PrintDefaults()
|
||||
}
|
||||
|
||||
// --config maps to the legacy -c/--config (required), --init to -i/--init.
|
||||
flag.StringVar(&args.Config, "config", "", "The configuration file `CONFIG_TOML` for coconut-leaf")
|
||||
flag.BoolVar(&args.Init, "init", false, "Set for initialize the calendar system")
|
||||
|
||||
flag.Parse()
|
||||
|
||||
// The standard flag package has no built-in "required", so validate manually.
|
||||
if args.Config == "" {
|
||||
fmt.Fprintln(os.Stderr, "error: the required flag --config is not provided")
|
||||
flag.Usage()
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
return args
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
{
|
||||
"database-type": "sqlite",
|
||||
"database-config": {
|
||||
"user": "",
|
||||
"password": "",
|
||||
"db": "",
|
||||
"url": "",
|
||||
"port": 3306
|
||||
},
|
||||
"web": {
|
||||
"port": 8888
|
||||
},
|
||||
"debug": true
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/BurntSushi/toml"
|
||||
)
|
||||
|
||||
// DatabaseDriver represents the database driver specified in the config file,
|
||||
// mirroring the legacy DatabaseDriver(StrEnum). It is a numeric enum simulated
|
||||
// with const + iota; its string form is produced by databaseDriverFromString.
|
||||
type DatabaseDriver int
|
||||
|
||||
const (
|
||||
// DatabaseDriverSqlite means the SQLite database is used.
|
||||
DatabaseDriverSqlite DatabaseDriver = iota
|
||||
// DatabaseDriverMysql means the MySQL database is used.
|
||||
DatabaseDriverMysql
|
||||
)
|
||||
|
||||
// databaseDriverFromString converts a driver string from the config file into a
|
||||
// DatabaseDriver. An unrecognized string returns an error.
|
||||
func databaseDriverFromString(s string) (DatabaseDriver, error) {
|
||||
switch s {
|
||||
case "sqlite":
|
||||
return DatabaseDriverSqlite, nil
|
||||
case "mysql":
|
||||
return DatabaseDriverMysql, nil
|
||||
default:
|
||||
return 0, fmt.Errorf("invalid database driver: %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// SqliteDatabaseConfig is the connection config for SQLite, mirroring the
|
||||
// legacy SqliteDatabaseConfig.
|
||||
type SqliteDatabaseConfig struct {
|
||||
// Path is the database file path.
|
||||
Path string `toml:"path"`
|
||||
}
|
||||
|
||||
// MysqlDatabaseConfig is the connection config for MySQL, mirroring the legacy
|
||||
// MysqlDatabaseConfig.
|
||||
type MysqlDatabaseConfig struct {
|
||||
// Host is the database host.
|
||||
Host string `toml:"host"`
|
||||
// Port is the database port.
|
||||
Port int `toml:"port"`
|
||||
// User is the database user.
|
||||
User string `toml:"user"`
|
||||
// Password is the database password.
|
||||
Password string `toml:"password"`
|
||||
// Database is the database name.
|
||||
Database string `toml:"database"`
|
||||
}
|
||||
|
||||
// DatabaseConfig describes the database driver and its concrete config, mirroring
|
||||
// the legacy DatabaseConfig. Driver is the discriminator deciding whether Sqlite
|
||||
// or Mysql is populated.
|
||||
type DatabaseConfig struct {
|
||||
// Driver is the selected database driver.
|
||||
Driver DatabaseDriver
|
||||
// Sqlite is non-nil when Driver is DatabaseDriverSqlite.
|
||||
Sqlite *SqliteDatabaseConfig
|
||||
// Mysql is non-nil when Driver is DatabaseDriverMysql.
|
||||
Mysql *MysqlDatabaseConfig
|
||||
}
|
||||
|
||||
// WebConfig is the web server config, mirroring the legacy WebConfig.
|
||||
type WebConfig struct {
|
||||
// Port is the web server listening port.
|
||||
Port int `toml:"port"`
|
||||
}
|
||||
|
||||
// OthersConfig holds miscellaneous options, mirroring the legacy OthersConfig.
|
||||
type OthersConfig struct {
|
||||
// Debug indicates whether debug mode is enabled.
|
||||
Debug bool `toml:"debug"`
|
||||
// AutoTokenCleanDuration is the interval (in seconds) for auto-cleaning
|
||||
// outdated tokens.
|
||||
AutoTokenCleanDuration int `toml:"auto-token-clean-duration"`
|
||||
}
|
||||
|
||||
// Config is the full configuration parsed from the config file, mirroring the
|
||||
// legacy Config.
|
||||
type Config struct {
|
||||
// Database is the database-related config.
|
||||
Database DatabaseConfig
|
||||
// Web is the web-server-related config.
|
||||
Web WebConfig
|
||||
// Others is the miscellaneous config.
|
||||
Others OthersConfig
|
||||
}
|
||||
|
||||
// rawDatabaseConfig is an internal struct used only for TOML decoding. Its
|
||||
// Config field is stored as a toml.Primitive so it can be dispatched and decoded
|
||||
// in two phases based on Driver.
|
||||
type rawDatabaseConfig struct {
|
||||
Driver string `toml:"driver"`
|
||||
Config toml.Primitive `toml:"config"`
|
||||
}
|
||||
|
||||
// rawConfig is an internal struct used only for TOML decoding, in tandem with
|
||||
// the two-phase decode.
|
||||
type rawConfig struct {
|
||||
Database rawDatabaseConfig `toml:"database"`
|
||||
Web WebConfig `toml:"web"`
|
||||
Others OthersConfig `toml:"others"`
|
||||
}
|
||||
|
||||
// Load reads and parses the TOML config file at the given path, returning the
|
||||
// parsed config or an error. It merges the legacy setup_config and get_config:
|
||||
// the first phase uses toml.DecodeFile to defer database.config, and the second
|
||||
// phase dispatches PrimitiveDecode into SqliteDatabaseConfig or
|
||||
// MysqlDatabaseConfig based on the driver.
|
||||
func Load(path string) (*Config, error) {
|
||||
var raw rawConfig
|
||||
meta, err := toml.DecodeFile(path, &raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
driver, err := databaseDriverFromString(raw.Database.Driver)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cfg := &Config{
|
||||
Web: raw.Web,
|
||||
Others: raw.Others,
|
||||
Database: DatabaseConfig{
|
||||
Driver: driver,
|
||||
},
|
||||
}
|
||||
|
||||
switch driver {
|
||||
case DatabaseDriverSqlite:
|
||||
var s SqliteDatabaseConfig
|
||||
if err := meta.PrimitiveDecode(raw.Database.Config, &s); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg.Database.Sqlite = &s
|
||||
case DatabaseDriverMysql:
|
||||
var m MysqlDatabaseConfig
|
||||
if err := meta.PrimitiveDecode(raw.Database.Config, &m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg.Database.Mysql = &m
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
|
||||
"github.com/yyc12345/coconut-leaf/backend/config"
|
||||
)
|
||||
|
||||
// CalendarUpdateOptions carries the optional fields of CalendarUpdate. A nil
|
||||
// pointer means "not provided", mirroring the legacy **optArgs semantics: a
|
||||
// field is applied only when its pointer is non-nil.
|
||||
type CalendarUpdateOptions struct {
|
||||
BelongTo *string
|
||||
Title *string
|
||||
Description *string
|
||||
EventDateTimeStart *int64
|
||||
EventDateTimeEnd *int64
|
||||
LoopRules *string
|
||||
TimezoneOffset *int64
|
||||
}
|
||||
|
||||
// AdminUpdateOptions carries the optional fields of AdminUpdate. A nil pointer
|
||||
// means "not provided".
|
||||
type AdminUpdateOptions struct {
|
||||
Password *string
|
||||
IsAdmin *bool
|
||||
}
|
||||
|
||||
// Deps bundles the shared dependencies a database implementation needs: the
|
||||
// loaded configuration and a logger. It is passed to database constructors and
|
||||
// stored inside each implementation so they can read config and emit logs.
|
||||
type Deps struct {
|
||||
Cfg *config.Config
|
||||
Logger *slog.Logger
|
||||
}
|
||||
|
||||
// Database describes every database operation the Gin server may use. It is the
|
||||
// Go equivalent of the legacy CalendarDatabase public surface: each method takes
|
||||
// a context.Context for cancellation and returns (any, error). The server layer
|
||||
// is responsible for wrapping the result into an HTTP response body.
|
||||
type Database interface {
|
||||
Init(username, password string) error
|
||||
Close() error
|
||||
|
||||
CommonSalt(ctx context.Context, username string) (any, error)
|
||||
CommonLogin(ctx context.Context, username, password, clientUa, clientIp string) (any, error)
|
||||
CommonWebLogin(ctx context.Context, username, password, clientUa, clientIp string) (any, error)
|
||||
CommonLogout(ctx context.Context, token string) (any, error)
|
||||
CommonTokenValid(ctx context.Context, token string) (any, error)
|
||||
|
||||
CalendarGetFull(ctx context.Context, token string, startDateTime, endDateTime int64) (any, error)
|
||||
CalendarGetList(ctx context.Context, token string, startDateTime, endDateTime int64) (any, error)
|
||||
CalendarGetDetail(ctx context.Context, token, uuid string) (any, error)
|
||||
CalendarUpdate(ctx context.Context, token, uuid, lastChange string, opts CalendarUpdateOptions) (any, error)
|
||||
CalendarAdd(ctx context.Context, token, belongTo, title, description string, eventDateTimeStart, eventDateTimeEnd int64, loopRules string, timezoneOffset int64) (any, error)
|
||||
CalendarDelete(ctx context.Context, token, uuid, lastChange string) (any, error)
|
||||
|
||||
CollectionGetFullOwn(ctx context.Context, token string) (any, error)
|
||||
CollectionGetListOwn(ctx context.Context, token string) (any, error)
|
||||
CollectionGetDetailOwn(ctx context.Context, token, uuid string) (any, error)
|
||||
CollectionAddOwn(ctx context.Context, token, name string) (any, error)
|
||||
CollectionUpdateOwn(ctx context.Context, token, uuid, name, lastChange string) (any, error)
|
||||
CollectionDeleteOwn(ctx context.Context, token, uuid, lastChange string) (any, error)
|
||||
CollectionGetSharing(ctx context.Context, token, uuid string) (any, error)
|
||||
CollectionDeleteSharing(ctx context.Context, token, uuid, target, lastChange string) (any, error)
|
||||
CollectionAddSharing(ctx context.Context, token, uuid, target, lastChange string) (any, error)
|
||||
CollectionGetShared(ctx context.Context, token string) (any, error)
|
||||
|
||||
TodoGetFull(ctx context.Context, token string) (any, error)
|
||||
TodoGetList(ctx context.Context, token string) (any, error)
|
||||
TodoGetDetail(ctx context.Context, token, uuid string) (any, error)
|
||||
TodoAdd(ctx context.Context, token string) (any, error)
|
||||
TodoUpdate(ctx context.Context, token, uuid, data, lastChange string) (any, error)
|
||||
TodoDelete(ctx context.Context, token, uuid, lastChange string) (any, error)
|
||||
|
||||
AdminGet(ctx context.Context, token string) (any, error)
|
||||
AdminAdd(ctx context.Context, token, username string) (any, error)
|
||||
AdminUpdate(ctx context.Context, token, username string, opts AdminUpdateOptions) (any, error)
|
||||
AdminDelete(ctx context.Context, token, username string) (any, error)
|
||||
|
||||
ProfileIsAdmin(ctx context.Context, token string) (any, error)
|
||||
ProfileChangePassword(ctx context.Context, token, password string) (any, error)
|
||||
ProfileGetToken(ctx context.Context, token string) (any, error)
|
||||
ProfileDeleteToken(ctx context.Context, token, deleteToken string) (any, error)
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
)
|
||||
|
||||
var errNotImplemented = errors.New("mysql database: not implemented")
|
||||
|
||||
// stubDatabase provides a not-implemented default for every Database method.
|
||||
// MysqlDatabase embeds it so the interface is satisfied without hand-writing
|
||||
// each method; individual methods can be overridden on MysqlDatabase later.
|
||||
type stubDatabase struct{}
|
||||
|
||||
func (stubDatabase) Init(username, password string) error { return errNotImplemented }
|
||||
func (stubDatabase) Close() error { return errNotImplemented }
|
||||
|
||||
func (stubDatabase) CommonSalt(ctx context.Context, username string) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
func (stubDatabase) CommonLogin(ctx context.Context, username, password, clientUa, clientIp string) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
func (stubDatabase) CommonWebLogin(ctx context.Context, username, password, clientUa, clientIp string) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
func (stubDatabase) CommonLogout(ctx context.Context, token string) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
func (stubDatabase) CommonTokenValid(ctx context.Context, token string) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
|
||||
func (stubDatabase) CalendarGetFull(ctx context.Context, token string, startDateTime, endDateTime int64) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
func (stubDatabase) CalendarGetList(ctx context.Context, token string, startDateTime, endDateTime int64) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
func (stubDatabase) CalendarGetDetail(ctx context.Context, token, uuid string) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
func (stubDatabase) CalendarUpdate(ctx context.Context, token, uuid, lastChange string, opts CalendarUpdateOptions) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
func (stubDatabase) CalendarAdd(ctx context.Context, token, belongTo, title, description string, eventDateTimeStart, eventDateTimeEnd int64, loopRules string, timezoneOffset int64) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
func (stubDatabase) CalendarDelete(ctx context.Context, token, uuid, lastChange string) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
|
||||
func (stubDatabase) CollectionGetFullOwn(ctx context.Context, token string) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
func (stubDatabase) CollectionGetListOwn(ctx context.Context, token string) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
func (stubDatabase) CollectionGetDetailOwn(ctx context.Context, token, uuid string) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
func (stubDatabase) CollectionAddOwn(ctx context.Context, token, name string) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
func (stubDatabase) CollectionUpdateOwn(ctx context.Context, token, uuid, name, lastChange string) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
func (stubDatabase) CollectionDeleteOwn(ctx context.Context, token, uuid, lastChange string) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
func (stubDatabase) CollectionGetSharing(ctx context.Context, token, uuid string) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
func (stubDatabase) CollectionDeleteSharing(ctx context.Context, token, uuid, target, lastChange string) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
func (stubDatabase) CollectionAddSharing(ctx context.Context, token, uuid, target, lastChange string) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
func (stubDatabase) CollectionGetShared(ctx context.Context, token string) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
|
||||
func (stubDatabase) TodoGetFull(ctx context.Context, token string) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
func (stubDatabase) TodoGetList(ctx context.Context, token string) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
func (stubDatabase) TodoGetDetail(ctx context.Context, token, uuid string) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
func (stubDatabase) TodoAdd(ctx context.Context, token string) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
func (stubDatabase) TodoUpdate(ctx context.Context, token, uuid, data, lastChange string) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
func (stubDatabase) TodoDelete(ctx context.Context, token, uuid, lastChange string) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
|
||||
func (stubDatabase) AdminGet(ctx context.Context, token string) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
func (stubDatabase) AdminAdd(ctx context.Context, token, username string) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
func (stubDatabase) AdminUpdate(ctx context.Context, token, username string, opts AdminUpdateOptions) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
func (stubDatabase) AdminDelete(ctx context.Context, token, username string) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
|
||||
func (stubDatabase) ProfileIsAdmin(ctx context.Context, token string) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
func (stubDatabase) ProfileChangePassword(ctx context.Context, token, password string) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
func (stubDatabase) ProfileGetToken(ctx context.Context, token string) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
func (stubDatabase) ProfileDeleteToken(ctx context.Context, token, deleteToken string) (any, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
|
||||
// MysqlDatabase implements Database as a fully not-implemented stub by
|
||||
// embedding stubDatabase. Real MySQL support can be filled in later by
|
||||
// overriding individual methods.
|
||||
type MysqlDatabase struct {
|
||||
stubDatabase
|
||||
deps Deps
|
||||
}
|
||||
|
||||
// NewMysqlDatabase returns a not-implemented MysqlDatabase. The deps are stored
|
||||
// for symmetry with NewSqlite3Database but not yet used.
|
||||
func NewMysqlDatabase(deps Deps) (*MysqlDatabase, error) {
|
||||
return &MysqlDatabase{deps: deps}, nil
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,444 @@
|
||||
package dt
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yyc12345/coconut-leaf/backend/utils"
|
||||
)
|
||||
|
||||
// All time values in this file use minute-granularity timestamps (UNIX seconds
|
||||
// / 60), mirroring the legacy dt.py. tzoffset is also in minutes.
|
||||
|
||||
var monthDayCount = [12]int64{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
|
||||
|
||||
var (
|
||||
minDatetime = time.Date(1950, time.January, 1, 0, 0, 0, 0, time.UTC)
|
||||
maxDatetime = time.Date(2200, time.January, 1, 0, 0, 0, 0, time.UTC)
|
||||
minTimestamp = minDatetime.Unix() / 60
|
||||
maxTimestamp = maxDatetime.Unix() / 60
|
||||
maxDatetimeYear = int64(maxDatetime.Year())
|
||||
)
|
||||
|
||||
const (
|
||||
day1Span = int64(60 * 24)
|
||||
day7Span = int64(7) * day1Span
|
||||
)
|
||||
|
||||
var (
|
||||
loopYearRule = regexp.MustCompile(`^Y([SR]{1})([1-9][0-9]*)$`)
|
||||
loopMonthRule = regexp.MustCompile(`^M([SR]{1})([ABCD])([1-9][0-9]*)$`)
|
||||
loopWeekRule = regexp.MustCompile(`^W([TF]{7})([1-9][0-9]*)$`)
|
||||
loopDayRule = regexp.MustCompile(`^D([1-9][0-9]*)$`)
|
||||
|
||||
loopStopInfinity = regexp.MustCompile(`^F$`)
|
||||
loopStopDatetime = regexp.MustCompile(`^D([1-9][0-9]*|0)$`)
|
||||
loopStopTimes = regexp.MustCompile(`^T([1-9][0-9]*)$`)
|
||||
)
|
||||
|
||||
type loopHandler func(sub []string, starttime, loopTimes, tzoffset int64) (int64, error)
|
||||
|
||||
var loopRules = []struct {
|
||||
re *regexp.Regexp
|
||||
handler loopHandler
|
||||
}{
|
||||
{loopYearRule, loopHandleYear},
|
||||
{loopMonthRule, loopHandleMonth},
|
||||
{loopWeekRule, loopHandleWeek},
|
||||
{loopDayRule, loopHandleDay},
|
||||
}
|
||||
|
||||
// ResolveLoopStr parses a loop-rule string of the form "[rules]-[stop]" and
|
||||
// returns the loop end timestamp (minute granularity), given the start time and
|
||||
// timezone offset (both in minutes). Mirrors the legacy dt.ResolveLoopStr.
|
||||
func ResolveLoopStr(strl string, starttime, tzoffset int64) (int64, error) {
|
||||
// check no loop
|
||||
if strl == "" {
|
||||
return starttime, nil
|
||||
}
|
||||
|
||||
parts := strings.Split(strl, "-")
|
||||
if len(parts) != 2 {
|
||||
return 0, errors.New("invalid loop rule: expected exactly one '-' separator")
|
||||
}
|
||||
rulesStr, stopStr := parts[0], parts[1]
|
||||
|
||||
// try compute from loopStop
|
||||
if loopStopInfinity.MatchString(stopStr) {
|
||||
return maxTimestamp, nil
|
||||
}
|
||||
if m := loopStopDatetime.FindStringSubmatch(stopStr); m != nil {
|
||||
ts, err := strconv.ParseInt(m[1], 10, 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("invalid loop datetime stop: %w", err)
|
||||
}
|
||||
return ts, nil
|
||||
}
|
||||
|
||||
var loopTimes int64
|
||||
if m := loopStopTimes.FindStringSubmatch(stopStr); m != nil {
|
||||
t, err := strconv.ParseInt(m[1], 10, 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("invalid loop times stop: %w", err)
|
||||
}
|
||||
loopTimes = t
|
||||
} else {
|
||||
return 0, errors.New("invalid loop stop rules")
|
||||
}
|
||||
|
||||
for _, rule := range loopRules {
|
||||
if m := rule.re.FindStringSubmatch(rulesStr); m != nil {
|
||||
return rule.handler(m, starttime, loopTimes, tzoffset)
|
||||
}
|
||||
}
|
||||
return 0, errors.New("invalid loop rules")
|
||||
}
|
||||
|
||||
// clientDateComponents extracts the (year, month, day) wall-clock components of
|
||||
// starttime (minute timestamp) under the fixed offset tzoffset (minutes). This
|
||||
// mirrors python's datetime.fromtimestamp(starttime*60, UTCTimezone(tzoffset)).
|
||||
// Note time.FixedZone takes seconds, hence tzoffset*60.
|
||||
func clientDateComponents(starttime int64, tzoffset int64) (int64, int64, int64) {
|
||||
loc := time.FixedZone("offset", int(tzoffset*60))
|
||||
t := time.Unix(starttime*60, 0).In(loc)
|
||||
return int64(t.Year()), int64(t.Month()), int64(t.Day())
|
||||
}
|
||||
|
||||
func loopHandleYear(sub []string, starttime, times, tzoffset int64) (int64, error) {
|
||||
clientYear, clientMonth, clientDay := clientDateComponents(starttime, tzoffset)
|
||||
isStrict := sub[1] == "S"
|
||||
yearSpan, err := strconv.ParseInt(sub[2], 10, 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("invalid year span: %w", err)
|
||||
}
|
||||
|
||||
times--
|
||||
newYear, newMonth, newDay := clientYear, clientMonth, clientDay
|
||||
if clientMonth == 2 && clientDay == 29 {
|
||||
if isStrict {
|
||||
realSpan := utils.LCM(yearSpan, 4)
|
||||
valCache := starttime
|
||||
for valCache < maxTimestamp && times > 0 {
|
||||
newYear += realSpan
|
||||
if !isLeapYear(newYear) {
|
||||
continue
|
||||
}
|
||||
valCache = starttime + day1Span*(daysCount(newYear, newMonth, newDay)-daysCount(clientYear, clientMonth, clientDay))
|
||||
times--
|
||||
}
|
||||
} else {
|
||||
newYear += times * yearSpan
|
||||
if !isLeapYear(newYear) {
|
||||
newDay = 28
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// if times == 1, no extra datetime need to be added
|
||||
newYear += times * yearSpan
|
||||
}
|
||||
|
||||
val := starttime + day1Span*(daysCount(newYear, newMonth, newDay)-daysCount(clientYear, clientMonth, clientDay))
|
||||
if val < maxTimestamp {
|
||||
return val, nil
|
||||
} else {
|
||||
return maxTimestamp, nil
|
||||
}
|
||||
}
|
||||
|
||||
func loopHandleMonth(sub []string, starttime, times, tzoffset int64) (int64, error) {
|
||||
isStrict := sub[1] == "S"
|
||||
loopType := sub[2]
|
||||
monthSpan, err := strconv.ParseInt(sub[3], 10, 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("invalid month span: %w", err)
|
||||
}
|
||||
|
||||
// we should get original data in each method
|
||||
times--
|
||||
clientYear, clientMonth, clientDay := clientDateComponents(starttime, tzoffset)
|
||||
newYear, newMonth, newDay := clientYear, clientMonth, clientDay
|
||||
// data struct
|
||||
// ds =
|
||||
// (dayForwards || dayBackwards || weeksForward, dayOfWeek || weeksBackwards, dayOfWeek)
|
||||
// ( A || B || C || D )
|
||||
ds := getDayInMonth(clientYear, clientMonth, clientDay)
|
||||
|
||||
advanceMonth := func() {
|
||||
newMonth += monthSpan
|
||||
if newMonth > 12 {
|
||||
newYear += (newMonth - 1) / 12
|
||||
newMonth = ((newMonth - 1) % 12) + 1
|
||||
}
|
||||
}
|
||||
|
||||
if isStrict {
|
||||
switch loopType {
|
||||
case "A":
|
||||
for times > 0 {
|
||||
advanceMonth()
|
||||
if newYear > maxDatetimeYear {
|
||||
break
|
||||
}
|
||||
maxDays := monthDayCount[newMonth-1]
|
||||
if newMonth == 2 && isLeapYear(newYear) {
|
||||
maxDays++
|
||||
}
|
||||
if ds.daysForward <= maxDays {
|
||||
times--
|
||||
}
|
||||
}
|
||||
case "B":
|
||||
for times > 0 {
|
||||
advanceMonth()
|
||||
if newYear > maxDatetimeYear {
|
||||
break
|
||||
}
|
||||
maxDays := monthDayCount[newMonth-1]
|
||||
if newMonth == 2 && isLeapYear(newYear) {
|
||||
maxDays++
|
||||
}
|
||||
if ds.daysBackward <= maxDays {
|
||||
times--
|
||||
}
|
||||
}
|
||||
case "C":
|
||||
for times > 0 {
|
||||
advanceMonth()
|
||||
if newYear > maxDatetimeYear {
|
||||
break
|
||||
}
|
||||
ms := getMonthWeekStatistics(newYear, newMonth)
|
||||
if ds.weeksForward <= ms[ds.weeksForwardDayOfWeek] {
|
||||
times--
|
||||
}
|
||||
}
|
||||
case "D":
|
||||
for times > 0 {
|
||||
advanceMonth()
|
||||
if newYear > maxDatetimeYear {
|
||||
break
|
||||
}
|
||||
ms := getMonthWeekStatistics(newYear, newMonth)
|
||||
if ds.weeksBackward <= ms[ds.weeksBackwardDayOfWeek] {
|
||||
times--
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
newMonth += times * monthSpan
|
||||
newYear += (newMonth - 1) / 12
|
||||
newMonth = ((newMonth - 1) % 12) + 1
|
||||
}
|
||||
|
||||
// all method need calc newDay and it should be the last day of current selected month
|
||||
// so calc it in there
|
||||
newDay = monthDayCount[newMonth-1]
|
||||
if newMonth == 2 && isLeapYear(newYear) {
|
||||
newDay++
|
||||
}
|
||||
val := starttime + day1Span*(daysCount(newYear, newMonth, newDay)-daysCount(clientYear, clientMonth, clientDay))
|
||||
if val < maxTimestamp {
|
||||
return val, nil
|
||||
} else {
|
||||
return maxTimestamp, nil
|
||||
}
|
||||
}
|
||||
|
||||
func loopHandleWeek(sub []string, starttime, times, tzoffset int64) (int64, error) {
|
||||
weekStr := sub[1]
|
||||
var weekOccupied [7]bool
|
||||
var weekEventCount int64
|
||||
for i := range 7 {
|
||||
weekOccupied[i] = weekStr[i] == 'T'
|
||||
if weekOccupied[i] {
|
||||
weekEventCount++
|
||||
}
|
||||
}
|
||||
if weekEventCount == 0 {
|
||||
return 0, errors.New("invalid week format")
|
||||
}
|
||||
|
||||
weekSpan, err := strconv.ParseInt(sub[2], 10, 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("invalid week span: %w", err)
|
||||
}
|
||||
|
||||
// Use the ported dayOfWeek (Monday=0) instead of Go's time.Weekday (Sunday=0)
|
||||
// so the week rule's Monday-first indexing stays consistent.
|
||||
cy, cm, cd := clientDateComponents(starttime, tzoffset)
|
||||
nowDayOfWeek := dayOfWeek(cy, cm, cd)
|
||||
if !weekOccupied[nowDayOfWeek] {
|
||||
// if first event is not suit for week loop rules, minus one more event to suit it.
|
||||
times--
|
||||
}
|
||||
fullWeek := times / weekEventCount
|
||||
remainEvent := times % weekEventCount
|
||||
|
||||
val := starttime + day7Span*fullWeek*weekSpan
|
||||
if val > maxTimestamp {
|
||||
// return now, to reduce calc usage
|
||||
return maxTimestamp, nil
|
||||
}
|
||||
|
||||
for remainEvent != 0 {
|
||||
val += day1Span
|
||||
if weekOccupied[nowDayOfWeek%7] {
|
||||
remainEvent--
|
||||
}
|
||||
nowDayOfWeek++
|
||||
}
|
||||
|
||||
val--
|
||||
if val < maxTimestamp {
|
||||
return val, nil
|
||||
} else {
|
||||
return maxTimestamp, nil
|
||||
}
|
||||
}
|
||||
|
||||
func loopHandleDay(sub []string, starttime, times, tzoffset int64) (int64, error) {
|
||||
span, err := strconv.ParseInt(sub[1], 10, 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("invalid day span: %w", err)
|
||||
}
|
||||
val := starttime + day1Span*times*span - 1
|
||||
if val < maxTimestamp {
|
||||
return val, nil
|
||||
}
|
||||
return maxTimestamp, nil
|
||||
}
|
||||
|
||||
// leapYearCountEx counts leap years following the proleptic Gregorian
|
||||
// 4/100/400 rule. NOTE: the legacy python had a typo in the baseYear branch
|
||||
// (subtracted /400 instead of /100, which cancelled the +/400); it is corrected
|
||||
// here. The fix has no observable effect on current call sites, since baseYear
|
||||
// is always 1 and floor(1/n)=0 for n in {4,100,400}.
|
||||
func leapYearCountEx(endYear int64, includeThis bool, baseYear int64, includeBase bool) int64 {
|
||||
if !includeThis {
|
||||
endYear--
|
||||
}
|
||||
if includeBase {
|
||||
baseYear--
|
||||
}
|
||||
|
||||
endly := endYear / 4
|
||||
endly -= endYear / 100
|
||||
endly += endYear / 400
|
||||
|
||||
basely := baseYear / 4
|
||||
basely -= baseYear / 100
|
||||
basely += baseYear / 400
|
||||
|
||||
return endly - basely
|
||||
}
|
||||
|
||||
func leapYearCount(year int64) int64 {
|
||||
return leapYearCountEx(year, false, 1, true)
|
||||
}
|
||||
|
||||
func isLeapYear(year int64) bool {
|
||||
isLeap := false
|
||||
if year%4 == 0 {
|
||||
isLeap = true
|
||||
}
|
||||
if year%100 == 0 {
|
||||
isLeap = false
|
||||
}
|
||||
if year%400 == 0 {
|
||||
isLeap = true
|
||||
}
|
||||
return isLeap
|
||||
}
|
||||
|
||||
func daysCount(year, month, day int64) int64 {
|
||||
ly := leapYearCountEx(year, false, 1, true)
|
||||
days := int64(365) * (year - 1)
|
||||
days += ly
|
||||
|
||||
for index := int64(1); index < month; index++ {
|
||||
days += monthDayCount[index-1]
|
||||
}
|
||||
if month > 2 && isLeapYear(year) {
|
||||
days++
|
||||
}
|
||||
|
||||
days += day - 1
|
||||
return days
|
||||
}
|
||||
|
||||
// dayOfWeek returns the day of week with Monday=0 .. Sunday=6 (independent of
|
||||
// Go's time.Weekday convention), derived from the portable daysCount.
|
||||
func dayOfWeek(year, month, day int64) int64 {
|
||||
// As we know, Jan 1, 1900 is Monday.
|
||||
// According to this, we can speculate Jan 1, 0001 also is Monday.
|
||||
return daysCount(year, month, day) % 7
|
||||
}
|
||||
|
||||
// dayInMonthInfo holds positional statistics for a day within its month. The
|
||||
// day-of-week values use Monday=0 indexing.
|
||||
type dayInMonthInfo struct {
|
||||
// daysForward is the day count to this day, counting from month head to tail.
|
||||
daysForward int64
|
||||
// daysBackward is the day count to this day, counting from month tail to head.
|
||||
daysBackward int64
|
||||
// weeksForward is the count of the week this day is located in, counting from
|
||||
// month head to tail.
|
||||
weeksForward int64
|
||||
// weeksForwardDayOfWeek is the day-of-week index paired with weeksForward.
|
||||
weeksForwardDayOfWeek int64
|
||||
// weeksBackward is the count of the week this day is located in, counting from
|
||||
// month tail to head.
|
||||
weeksBackward int64
|
||||
// weeksBackwardDayOfWeek is the day-of-week index paired with weeksBackward.
|
||||
weeksBackwardDayOfWeek int64
|
||||
}
|
||||
|
||||
// getDayInMonth returns the positional statistics of the given date within its
|
||||
// month.
|
||||
func getDayInMonth(year, month, day int64) dayInMonthInfo {
|
||||
days := monthDayCount[month-1]
|
||||
if month == 2 && isLeapYear(year) {
|
||||
days++
|
||||
}
|
||||
firstDayOfWeek := dayOfWeek(year, month, 1)
|
||||
dow := (firstDayOfWeek + day - 1) % 7
|
||||
|
||||
daysForward := day
|
||||
daysBackward := days - day + 1
|
||||
weeksForward := (daysForward-1)/7 + 1
|
||||
weeksBackward := (daysBackward-1)/7 + 1
|
||||
|
||||
return dayInMonthInfo{
|
||||
daysForward: daysForward,
|
||||
daysBackward: daysBackward,
|
||||
weeksForward: weeksForward,
|
||||
weeksForwardDayOfWeek: dow,
|
||||
weeksBackward: weeksBackward,
|
||||
weeksBackwardDayOfWeek: dow,
|
||||
}
|
||||
}
|
||||
|
||||
// getMonthWeekStatistics returns, for each weekday Monday=0..Sunday=6, how many
|
||||
// times that weekday occurs in the given month.
|
||||
func getMonthWeekStatistics(year, month int64) [7]int64 {
|
||||
days := monthDayCount[month-1]
|
||||
if month == 2 && isLeapYear(year) {
|
||||
days++
|
||||
}
|
||||
firstDayOfWeek := dayOfWeek(year, month, 1)
|
||||
// lastDayOfWeek := (firstDayOfWeek + days - 1) % 7
|
||||
|
||||
result := [7]int64{4, 4, 4, 4, 4, 4, 4}
|
||||
remain := days % 7
|
||||
week := firstDayOfWeek
|
||||
for remain > 0 {
|
||||
result[week%7]++
|
||||
week++
|
||||
remain--
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
module github.com/yyc12345/coconut-leaf/backend
|
||||
|
||||
go 1.26.2
|
||||
|
||||
require (
|
||||
github.com/BurntSushi/toml v1.6.0
|
||||
github.com/gin-gonic/gin v1.12.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/bytedance/gopkg v0.1.4 // indirect
|
||||
github.com/bytedance/sonic v1.15.2 // indirect
|
||||
github.com/bytedance/sonic/loader v0.5.1 // indirect
|
||||
github.com/cloudwego/base64x v0.1.7 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.13 // indirect
|
||||
github.com/gin-contrib/sse v1.1.1 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.30.3 // indirect
|
||||
github.com/goccy/go-json v0.10.6 // indirect
|
||||
github.com/goccy/go-yaml v1.19.2 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.4.0 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.22 // indirect
|
||||
github.com/mattn/go-sqlite3 v1.14.48 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.4.3 // indirect
|
||||
github.com/quic-go/qpack v0.6.0 // indirect
|
||||
github.com/quic-go/quic-go v0.60.0 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.3.1 // indirect
|
||||
go.mongodb.org/mongo-driver/v2 v2.8.0 // indirect
|
||||
golang.org/x/arch v0.29.0 // indirect
|
||||
golang.org/x/crypto v0.54.0 // indirect
|
||||
golang.org/x/net v0.57.0 // indirect
|
||||
golang.org/x/sys v0.47.0 // indirect
|
||||
golang.org/x/text v0.40.0 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
)
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
|
||||
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
|
||||
github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M=
|
||||
github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM=
|
||||
github.com/bytedance/gopkg v0.1.4 h1:oZnQwnX82KAIWb7033bEwtxvTqXcYMxDBaQxo5JJHWM=
|
||||
github.com/bytedance/gopkg v0.1.4/go.mod h1:v1zWfPm21Fb+OsyXN2VAHdL6TBb2L88anLQgdyje6R4=
|
||||
github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE=
|
||||
github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k=
|
||||
github.com/bytedance/sonic v1.15.2 h1:90H+rcF/FwLXwfB1cudOLq/je83n683Utf4Cbp0xHCo=
|
||||
github.com/bytedance/sonic v1.15.2/go.mod h1:mT2NbXunuaEbnZ+mRIX/vYqKISmgEuHFDI4UzmKx2SA=
|
||||
github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE=
|
||||
github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
|
||||
github.com/bytedance/sonic/loader v0.5.1 h1:Ygpfa9zwRCCKSlrp5bBP/b/Xzc3VxsAW+5NIYXrOOpI=
|
||||
github.com/bytedance/sonic/loader v0.5.1/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
|
||||
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
|
||||
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
|
||||
github.com/cloudwego/base64x v0.1.7 h1:NppS+Fgzg5ovhn4NkUXaDT3x9jldgH5ToMCqzBSi2zI=
|
||||
github.com/cloudwego/base64x v0.1.7/go.mod h1:Cu1PV9zfrSf7ET2tIbWbbEy7jO7HHJ13q4X2SQ8aWYg=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw=
|
||||
github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
||||
github.com/gabriel-vasile/mimetype v1.4.13 h1:46nXokslUBsAJE/wMsp5gtO500a4F3Nkz9Ufpk2AcUM=
|
||||
github.com/gabriel-vasile/mimetype v1.4.13/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
||||
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
|
||||
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
|
||||
github.com/gin-contrib/sse v1.1.1 h1:uGYpNwTacv5R68bSGMapo62iLTRa9l5zxGCps4hK6ko=
|
||||
github.com/gin-contrib/sse v1.1.1/go.mod h1:QXzuVkA0YO7o/gun03UI1Q+FTI8ZV/n5t03kIQAI89s=
|
||||
github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8=
|
||||
github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w=
|
||||
github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM=
|
||||
github.com/go-playground/validator/v10 v10.30.3 h1:4MU6YkEwx7GbcPJOZxrtbu+QfF3pJLJuaYTeAH0DYy8=
|
||||
github.com/go-playground/validator/v10 v10.30.3/go.mod h1:4Axh7oCNGcoGkqLoE4YWt6n20mcEIsPRlB7vPk3lpyc=
|
||||
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
||||
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||
github.com/goccy/go-json v0.10.6 h1:p8HrPJzOakx/mn/bQtjgNjdTcN+/S6FcG2CTtQOrHVU=
|
||||
github.com/goccy/go-json v0.10.6/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||
github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
|
||||
github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||
github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
|
||||
github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4=
|
||||
github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
|
||||
github.com/mattn/go-sqlite3 v1.14.48 h1:7XHIgl0a8HwOaiK4E47ozLkST78rR9+OtNGx27D/TFs=
|
||||
github.com/mattn/go-sqlite3 v1.14.48/go.mod h1:6JTjA44L93a0QCyJef5YvlPoKXntQPjzWv5gtm9sB6w=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY=
|
||||
github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
|
||||
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
|
||||
github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw=
|
||||
github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU=
|
||||
github.com/quic-go/quic-go v0.60.0 h1:xcQioE8OM66UQLeUMHltK1CCcOu3JbVB4JAQdDQSB+0=
|
||||
github.com/quic-go/quic-go v0.60.0/go.mod h1:wpKpjmPpftl30sL6pFh7REVpjbcCVy4zt2vDyK1TuJk=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=
|
||||
github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
|
||||
go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE=
|
||||
go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
|
||||
go.mongodb.org/mongo-driver/v2 v2.8.0 h1:CxWDGQYY8QQwNjAl/aq2sfWakdnWZynnqJ9F4DhHbP8=
|
||||
go.mongodb.org/mongo-driver/v2 v2.8.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
|
||||
go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
|
||||
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
|
||||
golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI=
|
||||
golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
|
||||
golang.org/x/arch v0.29.0 h1:8sSET5wB0+exBm0FGmOtdHMqjlRdV2DRD3/IV6OZgho=
|
||||
golang.org/x/arch v0.29.0/go.mod h1:0X+GdSIP+kL5wPmpK7sdkEVTt2XoYP0cSjQSbZBwOi8=
|
||||
golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=
|
||||
golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=
|
||||
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
|
||||
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
|
||||
golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=
|
||||
golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=
|
||||
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
|
||||
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
|
||||
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=
|
||||
golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=
|
||||
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
|
||||
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
|
||||
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
|
||||
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,42 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"os"
|
||||
)
|
||||
|
||||
// LoggerLevel expresses the desired logging verbosity. Unlike a full log-level
|
||||
// enum, it only distinguishes between a verbose development mode and a quieter
|
||||
// production mode; it is converted to an slog.Level by New.
|
||||
type LoggerLevel int
|
||||
|
||||
const (
|
||||
// Development enables debug-level output, suitable for local development.
|
||||
Development LoggerLevel = iota
|
||||
// Production limits output to info level and above.
|
||||
Production
|
||||
)
|
||||
|
||||
// toSlogLevel converts a LoggerLevel into the corresponding slog.Level,
|
||||
// defaulting to info for any unrecognized value.
|
||||
func toSlogLevel(level LoggerLevel) slog.Level {
|
||||
switch level {
|
||||
case Development:
|
||||
return slog.LevelDebug
|
||||
case Production:
|
||||
return slog.LevelInfo
|
||||
default:
|
||||
return slog.LevelInfo
|
||||
}
|
||||
}
|
||||
|
||||
// New creates a *slog.Logger that writes to os.Stderr via slog's default
|
||||
// TextHandler, with its verbosity driven by the given LoggerLevel. This
|
||||
// replaces the legacy module-level singleton LOGGER; callers own the returned
|
||||
// logger and thread it through to sub-modules.
|
||||
func New(level LoggerLevel) *slog.Logger {
|
||||
handler := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
|
||||
Level: toSlogLevel(level),
|
||||
})
|
||||
return slog.New(handler)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// main.go
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/yyc12345/coconut-leaf/backend/cli"
|
||||
"github.com/yyc12345/coconut-leaf/backend/config"
|
||||
"github.com/yyc12345/coconut-leaf/backend/logger"
|
||||
)
|
||||
|
||||
func main() {
|
||||
args := cli.Parse()
|
||||
|
||||
cfg, err := config.Load(args.Config)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
var loggerLevel logger.LoggerLevel
|
||||
if cfg.Others.Debug {
|
||||
loggerLevel = logger.Development
|
||||
} else {
|
||||
loggerLevel = logger.Production
|
||||
}
|
||||
logger := logger.New(loggerLevel)
|
||||
|
||||
_ = logger
|
||||
|
||||
// 创建默认的 Gin 引擎(包含 Logger 和 Recovery 中间件)
|
||||
r := gin.Default()
|
||||
|
||||
// 定义路由
|
||||
r.GET("/", func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"message": "Hello, Gin!",
|
||||
})
|
||||
})
|
||||
|
||||
//启动服务器(默认端口8088)
|
||||
r.Run(":8080")
|
||||
}
|
||||
@@ -1,457 +0,0 @@
|
||||
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",
|
||||
)
|
||||
calendar_db = database.CalendarDatabase()
|
||||
|
||||
# render_static_resources = None
|
||||
|
||||
# =============================================database
|
||||
|
||||
# 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'])
|
||||
def api_common_saltHandle():
|
||||
return SmartDbCaller(calendar_db.common_salt,
|
||||
(('username', str, False), ),
|
||||
None)
|
||||
|
||||
@app.route('/api/common/login', methods=['POST'])
|
||||
def api_common_loginHandle():
|
||||
# construct client data first
|
||||
clientUa = request.user_agent.string
|
||||
if request.headers.getlist("X-Forwarded-For"):
|
||||
clientIp = request.headers.getlist("X-Forwarded-For")[0]
|
||||
else:
|
||||
clientIp = request.remote_addr
|
||||
|
||||
return SmartDbCaller(calendar_db.common_login,
|
||||
(('username', str, False),
|
||||
('password', str, False),
|
||||
('clientUa', str, False),
|
||||
('clientIp', str, False)),
|
||||
{
|
||||
'clientUa': clientUa,
|
||||
'clientIp': clientIp
|
||||
})
|
||||
|
||||
@app.route('/api/common/webLogin', methods=['POST'])
|
||||
def api_common_webLoginHandle():
|
||||
# construct client data first
|
||||
clientUa = request.user_agent.string
|
||||
if request.headers.getlist("X-Forwarded-For"):
|
||||
clientIp = request.headers.getlist("X-Forwarded-For")[0]
|
||||
else:
|
||||
clientIp = request.remote_addr
|
||||
|
||||
return SmartDbCaller(calendar_db.common_webLogin,
|
||||
(('username', str, False),
|
||||
('password', str, False),
|
||||
('clientUa', str, False),
|
||||
('clientIp', str, False)),
|
||||
{
|
||||
'clientUa': clientUa,
|
||||
'clientIp': clientIp
|
||||
})
|
||||
|
||||
@app.route('/api/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'])
|
||||
def api_common_tokenValidHandle():
|
||||
return SmartDbCaller(calendar_db.common_tokenValid,
|
||||
(('token', str, False), ),
|
||||
None)
|
||||
|
||||
# ================================ calendar
|
||||
|
||||
@app.route('/api/calendar/getFull', methods=['POST'])
|
||||
def api_calendar_getFullHandle():
|
||||
return SmartDbCaller(calendar_db.calendar_getFull,
|
||||
(('token', str, False),
|
||||
('startDateTime', int, False),
|
||||
('endDateTime', int, False)),
|
||||
None)
|
||||
|
||||
@app.route('/api/calendar/getList', methods=['POST'])
|
||||
def api_calendar_getListHandle():
|
||||
return SmartDbCaller(calendar_db.calendar_getList,
|
||||
(('token', str, False),
|
||||
('startDateTime', int, False),
|
||||
('endDateTime', int, False)),
|
||||
None)
|
||||
|
||||
@app.route('/api/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'])
|
||||
def api_calendar_updateHandle():
|
||||
return SmartDbCaller(calendar_db.calendar_update,
|
||||
(('token', str, False),
|
||||
('uuid', str, False),
|
||||
('belongTo', str, True),
|
||||
('title', str, True),
|
||||
('description', str, True),
|
||||
('eventDateTimeStart', int, True),
|
||||
('eventDateTimeEnd', int, True),
|
||||
('loopRules', str, True),
|
||||
('timezoneOffset', int, True),
|
||||
('lastChange', str, False)),
|
||||
None)
|
||||
|
||||
@app.route('/api/calendar/add', methods=['POST'])
|
||||
def api_calendar_addHandle():
|
||||
return SmartDbCaller(calendar_db.calendar_add,
|
||||
(('token', str, False),
|
||||
('belongTo', str, False),
|
||||
('title', str, False),
|
||||
('description', str, False),
|
||||
('eventDateTimeStart', int, False),
|
||||
('eventDateTimeEnd', int, False),
|
||||
('loopRules', str, False),
|
||||
('timezoneOffset', int, False)),
|
||||
None)
|
||||
|
||||
@app.route('/api/calendar/delete', methods=['POST'])
|
||||
def api_calendar_deleteHandle():
|
||||
return SmartDbCaller(calendar_db.calendar_delete,
|
||||
(('token', str, False),
|
||||
('uuid', str, False),
|
||||
('lastChange', str, False)),
|
||||
None)
|
||||
|
||||
# ================================ collection
|
||||
|
||||
@app.route('/api/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'])
|
||||
def api_collection_getListOwnHandle():
|
||||
return SmartDbCaller(calendar_db.collection_getListOwn,
|
||||
(('token', str, False), ),
|
||||
None)
|
||||
|
||||
@app.route('/api/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'])
|
||||
def api_collection_addOwnHandle():
|
||||
return SmartDbCaller(calendar_db.collection_addOwn,
|
||||
(('token', str, False),
|
||||
('name', str, False)),
|
||||
None)
|
||||
|
||||
@app.route('/api/collection/updateOwn', methods=['POST'])
|
||||
def api_collection_updateOwnHandle():
|
||||
return SmartDbCaller(calendar_db.collection_updateOwn,
|
||||
(('token', str, False),
|
||||
('uuid', str, False),
|
||||
('name', str, False),
|
||||
('lastChange', str, False)),
|
||||
None)
|
||||
|
||||
@app.route('/api/collection/deleteOwn', methods=['POST'])
|
||||
def api_collection_deleteOwnHandle():
|
||||
return SmartDbCaller(calendar_db.collection_deleteOwn,
|
||||
(('token', str, False),
|
||||
('uuid', str, False),
|
||||
('lastChange', str, False)),
|
||||
None)
|
||||
|
||||
|
||||
@app.route('/api/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'])
|
||||
def api_collection_deleteSharingHandle():
|
||||
return SmartDbCaller(calendar_db.collection_deleteSharing,
|
||||
(('token', str, False),
|
||||
('uuid', str, False),
|
||||
('target', str, False),
|
||||
('lastChange', str, False)),
|
||||
None)
|
||||
|
||||
@app.route('/api/collection/addSharing', methods=['POST'])
|
||||
def api_collection_addSharingHandle():
|
||||
return SmartDbCaller(calendar_db.collection_addSharing,
|
||||
(('token', str, False),
|
||||
('uuid', str, False),
|
||||
('target', str, False),
|
||||
('lastChange', str, False)),
|
||||
None)
|
||||
|
||||
|
||||
@app.route('/api/collection/getShared', methods=['POST'])
|
||||
def api_collection_getSharedHandle():
|
||||
return SmartDbCaller(calendar_db.collection_getShared,
|
||||
(('token', str, False), ),
|
||||
None)
|
||||
|
||||
# ================================ todo
|
||||
|
||||
@app.route('/api/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'])
|
||||
def api_todo_getListHandle():
|
||||
return SmartDbCaller(calendar_db.todo_getList,
|
||||
(('token', str, False), ),
|
||||
None)
|
||||
|
||||
@app.route('/api/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'])
|
||||
def api_todo_addHandle():
|
||||
return SmartDbCaller(calendar_db.todo_add,
|
||||
(('token', str, False), ),
|
||||
None)
|
||||
|
||||
@app.route('/api/todo/update', methods=['POST'])
|
||||
def api_todo_updateHandle():
|
||||
return SmartDbCaller(calendar_db.todo_update,
|
||||
(('token', str, False),
|
||||
('uuid', str, False),
|
||||
('data', str, False),
|
||||
('lastChange', str, False)),
|
||||
None)
|
||||
|
||||
@app.route('/api/todo/delete', methods=['POST'])
|
||||
def api_todo_deleteHandle():
|
||||
return SmartDbCaller(calendar_db.todo_delete,
|
||||
(('token', str, False),
|
||||
('uuid', str, False),
|
||||
('lastChange', str, False)),
|
||||
None)
|
||||
|
||||
# ================================ admin
|
||||
|
||||
@app.route('/api/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'])
|
||||
def api_admin_addHandle():
|
||||
return SmartDbCaller(calendar_db.admin_add,
|
||||
(('token', str, False),
|
||||
('username', str, False)),
|
||||
None)
|
||||
|
||||
@app.route('/api/admin/update', methods=['POST'])
|
||||
def api_admin_updateHandle():
|
||||
return SmartDbCaller(calendar_db.admin_update,
|
||||
(('token', str, False),
|
||||
('username', str, False),
|
||||
('password', str, True),
|
||||
('isAdmin', utils.Str2Bool, True)),
|
||||
None)
|
||||
|
||||
@app.route('/api/admin/delete', methods=['POST'])
|
||||
def api_admin_deleteHandle():
|
||||
return SmartDbCaller(calendar_db.admin_delete,
|
||||
(('token', str, False),
|
||||
('username', str, False)),
|
||||
None)
|
||||
|
||||
# ================================ profile
|
||||
|
||||
@app.route('/api/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'])
|
||||
def api_profile_changePasswordHandle():
|
||||
return SmartDbCaller(calendar_db.profile_changePassword,
|
||||
(('token', str, False),
|
||||
('password', str, False)),
|
||||
None)
|
||||
|
||||
@app.route('/api/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'])
|
||||
def api_profile_deleteTokenHandle():
|
||||
return SmartDbCaller(calendar_db.profile_deleteToken,
|
||||
(('token', str, False),
|
||||
('deleteToken', str, False)),
|
||||
None)
|
||||
|
||||
# =============================================main run
|
||||
|
||||
'''
|
||||
def UpdateStaticResources():
|
||||
global render_static_resources
|
||||
if render_static_resources is not None:
|
||||
return
|
||||
|
||||
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')
|
||||
}
|
||||
'''
|
||||
|
||||
def SmartDbCaller(dbMethod, paramTuple, extraDict):
|
||||
result = (False, 'Invalid parameter', None)
|
||||
optCount = 0
|
||||
paramList = []
|
||||
optParamDict = {}
|
||||
# for each item,
|
||||
# item[0] is field name.
|
||||
# item[1] is type.
|
||||
# item[2] is whether it is optional field
|
||||
realForm = request.form.to_dict()
|
||||
if extraDict is not None:
|
||||
realForm.update(extraDict)
|
||||
for item in paramTuple:
|
||||
cache = item[1](realForm.get(item[0], None))
|
||||
if item[2]:
|
||||
# optional param
|
||||
if cache is not None:
|
||||
optParamDict[item[0]] = cache
|
||||
optCount += 1
|
||||
else:
|
||||
if cache is None:
|
||||
break
|
||||
paramList.append(cache)
|
||||
else:
|
||||
# at least one opt param
|
||||
if optCount == 0 or len(optParamDict) != 0:
|
||||
result = dbMethod(*paramList, **optParamDict)
|
||||
|
||||
return ConstructResponseBody(result)
|
||||
|
||||
def ConstructResponseBody(returnedTuple):
|
||||
return {
|
||||
'success': returnedTuple[0],
|
||||
'error': returnedTuple[1],
|
||||
'data': returnedTuple[2]
|
||||
}
|
||||
|
||||
def run():
|
||||
calendar_db.open()
|
||||
app.run(port=config.get_config().web.port)
|
||||
calendar_db.close()
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
CREATE TABLE user(
|
||||
[ccn_name] TEXT NOT NULL,
|
||||
[ccn_password] TEXT NOT NULL,
|
||||
[ccn_isAdmin] TINYINT NOT NULL CHECK(ccn_isAdmin = 1 OR ccn_isAdmin = 0),
|
||||
[ccn_salt] INTEGER NOT NULL,
|
||||
|
||||
PRIMARY KEY (ccn_name)
|
||||
);
|
||||
|
||||
CREATE TABLE token(
|
||||
[ccn_user] TEXT NOT NULL,
|
||||
[ccn_token] TEXT UNIQUE NOT NULL,
|
||||
[ccn_tokenExpireOn] BIGINT NOT NULL,
|
||||
[ccn_ua] TEXT NOT NULL,
|
||||
[ccn_ip] TEXT NOT NULL,
|
||||
|
||||
FOREIGN KEY (ccn_user) REFERENCES user(ccn_name) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE collection(
|
||||
[ccn_uuid] TEXT NOT NULL,
|
||||
[ccn_name] TEXT NOT NULL,
|
||||
[ccn_user] TEXT NOT NULL,
|
||||
[ccn_lastChange] TEXT NOT NULL,
|
||||
|
||||
PRIMARY KEY (ccn_uuid),
|
||||
FOREIGN KEY (ccn_user) REFERENCES user(ccn_name) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE share(
|
||||
[ccn_uuid] TEXT NOT NULL,
|
||||
[ccn_target] TEXT NOT NULL,
|
||||
|
||||
FOREIGN KEY (ccn_uuid) REFERENCES collection(ccn_uuid) ON DELETE CASCADE
|
||||
FOREIGN KEY (ccn_target) REFERENCES user(ccn_name) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE calendar(
|
||||
[ccn_uuid] TEXT NOT NULL,
|
||||
[ccn_belongTo] TEXT NOT NULL,
|
||||
|
||||
[ccn_title] TEXT NOT NULL,
|
||||
[ccn_description] TEXT NOT NULL,
|
||||
[ccn_lastChange] TEXT NOT NULL,
|
||||
|
||||
[ccn_eventDateTimeStart] BIGINT NOT NULL,
|
||||
[ccn_eventDateTimeEnd] BIGINT NOT NULL,
|
||||
[ccn_timezoneOffset] INT NOT NULL,
|
||||
|
||||
[ccn_loopRules] TEXT NOT NULL,
|
||||
[ccn_loopDateTimeStart] BIGINT NOT NULL,
|
||||
[ccn_loopDateTimeEnd] BIGINT NOT NULL,
|
||||
|
||||
PRIMARY KEY (ccn_uuid),
|
||||
FOREIGN KEY (ccn_belongTo) REFERENCES collection(ccn_uuid) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE todo(
|
||||
[ccn_uuid] TEXT NOT NULL,
|
||||
[ccn_belongTo] TEXT NOT NULL,
|
||||
|
||||
[ccn_data] TEXT NOT NULL,
|
||||
[ccn_lastChange] TEXT NOT NULL,
|
||||
|
||||
PRIMARY KEY (ccn_uuid),
|
||||
FOREIGN KEY (ccn_belongTo) REFERENCES user(ccn_name) ON DELETE CASCADE
|
||||
);
|
||||
@@ -1,52 +0,0 @@
|
||||
import hashlib
|
||||
import random
|
||||
import uuid
|
||||
import time
|
||||
import math
|
||||
|
||||
ValidUsername = set(map(lambda x:chr(x), range(48, 58, 1))) | set(map(lambda x:chr(x), range(65, 91, 1))) | set(map(lambda x:chr(x), range(97, 123, 1)))
|
||||
ValidPassword = set(map(lambda x:chr(x), range(33, 127, 1)))
|
||||
|
||||
def IsValidUsername(strl):
|
||||
return (len(set(strl) - ValidUsername) == 0)
|
||||
|
||||
def IsValidPassword(strl):
|
||||
return (len(set(strl) - ValidPassword) == 0)
|
||||
|
||||
def ComputePasswordHash(password):
|
||||
s = hashlib.sha256()
|
||||
s.update(password.encode('utf-8'))
|
||||
return s.hexdigest()
|
||||
|
||||
def GenerateUUID():
|
||||
return str(uuid.uuid1())
|
||||
|
||||
def GenerateToken(username):
|
||||
s = hashlib.sha256()
|
||||
s.update(username.encode('utf-8'))
|
||||
s.update(GenerateUUID().encode('utf-8'))
|
||||
return s.hexdigest()
|
||||
|
||||
def GenerateSalt():
|
||||
return random.randint(0, 6172748)
|
||||
|
||||
def ComputePasswordHashWithSalt(passwordHashed, salt):
|
||||
s = hashlib.sha256()
|
||||
s.update((passwordHashed + str(salt)).encode('utf-8'))
|
||||
return s.hexdigest()
|
||||
|
||||
def GetCurrentTimestamp():
|
||||
return int(time.time())
|
||||
|
||||
def GetTokenExpireOn():
|
||||
return GetCurrentTimestamp() + 60 * 60 * 24 * 2 # add 2 day from now
|
||||
|
||||
def Str2Bool(strl):
|
||||
return strl.lower() == 'true'
|
||||
|
||||
def GCD(a, b):
|
||||
return math.gcd(a, b)
|
||||
|
||||
def LCM(a, b):
|
||||
return int(a * b / GCD(a, b))
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"math/rand"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var (
|
||||
usernamePattern = regexp.MustCompile(`^[0-9A-Za-z]+$`)
|
||||
passwordPattern = regexp.MustCompile(`^[!-~]+$`)
|
||||
)
|
||||
|
||||
// IsValidUsername reports whether s is a valid username.
|
||||
func IsValidUsername(s string) bool {
|
||||
return usernamePattern.MatchString(s)
|
||||
}
|
||||
|
||||
// IsValidPassword reports whether s is a valid password.
|
||||
func IsValidPassword(s string) bool {
|
||||
return passwordPattern.MatchString(s)
|
||||
}
|
||||
|
||||
// ComputePasswordHash returns the lowercased SHA-256 hex digest of password.
|
||||
func ComputePasswordHash(password string) string {
|
||||
sum := sha256.Sum256([]byte(password))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// GenerateUUID returns a new UUID string, preferring version 1 (mirroring
|
||||
// python's uuid.uuid1()), falling back to a random version-4 UUID on error.
|
||||
func GenerateUUID() string {
|
||||
u, err := uuid.NewUUID()
|
||||
if err != nil {
|
||||
u = uuid.New()
|
||||
}
|
||||
return u.String()
|
||||
}
|
||||
|
||||
// GenerateToken returns a SHA-256 hex digest of the username concatenated with
|
||||
// a fresh UUID.
|
||||
func GenerateToken(username string) string {
|
||||
sum := sha256.Sum256([]byte(username + GenerateUUID()))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// GenerateSalt returns a random salt in the inclusive range [0, 6172748).
|
||||
func GenerateSalt() int {
|
||||
return rand.Intn(6172748)
|
||||
}
|
||||
|
||||
// ComputePasswordHashWithSalt returns the lowercased SHA-256 hex digest of
|
||||
// passwordHashed concatenated with the decimal string form of salt.
|
||||
func ComputePasswordHashWithSalt(passwordHashed string, salt int) string {
|
||||
sum := sha256.Sum256([]byte(passwordHashed + strconv.Itoa(salt)))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// GetCurrentTimestamp returns the current UNIX timestamp in seconds.
|
||||
func GetCurrentTimestamp() int {
|
||||
return int(time.Now().Unix())
|
||||
}
|
||||
|
||||
// GetTokenExpireOn returns the timestamp 2 days from now, used as the token
|
||||
// expiry.
|
||||
func GetTokenExpireOn() int {
|
||||
return GetCurrentTimestamp() + 60*60*24*2
|
||||
}
|
||||
|
||||
// Str2Bool reports whether s, compared case-insensitively, equals "true".
|
||||
func Str2Bool(s string) bool {
|
||||
return strings.ToLower(s) == "true"
|
||||
}
|
||||
|
||||
// GCD returns the greatest common divisor of a and b via the Euclidean
|
||||
// algorithm.
|
||||
func GCD(a, b int64) int64 {
|
||||
for b != 0 {
|
||||
a, b = b, a%b
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// LCM returns the least common multiple of a and b.
|
||||
func LCM(a, b int64) int64 {
|
||||
return (a * b) / GCD(a, b)
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Binary file not shown.
|
After Width: | Height: | Size: 68 KiB |
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,8 @@
|
||||
[*.{js,jsx,mjs,cjs,ts,tsx,mts,cts,vue,css,scss,sass,less,styl}]
|
||||
charset = utf-8
|
||||
indent_size = 2
|
||||
indent_style = space
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
end_of_line = lf
|
||||
max_line_length = 100
|
||||
@@ -0,0 +1 @@
|
||||
* text=auto eol=lf
|
||||
@@ -0,0 +1,39 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
.DS_Store
|
||||
dist
|
||||
dist-ssr
|
||||
coverage
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
|
||||
*.tsbuildinfo
|
||||
|
||||
.eslintcache
|
||||
|
||||
# Cypress
|
||||
/cypress/videos/
|
||||
/cypress/screenshots/
|
||||
|
||||
# Vitest
|
||||
__screenshots__/
|
||||
|
||||
# Vite
|
||||
*.timestamp-*-*.mjs
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"plugins": ["eslint", "typescript", "unicorn", "oxc", "vue"],
|
||||
"env": {
|
||||
"browser": true
|
||||
},
|
||||
"categories": {
|
||||
"correctness": "error"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
# coleaf-frontend
|
||||
|
||||
This template should help get you started developing with Vue 3 in Vite.
|
||||
|
||||
## Recommended IDE Setup
|
||||
|
||||
[VS Code](https://code.visualstudio.com/) + [Vue (Official)](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur).
|
||||
|
||||
## Recommended Browser Setup
|
||||
|
||||
- Chromium-based browsers (Chrome, Edge, Brave, etc.):
|
||||
- [Vue.js devtools](https://chromewebstore.google.com/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd)
|
||||
- [Turn on Custom Object Formatter in Chrome DevTools](http://bit.ly/object-formatters)
|
||||
- Firefox:
|
||||
- [Vue.js devtools](https://addons.mozilla.org/en-US/firefox/addon/vue-js-devtools/)
|
||||
- [Turn on Custom Object Formatter in Firefox DevTools](https://fxdx.dev/firefox-devtools-custom-object-formatters/)
|
||||
|
||||
## Type Support for `.vue` Imports in TS
|
||||
|
||||
TypeScript cannot handle type information for `.vue` imports by default, so we replace the `tsc` CLI with `vue-tsc` for type checking. In editors, we need [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) to make the TypeScript language service aware of `.vue` types.
|
||||
|
||||
## Customize configuration
|
||||
|
||||
See [Vite Configuration Reference](https://vite.dev/config/).
|
||||
|
||||
## Project Setup
|
||||
|
||||
```sh
|
||||
pnpm install
|
||||
```
|
||||
|
||||
### Compile and Hot-Reload for Development
|
||||
|
||||
```sh
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
### Type-Check, Compile and Minify for Production
|
||||
|
||||
```sh
|
||||
pnpm build
|
||||
```
|
||||
|
||||
### Lint with [ESLint](https://eslint.org/)
|
||||
|
||||
```sh
|
||||
pnpm lint
|
||||
```
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
@@ -0,0 +1,23 @@
|
||||
import { globalIgnores } from 'eslint/config'
|
||||
import { defineConfigWithVueTs, vueTsConfigs } from '@vue/eslint-config-typescript'
|
||||
import pluginVue from 'eslint-plugin-vue'
|
||||
import pluginOxlint from 'eslint-plugin-oxlint'
|
||||
|
||||
// To allow more languages other than `ts` in `.vue` files, uncomment the following lines:
|
||||
// import { configureVueProject } from '@vue/eslint-config-typescript'
|
||||
// configureVueProject({ scriptLangs: ['ts', 'tsx'] })
|
||||
// More info at https://github.com/vuejs/eslint-config-typescript/#advanced-setup
|
||||
|
||||
export default defineConfigWithVueTs(
|
||||
{
|
||||
name: 'app/files-to-lint',
|
||||
files: ['**/*.{vue,ts,mts,tsx}'],
|
||||
},
|
||||
|
||||
globalIgnores(['**/dist/**', '**/dist-ssr/**', '**/coverage/**']),
|
||||
|
||||
...pluginVue.configs['flat/essential'],
|
||||
vueTsConfigs.recommended,
|
||||
|
||||
...pluginOxlint.buildFromOxlintConfigFile('.oxlintrc.json'),
|
||||
)
|
||||
@@ -0,0 +1,16 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<link rel="icon" href="/favicon.ico">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>coconut-leaf</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"name": "coleaf-frontend",
|
||||
"version": "2.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "run-p type-check \"build-only {@}\" --",
|
||||
"preview": "vite preview",
|
||||
"build-only": "vite build",
|
||||
"type-check": "vue-tsc --build",
|
||||
"lint": "run-s lint:*",
|
||||
"lint:oxlint": "oxlint . --fix",
|
||||
"lint:eslint": "eslint . --fix --cache"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fortawesome/fontawesome-svg-core": "^7.2.0",
|
||||
"@fortawesome/free-solid-svg-icons": "^7.2.0",
|
||||
"@fortawesome/vue-fontawesome": "^3.2.0",
|
||||
"axios": "1.14.0",
|
||||
"bulma": "0.9.1",
|
||||
"pinia": "^3.0.4",
|
||||
"pinia-plugin-persistedstate": "^4.7.1",
|
||||
"vue": "^3.5.32",
|
||||
"vue-router": "^5.0.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tsconfig/node24": "^24.0.4",
|
||||
"@types/node": "^24.12.2",
|
||||
"@vitejs/plugin-vue": "^6.0.6",
|
||||
"@vue/eslint-config-typescript": "^14.7.0",
|
||||
"@vue/tsconfig": "^0.9.1",
|
||||
"eslint": "^10.2.1",
|
||||
"eslint-plugin-oxlint": "~1.60.0",
|
||||
"eslint-plugin-vue": "~10.8.0",
|
||||
"jiti": "^2.6.1",
|
||||
"npm-run-all2": "^8.0.4",
|
||||
"oxlint": "~1.60.0",
|
||||
"typescript": "~6.0.0",
|
||||
"vite": "^8.0.8",
|
||||
"vite-plugin-vue-devtools": "^8.1.1",
|
||||
"vue-tsc": "^3.2.6"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
}
|
||||
}
|
||||
Generated
+3584
File diff suppressed because it is too large.
Load diff
Binary file not shown.
|
After Width: | Height: | Size: 4.2 KiB |
@@ -0,0 +1,40 @@
|
||||
// 导入 Bulma
|
||||
@charset "utf-8";
|
||||
@import "bulma/bulma.sass";
|
||||
|
||||
// coconut-leaf 全局样式
|
||||
|
||||
// 卡片样式(作用于集合列表,Todo列表项等)
|
||||
div.paperbox-item {
|
||||
display: flex;
|
||||
flex-flow: row;
|
||||
align-items: flex-start;
|
||||
|
||||
padding: 1.25rem;
|
||||
margin-bottom: 1.25rem;
|
||||
}
|
||||
|
||||
div.paperbox-item-words {
|
||||
flex-grow: 1;
|
||||
flex-basis: 0;
|
||||
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
div.paperbox-item-icon {
|
||||
margin-left: 0.75rem;
|
||||
}
|
||||
|
||||
// 按钮列表样式
|
||||
|
||||
div.button-list {
|
||||
display: flex;
|
||||
flex-flow: row;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
div.button-list>* {
|
||||
margin-right: 0.75rem;
|
||||
margin-bottom: 0.75rem;
|
||||
margin-left: 0 !important;
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue';
|
||||
import { useLanguageStore } from './stores/language';
|
||||
import { useTokenStore } from './stores/token';
|
||||
import MessageBox from '@/components/MessageBox.vue';
|
||||
import { logout as apiCommonLogout } from './api/common';
|
||||
import { goToHome } from '@/router';
|
||||
|
||||
const language = useLanguageStore();
|
||||
const token = useTokenStore();
|
||||
|
||||
const isBurgerActive = ref<boolean>(false);
|
||||
|
||||
const messagebox = ref<InstanceType<typeof MessageBox>>();
|
||||
|
||||
const logout = async () => {
|
||||
const tokenStore = useTokenStore();
|
||||
const rv = await apiCommonLogout(tokenStore.currentToken);
|
||||
if (rv) {
|
||||
// OK. We logged out.
|
||||
// Clear token.
|
||||
tokenStore.logout();
|
||||
// And go to Home page
|
||||
goToHome();
|
||||
} else {
|
||||
// Show logout error.
|
||||
messagebox.value?.show("Fail to logout due to unknow reason. Consider refreshing page to solve problem.");
|
||||
}
|
||||
}
|
||||
|
||||
// Process burger menu.
|
||||
// This is copied from Bulma website and modified for Vue.
|
||||
// Check for click events on the navbar burger icon
|
||||
const toggleBurger = () => {
|
||||
// Toggle the "is-active" class on both the "navbar-burger" and the "navbar-menu"
|
||||
isBurgerActive.value = !isBurgerActive.value
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<nav class="navbar has-shadow is-spaced bd-navbar" role="navigation" aria-label="main navigation">
|
||||
<div class="navbar-brand">
|
||||
<router-link class="navbar-item" to="/">
|
||||
<img src="/favicon.ico"><b style="margin:0 0 0 14px;">coconut-leaf</b>
|
||||
</router-link>
|
||||
|
||||
<a role="button" class="navbar-burger burger" :class="{ 'is-active': isBurgerActive }" @click="toggleBurger"
|
||||
aria-label="menu" aria-expanded="false" data-target="coleaf-navbar">
|
||||
<span aria-hidden="true"></span>
|
||||
<span aria-hidden="true"></span>
|
||||
<span aria-hidden="true"></span>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div id="coleaf-navbar" class="navbar-menu" :class="{ 'is-active': isBurgerActive }">
|
||||
<div class="navbar-start">
|
||||
<router-link class="navbar-item" to="/home">Home</router-link>
|
||||
<router-link v-if="token.isLoggedIn" class="navbar-item" to="/collection">Collection</router-link>
|
||||
<router-link v-if="token.isLoggedIn" class="navbar-item" to="/calendar">Calendar</router-link>
|
||||
<router-link v-if="token.isLoggedIn" class="navbar-item" to="/todo">Todo</router-link>
|
||||
<router-link v-if="token.isLoggedIn" class="navbar-item" to="/admin">Admin</router-link>
|
||||
</div>
|
||||
|
||||
<div class="navbar-end">
|
||||
<p class="navbar-item">
|
||||
<router-link v-if="!token.isLoggedIn" class="button is-primary" to="/login">Login</router-link>
|
||||
</p>
|
||||
<p class="navbar-item">
|
||||
<a v-if="token.isLoggedIn" class="button is-primary" @click="logout">Logout</a>
|
||||
</p>
|
||||
|
||||
<div class="navbar-item has-dropdown is-hoverable">
|
||||
<a v-if="language.isEnglish" class="navbar-link">English</a>
|
||||
<a v-else-if="language.isSimplifiedChinese" class="navbar-link">简体中文</a>
|
||||
|
||||
<div class="navbar-dropdown">
|
||||
<a @click="language.changeToEnglish()" class="navbar-item">English</a>
|
||||
<a @click="language.changeToSimplifiedChinese()" class="navbar-item">简体中文</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<!-- The output result of router -->
|
||||
<router-view></router-view>
|
||||
|
||||
<MessageBox ref="messagebox" />
|
||||
</template>
|
||||
|
||||
<style scoped></style>
|
||||
@@ -0,0 +1,63 @@
|
||||
import { apiWrapper, boolApiWrapper } from './index';
|
||||
|
||||
/** A raw admin user row as returned by the API (positional from SQL columns) */
|
||||
export type AdminUserRow = [
|
||||
name: string,
|
||||
isAdmin: boolean,
|
||||
];
|
||||
|
||||
/**
|
||||
* Fetch all users (admin only).
|
||||
*
|
||||
* @param token - The auth token (must belong to an admin user)
|
||||
* @returns An array of {@link AdminUserRow} on success, or `undefined` on failure
|
||||
*/
|
||||
export async function get(token: string): Promise<AdminUserRow[] | undefined> {
|
||||
return apiWrapper<AdminUserRow[]>('/api/admin/get', { token });
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new user (admin only).
|
||||
*
|
||||
* @param token - The auth token (must belong to an admin user)
|
||||
* @param username - The new username
|
||||
* @returns A single {@link AdminUserRow} of the newly created user on success, or `undefined` on failure
|
||||
*/
|
||||
export async function add(token: string, username: string): Promise<AdminUserRow | undefined> {
|
||||
return apiWrapper<AdminUserRow>('/api/admin/add', { token, username });
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an existing user's password and/or admin status (admin only).
|
||||
*
|
||||
* @param token - The auth token (must belong to an admin user)
|
||||
* @param username - The target user's username
|
||||
* @param password - (optional) The new password (plaintext, will be hashed server-side)
|
||||
* @param isAdmin - (optional) Whether the user should be an admin
|
||||
* @returns `true` on success, `false` on failure (or if no changes were provided)
|
||||
*/
|
||||
export async function update(
|
||||
token: string,
|
||||
username: string,
|
||||
password?: string,
|
||||
isAdmin?: boolean,
|
||||
): Promise<boolean> {
|
||||
const data: Record<string, any> = { token, username };
|
||||
if (password !== undefined) data.password = password;
|
||||
if (isAdmin !== undefined) data.isAdmin = isAdmin;
|
||||
|
||||
if (Object.keys(data).length <= 2) return false;
|
||||
|
||||
return boolApiWrapper('/api/admin/update', data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a user (admin only).
|
||||
*
|
||||
* @param token - The auth token (must belong to an admin user)
|
||||
* @param username - The username to delete
|
||||
* @returns `true` on success, `false` on failure
|
||||
*/
|
||||
export async function del(token: string, username: string): Promise<boolean> {
|
||||
return boolApiWrapper('/api/admin/delete', { token, username });
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
import { apiWrapper, boolApiWrapper } from './index';
|
||||
|
||||
/** A raw calendar row as returned by the API (positional from SQL columns) */
|
||||
export type CalendarRow = [
|
||||
uuid: string,
|
||||
belongTo: string,
|
||||
title: string,
|
||||
description: string,
|
||||
lastChange: string,
|
||||
eventDateTimeStart: number,
|
||||
eventDateTimeEnd: number,
|
||||
timezoneOffset: number,
|
||||
loopRules: string,
|
||||
loopDateTimeStart: number,
|
||||
loopDateTimeEnd: number,
|
||||
];
|
||||
|
||||
/** Serialized description object stored in the `description` column */
|
||||
export interface CalendarDescription {
|
||||
description: string;
|
||||
color: string;
|
||||
}
|
||||
|
||||
/** Default color used when deserialization fails */
|
||||
const DEFAULT_COLOR = '#3388ff';
|
||||
|
||||
/**
|
||||
* Serialize a calendar description and color into a JSON string
|
||||
* for storage in the `description` column.
|
||||
*
|
||||
* @param description - The description text
|
||||
* @param color - The color string (e.g. `#ff0000`)
|
||||
* @returns The JSON-serialized string
|
||||
*/
|
||||
export function serializeDescription(description: string, color: string): string {
|
||||
return JSON.stringify({ description, color });
|
||||
}
|
||||
|
||||
/**
|
||||
* Deserialize a JSON description string back into an object.
|
||||
* Returns a default object on parse errors.
|
||||
*
|
||||
* @param str - The JSON string to deserialize
|
||||
* @returns The parsed {@link CalendarDescription} object
|
||||
*/
|
||||
export function deserializeDescription(str: string): CalendarDescription {
|
||||
try {
|
||||
return JSON.parse(str) as CalendarDescription;
|
||||
} catch {
|
||||
return { description: '', color: DEFAULT_COLOR };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch all calendar events within the given time range for the current user.
|
||||
*
|
||||
* @param token - The auth token
|
||||
* @param startDateTime - Start of the time range (unix timestamp)
|
||||
* @param endDateTime - End of the time range (unix timestamp)
|
||||
* @returns An array of {@link CalendarRow} on success, or `undefined` on failure
|
||||
*/
|
||||
export async function getFull(token: string, startDateTime: number, endDateTime: number): Promise<CalendarRow[] | undefined> {
|
||||
return apiWrapper<CalendarRow[]>('/api/calendar/getFull', {
|
||||
token,
|
||||
startDateTime,
|
||||
endDateTime,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the full detail of a single calendar event by UUID.
|
||||
*
|
||||
* @param token - The auth token
|
||||
* @param uuid - The event UUID
|
||||
* @returns A single {@link CalendarRow} on success, or `undefined` on failure
|
||||
*/
|
||||
export async function getDetail(token: string, uuid: string): Promise<CalendarRow | undefined> {
|
||||
return apiWrapper<CalendarRow>('/api/calendar/getDetail', {
|
||||
token,
|
||||
uuid,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an existing calendar event. Only the fields provided will be updated.
|
||||
*
|
||||
* @param token - The auth token
|
||||
* @param uuid - The event UUID
|
||||
* @param lastChange - The last known `lastChange` value (optimistic concurrency)
|
||||
* @param belongTo - (optional) Collection UUID this event belongs to
|
||||
* @param title - (optional) Event title
|
||||
* @param description - (optional) Event description (serialized JSON)
|
||||
* @param eventDateTimeStart - (optional) Start time (unix timestamp)
|
||||
* @param eventDateTimeEnd - (optional) End time (unix timestamp)
|
||||
* @param loopRules - (optional) Loop rules string
|
||||
* @param timezoneOffset - (optional) Timezone offset in minutes
|
||||
* @returns The new `lastChange` value on success, or `undefined` on failure
|
||||
*/
|
||||
export async function update(
|
||||
token: string,
|
||||
uuid: string,
|
||||
lastChange: string,
|
||||
belongTo?: string,
|
||||
title?: string,
|
||||
description?: string,
|
||||
eventDateTimeStart?: number,
|
||||
eventDateTimeEnd?: number,
|
||||
loopRules?: string,
|
||||
timezoneOffset?: number,
|
||||
): Promise<string | undefined> {
|
||||
const data: Record<string, any> = { token, uuid, lastChange };
|
||||
if (belongTo !== undefined) data.belongTo = belongTo;
|
||||
if (title !== undefined) data.title = title;
|
||||
if (description !== undefined) data.description = description;
|
||||
if (eventDateTimeStart !== undefined) data.eventDateTimeStart = eventDateTimeStart;
|
||||
if (eventDateTimeEnd !== undefined) data.eventDateTimeEnd = eventDateTimeEnd;
|
||||
if (loopRules !== undefined) data.loopRules = loopRules;
|
||||
if (timezoneOffset !== undefined) data.timezoneOffset = timezoneOffset;
|
||||
|
||||
return apiWrapper<string>('/api/calendar/update', data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new calendar event.
|
||||
*
|
||||
* @param token - The auth token
|
||||
* @param belongTo - Collection UUID this event belongs to
|
||||
* @param title - Event title
|
||||
* @param description - Event description (serialized JSON)
|
||||
* @param eventDateTimeStart - Start time (unix timestamp)
|
||||
* @param eventDateTimeEnd - End time (unix timestamp)
|
||||
* @param loopRules - Loop rules string
|
||||
* @param timezoneOffset - Timezone offset in minutes
|
||||
* @returns The new event UUID on success, or `undefined` on failure
|
||||
*/
|
||||
export async function add(
|
||||
token: string,
|
||||
belongTo: string,
|
||||
title: string,
|
||||
description: string,
|
||||
eventDateTimeStart: number,
|
||||
eventDateTimeEnd: number,
|
||||
loopRules: string,
|
||||
timezoneOffset: number,
|
||||
): Promise<string | undefined> {
|
||||
return apiWrapper<string>('/api/calendar/add', {
|
||||
token,
|
||||
belongTo,
|
||||
title,
|
||||
description,
|
||||
eventDateTimeStart,
|
||||
eventDateTimeEnd,
|
||||
loopRules,
|
||||
timezoneOffset,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a calendar event.
|
||||
*
|
||||
* @param token - The auth token
|
||||
* @param uuid - The event UUID
|
||||
* @param lastChange - The last known `lastChange` value (optimistic concurrency)
|
||||
* @returns `true` on success, `false` on failure
|
||||
*/
|
||||
export async function del(token: string, uuid: string, lastChange: string): Promise<boolean> {
|
||||
return boolApiWrapper('/api/calendar/delete', {
|
||||
token,
|
||||
uuid,
|
||||
lastChange,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import { apiWrapper, boolApiWrapper } from './index';
|
||||
|
||||
/** A raw collection row as returned by the API (positional from SQL columns) */
|
||||
export type CollectionRow = [
|
||||
uuid: string,
|
||||
name: string,
|
||||
lastChange: string,
|
||||
];
|
||||
|
||||
/** A raw shared collection row as returned by the API */
|
||||
export type SharedCollectionRow = [
|
||||
uuid: string,
|
||||
name: string,
|
||||
user: string,
|
||||
];
|
||||
|
||||
/**
|
||||
* Fetch all collections owned by the current user.
|
||||
*
|
||||
* @param token - The auth token
|
||||
* @returns An array of {@link CollectionRow} on success, or `undefined` on failure
|
||||
*/
|
||||
export async function getFullOwn(token: string): Promise<CollectionRow[] | undefined> {
|
||||
return apiWrapper<CollectionRow[]>('/api/collection/getFullOwn', { token });
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the detail of a single owned collection by UUID.
|
||||
*
|
||||
* @param token - The auth token
|
||||
* @param uuid - The collection UUID
|
||||
* @returns A single {@link CollectionRow} on success, or `undefined` on failure
|
||||
*/
|
||||
export async function getDetailOwn(token: string, uuid: string): Promise<CollectionRow | undefined> {
|
||||
return apiWrapper<CollectionRow>('/api/collection/getDetailOwn', { token, uuid });
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new collection.
|
||||
*
|
||||
* @param token - The auth token
|
||||
* @param name - The collection name
|
||||
* @returns The new collection UUID on success, or `undefined` on failure
|
||||
*/
|
||||
export async function addOwn(token: string, name: string): Promise<string | undefined> {
|
||||
return apiWrapper<string>('/api/collection/addOwn', { token, name });
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an existing collection's name.
|
||||
*
|
||||
* @param token - The auth token
|
||||
* @param uuid - The collection UUID
|
||||
* @param name - The new collection name
|
||||
* @param lastChange - The last known `lastChange` value (optimistic concurrency)
|
||||
* @returns The new `lastChange` value on success, or `undefined` on failure
|
||||
*/
|
||||
export async function updateOwn(token: string, uuid: string, name: string, lastChange: string): Promise<string | undefined> {
|
||||
return apiWrapper<string>('/api/collection/updateOwn', { token, uuid, name, lastChange });
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete an owned collection.
|
||||
*
|
||||
* @param token - The auth token
|
||||
* @param uuid - The collection UUID
|
||||
* @param lastChange - The last known `lastChange` value (optimistic concurrency)
|
||||
* @returns `true` on success, `false` on failure
|
||||
*/
|
||||
export async function deleteOwn(token: string, uuid: string, lastChange: string): Promise<boolean> {
|
||||
return boolApiWrapper('/api/collection/deleteOwn', { token, uuid, lastChange });
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch all users this collection is shared with.
|
||||
*
|
||||
* @param token - The auth token
|
||||
* @param uuid - The collection UUID
|
||||
* @returns An array of target usernames on success, or `undefined` on failure
|
||||
*/
|
||||
export async function getSharing(token: string, uuid: string): Promise<string[] | undefined> {
|
||||
return apiWrapper<string[]>('/api/collection/getSharing', { token, uuid });
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a sharing target from a collection.
|
||||
*
|
||||
* @param token - The auth token
|
||||
* @param uuid - The collection UUID
|
||||
* @param target - The username to unshare with
|
||||
* @param lastChange - The last known `lastChange` value (optimistic concurrency)
|
||||
* @returns The new `lastChange` value on success, or `undefined` on failure
|
||||
*/
|
||||
export async function deleteSharing(token: string, uuid: string, target: string, lastChange: string): Promise<string | undefined> {
|
||||
return apiWrapper<string>('/api/collection/deleteSharing', { token, uuid, target, lastChange });
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a sharing target to a collection.
|
||||
*
|
||||
* @param token - The auth token
|
||||
* @param uuid - The collection UUID
|
||||
* @param target - The username to share with
|
||||
* @param lastChange - The last known `lastChange` value (optimistic concurrency)
|
||||
* @returns The new `lastChange` value on success, or `undefined` on failure
|
||||
*/
|
||||
export async function addSharing(token: string, uuid: string, target: string, lastChange: string): Promise<string | undefined> {
|
||||
return apiWrapper<string>('/api/collection/addSharing', { token, uuid, target, lastChange });
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch all collections shared with the current user.
|
||||
*
|
||||
* @param token - The auth token
|
||||
* @returns An array of {@link SharedCollectionRow} on success, or `undefined` on failure
|
||||
*/
|
||||
export async function getShared(token: string): Promise<SharedCollectionRow[] | undefined> {
|
||||
return apiWrapper<SharedCollectionRow[]>('/api/collection/getShared', { token });
|
||||
}
|
||||
Loaded 100 of 133 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user