Skip to content

Commit

Permalink
Add max memo content length config option
Browse files Browse the repository at this point in the history
  • Loading branch information
xwjdsh committed Jan 18, 2024
1 parent 2a4ebf5 commit 94c9a4d
Show file tree
Hide file tree
Showing 25 changed files with 98 additions and 15 deletions.
9 changes: 7 additions & 2 deletions api/v1/system.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ type SystemStatus struct {
DisablePublicMemos bool `json:"disablePublicMemos"`
// Max upload size.
MaxUploadSizeMiB int `json:"maxUploadSizeMiB"`
// Max memo content length.
MaxMemoContentLength int `json:"maxMemoContentLength"`
// Additional style.
AdditionalStyle string `json:"additionalStyle"`
// Additional script.
Expand Down Expand Up @@ -75,8 +77,9 @@ func (s *APIV1Service) GetSystemStatus(c echo.Context) error {
Version: s.Profile.Version,
},
// Allow sign up by default.
AllowSignUp: true,
MaxUploadSizeMiB: 32,
AllowSignUp: true,
MaxUploadSizeMiB: 32,
MaxMemoContentLength: 8192,
CustomizedProfile: CustomizedProfile{
Name: "Memos",
Locale: "en",
Expand Down Expand Up @@ -122,6 +125,8 @@ func (s *APIV1Service) GetSystemStatus(c echo.Context) error {
systemStatus.DisablePublicMemos = baseValue.(bool)
case SystemSettingMaxUploadSizeMiBName.String():
systemStatus.MaxUploadSizeMiB = int(baseValue.(float64))
case SystemSettingMaxMemoContentLengthName.String():
systemStatus.MaxMemoContentLength = int(baseValue.(float64))
case SystemSettingAdditionalStyleName.String():
systemStatus.AdditionalStyle = baseValue.(string)
case SystemSettingAdditionalScriptName.String():
Expand Down
7 changes: 7 additions & 0 deletions api/v1/system_setting.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ const (
SystemSettingDisablePublicMemosName SystemSettingName = "disable-public-memos"
// SystemSettingMaxUploadSizeMiBName is the name of max upload size setting.
SystemSettingMaxUploadSizeMiBName SystemSettingName = "max-upload-size-mib"
// SystemSettingMaxMemoContentLengthName is the name of max memo content length setting.
SystemSettingMaxMemoContentLengthName SystemSettingName = "max-memo-content-length"
// SystemSettingAdditionalStyleName is the name of additional style.
SystemSettingAdditionalStyleName SystemSettingName = "additional-style"
// SystemSettingAdditionalScriptName is the name of additional script.
Expand Down Expand Up @@ -209,6 +211,11 @@ func (upsert UpsertSystemSettingRequest) Validate() error {
if err := json.Unmarshal([]byte(upsert.Value), &value); err != nil {
return errors.Errorf(systemSettingUnmarshalError, settingName)
}
case SystemSettingMaxMemoContentLengthName:
var value int
if err := json.Unmarshal([]byte(upsert.Value), &value); err != nil {
return errors.Errorf(systemSettingUnmarshalError, settingName)
}
case SystemSettingAdditionalStyleName:
var value string
if err := json.Unmarshal([]byte(upsert.Value), &value); err != nil {
Expand Down
22 changes: 16 additions & 6 deletions api/v2/memo_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"strconv"
"time"

"github.com/google/cel-go/cel"
Expand All @@ -27,10 +28,6 @@ import (
"github.com/usememos/memos/store"
)

const (
MaxContentLength = 8 * 1024
)

func (s *APIV2Service) CreateMemo(ctx context.Context, request *apiv2pb.CreateMemoRequest) (*apiv2pb.CreateMemoResponse, error) {
user, err := getCurrentUser(ctx, s.Store)
if err != nil {
Expand All @@ -39,7 +36,14 @@ func (s *APIV2Service) CreateMemo(ctx context.Context, request *apiv2pb.CreateMe
if user == nil {
return nil, status.Errorf(codes.PermissionDenied, "permission denied")
}
if len(request.Content) > MaxContentLength {

maxContentLengthSetting := s.Store.GetSystemSettingValueWithDefault(ctx, apiv1.SystemSettingMaxMemoContentLengthName.String(), "8192")
settingMaxContentLength, err := strconv.Atoi(maxContentLengthSetting)
if err != nil {
log.Warn("Failed to parse max content length", zap.Error(err))
}

if len(request.Content) > settingMaxContentLength {
return nil, status.Errorf(codes.InvalidArgument, "content too long")
}

Expand Down Expand Up @@ -302,7 +306,13 @@ func (s *APIV2Service) UpdateMemo(ctx context.Context, request *apiv2pb.UpdateMe
}
}
}
if update.Content != nil && len(*update.Content) > MaxContentLength {
maxContentLengthSetting := s.Store.GetSystemSettingValueWithDefault(ctx, apiv1.SystemSettingMaxMemoContentLengthName.String(), "8192")
settingMaxContentLength, err := strconv.Atoi(maxContentLengthSetting)
if err != nil {
log.Warn("Failed to parse max content length", zap.Error(err))
}

if update.Content != nil && len(*update.Content) > settingMaxContentLength {
return nil, status.Errorf(codes.InvalidArgument, "content too long")
}

Expand Down
1 change: 1 addition & 0 deletions web/src/components/MemoEditor/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import Editor, { EditorRefActions } from "./Editor";
import RelationListView from "./RelationListView";
import ResourceListView from "./ResourceListView";
import { handleEditorKeydownWithMarkdownShortcuts, hyperlinkHighlightedText } from "./handlers";

Check failure on line 27 in web/src/components/MemoEditor/index.tsx

View workflow job for this annotation

GitHub Actions / eslint-checks

Delete `";⏎import·{·ClientError·}·from·"nice-grpc-web`
import { ClientError } from "nice-grpc-web";

Check failure on line 28 in web/src/components/MemoEditor/index.tsx

View workflow job for this annotation

GitHub Actions / eslint-checks

'ClientError' is defined but never used

interface Props {
className?: string;
Expand Down
40 changes: 40 additions & 0 deletions web/src/components/Settings/SystemSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ interface State {
additionalStyle: string;
additionalScript: string;
maxUploadSizeMiB: number;
maxMemoContentLength: number;
memoDisplayWithUpdatedTs: boolean;
}

Expand All @@ -34,6 +35,7 @@ const SystemSection = () => {
additionalScript: systemStatus.additionalScript,
disablePublicMemos: systemStatus.disablePublicMemos,
maxUploadSizeMiB: systemStatus.maxUploadSizeMiB,
maxMemoContentLength: systemStatus.maxMemoContentLength,
memoDisplayWithUpdatedTs: systemStatus.memoDisplayWithUpdatedTs,
});
const [telegramBotToken, setTelegramBotToken] = useState<string>("");
Expand Down Expand Up @@ -238,10 +240,34 @@ const SystemSection = () => {
});
};

const handleMaxMemoContentLengthChanged = async (event: React.FocusEvent<HTMLInputElement>) => {
// fixes cursor skipping position on mobile
event.target.selectionEnd = event.target.value.length;

let num = parseInt(event.target.value);
if (Number.isNaN(num)) {
num = 0;
}
setState({
...state,
maxMemoContentLength: num,
});
event.target.value = num.toString();
globalStore.setSystemStatus({ maxMemoContentLength: num });
await api.upsertSystemSetting({
name: "max-memo-content-length",
value: JSON.stringify(num),
});
};

const handleMaxUploadSizeFocus = (event: React.FocusEvent<HTMLInputElement>) => {
event.target.select();
};

const handleMaxMemoContentLengthFocus = (event: React.FocusEvent<HTMLInputElement>) => {
event.target.select();
};

return (
<div className="w-full flex flex-col gap-2 pt-2 pb-4">
<p className="font-medium text-gray-700 dark:text-gray-500">{t("common.basic")}</p>
Expand Down Expand Up @@ -296,6 +322,20 @@ const SystemSection = () => {
onChange={handleMaxUploadSizeChanged}
/>
</div>
<div className="w-full flex flex-row justify-between items-center">
<div className="flex flex-row items-center">
<span className="text-sm mr-1">{t("setting.system-section.max-memo-content-length")}</span>
</div>
<Input
className="w-16"
sx={{
fontFamily: "monospace",
}}
defaultValue={state.maxMemoContentLength}
onFocus={handleMaxMemoContentLengthFocus}
onChange={handleMaxMemoContentLengthChanged}
/>
</div>
<Divider className="!mt-3 !my-4" />
<div className="w-full flex flex-row justify-between items-center">
<div className="flex flex-row items-center">
Expand Down
1 change: 1 addition & 0 deletions web/src/locales/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,7 @@
"enable-password-login-warning": "Dadurch wird die Passwortanmeldung für alle Benutzer aktiviert. Fahre nur fort, wenn du möchtest, dass sich Benutzer sowohl mit SSO als auch mit einem Passwort anmelden können",
"max-upload-size": "Maximale Uploadgröße (MiB)",
"max-upload-size-hint": "Empfohlene Wert ist 32 MiB.",
"max-memo-content-length": "Maximale Länge des Memo-Inhalts",
"server-name": "Servername",
"telegram-bot-token": "Telegram Bot Token",
"telegram-bot-token-description": "Telegram Bot Token oder API Proxy, wie `http…/bot<token>`",
Expand Down
1 change: 1 addition & 0 deletions web/src/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,7 @@
"disable-public-memos": "Disable public memos",
"max-upload-size": "Maximum upload size (MiB)",
"max-upload-size-hint": "Recommended value is 32 MiB.",
"max-memo-content-length": "Maximum memo content length",
"vacuum-hint": "Cleans up unused data.",
"additional-style": "Additional style",
"additional-script": "Additional script",
Expand Down
3 changes: 2 additions & 1 deletion web/src/locales/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,8 @@
"additional-style-placeholder": "Código CSS adicional",
"additional-script-placeholder": "Código JavaScript adicional",
"disable-public-memos": "Deshabilitar notas públicas",
"display-with-updated-time": "Display with updated time"
"display-with-updated-time": "Display with updated time",
"max-memo-content-length": "Longitud máxima del contenido de la nota"
},
"appearance-option": {
"system": "Según el sistema",
Expand Down
1 change: 1 addition & 0 deletions web/src/locales/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,7 @@
"enable-password-login-warning": "Ceci activera la connexion par mot de passe pour tous les utilisateurs. Ne continuez que si vous souhaitez que les utilisateurs puissent se connecter à la fois par SSO et par mot de passe",
"max-upload-size": "Taille maximale du téléversement (MiB)",
"max-upload-size-hint": "La valeur recommandée est 32 MiB.",
"max-memo-content-length": "Longueur maximale du contenu du memo",
"server-name": "Nom du serveur",
"telegram-bot-token": "Jeton du Bot Telegram",
"telegram-bot-token-description": "Jeton du Bot Telegram ou API Proxy comme `http…/bot<token>`",
Expand Down
1 change: 1 addition & 0 deletions web/src/locales/hr.json
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,7 @@
"enable-password-login-warning": "Ovo će omogućiti prijavu lozinkom za sve korisnike.",
"max-upload-size": "Maximalna veličina uploada (MiB)",
"max-upload-size-hint": "Preporučena vrijednost je 32 MiB.",
"max-memo-content-length": "Maximalna duljina sadržaja memoa",
"server-name": "Ime servera",
"telegram-bot-token": "Token Telegram Bota",
"telegram-bot-token-description": "Telegram Bot Token ili API Proxy kao `http.../bot<token>`",
Expand Down
1 change: 1 addition & 0 deletions web/src/locales/it.json
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,7 @@
"enable-password-login-warning": "Ciò consentirà l'accesso tramite password per tutti gli utenti. Continua solo se desideri che gli utenti possano accedere utilizzando sia SSO che password❗",
"max-upload-size": "Dimensione massima caricamento (MiB)",
"max-upload-size-hint": "Valore consigliato di 32 MiB.",
"max-memo-content-length": "Lunghezza massima memo",
"server-name": "Nome server",
"telegram-bot-token": "Token Bot Telegram",
"telegram-bot-token-description": "Token bot Telegram o API Proxy come `http.../bot<token>`",
Expand Down
1 change: 1 addition & 0 deletions web/src/locales/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,7 @@
"enable-password-login-warning": "これにより、すべてのユーザーのパスワードでのログインが有効になります。SSOとパスワードの両方を使用してログインできるようにしたい場合のみ、続行してください❗",
"max-upload-size": "最大ファイルサイズ(MiB)",
"max-upload-size-hint": "推奨サイズは32 MiBです。",
"max-memo-content-length": "メモの最大文字数",
"server-name": "サーバーの名前",
"telegram-bot-token": "Telegram Bot Token",
"telegram-bot-token-description": "Telegram Bot TokenかAPI Proxyを`http.../bot<token>`のように入力してください。",
Expand Down
1 change: 1 addition & 0 deletions web/src/locales/ko.json
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,7 @@
"enable-password-login-warning": "모든 사용자가 비밀번호를 사용해서 로그인할 수 있게 합니다. 사용자들이 SSO와 비밀번호 둘 다 사용할 수 있게 하고 싶은 경우에만 켜 주세요",
"max-upload-size": "최대 업로드 크기 (MiB)",
"max-upload-size-hint": "권장값은 32 MiB입니다.",
"max-memo-content-length": "메모 내용 최대 길이",
"server-name": "서버 이름",
"telegram-bot-token": "텔레그램 봇 연동",
"telegram-bot-token-description": "`http…/bot<token>` 형태의 API 프록시 또는 텔레그램 봇 토큰",
Expand Down
1 change: 1 addition & 0 deletions web/src/locales/nl.json
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@
"disable-public-memos": "Openbare memos uitzetten",
"max-upload-size": "Maximum uploadgrootte (MiB)",
"max-upload-size-hint": "32 MiB wordt aangeraden.",
"max-memo-content-length": "Maximum memo inhoudslengte",
"display-with-updated-time": "Laten zien met bewerkte tijd",
"telegram-bot-token": "Telegram bot token",
"telegram-bot-token-description": "Telegram bot token of API proxy zoals `http://.../bot<token>`",
Expand Down
3 changes: 2 additions & 1 deletion web/src/locales/pl.json
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,8 @@
"database-file-size": "Rozmiar bazy danych",
"disable-public-memos": "Wyłącz publiczne notatki",
"display-with-updated-time": "Display with updated time",
"server-name": "Nazwa serwera"
"server-name": "Nazwa serwera",
"max-memo-content-length": "Maksymalna długość treści notatki"
}
},
"tag-list": {
Expand Down
1 change: 1 addition & 0 deletions web/src/locales/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,7 @@
"enable-password-login-warning": "Isso permitirá o login com senha para todos os usuários. Continue apenas se desejar que os usuários possam fazer login usando SSO e senha local❗",
"max-upload-size": "Tamanho máximo de upload (MiB)",
"max-upload-size-hint": "O valor recomendado é 32 MiB.",
"max-memo-content-length": "Tamanho máximo do conteúdo do memo",
"server-name": "Nome do servidor",
"telegram-bot-token": "Token de Bot do Telegram",
"telegram-bot-token-description": "Token de Bot do Telegram ou Proxy de API, tipo `http…/bot<token>`",
Expand Down
1 change: 1 addition & 0 deletions web/src/locales/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,7 @@
"display-with-updated-time": "Отображать время обновления записи",
"max-upload-size": "Максимальный размер загрузки (МБ)",
"max-upload-size-hint": "Рекомендуемое значение 32 MБ.",
"max-memo-content-length": "Максимальная длина записи",
"server-name": "Имя сервера",
"telegram-bot-token": "Токен Telegram бота",
"telegram-bot-token-description": "Токен Telegram бота или прокси API вида `http.../bot<token>`",
Expand Down
3 changes: 2 additions & 1 deletion web/src/locales/sl.json
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,8 @@
"additional-script": "Dodatne skripte",
"additional-style-placeholder": "Dodatna CSS koda",
"additional-script-placeholder": "Dodatna JavaScript koda",
"display-with-updated-time": "Display with updated time"
"display-with-updated-time": "Display with updated time",
"max-memo-content-length": "Največja dolžina vsebine beležke"
},
"appearance-option": {
"system": "Sledi sistemu",
Expand Down
3 changes: 2 additions & 1 deletion web/src/locales/sv.json
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,8 @@
"additional-style-placeholder": "Ytterligare CSS kod",
"additional-script-placeholder": "Ytterligare JavaScript kod",
"disable-public-memos": "Inaktivera offentliga anteckningar",
"display-with-updated-time": "Display with updated time"
"display-with-updated-time": "Display with updated time",
"max-memo-content-length": "Max anteckningslängd"
},
"appearance-option": {
"system": "Follow system",
Expand Down
3 changes: 2 additions & 1 deletion web/src/locales/tr.json
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,8 @@
"additional-style-placeholder": "Ek CSS",
"additional-script-placeholder": "Ek JavaScript",
"disable-public-memos": "Halka açık notları devre dışı bırak",
"display-with-updated-time": "Display with updated time"
"display-with-updated-time": "Display with updated time",
"max-memo-content-length": "Maksimum not içeriği uzunluğu"
},
"appearance-option": {
"system": "Otomatik",
Expand Down
3 changes: 2 additions & 1 deletion web/src/locales/uk.json
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,8 @@
"additional-style-placeholder": "Додатковий CSS",
"additional-script-placeholder": "Додатковий JavaScript",
"disable-public-memos": "Disable public memos",
"display-with-updated-time": "Display with updated time"
"display-with-updated-time": "Display with updated time",
"max-memo-content-length": "Максимальна довжина нотатки"
},
"appearance-option": {
"system": "Автоматично",
Expand Down
3 changes: 2 additions & 1 deletion web/src/locales/vi.json
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,8 @@
"additional-style-placeholder": "Mã CSS bổ sung",
"additional-script-placeholder": "Mã JavaScript bổ sung",
"disable-public-memos": "Vô hiệu hóa ghi chú công khai",
"display-with-updated-time": "Display with updated time"
"display-with-updated-time": "Display with updated time",
"max-memo-content-length": "Độ dài tối đa của nội dung ghi chú"
},
"storage": "Kho lưu trữ",
"sso": "SSO",
Expand Down
1 change: 1 addition & 0 deletions web/src/locales/zh-Hans.json
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,7 @@
"enable-password-login-warning": "启用所有用户的密码登录。如果希望用户同时使用单点登录和密码登录,请开启密码登录",
"max-upload-size": "最大上传大小 (MiB)",
"max-upload-size-hint": "建议值为 32 MiB。",
"max-memo-content-length": "最大备忘录内容长度",
"server-name": "服务名称",
"telegram-bot-token": "Telegram 机器人 Token",
"telegram-bot-token-description": "Telegram 机器人 Token 或 `http…/bot<token>` 格式的代理地址",
Expand Down
1 change: 1 addition & 0 deletions web/src/locales/zh-Hant.json
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,7 @@
"enable-password-login-warning": "啟用所有使用者的密碼登入。如果希望使用者同時使用 SSO 和密碼登入,請開啟密碼登入",
"max-upload-size": "最大上傳檔案大小 (MiB)",
"max-upload-size-hint": "建議值為 32 MiB。",
"max-memo-content-length": "最大備忘錄內容長度",
"server-name": "伺服器名稱",
"telegram-bot-token": "Telegram 機器人權杖",
"telegram-bot-token-description": "Telegram 機器人權杖或 API Proxy,如 `http.../bot<token>`",
Expand Down
1 change: 1 addition & 0 deletions web/src/types/modules/system.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ interface SystemStatus {
disablePasswordLogin: boolean;
disablePublicMemos: boolean;
maxUploadSizeMiB: number;
maxMemoContentLength: number;
additionalStyle: string;
additionalScript: string;
customizedProfile: CustomizedProfile;
Expand Down

0 comments on commit 94c9a4d

Please sign in to comment.