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
230 lines (191 loc) · 6.06 KB
/
main.py
File metadata and controls
230 lines (191 loc) · 6.06 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
from typing import List, Literal
from fastapi import 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 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 []
app = FastAPI()
# region UI
@app.get("/", include_in_schema=False)
@app.get("/login", include_in_schema=False)
@app.get("/search", include_in_schema=False)
@app.get("/new", include_in_schema=False)
@app.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 Login
if global_config.auth_type not in [AuthType.NONE, AuthType.READ_ONLY]:
@app.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
)
# endregion
# region Notes
# Get Note
@app.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
@app.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
@app.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
@app.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
@app.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)
@app.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
@app.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)
# endregion
# region Attachments
# Get Attachment
@app.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").
@app.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
@app.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
app.mount("/", StaticFiles(directory="client/dist"), name="dist")