forked from dullage/flatnotes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
266 lines (221 loc) · 7.39 KB
/
main.py
File metadata and controls
266 lines (221 loc) · 7.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
from typing import List, Literal
from fastapi import APIRouter, Depends, FastAPI, HTTPException, UploadFile
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
import api_messages
from attachments.base import BaseAttachments
from attachments.models import AttachmentCreateResponse
from auth.base import BaseAuth
from auth.models import Login, Token
from global_config import AuthType, GlobalConfig, GlobalConfigResponseModel
from helpers import replace_base_href
from notes.base import BaseNotes
from notes.models import Note, NoteCreate, NoteUpdate, SearchResult
global_config = GlobalConfig()
auth: BaseAuth = global_config.load_auth()
note_storage: BaseNotes = global_config.load_note_storage()
attachment_storage: BaseAttachments = global_config.load_attachment_storage()
auth_deps = [Depends(auth.authenticate)] if auth else []
router = APIRouter()
app = FastAPI(
docs_url=global_config.path_prefix + "/docs",
openapi_url=global_config.path_prefix + "/openapi.json",
)
replace_base_href("client/dist/index.html", global_config.path_prefix)
# region UI
@router.get("/", include_in_schema=False)
@router.get("/login", include_in_schema=False)
@router.get("/search", include_in_schema=False)
@router.get("/new", include_in_schema=False)
@router.get("/note/{title}", include_in_schema=False)
def root(title: str = ""):
with open("client/dist/index.html", "r", encoding="utf-8") as f:
html = f.read()
return HTMLResponse(content=html)
# endregion
# region Auth
if global_config.auth_type not in [AuthType.NONE, AuthType.READ_ONLY]:
@router.post("/api/token", response_model=Token)
def token(data: Login):
try:
return auth.login(data)
except ValueError:
raise HTTPException(
status_code=401, detail=api_messages.login_failed
)
@router.get("/api/auth-check", dependencies=auth_deps)
def auth_check() -> str:
"""A lightweight endpoint that simply returns 'OK' if the user is
authenticated."""
return "OK"
# endregion
# region Notes
# Get Note
@router.get(
"/api/notes/{title}",
dependencies=auth_deps,
response_model=Note,
)
def get_note(title: str):
"""Get a specific note."""
try:
return note_storage.get(title)
except ValueError:
raise HTTPException(
status_code=400, detail=api_messages.invalid_note_title
)
except FileNotFoundError:
raise HTTPException(404, api_messages.note_not_found)
if global_config.auth_type != AuthType.READ_ONLY:
# Create Note
@router.post(
"/api/notes",
dependencies=auth_deps,
response_model=Note,
)
def post_note(note: NoteCreate):
"""Create a new note."""
try:
return note_storage.create(note)
except ValueError:
raise HTTPException(
status_code=400,
detail=api_messages.invalid_note_title,
)
except FileExistsError:
raise HTTPException(
status_code=409, detail=api_messages.note_exists
)
# Update Note
@router.patch(
"/api/notes/{title}",
dependencies=auth_deps,
response_model=Note,
)
def patch_note(title: str, data: NoteUpdate):
try:
return note_storage.update(title, data)
except ValueError:
raise HTTPException(
status_code=400,
detail=api_messages.invalid_note_title,
)
except FileExistsError:
raise HTTPException(
status_code=409, detail=api_messages.note_exists
)
except FileNotFoundError:
raise HTTPException(404, api_messages.note_not_found)
# Delete Note
@router.delete(
"/api/notes/{title}",
dependencies=auth_deps,
response_model=None,
)
def delete_note(title: str):
try:
note_storage.delete(title)
except ValueError:
raise HTTPException(
status_code=400,
detail=api_messages.invalid_note_title,
)
except FileNotFoundError:
raise HTTPException(404, api_messages.note_not_found)
# endregion
# region Search
@router.get(
"/api/search",
dependencies=auth_deps,
response_model=List[SearchResult],
)
def search(
term: str,
sort: Literal["score", "title", "lastModified"] = "score",
order: Literal["asc", "desc"] = "desc",
limit: int = None,
):
"""Perform a full text search on all notes."""
if sort == "lastModified":
sort = "last_modified"
return note_storage.search(term, sort=sort, order=order, limit=limit)
@router.get(
"/api/tags",
dependencies=auth_deps,
response_model=List[str],
)
def get_tags():
"""Get a list of all indexed tags."""
return note_storage.get_tags()
# endregion
# region Config
@router.get("/api/config", response_model=GlobalConfigResponseModel)
def get_config():
"""Retrieve server-side config required for the UI."""
return GlobalConfigResponseModel(
auth_type=global_config.auth_type,
quick_access_hide=global_config.quick_access_hide,
quick_access_title=global_config.quick_access_title,
quick_access_term=global_config.quick_access_term,
quick_access_sort=global_config.quick_access_sort,
quick_access_limit=global_config.quick_access_limit,
)
# endregion
# region Attachments
# Get Attachment
@router.get(
"/api/attachments/{filename}",
dependencies=auth_deps,
)
# Include a secondary route used to create relative URLs that can be used
# outside the context of flatnotes (e.g. "/attachments/image.jpg").
@router.get(
"/attachments/{filename}",
dependencies=auth_deps,
include_in_schema=False,
)
def get_attachment(filename: str):
"""Download an attachment."""
try:
return attachment_storage.get(filename)
except ValueError:
raise HTTPException(
status_code=400,
detail=api_messages.invalid_attachment_filename,
)
except FileNotFoundError:
raise HTTPException(
status_code=404, detail=api_messages.attachment_not_found
)
if global_config.auth_type != AuthType.READ_ONLY:
# Create Attachment
@router.post(
"/api/attachments",
dependencies=auth_deps,
response_model=AttachmentCreateResponse,
)
def post_attachment(file: UploadFile):
"""Upload an attachment."""
try:
return attachment_storage.create(file)
except ValueError:
raise HTTPException(
status_code=400,
detail=api_messages.invalid_attachment_filename,
)
except FileExistsError:
raise HTTPException(409, api_messages.attachment_exists)
# endregion
# region Healthcheck
@router.get("/health")
def healthcheck() -> str:
"""A lightweight endpoint that simply returns 'OK' to indicate the server
is running."""
return "OK"
# endregion
app.include_router(router, prefix=global_config.path_prefix)
app.mount(
global_config.path_prefix,
StaticFiles(directory="client/dist"),
name="dist",
)