Files
open-webui/backend/open_webui/routers/notes.py
T
Classic298 18b9b449c7 fix: deleting a note leaves its chat counted in admin analytics (#35059)
Deleting a note, on its own or with the folder holding it, removed the note but kept the conversation from its chat panel. Admin analytics went on counting its messages and tokens, listed it as a session and showed its messages. Deleting a note now deletes its chats too, for everyone who chatted with it.

Fixes #35057
2026-11-25 13:13:28 +04:00

848 lines
28 KiB
Python

import logging
from typing import Optional
from uuid import uuid4
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, Request, status
from open_webui.config import (
BYPASS_ADMIN_ACCESS_CONTROL,
ENABLE_ADMIN_CHAT_ACCESS,
ENABLE_ADMIN_EXPORT,
)
from open_webui.constants import ERROR_MESSAGES
from open_webui.events import EVENTS, publish_event
from open_webui.internal.db import get_async_session
from open_webui.models.access_grants import AccessGrantModel, AccessGrants, has_public_write_access_grant
from open_webui.models.chats import ChatForm, ChatResponse, Chats
from open_webui.models.config import Config
from open_webui.models.groups import Groups
from open_webui.models.notes import (
NoteForm,
NoteListResponse,
NoteModel,
NotePageConflict,
NotePageOperation,
Notes,
NoteUpdateForm,
NoteUserResponse,
get_content_files,
get_note_files,
matching_page,
)
from open_webui.models.tags import TagModel, Tags, get_tag_id
from open_webui.models.users import UserModel, UserResponse, Users
from open_webui.socket.main import close_changed_note_documents, close_note, leave_room_for_users, note_rooms, sio
from open_webui.utils.access_control import (
filter_allowed_access_grants,
has_permission,
validate_access_grants,
)
from open_webui.utils.access_control.files import has_access_to_note_files
from open_webui.utils.access_control.folders import has_folder_move_access, has_folder_write_access
from open_webui.utils.access_control.notes import has_note_access
from open_webui.utils.auth import get_admin_user, get_verified_user
from pydantic import BaseModel, Field
from sqlalchemy.ext.asyncio import AsyncSession
log = logging.getLogger(__name__)
router = APIRouter()
async def check_notes_access(user: UserModel, db: AsyncSession):
if not await Config.get('notes.enable'):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=ERROR_MESSAGES.FEATURE_DISABLED('Notes'),
)
if user.role != 'admin' and not await has_permission(
user.id, 'features.notes', await Config.get('user.permissions'), db=db
):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=ERROR_MESSAGES.UNAUTHORIZED,
)
def truncate_note_data(data: Optional[dict], max_length: int = 1000, query: str = '') -> Optional[dict]:
if not data:
return data
page = matching_page(data, query)
md = page['content'].get('md') or ''
return {
'content': {'md': md[:max_length]},
'page_count': len(data.get('pages') or [None]),
'page_id': page['id'],
'page_title': page['title'],
}
async def leave_note_rooms_for_revoked_users(
note: NoteModel, previous_access_grants: list[AccessGrantModel], db: AsyncSession | None = None
):
revoked_user_ids = await AccessGrants.get_revoked_user_ids_by_resource(
'note', note.id, previous_access_grants, db=db
)
revoked_user_ids.discard(note.user_id)
if not revoked_user_ids:
return
users = await Users.get_users_by_user_ids(list(revoked_user_ids), db=db)
# Admins retain access to notes regardless of grants, and the note's folder may still give it.
user_ids = [
user.id for user in users if user.role != 'admin' and not await has_note_access(user.id, note, 'read', db)
]
for room in note_rooms(note):
await leave_room_for_users(room, user_ids)
# Get Notes
class NoteItemResponse(BaseModel):
id: str
title: str
data: Optional[dict]
is_pinned: Optional[bool] = False
updated_at: int
created_at: int
user: Optional[UserResponse] = None
@router.get('/', response_model=list[NoteItemResponse])
async def get_notes(
request: Request,
page: Optional[int] = None,
user=Depends(get_verified_user),
db: AsyncSession = Depends(get_async_session),
):
await check_notes_access(user, db=db)
limit = None
skip = None
if page is not None:
limit = 60
skip = (page - 1) * limit
notes = await Notes.get_notes_by_user_id(user.id, 'read', skip=skip, limit=limit, db=db)
if not notes:
return []
user_ids = list(set(note.user_id for note in notes))
users = {user.id: user for user in await Users.get_users_by_user_ids(user_ids, db=db)}
pinned_note_ids = await Notes.get_pinned_note_ids(user.id, db=db)
return [
NoteUserResponse(
**{
**note.model_dump(),
'is_pinned': note.id in pinned_note_ids,
'data': truncate_note_data(note.data),
'user': UserResponse(**users[note.user_id].model_dump()),
}
)
for note in notes
if note.user_id in users
]
# Get Pinned Notes
@router.get('/pinned', response_model=list[NoteItemResponse])
async def get_pinned_notes(
request: Request,
user=Depends(get_verified_user),
db: AsyncSession = Depends(get_async_session),
):
await check_notes_access(user, db=db)
notes = await Notes.get_pinned_notes_by_user_id(user.id, 'read', db=db)
if not notes:
return []
user_ids = list(set(note.user_id for note in notes))
users = {user.id: user for user in await Users.get_users_by_user_ids(user_ids, db=db)}
return [
NoteUserResponse(
**{
**note.model_dump(),
'is_pinned': True,
'data': truncate_note_data(note.data),
'user': UserResponse(**users[note.user_id].model_dump()),
}
)
for note in notes
if note.user_id in users
]
@router.get('/search', response_model=NoteListResponse)
async def search_notes(
request: Request,
query: Optional[str] = None,
view_option: Optional[str] = None,
permission: Optional[str] = None,
order_by: Optional[str] = None,
direction: Optional[str] = None,
page: Optional[int] = 1,
tag_ids: list[str] = Query(default=[]),
user=Depends(get_verified_user),
db: AsyncSession = Depends(get_async_session),
):
await check_notes_access(user, db=db)
if len(tag_ids) > 50:
raise HTTPException(status_code=422, detail='Too many filters')
limit = None
skip = None
if page is not None:
limit = 60
skip = (page - 1) * limit
filter = {}
if query:
filter['query'] = query
if tag_ids:
filter['tag_ids'] = tag_ids
if view_option:
filter['view_option'] = view_option
if permission:
filter['permission'] = permission
if order_by:
filter['order_by'] = order_by
if direction:
filter['direction'] = direction
if not user.role == 'admin' or not BYPASS_ADMIN_ACCESS_CONTROL:
groups = await Groups.get_groups_by_member_id(user.id, db=db, include_inherited=True)
if groups:
filter['group_ids'] = [group.id for group in groups]
filter['user_id'] = user.id
result = await Notes.search_notes(user.id, filter, skip=skip, limit=limit, db=db)
pinned_note_ids = await Notes.get_pinned_note_ids(user.id, db=db)
for note in result.items:
note.is_pinned = note.id in pinned_note_ids
note.data = truncate_note_data(note.data, query=query or '')
return result
# Note Tags
@router.get('/tags', response_model=list[dict])
async def get_note_tag_counts(
permission: Optional[str] = None,
user=Depends(get_verified_user),
db: AsyncSession = Depends(get_async_session),
):
"""Tags on the notes the list shows, with note counts, for its tag filter."""
await check_notes_access(user, db=db)
filter = {}
if not user.role == 'admin' or not BYPASS_ADMIN_ACCESS_CONTROL:
groups = await Groups.get_groups_by_member_id(user.id, db=db, include_inherited=True)
if groups:
filter['group_ids'] = [group.id for group in groups]
filter['user_id'] = user.id
return await Notes.get_tag_counts(filter, permission=permission or 'write', db=db)
class NoteTagForm(BaseModel):
name: str = Field(min_length=1, max_length=64)
class NoteTagColorForm(NoteTagForm):
# A palette name chosen by the frontend, e.g. 'blue'; the server only stores it.
color: str = Field(min_length=1, max_length=32, pattern=r'^[a-z][a-z0-9-]*$')
async def get_note_with_tag_access(id: str, user, db: AsyncSession):
"""The note whose tags this user may change: anyone who can edit it.
Tags are the note owner's records, so an editor's change is made in the owner's tags.
"""
await check_notes_access(user, db=db)
note = await Notes.get_note_by_id(id, db=db)
if not note:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND)
if user.role != 'admin' and not await has_note_access(user.id, note, 'write', db):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT())
return note
@router.get('/{id}/tags', response_model=list[TagModel])
async def get_note_tags_by_id(
id: str,
user=Depends(get_verified_user),
db: AsyncSession = Depends(get_async_session),
):
await check_notes_access(user, db=db)
note = await Notes.get_note_by_id(id, db=db)
if not note:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND)
if user.role != 'admin' and not await has_note_access(user.id, note, 'read', db):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT())
return await Tags.get_tags_by_resource('note', id, db=db)
@router.post('/{id}/tags', response_model=list[TagModel])
async def add_note_tag_by_id(
id: str,
form_data: NoteTagForm,
user=Depends(get_verified_user),
db: AsyncSession = Depends(get_async_session),
):
note = await get_note_with_tag_access(id, user, db)
# 'none' is how filters name untagged notes.
if get_tag_id(form_data.name) == 'none':
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT('Tag name cannot be "None"')
)
await Tags.add_tag_to_resource('note', id, form_data.name, note.user_id, db=db)
return await Tags.get_tags_by_resource('note', id, db=db)
@router.delete('/{id}/tags', response_model=list[TagModel])
async def delete_note_tag_by_id(
id: str,
form_data: NoteTagForm,
user=Depends(get_verified_user),
db: AsyncSession = Depends(get_async_session),
):
note = await get_note_with_tag_access(id, user, db)
await Tags.remove_tag_from_resource('note', id, form_data.name, note.user_id, db=db)
return await Tags.get_tags_by_resource('note', id, db=db)
@router.patch('/{id}/tags', response_model=list[TagModel])
async def update_note_tag_color(
id: str,
form_data: NoteTagColorForm,
user=Depends(get_verified_user),
db: AsyncSession = Depends(get_async_session),
):
note = await get_note_with_tag_access(id, user, db)
tags = await Tags.get_tags_by_resources('note', [id], db=db)
if get_tag_id(form_data.name) not in [tag['id'] for tag in tags.get(id, [])]:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED)
if not await Tags.update_tag_color_by_name_and_user_id(form_data.name, note.user_id, form_data.color, db=db):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED)
return await Tags.get_tags_by_resource('note', id, db=db)
# Create New Note
@router.post('/create', response_model=Optional[NoteModel])
async def create_new_note(
request: Request,
form_data: NoteForm,
user=Depends(get_verified_user),
db: AsyncSession = Depends(get_async_session),
):
await check_notes_access(user, db=db)
if form_data.folder_id is not None and not await has_folder_write_access(user.id, form_data.folder_id, db=db):
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND)
form_data.access_grants = await filter_allowed_access_grants(
await Config.get('user.permissions'),
user.id,
user.role,
form_data.access_grants,
resource_type='note',
db=db,
)
if not await has_access_to_note_files(None, get_note_files(form_data.data), user, db=db):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT())
try:
note = await Notes.insert_new_note(user.id, form_data, db=db)
await publish_event(
request,
EVENTS.NOTE_CREATED,
actor=user,
subject_id=note.id,
data={'title': note.title, 'folder_id': note.folder_id},
)
return note
except Exception as e:
log.exception(e)
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
# Get Note By Id
class NoteResponse(NoteModel):
write_access: bool = False
@router.get('/{id}', response_model=Optional[NoteResponse])
async def get_note_by_id(
request: Request,
id: str,
user=Depends(get_verified_user),
db: AsyncSession = Depends(get_async_session),
):
await check_notes_access(user, db=db)
note = await Notes.get_note_by_id(id, db=db)
if not note:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND)
if user.role != 'admin' and not await has_note_access(user.id, note, 'read', db):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT())
write_access = (
user.role == 'admin'
or await has_note_access(user.id, note, 'write', db)
or has_public_write_access_grant(note.access_grants)
)
pinned_note_ids = await Notes.get_pinned_note_ids(user.id, db=db)
return NoteResponse(
**{**note.model_dump(), 'is_pinned': note.id in pinned_note_ids},
write_access=write_access,
)
@router.get('/{id}/chat', response_model=ChatResponse)
async def get_note_chat_by_id(
request: Request,
id: str,
user=Depends(get_verified_user),
db: AsyncSession = Depends(get_async_session),
):
log.info('[note-chat] get-or-create requested note_id=%s user_id=%s', id, user.id)
await check_notes_access(user, db=db)
note = await Notes.get_note_by_id(id, db=db)
if not note:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND)
if user.role != 'admin' and not await has_note_access(user.id, note, 'read', db):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT())
chat = await Chats.get_internal_chat_by_note_id(note.id, user.id, db=db)
if chat:
log.info('[note-chat] reusing hidden chat note_id=%s chat_id=%s user_id=%s', note.id, chat.id, user.id)
params = {**((chat.chat or {}).get('params') or {})}
changed = False
if 'note_id' in params:
del params['note_id']
changed = True
system = (
f'CONTEXT:\nCurrent note id: {note.id}\n'
'This chat is attached to the current note.\n'
'For edit requests like make this concise, rewrite, enhance, shorten, or update: call view_note then replace_note_content.\n'
'Do not say an edit is done unless replace_note_content succeeds.'
)
if params.get('system') != system:
params['system'] = system
changed = True
if changed:
updated_chat = await Chats.update_chat_by_id(chat.id, {'params': params}, db=db, touch=False)
if updated_chat:
return updated_chat
return chat
chat_id = str(uuid4())
chat = await Chats.insert_new_chat(
chat_id,
user.id,
ChatForm(
chat={
'id': chat_id,
'title': 'Chat',
'models': [''],
'params': {
'system': (
f'CONTEXT:\nCurrent note id: {note.id}\n'
'This chat is attached to the current note.\n'
'For edit requests like make this concise, rewrite, enhance, shorten, or update: call view_note then replace_note_content.\n'
'Do not say an edit is done unless replace_note_content succeeds.'
)
},
'history': {'messages': {}, 'currentId': None},
'messages': [],
'tags': [],
}
),
db=db,
internal_meta={'internal': True, 'type': 'note', 'note_id': note.id},
)
if not chat:
log.error('[note-chat] failed creating hidden chat note_id=%s user_id=%s', note.id, user.id)
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
log.info('[note-chat] created hidden chat note_id=%s chat_id=%s user_id=%s', note.id, chat.id, user.id)
return chat
@router.get('/{id}/chats', response_model=list[ChatResponse])
async def get_note_chats_by_id(
request: Request,
id: str,
user=Depends(get_verified_user),
db: AsyncSession = Depends(get_async_session),
):
await check_notes_access(user, db=db)
note = await Notes.get_note_by_id(id, db=db)
if not note:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND)
if user.role != 'admin' and not await has_note_access(user.id, note, 'read', db):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT())
chats = await Chats.get_internal_chats_by_note_id(note.id, user.id, db=db)
normalized_chats = []
for chat in chats:
params = {**((chat.chat or {}).get('params') or {})}
changed = False
if 'note_id' in params:
del params['note_id']
changed = True
system = (
f'CONTEXT:\nCurrent note id: {note.id}\n'
'This chat is attached to the current note.\n'
'For edit requests like make this concise, rewrite, enhance, shorten, or update: call view_note then replace_note_content.\n'
'Do not say an edit is done unless replace_note_content succeeds.'
)
if params.get('system') != system:
params['system'] = system
changed = True
if changed:
chat = await Chats.update_chat_by_id(chat.id, {'params': params}, db=db, touch=False) or chat
normalized_chats.append(chat)
return normalized_chats
@router.post('/{id}/chat', response_model=ChatResponse)
async def create_note_chat_by_id(
request: Request,
id: str,
user=Depends(get_verified_user),
db: AsyncSession = Depends(get_async_session),
):
await check_notes_access(user, db=db)
note = await Notes.get_note_by_id(id, db=db)
if not note:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND)
if user.role != 'admin' and not await has_note_access(user.id, note, 'read', db):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT())
chat_id = str(uuid4())
chat = await Chats.insert_new_chat(
chat_id,
user.id,
ChatForm(
chat={
'id': chat_id,
'title': 'Chat',
'models': [''],
'params': {
'system': (
f'CONTEXT:\nCurrent note id: {note.id}\n'
'This chat is attached to the current note.\n'
'For edit requests like make this concise, rewrite, enhance, shorten, or update: call view_note then replace_note_content.\n'
'Do not say an edit is done unless replace_note_content succeeds.'
)
},
'history': {'messages': {}, 'currentId': None},
'messages': [],
'tags': [],
}
),
db=db,
internal_meta={'internal': True, 'type': 'note', 'note_id': note.id},
)
if not chat:
log.error('[note-chat] failed creating hidden chat note_id=%s user_id=%s', note.id, user.id)
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
log.info('[note-chat] created hidden chat note_id=%s chat_id=%s user_id=%s', note.id, chat.id, user.id)
return chat
# Update Note By Id
@router.post('/{id}/update', response_model=Optional[NoteModel])
async def update_note_by_id(
request: Request,
id: str,
form_data: NoteUpdateForm,
user=Depends(get_verified_user),
db: AsyncSession = Depends(get_async_session),
):
await check_notes_access(user, db=db)
note = await Notes.get_note_by_id(id, db=db)
if not note:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND)
if user.role != 'admin' and not await has_note_access(user.id, note, 'write', db):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT())
if form_data.data and not await has_access_to_note_files(
note, get_content_files(form_data.data.get('content')), user, db=db
):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT())
try:
if form_data.page_generation is not None:
raise ValueError('Page generation is managed by collaboration')
previous = note
note = await Notes.update_note_by_id(id, form_data, db=db)
await close_changed_note_documents(previous, note)
pinned_note_ids = await Notes.get_pinned_note_ids(user.id, db=db)
note.is_pinned = note.id in pinned_note_ids
event_data = note.model_dump()
if form_data.data is not None:
event_data['data'] = {
key: note.data.get(key) for key in form_data.data.keys() if note.data is not None and key in note.data
}
if form_data.page_operation or (form_data.data and {'content', 'files'} & form_data.data.keys()):
event_data['data'] = note.data
await sio.emit(
'events',
{'data': {'type': 'note:updated', 'data': event_data}},
to=f'note:{note.id}',
)
await publish_event(
request,
EVENTS.NOTE_UPDATED,
actor=user,
subject_id=note.id,
data={'title': note.title},
)
return note
except NotePageConflict as e:
raise HTTPException(status_code=409, detail=str(e))
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
log.exception(e)
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
@router.post('/{id}/pages/update', response_model=NoteModel)
async def update_note_pages(
request: Request,
id: str,
form_data: NotePageOperation,
user=Depends(get_verified_user),
db: AsyncSession = Depends(get_async_session),
):
return await update_note_by_id(request, id, NoteUpdateForm(page_operation=form_data), user, db)
# Update Note Access By Id
class NoteAccessGrantsForm(BaseModel):
access_grants: list[dict]
@router.post('/{id}/access/update', response_model=Optional[NoteModel])
async def update_note_access_by_id(
request: Request,
id: str,
form_data: NoteAccessGrantsForm,
user=Depends(get_verified_user),
db: AsyncSession = Depends(get_async_session),
):
await check_notes_access(user, db=db)
note = await Notes.get_note_by_id(id, db=db)
if not note:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND)
if user.role != 'admin' and (
user.id != note.user_id
and not await AccessGrants.has_access(
user_id=user.id,
resource_type='note',
resource_id=note.id,
permission='write',
db=db,
)
):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT())
form_data.access_grants = await validate_access_grants(
await Config.get('user.permissions'),
user.id,
user.role,
form_data.access_grants,
resource_type='note',
)
await AccessGrants.set_access_grants('note', id, form_data.access_grants, db=db)
await leave_note_rooms_for_revoked_users(note, note.access_grants, db=db)
note = await Notes.get_note_by_id(id, db=db)
pinned_note_ids = await Notes.get_pinned_note_ids(user.id, db=db)
note.is_pinned = note.id in pinned_note_ids
await publish_event(
request,
EVENTS.NOTE_ACCESS_UPDATED,
actor=user,
subject_id=note.id,
)
return note
# Update Note Folder By Id
class NoteFolderIdForm(BaseModel):
folder_id: Optional[str] = None
@router.post('/{id}/folder', response_model=Optional[NoteModel])
async def update_note_folder_id_by_id(
request: Request,
id: str,
form_data: NoteFolderIdForm,
user=Depends(get_verified_user),
db: AsyncSession = Depends(get_async_session),
):
await check_notes_access(user, db=db)
note = await Notes.get_note_by_id(id, db=db)
if not note:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND)
if note.user_id != user.id and not await has_folder_move_access(
user.id, note.folder_id, form_data.folder_id, db=db
):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT())
# None is allowed: it moves the note out of any folder.
if form_data.folder_id is not None and not await has_folder_write_access(user.id, form_data.folder_id, db=db):
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND)
note = await Notes.update_note_folder_id_by_id(id, form_data.folder_id, db=db)
pinned_note_ids = await Notes.get_pinned_note_ids(user.id, db=db)
note.is_pinned = note.id in pinned_note_ids
await publish_event(
request,
EVENTS.NOTE_FOLDER_UPDATED,
actor=user,
subject_id=note.id,
data={'folder_id': form_data.folder_id},
)
return note
# Pin Note By Id
@router.post('/{id}/pin', response_model=Optional[NoteModel])
async def pin_note_by_id(
request: Request,
id: str,
user=Depends(get_verified_user),
db: AsyncSession = Depends(get_async_session),
):
await check_notes_access(user, db=db)
note = await Notes.get_note_by_id(id, db=db)
if not note:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND)
if user.role != 'admin' and not await has_note_access(user.id, note, 'read', db):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT())
note = await Notes.toggle_note_pinned_by_id(id, user.id, db=db)
pinned_note_ids = await Notes.get_pinned_note_ids(user.id, db=db)
note.is_pinned = note.id in pinned_note_ids
await publish_event(
request,
EVENTS.NOTE_PINNED if note.is_pinned else EVENTS.NOTE_UNPINNED,
actor=user,
subject_id=note.id,
subject_type='note',
)
return note
# Delete Note By Id
@router.delete('/{id}/delete', response_model=bool)
async def delete_note_by_id(
request: Request,
id: str,
user=Depends(get_verified_user),
db: AsyncSession = Depends(get_async_session),
):
await check_notes_access(user, db=db)
note = await Notes.get_note_by_id(id, db=db)
if not note:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND)
if user.role != 'admin' and (
user.id != note.user_id
and not await AccessGrants.has_access(
user_id=user.id,
resource_type='note',
resource_id=note.id,
permission='write',
db=db,
)
):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT())
try:
await Notes.delete_note_by_id(id, db=db)
for chat_id in await Chats.get_internal_chat_ids_by_note_id(id, db=db):
await Chats.delete_chat_by_id(chat_id, db=db)
await close_note(note)
await publish_event(
request,
EVENTS.NOTE_DELETED,
actor=user,
subject_id=id,
)
return True
except Exception as e:
log.exception(e)
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())