mirror of
https://github.com/mattermost/mattermost.git
synced 2026-04-13 13:08:56 -04:00
* Add CreatedBy and UpdatedBy to the properties fields and values (#34485) * Add CreatedBy and UpdatedBy to the properties fields and values * Fix types --------- Co-authored-by: Miguel de la Cruz <miguel@ctrlz.es> * Adds ObjectType to the property fields table (#34908) Co-authored-by: Miguel de la Cruz <miguel@ctrlz.es> * Update ObjectType migration setting an empty value and marking the column as not null (#34915) Co-authored-by: Miguel de la Cruz <miguel@ctrlz.es> * Adds uniqueness mechanisms to the property fields (#35058) * Adds uniqueness mechanisms to the property fields After adding ObjectType, this commit ensures that both the PSAv1 and PSAv2 schemas are supported, and enforces property uniqueness through both database indexes and a logical check when creating new property fields. * Adds uniqueness check to property updates Updates are covered on this commit and we refactor as well the SQL code to use the squirrel builder and work better with the conditional addition of the `existingID` piece of the query. * Add translations to error messages * Fixing retrylayer mocks * Remove retrylayer duplication * Address review comments * Fix comment to avoid linter issues * Address PR comments * Update server/channels/db/migrations/postgres/000157_add_object_type_to_property_fields.down.sql Co-authored-by: Alejandro García Montoro <alejandro.garciamontoro@gmail.com> * Update server/channels/db/migrations/postgres/000157_add_object_type_to_property_fields.up.sql Co-authored-by: Alejandro García Montoro <alejandro.garciamontoro@gmail.com> * Update server/channels/db/migrations/postgres/000157_add_object_type_to_property_fields.up.sql Co-authored-by: Alejandro García Montoro <alejandro.garciamontoro@gmail.com> * Update field validation to check only for valid target types * Update migrations to avoid concurrent index creation within a transaction * Update migrations to make all index ops concurrent * Update tests to use valid PSAv2 property fields * Adds a helper for valid PSAv2 TargetTypes --------- Co-authored-by: Miguel de la Cruz <miguel@ctrlz.es> Co-authored-by: Alejandro García Montoro <alejandro.garciamontoro@gmail.com> * Fix property tests (#35388) Co-authored-by: Miguel de la Cruz <miguel@ctrlz.es> * Adds Integrated Boards feature flag (#35378) Co-authored-by: Miguel de la Cruz <miguel@ctrlz.es> * Adds Integrated Boards MVP API changes (#34822) This PR includes the necessary changes for channels and posts endpoints and adds a set of generic endpoints to retrieve and manage property fields and values following the new Property System approach. Co-authored-by: Miguel de la Cruz <miguel@ctrlz.es> Co-authored-by: Mattermost Build <build@mattermost.com> * Property System Architecture permissions for v2 (#35113) * Adds uniqueness mechanisms to the property fields After adding ObjectType, this commit ensures that both the PSAv1 and PSAv2 schemas are supported, and enforces property uniqueness through both database indexes and a logical check when creating new property fields. * Adds uniqueness check to property updates Updates are covered on this commit and we refactor as well the SQL code to use the squirrel builder and work better with the conditional addition of the `existingID` piece of the query. * Add translations to error messages * Add the permissions to the migrations, model and update the store calls * Adds the property field and property group app layer * Adds authorization helpers for property fields and values * Make sure that users cannot lock themselves out of property fields * Migrate permissions from a JSON column to three normalized columns * Remove the audit comment * Use target level constants in authorization * Log authorization membership failures * Rename admin to sysadmin * Fix i18n sorting --------- Co-authored-by: Miguel de la Cruz <miguel@ctrlz.es> * Add Views store and app layer (#35361) * Add Views store and app layer for Integrated Boards Implements the View entity (model, SQL store, service, app) as described in the Integrated Boards tech spec. Views are channel-scoped board configurations with typed props (board, kanban subviews) and soft-delete. - public/model: View, ViewBoardProps, Subview, ViewPatch types with PreSave/PreUpdate/IsValid/Patch/Clone/Auditable - Migration 158: Views table with jsonb Props column and indexes - SqlViewStore: CRUD with nil-safe Props marshaling (AppendBinaryFlag) - ViewService: CreateView seeds default kanban subview and links the boards property field; caches boardPropertyFieldID at startup - App layer: CreateView/GetView/GetViewsForChannel/UpdateView/DeleteView with channel-membership permission checks and WebSocket events (view_created, view_updated, view_deleted) - doSetupBoardsPropertyField: registers the Boards property group and board field in NewServer() before ViewService construction - GetFieldByName now returns store.ErrNotFound instead of raw sql.ErrNoRows * Move permission checks out of App layer for views - Remove HasPermissionToChannel calls from all App view methods - Drop userID params from GetView, GetViewsForChannel, UpdateView, DeleteView - Fix doSetupBoardsPropertyField to include required TargetType for PSAv2 field * Make View service generic and enforce board validation in model - Remove board-specific auto-setup from service and server startup - Enforce that board views require Props, at least one subview, and at least one linked property in IsValid() - Move default subview seeding out of app layer; callers must provide valid props - Call PreSave on subviews during PreUpdate to assign IDs to new subviews - Update all tests to reflect the new validation requirements * Restore migrations files to match base branch * Distinguish ErrNotFound from other errors in view store Get * Use CONCURRENTLY and nontransactional for index operations in views migration * Split views index creation into separate nontransactional migrations * Update migrations.list * Update i18n translations for views * Fix makeView helper to include required Props for board view validation * Rename ctx parameter from c to rctx in OAuthProvider mock * Remove views service layer, call store directly from app * Return 500 for unexpected DB errors in GetView, 404 only for not-found * Harden View model: deep-copy Props, validate linked property IDs - Add ViewBoardProps.Clone() to deep-copy LinkedProperties and Subviews - Use it in View.Clone() and View.Patch() to prevent shared-slice aliasing - Iterate over LinkedProperties in View.IsValid() and reject invalid IDs with a dedicated i18n key - Register ViewStore in storetest AssertExpectations so mock expectations are enforced - Add tests covering all new behaviours * Restore autotranslation worker_stopped i18n translation * Fix view store test IDs and improve error handling in app layer - Use model.NewId() for linked property IDs in testUpdateView to fix validation failure (IsValid rejects non-UUID strings) - Fix import grouping in app/view.go (stdlib imports in one block) - Return 404 instead of 500 when Update/Delete store calls return ErrNotFound (e.g. concurrent deletion TOCTOU race) * Add View store mock to retrylayer test genStore helper The View store was added to the store interface but the genStore() helper in retrylayer_test.go was not updated, causing TestRetry to panic. Also removes the duplicate Recap mock registration. * Refactor view deletion and websocket event handling; update SQL store methods to use query builder * revert property field store * Remove useless migrations * Add cursor-based pagination to View store GetForChannel - Add ViewQueryCursor and ViewQueryOpts types with validation - Return (views, cursor, error) for caller-driven pagination - PerPage clamping: <=0 defaults to 20, >200 clamps to 200 - Support IncludeDeleted filter - Add comprehensive store tests for pagination, cursor edge cases, PerPage clamping, and invalid input rejection - Add app layer test for empty channelID → 400 - Update interface, retrylayer, timerlayer, and mock signatures Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Refactor test loops in ViewStore tests for improved readability * change pagination to limit/offset * Add upper-bound limits on View Subviews and LinkedProperties Defense-in-depth validation: cap Subviews at 50 and LinkedProperties at 500 to prevent abuse below the 300KB payload limit. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> * MM-67388, MM-66528, MM-67750: Add View REST API endpoints, websocket events, and sort order (#35442) * Add Views store and app layer for Integrated Boards Implements the View entity (model, SQL store, service, app) as described in the Integrated Boards tech spec. Views are channel-scoped board configurations with typed props (board, kanban subviews) and soft-delete. - public/model: View, ViewBoardProps, Subview, ViewPatch types with PreSave/PreUpdate/IsValid/Patch/Clone/Auditable - Migration 158: Views table with jsonb Props column and indexes - SqlViewStore: CRUD with nil-safe Props marshaling (AppendBinaryFlag) - ViewService: CreateView seeds default kanban subview and links the boards property field; caches boardPropertyFieldID at startup - App layer: CreateView/GetView/GetViewsForChannel/UpdateView/DeleteView with channel-membership permission checks and WebSocket events (view_created, view_updated, view_deleted) - doSetupBoardsPropertyField: registers the Boards property group and board field in NewServer() before ViewService construction - GetFieldByName now returns store.ErrNotFound instead of raw sql.ErrNoRows * Move permission checks out of App layer for views - Remove HasPermissionToChannel calls from all App view methods - Drop userID params from GetView, GetViewsForChannel, UpdateView, DeleteView - Fix doSetupBoardsPropertyField to include required TargetType for PSAv2 field * Make View service generic and enforce board validation in model - Remove board-specific auto-setup from service and server startup - Enforce that board views require Props, at least one subview, and at least one linked property in IsValid() - Move default subview seeding out of app layer; callers must provide valid props - Call PreSave on subviews during PreUpdate to assign IDs to new subviews - Update all tests to reflect the new validation requirements * Restore migrations files to match base branch * Distinguish ErrNotFound from other errors in view store Get * Use CONCURRENTLY and nontransactional for index operations in views migration * Split views index creation into separate nontransactional migrations * Update migrations.list * Update i18n translations for views * Fix makeView helper to include required Props for board view validation * Rename ctx parameter from c to rctx in OAuthProvider mock * Remove views service layer, call store directly from app * Return 500 for unexpected DB errors in GetView, 404 only for not-found * Harden View model: deep-copy Props, validate linked property IDs - Add ViewBoardProps.Clone() to deep-copy LinkedProperties and Subviews - Use it in View.Clone() and View.Patch() to prevent shared-slice aliasing - Iterate over LinkedProperties in View.IsValid() and reject invalid IDs with a dedicated i18n key - Register ViewStore in storetest AssertExpectations so mock expectations are enforced - Add tests covering all new behaviours * Restore autotranslation worker_stopped i18n translation * Fix view store test IDs and improve error handling in app layer - Use model.NewId() for linked property IDs in testUpdateView to fix validation failure (IsValid rejects non-UUID strings) - Fix import grouping in app/view.go (stdlib imports in one block) - Return 404 instead of 500 when Update/Delete store calls return ErrNotFound (e.g. concurrent deletion TOCTOU race) * Add View store mock to retrylayer test genStore helper The View store was added to the store interface but the genStore() helper in retrylayer_test.go was not updated, causing TestRetry to panic. Also removes the duplicate Recap mock registration. * Refactor view deletion and websocket event handling; update SQL store methods to use query builder * revert property field store * Add View API endpoints with OpenAPI spec, client methods, and i18n Implement REST API for channel views (board-type) behind the IntegratedBoards feature flag. Adds CRUD endpoints under /api/v4/channels/{channel_id}/views with permission checks matching the channel bookmark pattern. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Remove useless migrations * Add cursor-based pagination to View store GetForChannel - Add ViewQueryCursor and ViewQueryOpts types with validation - Return (views, cursor, error) for caller-driven pagination - PerPage clamping: <=0 defaults to 20, >200 clamps to 200 - Support IncludeDeleted filter - Add comprehensive store tests for pagination, cursor edge cases, PerPage clamping, and invalid input rejection - Add app layer test for empty channelID → 400 - Update interface, retrylayer, timerlayer, and mock signatures Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Add cursor-based pagination to View API for channel views * Enhance cursor handling in getViewsForChannel and update tests for pagination * Refactor test loops in ViewStore tests for improved readability * Refactor loop in TestGetViewsForChannel for improved readability * change pagination to limit/offset * switch to limit/offset pagination * Add upper-bound limits on View Subviews and LinkedProperties Defense-in-depth validation: cap Subviews at 50 and LinkedProperties at 500 to prevent abuse below the 300KB payload limit. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Add view sort order API endpoint Add POST /api/v4/channels/{channel_id}/views/{view_id}/sort_order endpoint following the channel bookmarks reorder pattern. Includes store, app, and API layers with full test coverage at each layer. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Add connectionId to view WebSocket events and sort_order API spec Thread connectionId from request header through all view handlers (create, update, delete, sort_order) to WebSocket events, matching the channel bookmarks pattern. Add sort_order endpoint to OpenAPI spec. Update minimum server version to 11.6. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Remove duplicate View/ViewPatch definitions from definitions.yaml The merge from integrated-boards-mvp introduced duplicate View and ViewPatch schema definitions that were already defined earlier in the file with more detail (including ViewBoardProps ref and enums). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Update minimum server version to 11.6 in views API spec Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Add missing translations for view sort order error messages Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Merge integrated-boards-mvp into ibmvp_api-views; remove spec files Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Fix flaky TestViewStore timestamp test on CI Add sleep before UpdateSortOrder to ensure timestamps differ, preventing same-millisecond comparisons on fast CI machines. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * remove duplicate views.yaml imclude * Use c.boolString() for include_deleted query param in GetViewsForChannel Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Fix views.yaml sort order schema: use integer type and require body Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Refactor view sort order tests to use named IDs instead of array indices Extract idA/idB/idC from views slice and add BEFORE/AFTER comments to make stateful subtest ordering easier to follow. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Return 404 instead of 403 for view operations on deleted channels Deleted channels should appear non-existent to callers rather than revealing their existence via a 403. Detailed error text explains the context for debugging. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * add missing channel deleteat checks * Use c.Params.Page instead of manual page query param parsing in getViewsForChannel c.Params already validates and defaults page/per_page, so the manual parsing was redundant. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Add support for total count in views retrieval * Add tests for handling deleted views in GetViewsForChannel and GetView * Short-circuit negative newIndex in UpdateSortOrder before opening transaction Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Add per-channel limit on views to bound UpdateSortOrder cost Without a cap, unbounded view creation makes sort-order updates increasingly expensive (CASE WHEN per view, row locks). Adds MaxViewsPerChannel=50 constant and enforces it in the app layer before saving. Includes API and app layer tests. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Remove include_deleted support from views API Soft-deleted views are structural metadata with low risk, but no other similar endpoint (e.g. channel bookmarks) exposes deleted records without an admin gate. Rather than adding an admin-only permission check for consistency, remove the feature entirely since there is no current use case. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Update view permissions to require `create_post` instead of channel management permissions * Remove obsolete view management error messages for direct and group messages --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> * feat(migrations): add user tracking and object type to property fields - Introduced user tracking columns (CreatedBy, UpdatedBy) to PropertyFields and PropertyValues. - Added ObjectType column to PropertyFields with associated unique indexes for legacy and typed properties. - Created new migration scripts for adding and dropping these features, including necessary indexes for data integrity. - Established views for managing property fields with new attributes. This update enhances the schema to support better tracking and categorization of property fields. * Add Property System Architecture v2 API endpoints (#35583) * Adds uniqueness mechanisms to the property fields After adding ObjectType, this commit ensures that both the PSAv1 and PSAv2 schemas are supported, and enforces property uniqueness through both database indexes and a logical check when creating new property fields. * Adds uniqueness check to property updates Updates are covered on this commit and we refactor as well the SQL code to use the squirrel builder and work better with the conditional addition of the `existingID` piece of the query. * Add translations to error messages * Add the permissions to the migrations, model and update the store calls * Adds the property field and property group app layer * Adds authorization helpers for property fields and values * Make sure that users cannot lock themselves out of property fields * Migrate permissions from a JSON column to three normalized columns * Remove the audit comment * Use target level constants in authorization * Log authorization membership failures * Rename admin to sysadmin * Adds the Property System Architecture v2 API endpoints * Adds permission checks to the create field endpoint * Add target access checks to value endpoints * Add default branches for object_type and target_type and extra guards for cursor client4 methods * Fix vet API mismatch * Fix error checks * Fix linter * Add merge semantics for property patch logic and API endpoint * Fix i18n * Fix duplicated patch elements and early return on bad cursor * Update docs to use enums * Fix i18n sorting * Update app layer to return model.AppError * Adds a limit to the number of property values that can be patched in the same request * Require target_type filter when searching property fields * Add objectType validation as part of field.IsValid() * Fix linter * Fix test with bad objecttpye * Fix test grouping --------- Co-authored-by: Miguel de la Cruz <miguel@ctrlz.es> * MM-67968: Flatten view model — remove icon, subviews, typed board props (#35726) * feat(views): flatten view model by removing icon, subview, and board props Simplifies the View data model as part of MM-67968: removes Icon, Subview, and ViewBoardProps types; renames ViewTypeBoard to ViewTypeKanban; replaces typed Props with StringInterface (map[string]any); adds migration 000167 to drop the Icon column from the Views table. Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * feat(api): update views OpenAPI spec to reflect flattened model Removes ViewBoardProps, Subview, and icon from the View and ViewPatch schemas. Changes type enum from board to kanban. Replaces typed props with a free-form StringInterface object. Aligns with MM-67968. Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * refactor(views): simplify store by dropping dbView and marshalViewProps StringInterface already implements driver.Valuer and sql.Scanner, so the manual JSON marshal/unmarshal and the dbView intermediate struct were redundant. model.View now scans directly from the database. Also removes the dead ViewMaxLinkedProperties constant and wraps the Commit() error in UpdateSortOrder. Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * fix(api): allow arbitrary JSON in view props OpenAPI schema The props field was restricted to string values via additionalProperties: { type: string }, conflicting with the Go model's StringInterface (map[string]any). Changed to additionalProperties: true in View, ViewPatch, and inline POST schemas. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * Adds basic implementation of the generic redux store for PSAv2 (#35512) * Adds basic implementation of the generic redux store for PSAv2 * Add created_by and updated_by to the test fixtures * Make target_id, target_type and object_type mandatory * Wrap getPropertyFieldsByIds and getPropertyValuesForTargetByFieldIds with createSelector * Address PR comments --------- Co-authored-by: Miguel de la Cruz <miguel@ctrlz.es> * Adds websocket messages for the PSAv2 API events (#35696) * Adds uniqueness mechanisms to the property fields After adding ObjectType, this commit ensures that both the PSAv1 and PSAv2 schemas are supported, and enforces property uniqueness through both database indexes and a logical check when creating new property fields. * Adds uniqueness check to property updates Updates are covered on this commit and we refactor as well the SQL code to use the squirrel builder and work better with the conditional addition of the `existingID` piece of the query. * Add translations to error messages * Add the permissions to the migrations, model and update the store calls * Adds the property field and property group app layer * Adds authorization helpers for property fields and values * Make sure that users cannot lock themselves out of property fields * Migrate permissions from a JSON column to three normalized columns * Remove the audit comment * Use target level constants in authorization * Log authorization membership failures * Rename admin to sysadmin * Adds the Property System Architecture v2 API endpoints * Adds permission checks to the create field endpoint * Add target access checks to value endpoints * Add default branches for object_type and target_type and extra guards for cursor client4 methods * Fix vet API mismatch * Fix error checks * Fix linter * Add merge semantics for property patch logic and API endpoint * Fix i18n * Fix duplicated patch elements and early return on bad cursor * Update docs to use enums * Fix i18n sorting * Update app layer to return model.AppError * Adds a limit to the number of property values that can be patched in the same request * Adds websocket messages for the PSAv2 API events * Add IsPSAv2 helper to the property field for clarity * Add guard against nil returns on field deletion * Add docs to the websocket endpoints --------- Co-authored-by: Miguel de la Cruz <miguel@ctrlz.es> * migrations: consolidate views migrations and reorder after master - Merged 000165 (create Views) with 000167 (drop Icon) since Icon was never needed - Renumbered branch migrations 159-166 → 160-167 so master's 000159 (deduplicate_policy_names) runs first - Regenerated migrations.list Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * Add API endpoint to retrieve posts for a specific view (#35604) Automatic Merge * Apply fixes after merge * Return a more specific error from getting multiple fields * Prevent getting broadcast params on field deletion if not needed * Remove duplicated migration code * Update property conflict code to always use master * Adds nil guard when iterating on property fields * Check that permission level is valid before getting rejected by the database * Validate correctness on TargetID for PSAv2 fields * Avoid PSAv1 using permissions or protected * Fix test data after validation change * Fix flaky search test * Adds more posts for filter use cases to properly test exclusions --------- Co-authored-by: Miguel de la Cruz <miguel@ctrlz.es> Co-authored-by: Alejandro García Montoro <alejandro.garciamontoro@gmail.com> Co-authored-by: Julien Tant <julien@craftyx.fr> Co-authored-by: Mattermost Build <build@mattermost.com> Co-authored-by: Julien Tant <785518+JulienTant@users.noreply.github.com> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
583 lines
21 KiB
Go
583 lines
21 KiB
Go
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
|
// See LICENSE.txt for license information.
|
|
|
|
package model
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"slices"
|
|
"unicode/utf8"
|
|
)
|
|
|
|
type PropertyFieldType string
|
|
|
|
// PropertyFieldTargetLevel represents the hierarchy level of a property field.
|
|
// Used both for TargetType field values and for conflict detection results.
|
|
type PropertyFieldTargetLevel string
|
|
|
|
// PermissionLevel represents the access level for property field operations
|
|
type PermissionLevel string
|
|
|
|
const (
|
|
PropertyFieldTypeText PropertyFieldType = "text"
|
|
PropertyFieldTypeSelect PropertyFieldType = "select"
|
|
PropertyFieldTypeMultiselect PropertyFieldType = "multiselect"
|
|
PropertyFieldTypeDate PropertyFieldType = "date"
|
|
PropertyFieldTypeUser PropertyFieldType = "user"
|
|
PropertyFieldTypeMultiuser PropertyFieldType = "multiuser"
|
|
|
|
PropertyFieldNameMaxRunes = 255
|
|
PropertyFieldTargetIDMaxRunes = 255
|
|
PropertyFieldTargetTypeMaxRunes = 255
|
|
PropertyFieldObjectTypeMaxRunes = 255
|
|
|
|
PropertyFieldTargetLevelSystem PropertyFieldTargetLevel = "system"
|
|
PropertyFieldTargetLevelTeam PropertyFieldTargetLevel = "team"
|
|
PropertyFieldTargetLevelChannel PropertyFieldTargetLevel = "channel"
|
|
|
|
PermissionLevelNone PermissionLevel = "none"
|
|
PermissionLevelSysadmin PermissionLevel = "sysadmin"
|
|
PermissionLevelMember PermissionLevel = "member"
|
|
|
|
PropertyFieldObjectTypePost = "post"
|
|
PropertyFieldObjectTypeChannel = "channel"
|
|
PropertyFieldObjectTypeUser = "user"
|
|
)
|
|
|
|
// validPermissionLevels contains all valid PermissionLevel values.
|
|
var validPermissionLevels = []PermissionLevel{PermissionLevelNone, PermissionLevelSysadmin, PermissionLevelMember}
|
|
|
|
// validPSAv2TargetTypes contains all valid TargetType values for PSAv2 properties.
|
|
var validPSAv2TargetTypes = []string{
|
|
string(PropertyFieldTargetLevelSystem),
|
|
string(PropertyFieldTargetLevelTeam),
|
|
string(PropertyFieldTargetLevelChannel),
|
|
}
|
|
|
|
// validPropertyFieldObjectTypes contains all valid ObjectType values for PSAv2 properties.
|
|
var validPropertyFieldObjectTypes = []string{
|
|
PropertyFieldObjectTypePost,
|
|
PropertyFieldObjectTypeChannel,
|
|
PropertyFieldObjectTypeUser,
|
|
}
|
|
|
|
type PropertyField struct {
|
|
ID string `json:"id"`
|
|
GroupID string `json:"group_id"`
|
|
Name string `json:"name"`
|
|
Type PropertyFieldType `json:"type"`
|
|
Attrs StringInterface `json:"attrs"`
|
|
TargetID string `json:"target_id"`
|
|
TargetType string `json:"target_type"`
|
|
ObjectType string `json:"object_type"`
|
|
Protected bool `json:"protected"`
|
|
PermissionField *PermissionLevel `json:"permission_field,omitempty"`
|
|
PermissionValues *PermissionLevel `json:"permission_values,omitempty"`
|
|
PermissionOptions *PermissionLevel `json:"permission_options,omitempty"`
|
|
CreateAt int64 `json:"create_at"`
|
|
UpdateAt int64 `json:"update_at"`
|
|
DeleteAt int64 `json:"delete_at"`
|
|
CreatedBy string `json:"created_by"`
|
|
UpdatedBy string `json:"updated_by"`
|
|
}
|
|
|
|
func (pf *PropertyField) Auditable() map[string]any {
|
|
return map[string]any{
|
|
"id": pf.ID,
|
|
"group_id": pf.GroupID,
|
|
"name": pf.Name,
|
|
"type": pf.Type,
|
|
"attrs": pf.Attrs,
|
|
"target_id": pf.TargetID,
|
|
"target_type": pf.TargetType,
|
|
"object_type": pf.ObjectType,
|
|
"protected": pf.Protected,
|
|
"permission_field": pf.PermissionField,
|
|
"permission_values": pf.PermissionValues,
|
|
"permission_options": pf.PermissionOptions,
|
|
"create_at": pf.CreateAt,
|
|
"update_at": pf.UpdateAt,
|
|
"delete_at": pf.DeleteAt,
|
|
"created_by": pf.CreatedBy,
|
|
"updated_by": pf.UpdatedBy,
|
|
}
|
|
}
|
|
|
|
// PreSave will set the Id if missing. It will also fill in the CreateAt, UpdateAt
|
|
// times and ensure DeleteAt is 0. It should be run before saving the field to the db.
|
|
func (pf *PropertyField) PreSave() {
|
|
if pf.ID == "" {
|
|
pf.ID = NewId()
|
|
}
|
|
|
|
pf.CreateAt = GetMillis()
|
|
pf.UpdateAt = pf.CreateAt
|
|
pf.DeleteAt = 0
|
|
}
|
|
|
|
// EnsureOptionIDs generates IDs for any options that don't have them in select/multiselect fields.
|
|
// This ensures option IDs are always set, similar to how field IDs are auto-generated.
|
|
func (pf *PropertyField) EnsureOptionIDs() error {
|
|
if pf.Type != PropertyFieldTypeSelect && pf.Type != PropertyFieldTypeMultiselect {
|
|
return nil
|
|
}
|
|
|
|
if pf.Attrs == nil {
|
|
return nil
|
|
}
|
|
|
|
optionsRaw, ok := pf.Attrs[PropertyFieldAttributeOptions]
|
|
if !ok {
|
|
return nil
|
|
}
|
|
|
|
// Normalize with JSON to handle any slice type
|
|
optionsBytes, err := json.Marshal(optionsRaw)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to marshal options for field ID %s: %w", pf.ID, err)
|
|
}
|
|
|
|
var options []map[string]any
|
|
if err := json.Unmarshal(optionsBytes, &options); err != nil {
|
|
return fmt.Errorf("invalid options format for field ID %s: %w", pf.ID, err)
|
|
}
|
|
|
|
for _, optMap := range options {
|
|
if id, ok := optMap["id"].(string); !ok || id == "" {
|
|
optMap["id"] = NewId()
|
|
}
|
|
}
|
|
|
|
// Convert back to []any to maintain type compatibility
|
|
optionsAny := make([]any, len(options))
|
|
for i, opt := range options {
|
|
optionsAny[i] = opt
|
|
}
|
|
pf.Attrs[PropertyFieldAttributeOptions] = optionsAny
|
|
|
|
return nil
|
|
}
|
|
|
|
func (pf *PropertyField) IsValid() error {
|
|
if !IsValidId(pf.ID) {
|
|
return NewAppError("PropertyField.IsValid", "model.property_field.is_valid.app_error", map[string]any{"FieldName": "id", "Reason": "invalid id"}, "", http.StatusBadRequest)
|
|
}
|
|
|
|
if !IsValidId(pf.GroupID) {
|
|
return NewAppError("PropertyField.IsValid", "model.property_field.is_valid.app_error", map[string]any{"FieldName": "group_id", "Reason": "invalid id"}, "id="+pf.ID, http.StatusBadRequest)
|
|
}
|
|
|
|
if pf.Name == "" {
|
|
return NewAppError("PropertyField.IsValid", "model.property_field.is_valid.app_error", map[string]any{"FieldName": "name", "Reason": "value cannot be empty"}, "id="+pf.ID, http.StatusBadRequest)
|
|
}
|
|
|
|
if utf8.RuneCountInString(pf.Name) > PropertyFieldNameMaxRunes {
|
|
return NewAppError("PropertyField.IsValid", "model.property_field.is_valid.app_error", map[string]any{"FieldName": "name", "Reason": "value exceeds maximum length"}, "id="+pf.ID, http.StatusBadRequest)
|
|
}
|
|
|
|
if utf8.RuneCountInString(pf.TargetType) > PropertyFieldTargetTypeMaxRunes {
|
|
return NewAppError("PropertyField.IsValid", "model.property_field.is_valid.app_error", map[string]any{"FieldName": "target_type", "Reason": "value exceeds maximum length"}, "id="+pf.ID, http.StatusBadRequest)
|
|
}
|
|
|
|
if utf8.RuneCountInString(pf.TargetID) > PropertyFieldTargetIDMaxRunes {
|
|
return NewAppError("PropertyField.IsValid", "model.property_field.is_valid.app_error", map[string]any{"FieldName": "target_id", "Reason": "value exceeds maximum length"}, "id="+pf.ID, http.StatusBadRequest)
|
|
}
|
|
|
|
if utf8.RuneCountInString(pf.ObjectType) > PropertyFieldObjectTypeMaxRunes {
|
|
return NewAppError("PropertyField.IsValid", "model.property_field.is_valid.app_error", map[string]any{"FieldName": "object_type", "Reason": "value exceeds maximum length"}, "id="+pf.ID, http.StatusBadRequest)
|
|
}
|
|
|
|
// PSAv2-specific validations: ObjectType, TargetType, and TargetType/TargetID consistency
|
|
if pf.IsPSAv2() {
|
|
if !IsValidPropertyFieldObjectType(pf.ObjectType) {
|
|
return NewAppError("PropertyField.IsValid", "model.property_field.is_valid.app_error", map[string]any{"FieldName": "object_type", "Reason": "unknown value"}, "id="+pf.ID, http.StatusBadRequest)
|
|
}
|
|
|
|
if !IsValidPSAv2PropertyFieldTargetType(pf.TargetType) {
|
|
return NewAppError("PropertyField.IsValid", "model.property_field.is_valid.app_error", map[string]any{"FieldName": "target_type", "Reason": "unknown value"}, "id="+pf.ID, http.StatusBadRequest)
|
|
}
|
|
|
|
switch pf.TargetType {
|
|
case string(PropertyFieldTargetLevelSystem):
|
|
if pf.TargetID != "" {
|
|
return NewAppError("PropertyField.IsValid", "model.property_field.is_valid.app_error", map[string]any{"FieldName": "target_id", "Reason": "must be empty for system target type"}, "id="+pf.ID, http.StatusBadRequest)
|
|
}
|
|
case string(PropertyFieldTargetLevelTeam), string(PropertyFieldTargetLevelChannel):
|
|
if !IsValidId(pf.TargetID) {
|
|
return NewAppError("PropertyField.IsValid", "model.property_field.is_valid.app_error", map[string]any{"FieldName": "target_id", "Reason": "must be a valid ID for team or channel target type"}, "id="+pf.ID, http.StatusBadRequest)
|
|
}
|
|
}
|
|
} else {
|
|
// PSAv1 properties cannot have permissions or be protected
|
|
if pf.Protected {
|
|
return NewAppError("PropertyField.IsValid", "model.property_field.is_valid.app_error", map[string]any{"FieldName": "protected", "Reason": "PSAv1 properties cannot be protected"}, "id="+pf.ID, http.StatusBadRequest)
|
|
}
|
|
|
|
if pf.PermissionField != nil {
|
|
return NewAppError("PropertyField.IsValid", "model.property_field.is_valid.app_error", map[string]any{"FieldName": "permission_field", "Reason": "PSAv1 properties cannot have permissions"}, "id="+pf.ID, http.StatusBadRequest)
|
|
}
|
|
|
|
if pf.PermissionValues != nil {
|
|
return NewAppError("PropertyField.IsValid", "model.property_field.is_valid.app_error", map[string]any{"FieldName": "permission_values", "Reason": "PSAv1 properties cannot have permissions"}, "id="+pf.ID, http.StatusBadRequest)
|
|
}
|
|
|
|
if pf.PermissionOptions != nil {
|
|
return NewAppError("PropertyField.IsValid", "model.property_field.is_valid.app_error", map[string]any{"FieldName": "permission_options", "Reason": "PSAv1 properties cannot have permissions"}, "id="+pf.ID, http.StatusBadRequest)
|
|
}
|
|
}
|
|
|
|
if pf.Type != PropertyFieldTypeText &&
|
|
pf.Type != PropertyFieldTypeSelect &&
|
|
pf.Type != PropertyFieldTypeMultiselect &&
|
|
pf.Type != PropertyFieldTypeDate &&
|
|
pf.Type != PropertyFieldTypeUser &&
|
|
pf.Type != PropertyFieldTypeMultiuser {
|
|
return NewAppError("PropertyField.IsValid", "model.property_field.is_valid.app_error", map[string]any{"FieldName": "type", "Reason": "unknown value"}, "id="+pf.ID, http.StatusBadRequest)
|
|
}
|
|
|
|
if pf.CreateAt == 0 {
|
|
return NewAppError("PropertyField.IsValid", "model.property_field.is_valid.app_error", map[string]any{"FieldName": "create_at", "Reason": "value cannot be zero"}, "id="+pf.ID, http.StatusBadRequest)
|
|
}
|
|
|
|
if pf.UpdateAt == 0 {
|
|
return NewAppError("PropertyField.IsValid", "model.property_field.is_valid.app_error", map[string]any{"FieldName": "update_at", "Reason": "value cannot be zero"}, "id="+pf.ID, http.StatusBadRequest)
|
|
}
|
|
|
|
if pf.PermissionField != nil && !slices.Contains(validPermissionLevels, *pf.PermissionField) {
|
|
return NewAppError("PropertyField.IsValid", "model.property_field.is_valid.app_error", map[string]any{"FieldName": "permission_field", "Reason": "invalid permission level"}, "id="+pf.ID, http.StatusBadRequest)
|
|
}
|
|
|
|
if pf.PermissionValues != nil && !slices.Contains(validPermissionLevels, *pf.PermissionValues) {
|
|
return NewAppError("PropertyField.IsValid", "model.property_field.is_valid.app_error", map[string]any{"FieldName": "permission_values", "Reason": "invalid permission level"}, "id="+pf.ID, http.StatusBadRequest)
|
|
}
|
|
|
|
if pf.PermissionOptions != nil && !slices.Contains(validPermissionLevels, *pf.PermissionOptions) {
|
|
return NewAppError("PropertyField.IsValid", "model.property_field.is_valid.app_error", map[string]any{"FieldName": "permission_options", "Reason": "invalid permission level"}, "id="+pf.ID, http.StatusBadRequest)
|
|
}
|
|
|
|
// Cross-validation: protected fields must have field permission set to "none"
|
|
if pf.Protected {
|
|
if pf.PermissionField == nil {
|
|
return NewAppError("PropertyField.IsValid", "model.property_field.is_valid.app_error", map[string]any{"FieldName": "permission_field", "Reason": "protected fields must have explicit permissions with field set to none"}, "id="+pf.ID, http.StatusBadRequest)
|
|
}
|
|
if *pf.PermissionField != PermissionLevelNone {
|
|
return NewAppError("PropertyField.IsValid", "model.property_field.is_valid.app_error", map[string]any{"FieldName": "permission_field", "Reason": "protected fields must have field permission set to none"}, "id="+pf.ID, http.StatusBadRequest)
|
|
}
|
|
}
|
|
|
|
// Cross-validation: non-protected fields cannot have field permission set to "none"
|
|
if !pf.Protected && pf.PermissionField != nil && *pf.PermissionField == PermissionLevelNone {
|
|
return NewAppError("PropertyField.IsValid", "model.property_field.is_valid.app_error", map[string]any{"FieldName": "permission_field", "Reason": "non-protected fields cannot have field permission set to none"}, "id="+pf.ID, http.StatusBadRequest)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
type PropertyFieldPatch struct {
|
|
Name *string `json:"name"`
|
|
Type *PropertyFieldType `json:"type"`
|
|
Attrs *StringInterface `json:"attrs"`
|
|
TargetID *string `json:"target_id"`
|
|
TargetType *string `json:"target_type"`
|
|
}
|
|
|
|
func (pfp *PropertyFieldPatch) Auditable() map[string]any {
|
|
return map[string]any{
|
|
"name": pfp.Name,
|
|
"type": pfp.Type,
|
|
"attrs": pfp.Attrs,
|
|
"target_id": pfp.TargetID,
|
|
"target_type": pfp.TargetType,
|
|
}
|
|
}
|
|
|
|
func (pfp *PropertyFieldPatch) IsValid() error {
|
|
if pfp.Name != nil && *pfp.Name == "" {
|
|
return NewAppError("PropertyFieldPatch.IsValid", "model.property_field.is_valid.app_error", map[string]any{"FieldName": "name", "Reason": "value cannot be empty"}, "", http.StatusBadRequest)
|
|
}
|
|
|
|
if pfp.Name != nil && utf8.RuneCountInString(*pfp.Name) > PropertyFieldNameMaxRunes {
|
|
return NewAppError("PropertyFieldPatch.IsValid", "model.property_field.is_valid.app_error", map[string]any{"FieldName": "name", "Reason": "value exceeds maximum length"}, "", http.StatusBadRequest)
|
|
}
|
|
|
|
if pfp.TargetType != nil && utf8.RuneCountInString(*pfp.TargetType) > PropertyFieldTargetTypeMaxRunes {
|
|
return NewAppError("PropertyFieldPatch.IsValid", "model.property_field.is_valid.app_error", map[string]any{"FieldName": "target_type", "Reason": "value exceeds maximum length"}, "", http.StatusBadRequest)
|
|
}
|
|
|
|
if pfp.TargetID != nil && utf8.RuneCountInString(*pfp.TargetID) > PropertyFieldTargetIDMaxRunes {
|
|
return NewAppError("PropertyFieldPatch.IsValid", "model.property_field.is_valid.app_error", map[string]any{"FieldName": "target_id", "Reason": "value exceeds maximum length"}, "", http.StatusBadRequest)
|
|
}
|
|
|
|
if pfp.Type != nil &&
|
|
*pfp.Type != PropertyFieldTypeText &&
|
|
*pfp.Type != PropertyFieldTypeSelect &&
|
|
*pfp.Type != PropertyFieldTypeMultiselect &&
|
|
*pfp.Type != PropertyFieldTypeDate &&
|
|
*pfp.Type != PropertyFieldTypeUser &&
|
|
*pfp.Type != PropertyFieldTypeMultiuser {
|
|
return NewAppError("PropertyFieldPatch.IsValid", "model.property_field.is_valid.app_error", map[string]any{"FieldName": "type", "Reason": "unknown value"}, "", http.StatusBadRequest)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// Patch applies a PropertyFieldPatch to the field. When mergeAttrs is true,
|
|
// only the keys present in the patch are updated in Attrs, with nil values
|
|
// deleting keys. When false, Attrs is replaced wholesale.
|
|
func (pf *PropertyField) Patch(patch *PropertyFieldPatch, mergeAttrs bool) {
|
|
if patch.Name != nil {
|
|
pf.Name = *patch.Name
|
|
}
|
|
|
|
if patch.Type != nil {
|
|
pf.Type = *patch.Type
|
|
}
|
|
|
|
if patch.Attrs != nil {
|
|
if mergeAttrs {
|
|
if pf.Attrs == nil {
|
|
pf.Attrs = make(StringInterface)
|
|
}
|
|
for key, value := range *patch.Attrs {
|
|
if value == nil {
|
|
delete(pf.Attrs, key)
|
|
} else {
|
|
pf.Attrs[key] = value
|
|
}
|
|
}
|
|
} else {
|
|
pf.Attrs = *patch.Attrs
|
|
}
|
|
}
|
|
|
|
if patch.TargetID != nil {
|
|
pf.TargetID = *patch.TargetID
|
|
}
|
|
|
|
if patch.TargetType != nil {
|
|
pf.TargetType = *patch.TargetType
|
|
}
|
|
}
|
|
|
|
// IsPSAv1 returns true if this property field uses the legacy PSAv1 schema.
|
|
// Legacy properties have an empty ObjectType and rely on simple TargetID uniqueness
|
|
// enforced by the idx_propertyfields_unique_legacy database constraint, rather than
|
|
// the hierarchical uniqueness model used by PSAv2 (ObjectType-based) properties.
|
|
func (pf *PropertyField) IsPSAv1() bool {
|
|
return pf.ObjectType == ""
|
|
}
|
|
|
|
// IsPSAv2 returns true if this property field uses the PSAv2 schema.
|
|
// PSAv2 properties have a non-empty ObjectType and use hierarchical
|
|
// uniqueness based on ObjectType, TargetType, and TargetID.
|
|
func (pf *PropertyField) IsPSAv2() bool {
|
|
return pf.ObjectType != ""
|
|
}
|
|
|
|
// IsValidPSAv2PropertyFieldTargetType checks if the given TargetType string is a valid
|
|
// PSAv2 target level
|
|
func IsValidPSAv2PropertyFieldTargetType(targetType string) bool {
|
|
return slices.Contains(validPSAv2TargetTypes, targetType)
|
|
}
|
|
|
|
// IsValidPropertyFieldObjectType checks if the given ObjectType string is a valid
|
|
// property field object type
|
|
func IsValidPropertyFieldObjectType(objectType string) bool {
|
|
return slices.Contains(validPropertyFieldObjectTypes, objectType)
|
|
}
|
|
|
|
type PropertyFieldSearchCursor struct {
|
|
PropertyFieldID string
|
|
CreateAt int64
|
|
}
|
|
|
|
func (p PropertyFieldSearchCursor) IsEmpty() bool {
|
|
return p.PropertyFieldID == "" && p.CreateAt == 0
|
|
}
|
|
|
|
func (p PropertyFieldSearchCursor) IsValid() error {
|
|
if p.IsEmpty() {
|
|
return nil
|
|
}
|
|
|
|
if p.CreateAt <= 0 {
|
|
return errors.New("create at cannot be negative or zero")
|
|
}
|
|
|
|
if !IsValidId(p.PropertyFieldID) {
|
|
return errors.New("property field id is invalid")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// PropertyFieldSearch captures the parameters provided by a client for
|
|
// searching property fields
|
|
type PropertyFieldSearch struct {
|
|
TargetType string `json:"target_type,omitempty"`
|
|
TargetID string `json:"target_id,omitempty"`
|
|
CursorID string `json:"cursor_id,omitempty"`
|
|
CursorCreateAt int64 `json:"cursor_create_at,omitempty"`
|
|
PerPage int `json:"per_page"`
|
|
}
|
|
|
|
type PropertyFieldSearchOpts struct {
|
|
GroupID string
|
|
ObjectType string
|
|
TargetType string
|
|
TargetIDs []string
|
|
SinceUpdateAt int64 // UpdatedAt after which to send the items
|
|
IncludeDeleted bool
|
|
Cursor PropertyFieldSearchCursor
|
|
PerPage int
|
|
}
|
|
|
|
func (pf *PropertyField) GetAttr(key string) any {
|
|
return pf.Attrs[key]
|
|
}
|
|
|
|
const PropertyFieldAttributeOptions = "options"
|
|
|
|
type PropertyOption interface {
|
|
GetID() string
|
|
GetName() string
|
|
SetID(id string)
|
|
IsValid() error
|
|
}
|
|
|
|
type PropertyOptions[T PropertyOption] []T
|
|
|
|
func NewPropertyOptionsFromFieldAttrs[T PropertyOption](optionsArr any) (PropertyOptions[T], error) {
|
|
options := PropertyOptions[T]{}
|
|
b, err := json.Marshal(optionsArr)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to marshal options: %w", err)
|
|
}
|
|
|
|
err = json.Unmarshal(b, &options)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to unmarshal options: %w", err)
|
|
}
|
|
|
|
for i := range options {
|
|
if options[i].GetID() == "" {
|
|
options[i].SetID(NewId())
|
|
}
|
|
}
|
|
|
|
return options, nil
|
|
}
|
|
|
|
func (p PropertyOptions[T]) IsValid() error {
|
|
if len(p) == 0 {
|
|
return errors.New("options list cannot be empty")
|
|
}
|
|
|
|
seenNames := make(map[string]struct{})
|
|
for i, option := range p {
|
|
if err := option.IsValid(); err != nil {
|
|
return fmt.Errorf("invalid option at index %d: %w", i, err)
|
|
}
|
|
|
|
if _, exists := seenNames[option.GetName()]; exists {
|
|
return fmt.Errorf("duplicate option name found at index %d: %s", i, option.GetName())
|
|
}
|
|
seenNames[option.GetName()] = struct{}{}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// PluginPropertyOption provides a simple implementation of PropertyOption for plugins
|
|
// using a map[string]string for flexible key-value storage
|
|
type PluginPropertyOption struct {
|
|
Data map[string]string `json:"data"`
|
|
}
|
|
|
|
func NewPluginPropertyOption(id, name string) *PluginPropertyOption {
|
|
return &PluginPropertyOption{
|
|
Data: map[string]string{
|
|
"id": id,
|
|
"name": name,
|
|
},
|
|
}
|
|
}
|
|
|
|
func (p *PluginPropertyOption) GetID() string {
|
|
if p.Data == nil {
|
|
return ""
|
|
}
|
|
return p.Data["id"]
|
|
}
|
|
|
|
func (p *PluginPropertyOption) GetName() string {
|
|
if p.Data == nil {
|
|
return ""
|
|
}
|
|
return p.Data["name"]
|
|
}
|
|
|
|
func (p *PluginPropertyOption) SetID(id string) {
|
|
if p.Data == nil {
|
|
p.Data = make(map[string]string)
|
|
}
|
|
p.Data["id"] = id
|
|
}
|
|
|
|
func (p *PluginPropertyOption) IsValid() error {
|
|
if p.Data == nil {
|
|
return errors.New("data cannot be nil")
|
|
}
|
|
|
|
id := p.GetID()
|
|
if id == "" {
|
|
return errors.New("id cannot be empty")
|
|
}
|
|
|
|
if !IsValidId(id) {
|
|
return errors.New("id is not a valid ID")
|
|
}
|
|
|
|
name := p.GetName()
|
|
if name == "" {
|
|
return errors.New("name cannot be empty")
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// GetValue retrieves a custom value from the option data
|
|
func (p *PluginPropertyOption) GetValue(key string) string {
|
|
if p.Data == nil {
|
|
return ""
|
|
}
|
|
return p.Data[key]
|
|
}
|
|
|
|
// SetValue sets a custom value in the option data
|
|
func (p *PluginPropertyOption) SetValue(key, value string) {
|
|
if p.Data == nil {
|
|
p.Data = make(map[string]string)
|
|
}
|
|
p.Data[key] = value
|
|
}
|
|
|
|
// MarshalJSON implements custom JSON marshaling to avoid wrapping in "data"
|
|
func (p *PluginPropertyOption) MarshalJSON() ([]byte, error) {
|
|
if p.Data == nil {
|
|
return json.Marshal(map[string]string{})
|
|
}
|
|
return json.Marshal(p.Data)
|
|
}
|
|
|
|
// UnmarshalJSON implements custom JSON unmarshaling to handle unwrapped JSON
|
|
func (p *PluginPropertyOption) UnmarshalJSON(data []byte) error {
|
|
var result map[string]string
|
|
if err := json.Unmarshal(data, &result); err != nil {
|
|
return err
|
|
}
|
|
p.Data = result
|
|
return nil
|
|
}
|