forked from tate233/todolist
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnote_model.py
More file actions
296 lines (249 loc) · 10.1 KB
/
note_model.py
File metadata and controls
296 lines (249 loc) · 10.1 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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
import json
import uuid
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Optional
class Note:
def __init__(self, title: str, content: str = "", category: str = "未分类",
tags: List[str] = None, note_id: str = None, created_at: str = None,
updated_at: str = None, is_favorite: bool = False):
self.id = note_id or str(uuid.uuid4())
self.title = title
self.content = content
self.category = category
self.tags = tags or []
self.created_at = created_at or datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self.updated_at = updated_at or self.created_at
self.is_favorite = is_favorite
self.word_count = len(content)
self.links = []
def to_dict(self) -> Dict:
return {
'id': self.id,
'title': self.title,
'content': self.content,
'category': self.category,
'tags': self.tags,
'created_at': self.created_at,
'updated_at': self.updated_at,
'is_favorite': self.is_favorite,
'word_count': self.word_count,
'links': self.links
}
@classmethod
def from_dict(cls, data: Dict) -> 'Note':
note = cls(
title=data['title'],
content=data.get('content', ''),
category=data.get('category', '未分类'),
tags=data.get('tags', []),
note_id=data.get('id'),
created_at=data.get('created_at'),
updated_at=data.get('updated_at'),
is_favorite=data.get('is_favorite', False)
)
note.links = data.get('links', [])
return note
def update(self, **kwargs):
for key, value in kwargs.items():
if hasattr(self, key) and value is not None:
setattr(self, key, value)
self.updated_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
if 'content' in kwargs:
self.word_count = len(kwargs['content'])
def add_tag(self, tag: str):
if tag and tag not in self.tags:
self.tags.append(tag)
self.updated_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def remove_tag(self, tag: str):
if tag in self.tags:
self.tags.remove(tag)
self.updated_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def add_link(self, note_id: str):
if note_id and note_id not in self.links and note_id != self.id:
self.links.append(note_id)
self.updated_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def remove_link(self, note_id: str):
if note_id in self.links:
self.links.remove(note_id)
self.updated_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
class NoteManager:
def __init__(self, storage_path: Path, notes_dir: Path):
self.storage_path = storage_path
self.notes_dir = notes_dir
self.notes: Dict[str, Note] = {}
self.load_notes()
def load_notes(self):
if self.storage_path.exists():
try:
with open(self.storage_path, 'r', encoding='utf-8') as f:
data = json.load(f)
self.notes = {
note_id: Note.from_dict(note_data)
for note_id, note_data in data.items()
}
except Exception as e:
print(f"加载笔记失败: {e}")
self.notes = {}
else:
self.notes = {}
def save_notes(self):
try:
data = {note_id: note.to_dict() for note_id, note in self.notes.items()}
with open(self.storage_path, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=4, ensure_ascii=False)
return True
except Exception as e:
print(f"保存笔记失败: {e}")
return False
def create_note(self, title: str, content: str = "", category: str = "未分类",
tags: List[str] = None) -> Note:
if not title or not title.strip():
raise ValueError("笔记标题不能为空")
note = Note(
title=title.strip(),
content=content,
category=category,
tags=tags or []
)
self.notes[note.id] = note
self._save_note_file(note)
self.save_notes()
return note
def get_note(self, note_id: str) -> Optional[Note]:
return self.notes.get(note_id)
def update_note(self, note_id: str, **kwargs) -> bool:
note = self.get_note(note_id)
if note:
note.update(**kwargs)
self._save_note_file(note)
self.save_notes()
return True
return False
def delete_note(self, note_id: str) -> bool:
note = self.get_note(note_id)
if note:
self._delete_note_file(note)
del self.notes[note_id]
self._remove_links_to_note(note_id)
self.save_notes()
return True
return False
def get_all_notes(self) -> List[Note]:
return list(self.notes.values())
def get_notes_by_category(self, category: str) -> List[Note]:
return [note for note in self.notes.values() if note.category == category]
def get_notes_by_tag(self, tag: str) -> List[Note]:
return [note for note in self.notes.values() if tag in note.tags]
def get_favorite_notes(self) -> List[Note]:
return [note for note in self.notes.values() if note.is_favorite]
def search_notes(self, keyword: str) -> List[Note]:
if not keyword:
return self.get_all_notes()
keyword = keyword.lower()
results = []
for note in self.notes.values():
if not (keyword in note.title.lower() or
keyword in note.content.lower() or
any(keyword in tag.lower() for tag in note.tags)):
continue
results.append(note)
return results
def get_linked_notes(self, note_id: str) -> List[Note]:
note = self.get_note(note_id)
if not note:
return []
linked_notes = []
for linked_id in note.links:
linked_note = self.get_note(linked_id)
if linked_note:
linked_notes.append(linked_note)
return linked_notes
def get_backlinks(self, note_id: str) -> List[Note]:
return [note for note in self.notes.values() if note_id in note.links]
def get_all_tags(self) -> List[str]:
tags = set()
for note in self.notes.values():
tags.update(note.tags)
return sorted(list(tags))
def get_statistics(self) -> Dict:
total_notes = len(self.notes)
total_words = sum(note.word_count for note in self.notes.values())
category_counts = {}
for note in self.notes.values():
category_counts[note.category] = category_counts.get(note.category, 0) + 1
tag_counts = {}
for note in self.notes.values():
for tag in note.tags:
tag_counts[tag] = tag_counts.get(tag, 0) + 1
return {
'total_notes': total_notes,
'total_words': total_words,
'categories': category_counts,
'tags': tag_counts,
'favorites': len(self.get_favorite_notes())
}
def sort_notes(self, by: str = "updated", reverse: bool = True) -> List[Note]:
notes = self.get_all_notes()
if by == "title":
return sorted(notes, key=lambda n: n.title, reverse=reverse)
elif by == "created":
return sorted(notes, key=lambda n: n.created_at, reverse=reverse)
elif by == "category":
return sorted(notes, key=lambda n: n.category, reverse=reverse)
elif by == "words":
return sorted(notes, key=lambda n: n.word_count, reverse=reverse)
else:
return sorted(notes, key=lambda n: n.updated_at, reverse=reverse)
def export_note(self, note_id: str, filepath: Path, format: str = "md") -> bool:
note = self.get_note(note_id)
if not note:
return False
try:
if format == "md":
content = f"# {note.title}\n\n"
content += f"**分类**: {note.category}\n"
content += f"**标签**: {', '.join(note.tags)}\n"
content += f"**创建时间**: {note.created_at}\n"
content += f"**更新时间**: {note.updated_at}\n\n"
content += "---\n\n"
content += note.content
with open(filepath, 'w', encoding='utf-8') as f:
f.write(content)
elif format == "txt":
with open(filepath, 'w', encoding='utf-8') as f:
f.write(f"{note.title}\n\n{note.content}")
return True
except Exception as e:
print(f"导出笔记失败: {e}")
return False
def import_note(self, filepath: Path, category: str = "未分类") -> Optional[Note]:
try:
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
title = filepath.stem
note = self.create_note(title, content, category)
return note
except Exception as e:
print(f"导入笔记失败: {e}")
return None
def _save_note_file(self, note: Note):
try:
filename = f"{note.id}.md"
filepath = self.notes_dir / filename
with open(filepath, 'w', encoding='utf-8') as f:
f.write(note.content)
except Exception as e:
print(f"保存笔记文件失败: {e}")
def _delete_note_file(self, note: Note):
try:
filename = f"{note.id}.md"
filepath = self.notes_dir / filename
if filepath.exists():
filepath.unlink()
except Exception as e:
print(f"删除笔记文件失败: {e}")
def _remove_links_to_note(self, note_id: str):
for note in self.notes.values():
if note_id in note.links:
note.remove_link(note_id)