notes.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. import json
  2. import logging
  3. from typing import Optional
  4. from fastapi import APIRouter, Depends, HTTPException, Request, status, BackgroundTasks
  5. from pydantic import BaseModel
  6. from open_webui.socket.main import sio
  7. from open_webui.models.users import Users, UserResponse
  8. from open_webui.models.notes import Notes, NoteModel, NoteForm, NoteUserResponse
  9. from open_webui.config import ENABLE_ADMIN_CHAT_ACCESS, ENABLE_ADMIN_EXPORT
  10. from open_webui.constants import ERROR_MESSAGES
  11. from open_webui.env import SRC_LOG_LEVELS
  12. from open_webui.utils.auth import get_admin_user, get_verified_user
  13. from open_webui.utils.access_control import has_access, has_permission
  14. log = logging.getLogger(__name__)
  15. log.setLevel(SRC_LOG_LEVELS["MODELS"])
  16. router = APIRouter()
  17. ############################
  18. # GetNotes
  19. ############################
  20. @router.get("/", response_model=list[NoteUserResponse])
  21. async def get_notes(request: Request, user=Depends(get_verified_user)):
  22. if user.role != "admin" and not has_permission(
  23. user.id, "features.notes", request.app.state.config.USER_PERMISSIONS
  24. ):
  25. raise HTTPException(
  26. status_code=status.HTTP_401_UNAUTHORIZED,
  27. detail=ERROR_MESSAGES.UNAUTHORIZED,
  28. )
  29. notes = [
  30. NoteUserResponse(
  31. **{
  32. **note.model_dump(),
  33. "user": UserResponse(**Users.get_user_by_id(note.user_id).model_dump()),
  34. }
  35. )
  36. for note in Notes.get_notes_by_user_id(user.id, "write")
  37. ]
  38. return notes
  39. class NoteTitleIdResponse(BaseModel):
  40. id: str
  41. title: str
  42. updated_at: int
  43. created_at: int
  44. @router.get("/list", response_model=list[NoteTitleIdResponse])
  45. async def get_note_list(
  46. request: Request, page: Optional[int] = None, user=Depends(get_verified_user)
  47. ):
  48. if user.role != "admin" and not has_permission(
  49. user.id, "features.notes", request.app.state.config.USER_PERMISSIONS
  50. ):
  51. raise HTTPException(
  52. status_code=status.HTTP_401_UNAUTHORIZED,
  53. detail=ERROR_MESSAGES.UNAUTHORIZED,
  54. )
  55. limit = None
  56. skip = None
  57. if page is not None:
  58. limit = 60
  59. skip = (page - 1) * limit
  60. notes = [
  61. NoteTitleIdResponse(**note.model_dump())
  62. for note in Notes.get_notes_by_user_id(user.id, "write", skip=skip, limit=limit)
  63. ]
  64. return notes
  65. ############################
  66. # CreateNewNote
  67. ############################
  68. @router.post("/create", response_model=Optional[NoteModel])
  69. async def create_new_note(
  70. request: Request, form_data: NoteForm, user=Depends(get_verified_user)
  71. ):
  72. if user.role != "admin" and not has_permission(
  73. user.id, "features.notes", request.app.state.config.USER_PERMISSIONS
  74. ):
  75. raise HTTPException(
  76. status_code=status.HTTP_401_UNAUTHORIZED,
  77. detail=ERROR_MESSAGES.UNAUTHORIZED,
  78. )
  79. try:
  80. note = Notes.insert_new_note(form_data, user.id)
  81. return note
  82. except Exception as e:
  83. log.exception(e)
  84. raise HTTPException(
  85. status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT()
  86. )
  87. ############################
  88. # GetNoteById
  89. ############################
  90. @router.get("/{id}", response_model=Optional[NoteModel])
  91. async def get_note_by_id(request: Request, id: str, user=Depends(get_verified_user)):
  92. if user.role != "admin" and not has_permission(
  93. user.id, "features.notes", request.app.state.config.USER_PERMISSIONS
  94. ):
  95. raise HTTPException(
  96. status_code=status.HTTP_401_UNAUTHORIZED,
  97. detail=ERROR_MESSAGES.UNAUTHORIZED,
  98. )
  99. note = Notes.get_note_by_id(id)
  100. if not note:
  101. raise HTTPException(
  102. status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND
  103. )
  104. if user.role != "admin" and (
  105. user.id != note.user_id
  106. and (not has_access(user.id, type="read", access_control=note.access_control))
  107. ):
  108. raise HTTPException(
  109. status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT()
  110. )
  111. return note
  112. ############################
  113. # UpdateNoteById
  114. ############################
  115. @router.post("/{id}/update", response_model=Optional[NoteModel])
  116. async def update_note_by_id(
  117. request: Request, id: str, form_data: NoteForm, user=Depends(get_verified_user)
  118. ):
  119. if user.role != "admin" and not has_permission(
  120. user.id, "features.notes", request.app.state.config.USER_PERMISSIONS
  121. ):
  122. raise HTTPException(
  123. status_code=status.HTTP_401_UNAUTHORIZED,
  124. detail=ERROR_MESSAGES.UNAUTHORIZED,
  125. )
  126. note = Notes.get_note_by_id(id)
  127. if not note:
  128. raise HTTPException(
  129. status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND
  130. )
  131. if user.role != "admin" and (
  132. user.id != note.user_id
  133. and not has_access(user.id, type="write", access_control=note.access_control)
  134. ):
  135. raise HTTPException(
  136. status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT()
  137. )
  138. try:
  139. note = Notes.update_note_by_id(id, form_data)
  140. await sio.emit(
  141. "note-events",
  142. note.model_dump(),
  143. to=f"note:{note.id}",
  144. )
  145. return note
  146. except Exception as e:
  147. log.exception(e)
  148. raise HTTPException(
  149. status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT()
  150. )
  151. ############################
  152. # DeleteNoteById
  153. ############################
  154. @router.delete("/{id}/delete", response_model=bool)
  155. async def delete_note_by_id(request: Request, id: str, user=Depends(get_verified_user)):
  156. if user.role != "admin" and not has_permission(
  157. user.id, "features.notes", request.app.state.config.USER_PERMISSIONS
  158. ):
  159. raise HTTPException(
  160. status_code=status.HTTP_401_UNAUTHORIZED,
  161. detail=ERROR_MESSAGES.UNAUTHORIZED,
  162. )
  163. note = Notes.get_note_by_id(id)
  164. if not note:
  165. raise HTTPException(
  166. status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND
  167. )
  168. if user.role != "admin" and (
  169. user.id != note.user_id
  170. and not has_access(user.id, type="write", access_control=note.access_control)
  171. ):
  172. raise HTTPException(
  173. status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT()
  174. )
  175. try:
  176. note = Notes.delete_note_by_id(id)
  177. return True
  178. except Exception as e:
  179. log.exception(e)
  180. raise HTTPException(
  181. status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT()
  182. )