2023-10-27 09:01:17 +08:00
|
|
|
package v2
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
2023-10-28 09:04:32 +08:00
|
|
|
|
|
|
|
"github.com/usememos/memos/internal/util"
|
2023-10-27 09:01:17 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2023-11-05 23:03:43 +08:00
|
|
|
UserNamePrefix = "users/"
|
2023-10-28 02:43:46 +08:00
|
|
|
InboxNamePrefix = "inboxes/"
|
2023-10-27 09:01:17 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
// GetNameParentTokens returns the tokens from a resource name.
|
|
|
|
func GetNameParentTokens(name string, tokenPrefixes ...string) ([]string, error) {
|
|
|
|
parts := strings.Split(name, "/")
|
|
|
|
if len(parts) != 2*len(tokenPrefixes) {
|
|
|
|
return nil, errors.Errorf("invalid request %q", name)
|
|
|
|
}
|
|
|
|
|
|
|
|
var tokens []string
|
|
|
|
for i, tokenPrefix := range tokenPrefixes {
|
|
|
|
if fmt.Sprintf("%s/", parts[2*i]) != tokenPrefix {
|
|
|
|
return nil, errors.Errorf("invalid prefix %q in request %q", tokenPrefix, name)
|
|
|
|
}
|
|
|
|
if parts[2*i+1] == "" {
|
|
|
|
return nil, errors.Errorf("invalid request %q with empty prefix %q", name, tokenPrefix)
|
|
|
|
}
|
|
|
|
tokens = append(tokens, parts[2*i+1])
|
|
|
|
}
|
|
|
|
return tokens, nil
|
|
|
|
}
|
|
|
|
|
2023-11-05 23:03:43 +08:00
|
|
|
// GetUsername returns the username from a resource name.
|
|
|
|
func GetUsername(name string) (string, error) {
|
|
|
|
tokens, err := GetNameParentTokens(name, UserNamePrefix)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return tokens[0], nil
|
|
|
|
}
|
|
|
|
|
2023-10-27 09:01:17 +08:00
|
|
|
// GetInboxID returns the inbox ID from a resource name.
|
|
|
|
func GetInboxID(name string) (int32, error) {
|
|
|
|
tokens, err := GetNameParentTokens(name, InboxNamePrefix)
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
2023-10-28 09:04:32 +08:00
|
|
|
id, err := util.ConvertStringToInt32(tokens[0])
|
2023-10-27 09:01:17 +08:00
|
|
|
if err != nil {
|
|
|
|
return 0, errors.Errorf("invalid inbox ID %q", tokens[0])
|
|
|
|
}
|
2023-10-28 09:04:32 +08:00
|
|
|
return id, nil
|
2023-10-27 09:01:17 +08:00
|
|
|
}
|