- Updated the Contacts API to support contact synchronization with incremental updates using sync tokens. - Added functionality for merging duplicate contacts on the server side. - Introduced new endpoints for enriching contact interactions, including mail, meetings, and files. - Implemented ETag support for contact updates to ensure data integrity. - Enhanced validation for sync tokens and interaction queries. - Updated project checklist to reflect the completion of Contacts API enhancements.
265 lines
8.2 KiB
Go
265 lines
8.2 KiB
Go
package contacts
|
|
|
|
import (
|
|
"errors"
|
|
"log/slog"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
"github.com/ultisuite/ulti-backend/internal/api/apiresponse"
|
|
"github.com/ultisuite/ulti-backend/internal/api/apivalidate"
|
|
"github.com/ultisuite/ulti-backend/internal/api/middleware"
|
|
"github.com/ultisuite/ulti-backend/internal/api/query"
|
|
"github.com/ultisuite/ulti-backend/internal/nextcloud"
|
|
"github.com/ultisuite/ulti-backend/internal/permission"
|
|
)
|
|
|
|
type Handler struct {
|
|
svc *Service
|
|
logger *slog.Logger
|
|
}
|
|
|
|
func NewHandler(nc *nextcloud.Client, db *pgxpool.Pool) *Handler {
|
|
return &Handler{
|
|
svc: NewService(nc, db),
|
|
logger: slog.Default().With("component", "contacts-api"),
|
|
}
|
|
}
|
|
|
|
func (h *Handler) Routes() chi.Router {
|
|
r := chi.NewRouter()
|
|
read := middleware.RequirePermission(permission.ResourceContacts, permission.LevelRead)
|
|
write := middleware.RequirePermission(permission.ResourceContacts, permission.LevelWrite)
|
|
|
|
r.With(read).Get("/books", h.ListAddressBooks)
|
|
r.With(read).Get("/books/{bookID}/sync", h.SyncContacts)
|
|
r.With(read).Get("/books/{bookID}", h.ListContacts)
|
|
r.With(read).Get("/books/{bookID}/interactions/*", h.GetContactInteractions)
|
|
r.With(read).Get("/search", h.SearchContacts)
|
|
r.With(read).Get("/interactions", h.GetInteractionsByEmail)
|
|
r.With(write).Post("/books/{bookID}", h.CreateContact)
|
|
r.With(write).Post("/books/{bookID}/merge-duplicates", h.MergeDuplicateContacts)
|
|
r.With(write).Put("/*", h.UpdateContact)
|
|
r.With(write).Delete("/*", h.DeleteContact)
|
|
return r
|
|
}
|
|
|
|
func (h *Handler) ListAddressBooks(w http.ResponseWriter, r *http.Request) {
|
|
claims := middleware.ClaimsFromContext(r.Context())
|
|
books, err := h.svc.ListAddressBooks(r.Context(), claims.Sub)
|
|
if err != nil {
|
|
h.logger.Error("list address books", "error", err)
|
|
apivalidate.WriteInternal(w, r)
|
|
return
|
|
}
|
|
apiresponse.WriteJSON(w, http.StatusOK, map[string]any{"address_books": books})
|
|
}
|
|
|
|
func (h *Handler) SyncContacts(w http.ResponseWriter, r *http.Request) {
|
|
claims := middleware.ClaimsFromContext(r.Context())
|
|
syncToken, verr := validateSyncToken(r.URL.Query().Get("sync_token"))
|
|
if verr != nil {
|
|
apivalidate.WriteValidationError(w, r, verr)
|
|
return
|
|
}
|
|
|
|
result, err := h.svc.SyncContacts(r.Context(), claims.Sub, chi.URLParam(r, "bookID"), syncToken)
|
|
if err != nil {
|
|
if errors.Is(err, nextcloud.ErrSyncTokenInvalid) {
|
|
apiresponse.WriteError(w, r, http.StatusConflict, "sync_token_invalid",
|
|
"sync token is no longer valid; omit sync_token to perform a full resync", nil)
|
|
return
|
|
}
|
|
h.logger.Error("sync contacts", "error", err)
|
|
apivalidate.WriteInternal(w, r)
|
|
return
|
|
}
|
|
apiresponse.WriteJSON(w, http.StatusOK, result)
|
|
}
|
|
|
|
func (h *Handler) ListContacts(w http.ResponseWriter, r *http.Request) {
|
|
claims := middleware.ClaimsFromContext(r.Context())
|
|
params, err := query.ParseListRequest(r)
|
|
if err != nil {
|
|
apivalidate.WriteQueryError(w, r, err)
|
|
return
|
|
}
|
|
|
|
result, err := h.svc.ListContacts(r.Context(), claims.Sub, chi.URLParam(r, "bookID"), params)
|
|
if err != nil {
|
|
h.logger.Error("list contacts", "error", err)
|
|
apivalidate.WriteInternal(w, r)
|
|
return
|
|
}
|
|
apiresponse.WriteJSON(w, http.StatusOK, result)
|
|
}
|
|
|
|
func (h *Handler) SearchContacts(w http.ResponseWriter, r *http.Request) {
|
|
claims := middleware.ClaimsFromContext(r.Context())
|
|
params, err := query.ParseListRequest(r)
|
|
if err != nil {
|
|
apivalidate.WriteQueryError(w, r, err)
|
|
return
|
|
}
|
|
|
|
bookID := r.URL.Query().Get("book_id")
|
|
if bookID == "" {
|
|
bookID = "contacts"
|
|
}
|
|
q := r.URL.Query().Get("q")
|
|
|
|
result, err := h.svc.SearchContacts(r.Context(), claims.Sub, bookID, q, params)
|
|
if err != nil {
|
|
h.logger.Error("search contacts", "error", err)
|
|
apivalidate.WriteInternal(w, r)
|
|
return
|
|
}
|
|
apiresponse.WriteJSON(w, http.StatusOK, result)
|
|
}
|
|
|
|
func (h *Handler) CreateContact(w http.ResponseWriter, r *http.Request) {
|
|
claims := middleware.ClaimsFromContext(r.Context())
|
|
|
|
var contact nextcloud.Contact
|
|
if err := apivalidate.DecodeJSON(w, r, maxRequestBody, &contact); err != nil {
|
|
return
|
|
}
|
|
if verr := validateCreateContact(&contact); verr != nil {
|
|
apivalidate.WriteValidationError(w, r, verr)
|
|
return
|
|
}
|
|
|
|
if err := h.svc.CreateContact(r.Context(), claims.Sub, chi.URLParam(r, "bookID"), &contact); err != nil {
|
|
h.logger.Error("create contact", "error", err)
|
|
apivalidate.WriteInternal(w, r)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusCreated)
|
|
}
|
|
|
|
func (h *Handler) UpdateContact(w http.ResponseWriter, r *http.Request) {
|
|
claims := middleware.ClaimsFromContext(r.Context())
|
|
contactPath := strings.TrimSuffix(chi.URLParam(r, "*"), "/")
|
|
if verr := validateDeletePath(contactPath); verr != nil {
|
|
apivalidate.WriteValidationError(w, r, verr)
|
|
return
|
|
}
|
|
ifMatch := strings.TrimSpace(r.Header.Get("If-Match"))
|
|
if verr := validateIfMatch(ifMatch); verr != nil {
|
|
apivalidate.WriteValidationError(w, r, verr)
|
|
return
|
|
}
|
|
|
|
var contact nextcloud.Contact
|
|
if err := apivalidate.DecodeJSON(w, r, maxRequestBody, &contact); err != nil {
|
|
return
|
|
}
|
|
if verr := validateCreateContact(&contact); verr != nil {
|
|
apivalidate.WriteValidationError(w, r, verr)
|
|
return
|
|
}
|
|
|
|
etag, err := h.svc.UpdateContact(r.Context(), claims.Sub, contactPath, ifMatch, &contact)
|
|
if err != nil {
|
|
if errors.Is(err, nextcloud.ErrETagMismatch) {
|
|
apiresponse.WriteError(w, r, http.StatusPreconditionFailed, "etag_mismatch", "etag does not match current resource version", nil)
|
|
return
|
|
}
|
|
h.logger.Error("update contact", "error", err)
|
|
apivalidate.WriteInternal(w, r)
|
|
return
|
|
}
|
|
apiresponse.WriteJSON(w, http.StatusOK, map[string]any{"etag": etag})
|
|
}
|
|
|
|
func (h *Handler) MergeDuplicateContacts(w http.ResponseWriter, r *http.Request) {
|
|
claims := middleware.ClaimsFromContext(r.Context())
|
|
|
|
var req MergeDuplicatesRequest
|
|
if r.ContentLength > 0 {
|
|
if err := apivalidate.DecodeJSON(w, r, maxRequestBody, &req); err != nil {
|
|
return
|
|
}
|
|
}
|
|
|
|
result, err := h.svc.MergeDuplicates(r.Context(), claims.Sub, chi.URLParam(r, "bookID"), req)
|
|
if err != nil {
|
|
h.logger.Error("merge duplicate contacts", "error", err)
|
|
apivalidate.WriteInternal(w, r)
|
|
return
|
|
}
|
|
apiresponse.WriteJSON(w, http.StatusOK, result)
|
|
}
|
|
|
|
func (h *Handler) GetInteractionsByEmail(w http.ResponseWriter, r *http.Request) {
|
|
claims := middleware.ClaimsFromContext(r.Context())
|
|
|
|
email, limit, verr := validateInteractionQuery(r.URL.Query().Get("email"), r.URL.Query().Get("limit"))
|
|
if verr != nil {
|
|
apivalidate.WriteValidationError(w, r, verr)
|
|
return
|
|
}
|
|
|
|
result, err := h.svc.ContactInteractionsByEmail(r.Context(), claims.Sub, email, limit)
|
|
if err != nil {
|
|
h.logger.Error("contact interactions by email", "error", err)
|
|
apivalidate.WriteInternal(w, r)
|
|
return
|
|
}
|
|
apiresponse.WriteJSON(w, http.StatusOK, result)
|
|
}
|
|
|
|
func (h *Handler) GetContactInteractions(w http.ResponseWriter, r *http.Request) {
|
|
claims := middleware.ClaimsFromContext(r.Context())
|
|
contactPath := strings.TrimSuffix(chi.URLParam(r, "*"), "/")
|
|
if verr := validateDeletePath(contactPath); verr != nil {
|
|
apivalidate.WriteValidationError(w, r, verr)
|
|
return
|
|
}
|
|
|
|
limit := 20
|
|
if raw := strings.TrimSpace(r.URL.Query().Get("limit")); raw != "" {
|
|
val, err := strconv.Atoi(raw)
|
|
if err != nil || val < 1 || val > 100 {
|
|
apivalidate.WriteValidationError(w, r, apivalidate.NewValidationError(apivalidate.FieldDetail{
|
|
Field: "limit", Message: "must be between 1 and 100",
|
|
}))
|
|
return
|
|
}
|
|
limit = val
|
|
}
|
|
|
|
result, err := h.svc.ContactInteractionsByPath(r.Context(), claims.Sub, contactPath, limit)
|
|
if err != nil {
|
|
if errors.Is(err, ErrContactEmailMissing) {
|
|
apivalidate.WriteValidationError(w, r, apivalidate.NewValidationError(apivalidate.FieldDetail{
|
|
Field: "email", Message: "required for enrichment",
|
|
}))
|
|
return
|
|
}
|
|
h.logger.Error("contact interactions by path", "error", err)
|
|
apivalidate.WriteInternal(w, r)
|
|
return
|
|
}
|
|
apiresponse.WriteJSON(w, http.StatusOK, result)
|
|
}
|
|
|
|
func (h *Handler) DeleteContact(w http.ResponseWriter, r *http.Request) {
|
|
claims := middleware.ClaimsFromContext(r.Context())
|
|
contactPath := chi.URLParam(r, "*")
|
|
if verr := validateDeletePath(contactPath); verr != nil {
|
|
apivalidate.WriteValidationError(w, r, verr)
|
|
return
|
|
}
|
|
if err := h.svc.DeleteContact(r.Context(), claims.Sub, contactPath); err != nil {
|
|
h.logger.Error("delete contact", "error", err)
|
|
apivalidate.WriteInternal(w, r)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|