From 349e6a59050a0beba82a7f626c2f72f6b8c88dde Mon Sep 17 00:00:00 2001 From: kolaente Date: Sun, 13 Nov 2022 17:07:01 +0100 Subject: [PATCH] feat: rename lists to projects --- pkg/caldav/parsing.go | 6 +- pkg/cmd/user.go | 10 +- pkg/config/config.go | 4 +- pkg/integrations/archived_test.go | 80 +-- pkg/integrations/kanban_test.go | 72 +-- pkg/integrations/link_sharing_auth_test.go | 6 +- pkg/integrations/link_sharing_test.go | 204 +++---- pkg/integrations/list_test.go | 116 ++-- pkg/integrations/task_collection_test.go | 38 +- pkg/integrations/task_comment_test.go | 2 +- pkg/integrations/task_test.go | 180 +++---- pkg/integrations/user_list_test.go | 6 +- pkg/metrics/metrics.go | 16 +- pkg/models/bulk_task.go | 22 +- pkg/models/bulk_task_test.go | 2 +- pkg/models/error.go | 364 ++++++------- pkg/models/events.go | 76 +-- pkg/models/export.go | 66 +-- pkg/models/favorites.go | 2 +- pkg/models/kanban.go | 66 +-- pkg/models/kanban_rights.go | 4 +- pkg/models/kanban_test.go | 40 +- pkg/models/label_rights.go | 2 +- pkg/models/label_task.go | 20 +- pkg/models/link_sharing.go | 74 +-- pkg/models/link_sharing_rights.go | 4 +- pkg/models/link_sharing_test.go | 18 +- pkg/models/list.go | 508 +++++++++--------- pkg/models/list_duplicate.go | 146 ++--- pkg/models/list_duplicate_test.go | 6 +- pkg/models/list_rights.go | 130 ++--- pkg/models/list_team.go | 136 ++--- pkg/models/list_team_rights.go | 22 +- pkg/models/list_team_test.go | 190 +++---- pkg/models/list_test.go | 180 +++---- pkg/models/list_users.go | 146 ++--- pkg/models/list_users_rights.go | 24 +- pkg/models/list_users_rights_test.go | 50 +- pkg/models/list_users_test.go | 278 +++++----- pkg/models/listeners.go | 54 +- pkg/models/mentions_test.go | 4 +- pkg/models/models.go | 6 +- pkg/models/namespace.go | 208 +++---- pkg/models/namespace_rights.go | 4 +- pkg/models/namespace_team_test.go | 2 +- pkg/models/namespace_test.go | 48 +- pkg/models/namespace_users_test.go | 4 +- pkg/models/notifications.go | 26 +- pkg/models/rights.go | 8 +- pkg/models/saved_filters.go | 32 +- pkg/models/saved_filters_test.go | 12 +- pkg/models/subscription.go | 44 +- pkg/models/subscription_rights.go | 4 +- pkg/models/subscription_test.go | 32 +- pkg/models/task_assignees.go | 42 +- pkg/models/task_assignees_rights.go | 6 +- pkg/models/task_attachment.go | 2 +- pkg/models/task_collection.go | 48 +- pkg/models/task_collection_sort.go | 2 +- pkg/models/task_collection_sort_test.go | 2 +- pkg/models/task_collection_test.go | 94 ++-- pkg/models/task_comments_test.go | 2 +- pkg/models/task_overdue_reminder.go | 2 +- pkg/models/task_relation.go | 2 +- pkg/models/task_relation_rights.go | 2 +- pkg/models/task_relation_test.go | 4 +- pkg/models/tasks.go | 172 +++--- pkg/models/tasks_rights.go | 26 +- pkg/models/tasks_test.go | 80 +-- pkg/models/team_members_rights.go | 2 +- pkg/models/teams.go | 6 +- pkg/models/teams_test.go | 2 +- pkg/models/unit_tests.go | 6 +- pkg/models/user_delete.go | 56 +- pkg/models/user_delete_test.go | 16 +- pkg/models/user_list.go | 32 +- pkg/models/users_list_test.go | 16 +- pkg/modules/auth/auth.go | 2 +- pkg/modules/background/background.go | 10 +- pkg/modules/background/handler/background.go | 112 ++-- pkg/modules/background/unsplash/proxy.go | 4 +- pkg/modules/background/unsplash/unsplash.go | 40 +- pkg/modules/background/upload/upload.go | 22 +- .../migration/create_from_structure.go | 42 +- .../migration/create_from_structure_test.go | 24 +- .../microsoft-todo/microsoft_todo.go | 76 +-- .../microsoft-todo/microsoft_todo_test.go | 18 +- pkg/modules/migration/migrator.go | 2 +- pkg/modules/migration/ticktick/ticktick.go | 30 +- .../migration/ticktick/ticktick_test.go | 118 ++-- pkg/modules/migration/todoist/todoist_test.go | 10 +- pkg/modules/migration/trello/trello.go | 30 +- pkg/modules/migration/trello/trello_test.go | 42 +- pkg/modules/migration/vikunja-file/vikunja.go | 10 +- .../migration/vikunja-file/vikunja_test.go | 8 +- pkg/routes/api/v1/docs.go | 14 +- pkg/routes/api/v1/link_sharing_auth.go | 6 +- pkg/routes/api/v1/list_by_namespace.go | 22 +- pkg/routes/api/v1/user_caldav_token.go | 2 +- pkg/routes/api/v1/user_list.go | 28 +- pkg/routes/api/v1/user_settings.go | 8 +- pkg/routes/api/v1/user_show.go | 2 +- pkg/routes/caldav/handler.go | 28 +- pkg/routes/caldav/listStorageProvider.go | 196 +++---- pkg/routes/metrics.go | 4 +- pkg/routes/routes.go | 121 ++--- pkg/user/notifications.go | 2 +- pkg/user/user.go | 4 +- pkg/user/user_create.go | 2 +- pkg/user/user_test.go | 24 +- pkg/user/users_list.go | 12 +- pkg/utils/umask_windows.go | 1 + tools.go | 1 + 113 files changed, 2753 insertions(+), 2750 deletions(-) diff --git a/pkg/caldav/parsing.go b/pkg/caldav/parsing.go index 26efee04f..4b887f86b 100644 --- a/pkg/caldav/parsing.go +++ b/pkg/caldav/parsing.go @@ -27,11 +27,11 @@ import ( ics "github.com/arran4/golang-ical" ) -func GetCaldavTodosForTasks(list *models.ListWithTasksAndBuckets, listTasks []*models.TaskWithComments) string { +func GetCaldavTodosForTasks(project *models.ProjectWithTasksAndBuckets, projectTasks []*models.TaskWithComments) string { // Make caldav todos from Vikunja todos var caldavtodos []*Todo - for _, t := range listTasks { + for _, t := range projectTasks { duration := t.EndDate.Sub(t.StartDate) var categories []string @@ -60,7 +60,7 @@ func GetCaldavTodosForTasks(list *models.ListWithTasksAndBuckets, listTasks []*m } caldavConfig := &Config{ - Name: list.Title, + Name: project.Title, ProdID: "Vikunja Todo App", } diff --git a/pkg/cmd/user.go b/pkg/cmd/user.go index 7e9f09f83..c9c0a3da5 100644 --- a/pkg/cmd/user.go +++ b/pkg/cmd/user.go @@ -73,7 +73,7 @@ func init() { // User deletion flags userDeleteCmd.Flags().BoolVarP(&userFlagDeleteNow, "now", "n", false, "If provided, deletes the user immediately instead of sending them an email first.") - userCmd.AddCommand(userListCmd, userCreateCmd, userUpdateCmd, userResetPasswordCmd, userChangeEnabledCmd, userDeleteCmd) + userCmd.AddCommand(userProjectCmd, userCreateCmd, userUpdateCmd, userResetPasswordCmd, userChangeEnabledCmd, userDeleteCmd) rootCmd.AddCommand(userCmd) } @@ -117,9 +117,9 @@ var userCmd = &cobra.Command{ Short: "Manage users locally through the cli.", } -var userListCmd = &cobra.Command{ - Use: "list", - Short: "Shows a list of all users.", +var userProjectCmd = &cobra.Command{ + Use: "project", + Short: "Shows a project of all users.", PreRun: func(cmd *cobra.Command, args []string) { initialize.FullInit() }, @@ -127,7 +127,7 @@ var userListCmd = &cobra.Command{ s := db.NewSession() defer s.Close() - users, err := user.ListAllUsers(s) + users, err := user.ProjectAllUsers(s) if err != nil { _ = s.Rollback() log.Fatalf("Error getting users: %s", err) diff --git a/pkg/config/config.go b/pkg/config/config.go index 23b927afc..c081b277c 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -164,7 +164,7 @@ const ( DefaultSettingsDiscoverableByName Key = `defaultsettings.discoverable_by_name` DefaultSettingsDiscoverableByEmail Key = `defaultsettings.discoverable_by_email` DefaultSettingsOverdueTaskRemindersEnabled Key = `defaultsettings.overdue_tasks_reminders_enabled` - DefaultSettingsDefaultListID Key = `defaultsettings.default_list_id` + DefaultSettingsDefaultProjectID Key = `defaultsettings.default_project_id` DefaultSettingsWeekStart Key = `defaultsettings.week_start` DefaultSettingsLanguage Key = `defaultsettings.language` DefaultSettingsTimezone Key = `defaultsettings.timezone` @@ -370,7 +370,7 @@ func InitDefaultConfig() { MigrationMicrosoftTodoEnable.setDefault(false) // Avatar AvatarGravaterExpiration.setDefault(3600) - // List Backgrounds + // Project Backgrounds BackgroundsEnabled.setDefault(true) BackgroundsUploadEnabled.setDefault(true) BackgroundsUnsplashEnabled.setDefault(false) diff --git a/pkg/integrations/archived_test.go b/pkg/integrations/archived_test.go index ac6e9bcab..50ab31e5d 100644 --- a/pkg/integrations/archived_test.go +++ b/pkg/integrations/archived_test.go @@ -28,37 +28,37 @@ import ( // This tests the following behaviour: // 1. A namespace should not be editable if it is archived. // 1. With the exception being to un-archive it. -// 2. A list which belongs to an archived namespace cannot be edited. -// 3. An archived list should not be editable. +// 2. A project which belongs to an archived namespace cannot be edited. +// 3. An archived project should not be editable. // 1. Except for un-archiving it. -// 4. It is not possible to un-archive a list individually if its namespace is archived. -// 5. Creating new lists on an archived namespace should not work. -// 6. Creating new tasks on an archived list should not work. -// 7. Creating new tasks on a list who's namespace is archived should not work. -// 8. Editing tasks on an archived list should not work. -// 9. Editing tasks on a list who's namespace is archived should not work. -// 10. Archived namespaces should not appear in the list with all namespaces. -// 11. Archived lists should not appear in the list with all lists. -// 12. Lists who's namespace is archived should not appear in the list with all lists. +// 4. It is not possible to un-archive a project individually if its namespace is archived. +// 5. Creating new projects on an archived namespace should not work. +// 6. Creating new tasks on an archived project should not work. +// 7. Creating new tasks on a project who's namespace is archived should not work. +// 8. Editing tasks on an archived project should not work. +// 9. Editing tasks on a project who's namespace is archived should not work. +// 10. Archived namespaces should not appear in the project with all namespaces. +// 11. Archived projects should not appear in the project with all projects. +// 12. Projects who's namespace is archived should not appear in the project with all projects. // // All of this is tested through integration tests because it's not yet clear if this will be implemented directly // or with some kind of middleware. // -// Maybe the inheritance of lists from namespaces could be solved with some kind of is_archived_inherited flag - -// that way I'd only need to implement the checking on a list level and update the flag for all lists once the -// namespace is archived. The archived flag would then be used to not accedentially unarchive lists which were +// Maybe the inheritance of projects from namespaces could be solved with some kind of is_archived_inherited flag - +// that way I'd only need to implement the checking on a project level and update the flag for all projects once the +// namespace is archived. The archived flag would then be used to not accedentially unarchive projects which were // already individually archived when the namespace was archived. // Should still test it all though. // // Namespace 16 is archived -// List 21 belongs to namespace 16 -// List 22 is archived individually +// Project 21 belongs to namespace 16 +// Project 22 is archived individually func TestArchived(t *testing.T) { - testListHandler := webHandlerTest{ + testProjectHandler := webHandlerTest{ user: &testuser1, strFunc: func() handler.CObject { - return &models.List{} + return &models.Project{} }, t: t, } @@ -116,54 +116,54 @@ func TestArchived(t *testing.T) { assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"is_archived":false`) }) - t.Run("no new lists", func(t *testing.T) { - _, err := testListHandler.testCreateWithUser(nil, map[string]string{"namespace": "16"}, `{"title":"Lorem"}`) + t.Run("no new projects", func(t *testing.T) { + _, err := testProjectHandler.testCreateWithUser(nil, map[string]string{"namespace": "16"}, `{"title":"Lorem"}`) assert.Error(t, err) assertHandlerErrorCode(t, err, models.ErrCodeNamespaceIsArchived) }) - t.Run("should not appear in the list", func(t *testing.T) { + t.Run("should not appear in the project", func(t *testing.T) { rec, err := testNamespaceHandler.testReadAllWithUser(nil, nil) assert.NoError(t, err) assert.NotContains(t, rec.Body.String(), `"title":"Archived testnamespace16"`) }) - t.Run("should appear in the list if explicitly requested", func(t *testing.T) { + t.Run("should appear in the project if explicitly requested", func(t *testing.T) { rec, err := testNamespaceHandler.testReadAllWithUser(url.Values{"is_archived": []string{"true"}}, nil) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Archived testnamespace16"`) }) }) - t.Run("list", func(t *testing.T) { + t.Run("project", func(t *testing.T) { taskTests := func(taskID string, errCode int, t *testing.T) { t.Run("task", func(t *testing.T) { t.Run("edit task", func(t *testing.T) { - _, err := testTaskHandler.testUpdateWithUser(nil, map[string]string{"listtask": taskID}, `{"title":"TestIpsum"}`) + _, err := testTaskHandler.testUpdateWithUser(nil, map[string]string{"projecttask": taskID}, `{"title":"TestIpsum"}`) assert.Error(t, err) assertHandlerErrorCode(t, err, errCode) }) t.Run("delete", func(t *testing.T) { - _, err := testTaskHandler.testDeleteWithUser(nil, map[string]string{"listtask": taskID}) + _, err := testTaskHandler.testDeleteWithUser(nil, map[string]string{"projecttask": taskID}) assert.Error(t, err) assertHandlerErrorCode(t, err, errCode) }) t.Run("add new labels", func(t *testing.T) { - _, err := testLabelHandler.testCreateWithUser(nil, map[string]string{"listtask": taskID}, `{"label_id":1}`) + _, err := testLabelHandler.testCreateWithUser(nil, map[string]string{"projecttask": taskID}, `{"label_id":1}`) assert.Error(t, err) assertHandlerErrorCode(t, err, errCode) }) t.Run("remove lables", func(t *testing.T) { - _, err := testLabelHandler.testDeleteWithUser(nil, map[string]string{"listtask": taskID, "label": "4"}) + _, err := testLabelHandler.testDeleteWithUser(nil, map[string]string{"projecttask": taskID, "label": "4"}) assert.Error(t, err) assertHandlerErrorCode(t, err, errCode) }) t.Run("add assignees", func(t *testing.T) { - _, err := testAssigneeHandler.testCreateWithUser(nil, map[string]string{"listtask": taskID}, `{"user_id":3}`) + _, err := testAssigneeHandler.testCreateWithUser(nil, map[string]string{"projecttask": taskID}, `{"user_id":3}`) assert.Error(t, err) assertHandlerErrorCode(t, err, errCode) }) t.Run("remove assignees", func(t *testing.T) { - _, err := testAssigneeHandler.testDeleteWithUser(nil, map[string]string{"listtask": taskID, "user": "2"}) + _, err := testAssigneeHandler.testDeleteWithUser(nil, map[string]string{"projecttask": taskID, "user": "2"}) assert.Error(t, err) assertHandlerErrorCode(t, err, errCode) }) @@ -194,45 +194,45 @@ func TestArchived(t *testing.T) { }) } - // The list belongs to an archived namespace + // The project belongs to an archived namespace t.Run("archived namespace", func(t *testing.T) { t.Run("not editable", func(t *testing.T) { - _, err := testListHandler.testUpdateWithUser(nil, map[string]string{"list": "21"}, `{"title":"TestIpsum","is_archived":true}`) + _, err := testProjectHandler.testUpdateWithUser(nil, map[string]string{"project": "21"}, `{"title":"TestIpsum","is_archived":true}`) assert.Error(t, err) assertHandlerErrorCode(t, err, models.ErrCodeNamespaceIsArchived) }) t.Run("no new tasks", func(t *testing.T) { - _, err := testTaskHandler.testCreateWithUser(nil, map[string]string{"list": "21"}, `{"title":"Lorem"}`) + _, err := testTaskHandler.testCreateWithUser(nil, map[string]string{"project": "21"}, `{"title":"Lorem"}`) assert.Error(t, err) assertHandlerErrorCode(t, err, models.ErrCodeNamespaceIsArchived) }) t.Run("not unarchivable", func(t *testing.T) { - _, err := testListHandler.testUpdateWithUser(nil, map[string]string{"list": "21"}, `{"title":"LoremIpsum","is_archived":false}`) + _, err := testProjectHandler.testUpdateWithUser(nil, map[string]string{"project": "21"}, `{"title":"LoremIpsum","is_archived":false}`) assert.Error(t, err) assertHandlerErrorCode(t, err, models.ErrCodeNamespaceIsArchived) }) taskTests("35", models.ErrCodeNamespaceIsArchived, t) }) - // The list itself is archived + // The project itself is archived t.Run("archived individually", func(t *testing.T) { t.Run("not editable", func(t *testing.T) { - _, err := testListHandler.testUpdateWithUser(nil, map[string]string{"list": "22"}, `{"title":"TestIpsum","is_archived":true}`) + _, err := testProjectHandler.testUpdateWithUser(nil, map[string]string{"project": "22"}, `{"title":"TestIpsum","is_archived":true}`) assert.Error(t, err) - assertHandlerErrorCode(t, err, models.ErrCodeListIsArchived) + assertHandlerErrorCode(t, err, models.ErrCodeProjectIsArchived) }) t.Run("no new tasks", func(t *testing.T) { - _, err := testTaskHandler.testCreateWithUser(nil, map[string]string{"list": "22"}, `{"title":"Lorem"}`) + _, err := testTaskHandler.testCreateWithUser(nil, map[string]string{"project": "22"}, `{"title":"Lorem"}`) assert.Error(t, err) - assertHandlerErrorCode(t, err, models.ErrCodeListIsArchived) + assertHandlerErrorCode(t, err, models.ErrCodeProjectIsArchived) }) t.Run("unarchivable", func(t *testing.T) { - rec, err := testListHandler.testUpdateWithUser(nil, map[string]string{"list": "22"}, `{"title":"LoremIpsum","is_archived":false,"namespace_id":1}`) + rec, err := testProjectHandler.testUpdateWithUser(nil, map[string]string{"project": "22"}, `{"title":"LoremIpsum","is_archived":false,"namespace_id":1}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"is_archived":false`) }) - taskTests("36", models.ErrCodeListIsArchived, t) + taskTests("36", models.ErrCodeProjectIsArchived, t) }) }) } diff --git a/pkg/integrations/kanban_test.go b/pkg/integrations/kanban_test.go index d2291aa41..13c0c1f9d 100644 --- a/pkg/integrations/kanban_test.go +++ b/pkg/integrations/kanban_test.go @@ -39,7 +39,7 @@ func TestBucket(t *testing.T) { linkShare: &models.LinkSharing{ ID: 2, Hash: "test2", - ListID: 2, + ProjectID: 2, Right: models.RightWrite, SharingType: models.SharingTypeWithoutPassword, SharedByID: 1, @@ -51,17 +51,17 @@ func TestBucket(t *testing.T) { } t.Run("ReadAll", func(t *testing.T) { t.Run("Normal", func(t *testing.T) { - rec, err := testHandler.testReadAllWithUser(nil, map[string]string{"list": "1"}) + rec, err := testHandler.testReadAllWithUser(nil, map[string]string{"project": "1"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `testbucket1`) assert.Contains(t, rec.Body.String(), `testbucket2`) assert.Contains(t, rec.Body.String(), `testbucket3`) - assert.NotContains(t, rec.Body.String(), `testbucket4`) // Different List + assert.NotContains(t, rec.Body.String(), `testbucket4`) // Different Project }) }) t.Run("Update", func(t *testing.T) { t.Run("Normal", func(t *testing.T) { - // Check the list was loaded successfully afterwards, see testReadOneWithUser + // Check the project was loaded successfully afterwards, see testReadOneWithUser rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"bucket": "1"}, `{"title":"TestLoremIpsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"TestLoremIpsum"`) @@ -150,7 +150,7 @@ func TestBucket(t *testing.T) { }) t.Run("Delete", func(t *testing.T) { t.Run("Normal", func(t *testing.T) { - rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"list": "1", "bucket": "1"}) + rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"project": "1", "bucket": "1"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"message":"Successfully deleted."`) }) @@ -162,70 +162,70 @@ func TestBucket(t *testing.T) { t.Run("Rights check", func(t *testing.T) { t.Run("Forbidden", func(t *testing.T) { // Owned by user13 - _, err := testHandler.testDeleteWithUser(nil, map[string]string{"list": "20", "bucket": "5"}) + _, err := testHandler.testDeleteWithUser(nil, map[string]string{"project": "20", "bucket": "5"}) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via Team readonly", func(t *testing.T) { - _, err := testHandler.testDeleteWithUser(nil, map[string]string{"list": "6", "bucket": "6"}) + _, err := testHandler.testDeleteWithUser(nil, map[string]string{"project": "6", "bucket": "6"}) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via Team write", func(t *testing.T) { - rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"list": "7", "bucket": "7"}) + rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"project": "7", "bucket": "7"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"message":"Successfully deleted."`) }) t.Run("Shared Via Team admin", func(t *testing.T) { - rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"list": "8", "bucket": "8"}) + rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"project": "8", "bucket": "8"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"message":"Successfully deleted."`) }) t.Run("Shared Via User readonly", func(t *testing.T) { - _, err := testHandler.testDeleteWithUser(nil, map[string]string{"list": "9", "bucket": "9"}) + _, err := testHandler.testDeleteWithUser(nil, map[string]string{"project": "9", "bucket": "9"}) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via User write", func(t *testing.T) { - rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"list": "10", "bucket": "10"}) + rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"project": "10", "bucket": "10"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"message":"Successfully deleted."`) }) t.Run("Shared Via User admin", func(t *testing.T) { - rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"list": "11", "bucket": "11"}) + rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"project": "11", "bucket": "11"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"message":"Successfully deleted."`) }) t.Run("Shared Via NamespaceTeam readonly", func(t *testing.T) { - _, err := testHandler.testDeleteWithUser(nil, map[string]string{"list": "12", "bucket": "12"}) + _, err := testHandler.testDeleteWithUser(nil, map[string]string{"project": "12", "bucket": "12"}) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via NamespaceTeam write", func(t *testing.T) { - rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"list": "13", "bucket": "13"}) + rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"project": "13", "bucket": "13"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"message":"Successfully deleted."`) }) t.Run("Shared Via NamespaceTeam admin", func(t *testing.T) { - rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"list": "14", "bucket": "14"}) + rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"project": "14", "bucket": "14"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"message":"Successfully deleted."`) }) t.Run("Shared Via NamespaceUser readonly", func(t *testing.T) { - _, err := testHandler.testDeleteWithUser(nil, map[string]string{"list": "15", "bucket": "15"}) + _, err := testHandler.testDeleteWithUser(nil, map[string]string{"project": "15", "bucket": "15"}) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via NamespaceUser write", func(t *testing.T) { - rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"list": "16", "bucket": "16"}) + rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"project": "16", "bucket": "16"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"message":"Successfully deleted."`) }) t.Run("Shared Via NamespaceUser admin", func(t *testing.T) { - rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"list": "17", "bucket": "17"}) + rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"project": "17", "bucket": "17"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"message":"Successfully deleted."`) }) @@ -233,92 +233,92 @@ func TestBucket(t *testing.T) { }) t.Run("Create", func(t *testing.T) { t.Run("Normal", func(t *testing.T) { - rec, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "1"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "1"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) }) t.Run("Nonexisting", func(t *testing.T) { - _, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "9999"}, `{"title":"Lorem Ipsum"}`) + _, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "9999"}, `{"title":"Lorem Ipsum"}`) assert.Error(t, err) - assertHandlerErrorCode(t, err, models.ErrCodeListDoesNotExist) + assertHandlerErrorCode(t, err, models.ErrCodeProjectDoesNotExist) }) t.Run("Rights check", func(t *testing.T) { t.Run("Forbidden", func(t *testing.T) { // Owned by user13 - _, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "20"}, `{"title":"Lorem Ipsum"}`) + _, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "20"}, `{"title":"Lorem Ipsum"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via Team readonly", func(t *testing.T) { - _, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "6"}, `{"title":"Lorem Ipsum"}`) + _, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "6"}, `{"title":"Lorem Ipsum"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via Team write", func(t *testing.T) { - rec, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "7"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "7"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) }) t.Run("Shared Via Team admin", func(t *testing.T) { - rec, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "8"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "8"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) }) t.Run("Shared Via User readonly", func(t *testing.T) { - _, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "9"}, `{"title":"Lorem Ipsum"}`) + _, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "9"}, `{"title":"Lorem Ipsum"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via User write", func(t *testing.T) { - rec, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "10"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "10"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) }) t.Run("Shared Via User admin", func(t *testing.T) { - rec, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "11"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "11"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) }) t.Run("Shared Via NamespaceTeam readonly", func(t *testing.T) { - _, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "12"}, `{"title":"Lorem Ipsum"}`) + _, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "12"}, `{"title":"Lorem Ipsum"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via NamespaceTeam write", func(t *testing.T) { - rec, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "13"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "13"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) }) t.Run("Shared Via NamespaceTeam admin", func(t *testing.T) { - rec, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "14"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "14"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) }) t.Run("Shared Via NamespaceUser readonly", func(t *testing.T) { - _, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "15"}, `{"title":"Lorem Ipsum"}`) + _, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "15"}, `{"title":"Lorem Ipsum"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via NamespaceUser write", func(t *testing.T) { - rec, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "16"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "16"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) }) t.Run("Shared Via NamespaceUser admin", func(t *testing.T) { - rec, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "17"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "17"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) }) }) t.Run("Link Share", func(t *testing.T) { - rec, err := testHandlerLinkShareWrite.testCreateWithLinkShare(nil, map[string]string{"list": "2"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandlerLinkShareWrite.testCreateWithLinkShare(nil, map[string]string{"project": "2"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) db.AssertExists(t, "buckets", map[string]interface{}{ - "list_id": 2, + "project_id": 2, "created_by_id": -2, "title": "Lorem Ipsum", }, false) diff --git a/pkg/integrations/link_sharing_auth_test.go b/pkg/integrations/link_sharing_auth_test.go index 53d694fba..aa5889a73 100644 --- a/pkg/integrations/link_sharing_auth_test.go +++ b/pkg/integrations/link_sharing_auth_test.go @@ -31,14 +31,14 @@ func TestLinkSharingAuth(t *testing.T) { assert.NoError(t, err) assert.Equal(t, http.StatusOK, rec.Code) assert.Contains(t, rec.Body.String(), `"token":"`) - assert.Contains(t, rec.Body.String(), `"list_id":1`) + assert.Contains(t, rec.Body.String(), `"project_id":1`) }) t.Run("Without Password, Password Provided", func(t *testing.T) { rec, err := newTestRequest(t, http.MethodPost, apiv1.AuthenticateLinkShare, `{"password":"somethingsomething"}`, nil, map[string]string{"share": "test"}) assert.NoError(t, err) assert.Equal(t, http.StatusOK, rec.Code) assert.Contains(t, rec.Body.String(), `"token":"`) - assert.Contains(t, rec.Body.String(), `"list_id":1`) + assert.Contains(t, rec.Body.String(), `"project_id":1`) }) t.Run("With Password, No Password Provided", func(t *testing.T) { _, err := newTestRequest(t, http.MethodPost, apiv1.AuthenticateLinkShare, ``, nil, map[string]string{"share": "testWithPassword"}) @@ -50,7 +50,7 @@ func TestLinkSharingAuth(t *testing.T) { assert.NoError(t, err) assert.Equal(t, http.StatusOK, rec.Code) assert.Contains(t, rec.Body.String(), `"token":"`) - assert.Contains(t, rec.Body.String(), `"list_id":1`) + assert.Contains(t, rec.Body.String(), `"project_id":1`) }) t.Run("With Wrong Password", func(t *testing.T) { _, err := newTestRequest(t, http.MethodPost, apiv1.AuthenticateLinkShare, `{"password":"someWrongPassword"}`, nil, map[string]string{"share": "testWithPassword"}) diff --git a/pkg/integrations/link_sharing_test.go b/pkg/integrations/link_sharing_test.go index 55874cb3c..790fe85c0 100644 --- a/pkg/integrations/link_sharing_test.go +++ b/pkg/integrations/link_sharing_test.go @@ -31,7 +31,7 @@ func TestLinkSharing(t *testing.T) { linkshareRead := &models.LinkSharing{ ID: 1, Hash: "test1", - ListID: 1, + ProjectID: 1, Right: models.RightRead, SharingType: models.SharingTypeWithoutPassword, SharedByID: 1, @@ -40,7 +40,7 @@ func TestLinkSharing(t *testing.T) { linkShareWrite := &models.LinkSharing{ ID: 2, Hash: "test2", - ListID: 2, + ProjectID: 2, Right: models.RightWrite, SharingType: models.SharingTypeWithoutPassword, SharedByID: 1, @@ -49,7 +49,7 @@ func TestLinkSharing(t *testing.T) { linkShareAdmin := &models.LinkSharing{ ID: 3, Hash: "test3", - ListID: 3, + ProjectID: 3, Right: models.RightAdmin, SharingType: models.SharingTypeWithoutPassword, SharedByID: 1, @@ -65,102 +65,102 @@ func TestLinkSharing(t *testing.T) { } t.Run("Forbidden", func(t *testing.T) { t.Run("read only", func(t *testing.T) { - _, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "20"}, `{"right":0}`) + _, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "20"}, `{"right":0}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("write", func(t *testing.T) { - _, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "20"}, `{"right":1}`) + _, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "20"}, `{"right":1}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("admin", func(t *testing.T) { - _, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "20"}, `{"right":2}`) + _, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "20"}, `{"right":2}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) }) t.Run("Read only access", func(t *testing.T) { t.Run("read only", func(t *testing.T) { - _, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "9"}, `{"right":0}`) + _, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "9"}, `{"right":0}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("write", func(t *testing.T) { - _, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "9"}, `{"right":1}`) + _, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "9"}, `{"right":1}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("admin", func(t *testing.T) { - _, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "9"}, `{"right":2}`) + _, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "9"}, `{"right":2}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) }) t.Run("Write access", func(t *testing.T) { t.Run("read only", func(t *testing.T) { - req, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "10"}, `{"right":0}`) + req, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "10"}, `{"right":0}`) assert.NoError(t, err) assert.Contains(t, req.Body.String(), `"hash":`) }) t.Run("write", func(t *testing.T) { - req, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "10"}, `{"right":1}`) + req, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "10"}, `{"right":1}`) assert.NoError(t, err) assert.Contains(t, req.Body.String(), `"hash":`) }) t.Run("admin", func(t *testing.T) { - _, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "10"}, `{"right":2}`) + _, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "10"}, `{"right":2}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) }) t.Run("Admin access", func(t *testing.T) { t.Run("read only", func(t *testing.T) { - req, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "11"}, `{"right":0}`) + req, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "11"}, `{"right":0}`) assert.NoError(t, err) assert.Contains(t, req.Body.String(), `"hash":`) }) t.Run("write", func(t *testing.T) { - req, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "11"}, `{"right":1}`) + req, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "11"}, `{"right":1}`) assert.NoError(t, err) assert.Contains(t, req.Body.String(), `"hash":`) }) t.Run("admin", func(t *testing.T) { - req, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "11"}, `{"right":2}`) + req, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "11"}, `{"right":2}`) assert.NoError(t, err) assert.Contains(t, req.Body.String(), `"hash":`) }) }) }) - t.Run("Lists", func(t *testing.T) { - testHandlerListReadOnly := webHandlerTest{ + t.Run("Projects", func(t *testing.T) { + testHandlerProjectReadOnly := webHandlerTest{ linkShare: linkshareRead, strFunc: func() handler.CObject { - return &models.List{} + return &models.Project{} }, t: t, } - testHandlerListWrite := webHandlerTest{ + testHandlerProjectWrite := webHandlerTest{ linkShare: linkShareWrite, strFunc: func() handler.CObject { - return &models.List{} + return &models.Project{} }, t: t, } - testHandlerListAdmin := webHandlerTest{ + testHandlerProjectAdmin := webHandlerTest{ linkShare: linkShareAdmin, strFunc: func() handler.CObject { - return &models.List{} + return &models.Project{} }, t: t, } t.Run("ReadAll", func(t *testing.T) { t.Run("Normal", func(t *testing.T) { - rec, err := testHandlerListReadOnly.testReadAllWithLinkShare(nil, nil) + rec, err := testHandlerProjectReadOnly.testReadAllWithLinkShare(nil, nil) assert.NoError(t, err) - // Should only return the shared list, nothing else + // Should only return the shared project, nothing else assert.Contains(t, rec.Body.String(), `Test1`) assert.NotContains(t, rec.Body.String(), `Test2`) assert.NotContains(t, rec.Body.String(), `Test3`) @@ -168,9 +168,9 @@ func TestLinkSharing(t *testing.T) { assert.NotContains(t, rec.Body.String(), `Test5`) }) t.Run("Search", func(t *testing.T) { - rec, err := testHandlerListReadOnly.testReadAllWithLinkShare(url.Values{"s": []string{"est1"}}, nil) + rec, err := testHandlerProjectReadOnly.testReadAllWithLinkShare(url.Values{"s": []string{"est1"}}, nil) assert.NoError(t, err) - // Should only return the shared list, nothing else + // Should only return the shared project, nothing else assert.Contains(t, rec.Body.String(), `Test1`) assert.NotContains(t, rec.Body.String(), `Test2`) assert.NotContains(t, rec.Body.String(), `Test3`) @@ -180,35 +180,35 @@ func TestLinkSharing(t *testing.T) { }) t.Run("ReadOne", func(t *testing.T) { t.Run("Normal", func(t *testing.T) { - rec, err := testHandlerListReadOnly.testReadOneWithLinkShare(nil, map[string]string{"list": "1"}) + rec, err := testHandlerProjectReadOnly.testReadOneWithLinkShare(nil, map[string]string{"project": "1"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Test1"`) assert.NotContains(t, rec.Body.String(), `"title":"Test2"`) }) t.Run("Nonexisting", func(t *testing.T) { - _, err := testHandlerListReadOnly.testReadOneWithLinkShare(nil, map[string]string{"list": "9999999"}) + _, err := testHandlerProjectReadOnly.testReadOneWithLinkShare(nil, map[string]string{"project": "9999999"}) assert.Error(t, err) - assertHandlerErrorCode(t, err, models.ErrCodeListDoesNotExist) + assertHandlerErrorCode(t, err, models.ErrCodeProjectDoesNotExist) }) t.Run("Rights check", func(t *testing.T) { t.Run("Forbidden", func(t *testing.T) { - // List 2, not shared with this token - _, err := testHandlerListReadOnly.testReadOneWithLinkShare(nil, map[string]string{"list": "2"}) + // Project 2, not shared with this token + _, err := testHandlerProjectReadOnly.testReadOneWithLinkShare(nil, map[string]string{"project": "2"}) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `You don't have the right to see this`) }) t.Run("Shared readonly", func(t *testing.T) { - rec, err := testHandlerListReadOnly.testReadOneWithLinkShare(nil, map[string]string{"list": "1"}) + rec, err := testHandlerProjectReadOnly.testReadOneWithLinkShare(nil, map[string]string{"project": "1"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Test1"`) }) t.Run("Shared write", func(t *testing.T) { - rec, err := testHandlerListWrite.testReadOneWithLinkShare(nil, map[string]string{"list": "2"}) + rec, err := testHandlerProjectWrite.testReadOneWithLinkShare(nil, map[string]string{"project": "2"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Test2"`) }) t.Run("Shared admin", func(t *testing.T) { - rec, err := testHandlerListAdmin.testReadOneWithLinkShare(nil, map[string]string{"list": "3"}) + rec, err := testHandlerProjectAdmin.testReadOneWithLinkShare(nil, map[string]string{"project": "3"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Test3"`) }) @@ -216,28 +216,28 @@ func TestLinkSharing(t *testing.T) { }) t.Run("Update", func(t *testing.T) { t.Run("Nonexisting", func(t *testing.T) { - _, err := testHandlerListReadOnly.testUpdateWithLinkShare(nil, map[string]string{"list": "9999999"}, `{"title":"TestLoremIpsum"}`) + _, err := testHandlerProjectReadOnly.testUpdateWithLinkShare(nil, map[string]string{"project": "9999999"}, `{"title":"TestLoremIpsum"}`) assert.Error(t, err) - assertHandlerErrorCode(t, err, models.ErrCodeListDoesNotExist) + assertHandlerErrorCode(t, err, models.ErrCodeProjectDoesNotExist) }) t.Run("Rights check", func(t *testing.T) { t.Run("Forbidden", func(t *testing.T) { - _, err := testHandlerListReadOnly.testUpdateWithLinkShare(nil, map[string]string{"list": "2"}, `{"title":"TestLoremIpsum"}`) + _, err := testHandlerProjectReadOnly.testUpdateWithLinkShare(nil, map[string]string{"project": "2"}, `{"title":"TestLoremIpsum"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared readonly", func(t *testing.T) { - _, err := testHandlerListReadOnly.testUpdateWithLinkShare(nil, map[string]string{"list": "1"}, `{"title":"TestLoremIpsum"}`) + _, err := testHandlerProjectReadOnly.testUpdateWithLinkShare(nil, map[string]string{"project": "1"}, `{"title":"TestLoremIpsum"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared write", func(t *testing.T) { - rec, err := testHandlerListWrite.testUpdateWithLinkShare(nil, map[string]string{"list": "2"}, `{"title":"TestLoremIpsum","namespace_id":1}`) + rec, err := testHandlerProjectWrite.testUpdateWithLinkShare(nil, map[string]string{"project": "2"}, `{"title":"TestLoremIpsum","namespace_id":1}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"TestLoremIpsum"`) }) t.Run("Shared admin", func(t *testing.T) { - rec, err := testHandlerListAdmin.testUpdateWithLinkShare(nil, map[string]string{"list": "3"}, `{"title":"TestLoremIpsum","namespace_id":2}`) + rec, err := testHandlerProjectAdmin.testUpdateWithLinkShare(nil, map[string]string{"project": "3"}, `{"title":"TestLoremIpsum","namespace_id":2}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"TestLoremIpsum"`) }) @@ -245,54 +245,54 @@ func TestLinkSharing(t *testing.T) { }) t.Run("Delete", func(t *testing.T) { t.Run("Nonexisting", func(t *testing.T) { - _, err := testHandlerListReadOnly.testDeleteWithLinkShare(nil, map[string]string{"list": "9999999"}) + _, err := testHandlerProjectReadOnly.testDeleteWithLinkShare(nil, map[string]string{"project": "9999999"}) assert.Error(t, err) - assertHandlerErrorCode(t, err, models.ErrCodeListDoesNotExist) + assertHandlerErrorCode(t, err, models.ErrCodeProjectDoesNotExist) }) t.Run("Rights check", func(t *testing.T) { t.Run("Forbidden", func(t *testing.T) { - _, err := testHandlerListReadOnly.testDeleteWithLinkShare(nil, map[string]string{"list": "1"}) + _, err := testHandlerProjectReadOnly.testDeleteWithLinkShare(nil, map[string]string{"project": "1"}) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared readonly", func(t *testing.T) { - _, err := testHandlerListReadOnly.testDeleteWithLinkShare(nil, map[string]string{"list": "1"}) + _, err := testHandlerProjectReadOnly.testDeleteWithLinkShare(nil, map[string]string{"project": "1"}) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared write", func(t *testing.T) { - _, err := testHandlerListWrite.testDeleteWithLinkShare(nil, map[string]string{"list": "2"}) + _, err := testHandlerProjectWrite.testDeleteWithLinkShare(nil, map[string]string{"project": "2"}) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared admin", func(t *testing.T) { - rec, err := testHandlerListAdmin.testDeleteWithLinkShare(nil, map[string]string{"list": "3"}) + rec, err := testHandlerProjectAdmin.testDeleteWithLinkShare(nil, map[string]string{"project": "3"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"message":"Successfully deleted."`) }) }) }) - // Creating a list should always be forbidden, since users need access to a namespace to create a list + // Creating a project should always be forbidden, since users need access to a namespace to create a project t.Run("Create", func(t *testing.T) { t.Run("Nonexisting", func(t *testing.T) { - _, err := testHandlerListReadOnly.testCreateWithLinkShare(nil, map[string]string{"namespace": "999999"}, `{"title":"Lorem"}`) + _, err := testHandlerProjectReadOnly.testCreateWithLinkShare(nil, map[string]string{"namespace": "999999"}, `{"title":"Lorem"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Rights check", func(t *testing.T) { t.Run("Shared readonly", func(t *testing.T) { - _, err := testHandlerListReadOnly.testCreateWithLinkShare(nil, map[string]string{"namespace": "1"}, `{"title":"Lorem","description":"Lorem Ipsum"}`) + _, err := testHandlerProjectReadOnly.testCreateWithLinkShare(nil, map[string]string{"namespace": "1"}, `{"title":"Lorem","description":"Lorem Ipsum"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared write", func(t *testing.T) { - _, err := testHandlerListWrite.testCreateWithLinkShare(nil, map[string]string{"namespace": "2"}, `{"title":"Lorem","description":"Lorem Ipsum"}`) + _, err := testHandlerProjectWrite.testCreateWithLinkShare(nil, map[string]string{"namespace": "2"}, `{"title":"Lorem","description":"Lorem Ipsum"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared admin", func(t *testing.T) { - _, err := testHandlerListAdmin.testCreateWithLinkShare(nil, map[string]string{"namespace": "3"}, `{"title":"Lorem","description":"Lorem Ipsum"}`) + _, err := testHandlerProjectAdmin.testCreateWithLinkShare(nil, map[string]string{"namespace": "3"}, `{"title":"Lorem","description":"Lorem Ipsum"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) @@ -301,74 +301,74 @@ func TestLinkSharing(t *testing.T) { t.Run("Right Management", func(t *testing.T) { t.Run("Users", func(t *testing.T) { - testHandlerListUserReadOnly := webHandlerTest{ + testHandlerProjectUserReadOnly := webHandlerTest{ linkShare: linkshareRead, strFunc: func() handler.CObject { - return &models.ListUser{} + return &models.ProjectUser{} }, t: t, } - testHandlerListUserWrite := webHandlerTest{ + testHandlerProjectUserWrite := webHandlerTest{ linkShare: linkShareWrite, strFunc: func() handler.CObject { - return &models.ListUser{} + return &models.ProjectUser{} }, t: t, } - testHandlerListUserAdmin := webHandlerTest{ + testHandlerProjectUserAdmin := webHandlerTest{ linkShare: linkShareAdmin, strFunc: func() handler.CObject { - return &models.ListUser{} + return &models.ProjectUser{} }, t: t, } t.Run("ReadAll", func(t *testing.T) { t.Run("Shared readonly", func(t *testing.T) { - rec, err := testHandlerListUserReadOnly.testReadAllWithLinkShare(nil, map[string]string{"list": "1"}) + rec, err := testHandlerProjectUserReadOnly.testReadAllWithLinkShare(nil, map[string]string{"project": "1"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `[]`) }) t.Run("Shared write", func(t *testing.T) { - rec, err := testHandlerListUserWrite.testReadAllWithLinkShare(nil, map[string]string{"list": "2"}) + rec, err := testHandlerProjectUserWrite.testReadAllWithLinkShare(nil, map[string]string{"project": "2"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `[]`) }) t.Run("Shared admin", func(t *testing.T) { - rec, err := testHandlerListUserAdmin.testReadAllWithLinkShare(nil, map[string]string{"list": "3"}) + rec, err := testHandlerProjectUserAdmin.testReadAllWithLinkShare(nil, map[string]string{"project": "3"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"username":"user1"`) }) }) t.Run("Create", func(t *testing.T) { t.Run("Shared readonly", func(t *testing.T) { - _, err := testHandlerListUserReadOnly.testCreateWithLinkShare(nil, map[string]string{"list": "1"}, `{"user_id":"user1"}`) + _, err := testHandlerProjectUserReadOnly.testCreateWithLinkShare(nil, map[string]string{"project": "1"}, `{"user_id":"user1"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared write", func(t *testing.T) { - _, err := testHandlerListUserWrite.testCreateWithLinkShare(nil, map[string]string{"list": "2"}, `{"user_id":"user1"}`) + _, err := testHandlerProjectUserWrite.testCreateWithLinkShare(nil, map[string]string{"project": "2"}, `{"user_id":"user1"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared admin", func(t *testing.T) { - _, err := testHandlerListUserAdmin.testCreateWithLinkShare(nil, map[string]string{"list": "3"}, `{"user_id":"user1"}`) + _, err := testHandlerProjectUserAdmin.testCreateWithLinkShare(nil, map[string]string{"project": "3"}, `{"user_id":"user1"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) }) t.Run("Update", func(t *testing.T) { t.Run("Shared readonly", func(t *testing.T) { - _, err := testHandlerListUserReadOnly.testUpdateWithLinkShare(nil, map[string]string{"list": "1"}, `{"user_id":"user1"}`) + _, err := testHandlerProjectUserReadOnly.testUpdateWithLinkShare(nil, map[string]string{"project": "1"}, `{"user_id":"user1"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared write", func(t *testing.T) { - _, err := testHandlerListUserWrite.testUpdateWithLinkShare(nil, map[string]string{"list": "2"}, `{"user_id":"user1"}`) + _, err := testHandlerProjectUserWrite.testUpdateWithLinkShare(nil, map[string]string{"project": "2"}, `{"user_id":"user1"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared admin", func(t *testing.T) { - _, err := testHandlerListUserAdmin.testUpdateWithLinkShare(nil, map[string]string{"list": "3"}, `{"user_id":"user1"}`) + _, err := testHandlerProjectUserAdmin.testUpdateWithLinkShare(nil, map[string]string{"project": "3"}, `{"user_id":"user1"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) @@ -376,91 +376,91 @@ func TestLinkSharing(t *testing.T) { }) t.Run("Delete", func(t *testing.T) { t.Run("Shared readonly", func(t *testing.T) { - _, err := testHandlerListUserReadOnly.testDeleteWithLinkShare(nil, map[string]string{"list": "1"}) + _, err := testHandlerProjectUserReadOnly.testDeleteWithLinkShare(nil, map[string]string{"project": "1"}) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared write", func(t *testing.T) { - _, err := testHandlerListUserWrite.testDeleteWithLinkShare(nil, map[string]string{"list": "2"}) + _, err := testHandlerProjectUserWrite.testDeleteWithLinkShare(nil, map[string]string{"project": "2"}) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared admin", func(t *testing.T) { - _, err := testHandlerListUserAdmin.testDeleteWithLinkShare(nil, map[string]string{"list": "3"}) + _, err := testHandlerProjectUserAdmin.testDeleteWithLinkShare(nil, map[string]string{"project": "3"}) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) }) }) t.Run("Teams", func(t *testing.T) { - testHandlerListTeamReadOnly := webHandlerTest{ + testHandlerProjectTeamReadOnly := webHandlerTest{ linkShare: linkshareRead, strFunc: func() handler.CObject { - return &models.TeamList{} + return &models.TeamProject{} }, t: t, } - testHandlerListTeamWrite := webHandlerTest{ + testHandlerProjectTeamWrite := webHandlerTest{ linkShare: linkShareWrite, strFunc: func() handler.CObject { - return &models.TeamList{} + return &models.TeamProject{} }, t: t, } - testHandlerListTeamAdmin := webHandlerTest{ + testHandlerProjectTeamAdmin := webHandlerTest{ linkShare: linkShareAdmin, strFunc: func() handler.CObject { - return &models.TeamList{} + return &models.TeamProject{} }, t: t, } t.Run("ReadAll", func(t *testing.T) { t.Run("Shared readonly", func(t *testing.T) { - rec, err := testHandlerListTeamReadOnly.testReadAllWithLinkShare(nil, map[string]string{"list": "1"}) + rec, err := testHandlerProjectTeamReadOnly.testReadAllWithLinkShare(nil, map[string]string{"project": "1"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `[]`) }) t.Run("Shared write", func(t *testing.T) { - rec, err := testHandlerListTeamWrite.testReadAllWithLinkShare(nil, map[string]string{"list": "2"}) + rec, err := testHandlerProjectTeamWrite.testReadAllWithLinkShare(nil, map[string]string{"project": "2"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `[]`) }) t.Run("Shared admin", func(t *testing.T) { - rec, err := testHandlerListTeamAdmin.testReadAllWithLinkShare(nil, map[string]string{"list": "3"}) + rec, err := testHandlerProjectTeamAdmin.testReadAllWithLinkShare(nil, map[string]string{"project": "3"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"name":"testteam1"`) }) }) t.Run("Create", func(t *testing.T) { t.Run("Shared readonly", func(t *testing.T) { - _, err := testHandlerListTeamReadOnly.testCreateWithLinkShare(nil, map[string]string{"list": "1"}, `{"team_id":1}`) + _, err := testHandlerProjectTeamReadOnly.testCreateWithLinkShare(nil, map[string]string{"project": "1"}, `{"team_id":1}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared write", func(t *testing.T) { - _, err := testHandlerListTeamWrite.testCreateWithLinkShare(nil, map[string]string{"list": "2"}, `{"team_id":1}`) + _, err := testHandlerProjectTeamWrite.testCreateWithLinkShare(nil, map[string]string{"project": "2"}, `{"team_id":1}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared admin", func(t *testing.T) { - _, err := testHandlerListTeamAdmin.testCreateWithLinkShare(nil, map[string]string{"list": "3"}, `{"team_id":1}`) + _, err := testHandlerProjectTeamAdmin.testCreateWithLinkShare(nil, map[string]string{"project": "3"}, `{"team_id":1}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) }) t.Run("Update", func(t *testing.T) { t.Run("Shared readonly", func(t *testing.T) { - _, err := testHandlerListTeamReadOnly.testUpdateWithLinkShare(nil, map[string]string{"list": "1"}, `{"team_id":1}`) + _, err := testHandlerProjectTeamReadOnly.testUpdateWithLinkShare(nil, map[string]string{"project": "1"}, `{"team_id":1}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared write", func(t *testing.T) { - _, err := testHandlerListTeamWrite.testUpdateWithLinkShare(nil, map[string]string{"list": "2"}, `{"team_id":1}`) + _, err := testHandlerProjectTeamWrite.testUpdateWithLinkShare(nil, map[string]string{"project": "2"}, `{"team_id":1}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared admin", func(t *testing.T) { - _, err := testHandlerListTeamAdmin.testUpdateWithLinkShare(nil, map[string]string{"list": "3"}, `{"team_id":1}`) + _, err := testHandlerProjectTeamAdmin.testUpdateWithLinkShare(nil, map[string]string{"project": "3"}, `{"team_id":1}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) @@ -468,17 +468,17 @@ func TestLinkSharing(t *testing.T) { }) t.Run("Delete", func(t *testing.T) { t.Run("Shared readonly", func(t *testing.T) { - _, err := testHandlerListTeamReadOnly.testDeleteWithLinkShare(nil, map[string]string{"list": "1"}) + _, err := testHandlerProjectTeamReadOnly.testDeleteWithLinkShare(nil, map[string]string{"project": "1"}) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared write", func(t *testing.T) { - _, err := testHandlerListTeamWrite.testDeleteWithLinkShare(nil, map[string]string{"list": "2"}) + _, err := testHandlerProjectTeamWrite.testDeleteWithLinkShare(nil, map[string]string{"project": "2"}) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared admin", func(t *testing.T) { - _, err := testHandlerListTeamAdmin.testDeleteWithLinkShare(nil, map[string]string{"list": "3"}) + _, err := testHandlerProjectTeamAdmin.testDeleteWithLinkShare(nil, map[string]string{"project": "3"}) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) @@ -586,34 +586,34 @@ func TestLinkSharing(t *testing.T) { }) t.Run("Create", func(t *testing.T) { t.Run("Shared readonly", func(t *testing.T) { - _, err := testHandlerTaskReadOnly.testCreateWithLinkShare(nil, map[string]string{"list": "1"}, `{"title":"Lorem Ipsum"}`) + _, err := testHandlerTaskReadOnly.testCreateWithLinkShare(nil, map[string]string{"project": "1"}, `{"title":"Lorem Ipsum"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared write", func(t *testing.T) { - rec, err := testHandlerTaskWrite.testCreateWithLinkShare(nil, map[string]string{"list": "2"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandlerTaskWrite.testCreateWithLinkShare(nil, map[string]string{"project": "2"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) }) t.Run("Shared admin", func(t *testing.T) { - rec, err := testHandlerTaskAdmin.testCreateWithLinkShare(nil, map[string]string{"list": "3"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandlerTaskAdmin.testCreateWithLinkShare(nil, map[string]string{"project": "3"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) }) }) t.Run("Update", func(t *testing.T) { t.Run("Shared readonly", func(t *testing.T) { - _, err := testHandlerTaskReadOnly.testUpdateWithLinkShare(nil, map[string]string{"listtask": "1"}, `{"title":"Lorem Ipsum"}`) + _, err := testHandlerTaskReadOnly.testUpdateWithLinkShare(nil, map[string]string{"projecttask": "1"}, `{"title":"Lorem Ipsum"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared write", func(t *testing.T) { - rec, err := testHandlerTaskWrite.testUpdateWithLinkShare(nil, map[string]string{"listtask": "13"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandlerTaskWrite.testUpdateWithLinkShare(nil, map[string]string{"projecttask": "13"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) }) t.Run("Shared admin", func(t *testing.T) { - rec, err := testHandlerTaskAdmin.testUpdateWithLinkShare(nil, map[string]string{"listtask": "32"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandlerTaskAdmin.testUpdateWithLinkShare(nil, map[string]string{"projecttask": "32"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) }) @@ -621,17 +621,17 @@ func TestLinkSharing(t *testing.T) { }) t.Run("Delete", func(t *testing.T) { t.Run("Shared readonly", func(t *testing.T) { - _, err := testHandlerTaskReadOnly.testDeleteWithLinkShare(nil, map[string]string{"listtask": "1"}) + _, err := testHandlerTaskReadOnly.testDeleteWithLinkShare(nil, map[string]string{"projecttask": "1"}) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared write", func(t *testing.T) { - rec, err := testHandlerTaskWrite.testDeleteWithLinkShare(nil, map[string]string{"listtask": "13"}) + rec, err := testHandlerTaskWrite.testDeleteWithLinkShare(nil, map[string]string{"projecttask": "13"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `Successfully deleted.`) }) t.Run("Shared admin", func(t *testing.T) { - rec, err := testHandlerTaskAdmin.testDeleteWithLinkShare(nil, map[string]string{"listtask": "32"}) + rec, err := testHandlerTaskAdmin.testDeleteWithLinkShare(nil, map[string]string{"projecttask": "32"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `Successfully deleted.`) }) @@ -738,34 +738,34 @@ func TestLinkSharing(t *testing.T) { } t.Run("ReadAll", func(t *testing.T) { t.Run("Shared readonly", func(t *testing.T) { - rec, err := testHandlerLinkShareReadOnly.testReadAllWithLinkShare(nil, map[string]string{"list": "1"}) + rec, err := testHandlerLinkShareReadOnly.testReadAllWithLinkShare(nil, map[string]string{"project": "1"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"hash":"test"`) }) t.Run("Shared write", func(t *testing.T) { - rec, err := testHandlerLinkShareWrite.testReadAllWithLinkShare(nil, map[string]string{"list": "2"}) + rec, err := testHandlerLinkShareWrite.testReadAllWithLinkShare(nil, map[string]string{"project": "2"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"hash":"test2"`) }) t.Run("Shared admin", func(t *testing.T) { - rec, err := testHandlerLinkShareAdmin.testReadAllWithLinkShare(nil, map[string]string{"list": "3"}) + rec, err := testHandlerLinkShareAdmin.testReadAllWithLinkShare(nil, map[string]string{"project": "3"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"hash":"test3"`) }) }) t.Run("Create", func(t *testing.T) { t.Run("Shared readonly", func(t *testing.T) { - _, err := testHandlerLinkShareReadOnly.testCreateWithLinkShare(nil, map[string]string{"list": "1"}, `{}`) + _, err := testHandlerLinkShareReadOnly.testCreateWithLinkShare(nil, map[string]string{"project": "1"}, `{}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared write", func(t *testing.T) { - _, err := testHandlerLinkShareWrite.testCreateWithLinkShare(nil, map[string]string{"list": "2"}, `{}`) + _, err := testHandlerLinkShareWrite.testCreateWithLinkShare(nil, map[string]string{"project": "2"}, `{}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared admin", func(t *testing.T) { - _, err := testHandlerLinkShareAdmin.testCreateWithLinkShare(nil, map[string]string{"list": "3"}, `{}`) + _, err := testHandlerLinkShareAdmin.testCreateWithLinkShare(nil, map[string]string{"project": "3"}, `{}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) diff --git a/pkg/integrations/list_test.go b/pkg/integrations/list_test.go index bee49e973..94165d3bd 100644 --- a/pkg/integrations/list_test.go +++ b/pkg/integrations/list_test.go @@ -26,11 +26,11 @@ import ( "github.com/stretchr/testify/assert" ) -func TestList(t *testing.T) { +func TestProject(t *testing.T) { testHandler := webHandlerTest{ user: &testuser1, strFunc: func() handler.CObject { - return &models.List{} + return &models.Project{} }, t: t, } @@ -40,7 +40,7 @@ func TestList(t *testing.T) { assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `Test1`) assert.NotContains(t, rec.Body.String(), `Test2"`) - assert.Contains(t, rec.Body.String(), `Test3`) // Shared directly via users_list + assert.Contains(t, rec.Body.String(), `Test3`) // Shared directly via users_project assert.Contains(t, rec.Body.String(), `Test4`) // Shared via namespace assert.NotContains(t, rec.Body.String(), `Test5`) assert.NotContains(t, rec.Body.String(), `Test21`) // Archived through namespace @@ -55,12 +55,12 @@ func TestList(t *testing.T) { assert.NotContains(t, rec.Body.String(), `Test4`) assert.NotContains(t, rec.Body.String(), `Test5`) }) - t.Run("Normal with archived lists", func(t *testing.T) { + t.Run("Normal with archived projects", func(t *testing.T) { rec, err := testHandler.testReadAllWithUser(url.Values{"is_archived": []string{"true"}}, nil) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `Test1`) assert.NotContains(t, rec.Body.String(), `Test2"`) - assert.Contains(t, rec.Body.String(), `Test3`) // Shared directly via users_list + assert.Contains(t, rec.Body.String(), `Test3`) // Shared directly via users_project assert.Contains(t, rec.Body.String(), `Test4`) // Shared via namespace assert.NotContains(t, rec.Body.String(), `Test5`) assert.Contains(t, rec.Body.String(), `Test21`) // Archived through namespace @@ -69,7 +69,7 @@ func TestList(t *testing.T) { }) t.Run("ReadOne", func(t *testing.T) { t.Run("Normal", func(t *testing.T) { - rec, err := testHandler.testReadOneWithUser(nil, map[string]string{"list": "1"}) + rec, err := testHandler.testReadOneWithUser(nil, map[string]string{"project": "1"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Test1"`) assert.NotContains(t, rec.Body.String(), `"title":"Test2"`) @@ -79,89 +79,89 @@ func TestList(t *testing.T) { assert.Equal(t, "2", rec.Result().Header.Get("x-max-right")) // User 1 is owner so they should have admin rights. }) t.Run("Nonexisting", func(t *testing.T) { - _, err := testHandler.testReadOneWithUser(nil, map[string]string{"list": "9999"}) + _, err := testHandler.testReadOneWithUser(nil, map[string]string{"project": "9999"}) assert.Error(t, err) - assertHandlerErrorCode(t, err, models.ErrCodeListDoesNotExist) + assertHandlerErrorCode(t, err, models.ErrCodeProjectDoesNotExist) }) t.Run("Rights check", func(t *testing.T) { t.Run("Forbidden", func(t *testing.T) { // Owned by user13 - rec, err := testHandler.testReadOneWithUser(nil, map[string]string{"list": "20"}) + rec, err := testHandler.testReadOneWithUser(nil, map[string]string{"project": "20"}) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `You don't have the right to see this`) assert.Empty(t, rec.Result().Header.Get("x-max-rights")) }) t.Run("Shared Via Team readonly", func(t *testing.T) { - rec, err := testHandler.testReadOneWithUser(nil, map[string]string{"list": "6"}) + rec, err := testHandler.testReadOneWithUser(nil, map[string]string{"project": "6"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Test6"`) assert.Equal(t, "0", rec.Result().Header.Get("x-max-right")) }) t.Run("Shared Via Team write", func(t *testing.T) { - rec, err := testHandler.testReadOneWithUser(nil, map[string]string{"list": "7"}) + rec, err := testHandler.testReadOneWithUser(nil, map[string]string{"project": "7"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Test7"`) assert.Equal(t, "1", rec.Result().Header.Get("x-max-right")) }) t.Run("Shared Via Team admin", func(t *testing.T) { - rec, err := testHandler.testReadOneWithUser(nil, map[string]string{"list": "8"}) + rec, err := testHandler.testReadOneWithUser(nil, map[string]string{"project": "8"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Test8"`) assert.Equal(t, "2", rec.Result().Header.Get("x-max-right")) }) t.Run("Shared Via User readonly", func(t *testing.T) { - rec, err := testHandler.testReadOneWithUser(nil, map[string]string{"list": "9"}) + rec, err := testHandler.testReadOneWithUser(nil, map[string]string{"project": "9"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Test9"`) assert.Equal(t, "0", rec.Result().Header.Get("x-max-right")) }) t.Run("Shared Via User write", func(t *testing.T) { - rec, err := testHandler.testReadOneWithUser(nil, map[string]string{"list": "10"}) + rec, err := testHandler.testReadOneWithUser(nil, map[string]string{"project": "10"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Test10"`) assert.Equal(t, "1", rec.Result().Header.Get("x-max-right")) }) t.Run("Shared Via User admin", func(t *testing.T) { - rec, err := testHandler.testReadOneWithUser(nil, map[string]string{"list": "11"}) + rec, err := testHandler.testReadOneWithUser(nil, map[string]string{"project": "11"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Test11"`) assert.Equal(t, "2", rec.Result().Header.Get("x-max-right")) }) t.Run("Shared Via NamespaceTeam readonly", func(t *testing.T) { - rec, err := testHandler.testReadOneWithUser(nil, map[string]string{"list": "12"}) + rec, err := testHandler.testReadOneWithUser(nil, map[string]string{"project": "12"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Test12"`) assert.Equal(t, "0", rec.Result().Header.Get("x-max-right")) }) t.Run("Shared Via NamespaceTeam write", func(t *testing.T) { - rec, err := testHandler.testReadOneWithUser(nil, map[string]string{"list": "13"}) + rec, err := testHandler.testReadOneWithUser(nil, map[string]string{"project": "13"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Test13"`) assert.Equal(t, "1", rec.Result().Header.Get("x-max-right")) }) t.Run("Shared Via NamespaceTeam admin", func(t *testing.T) { - rec, err := testHandler.testReadOneWithUser(nil, map[string]string{"list": "14"}) + rec, err := testHandler.testReadOneWithUser(nil, map[string]string{"project": "14"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Test14"`) assert.Equal(t, "2", rec.Result().Header.Get("x-max-right")) }) t.Run("Shared Via NamespaceUser readonly", func(t *testing.T) { - rec, err := testHandler.testReadOneWithUser(nil, map[string]string{"list": "15"}) + rec, err := testHandler.testReadOneWithUser(nil, map[string]string{"project": "15"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Test15"`) assert.Equal(t, "0", rec.Result().Header.Get("x-max-right")) }) t.Run("Shared Via NamespaceUser write", func(t *testing.T) { - rec, err := testHandler.testReadOneWithUser(nil, map[string]string{"list": "16"}) + rec, err := testHandler.testReadOneWithUser(nil, map[string]string{"project": "16"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Test16"`) assert.Equal(t, "1", rec.Result().Header.Get("x-max-right")) }) t.Run("Shared Via NamespaceUser admin", func(t *testing.T) { - rec, err := testHandler.testReadOneWithUser(nil, map[string]string{"list": "17"}) + rec, err := testHandler.testReadOneWithUser(nil, map[string]string{"project": "17"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Test17"`) assert.Equal(t, "2", rec.Result().Header.Get("x-max-right")) @@ -170,101 +170,101 @@ func TestList(t *testing.T) { }) t.Run("Update", func(t *testing.T) { t.Run("Normal", func(t *testing.T) { - // Check the list was loaded successfully afterwards, see testReadOneWithUser - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"list": "1"}, `{"title":"TestLoremIpsum","namespace_id":1}`) + // Check the project was loaded successfully afterwards, see testReadOneWithUser + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"project": "1"}, `{"title":"TestLoremIpsum","namespace_id":1}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"TestLoremIpsum"`) // The description should not be updated but returned correctly assert.Contains(t, rec.Body.String(), `description":"Lorem Ipsum`) }) t.Run("Nonexisting", func(t *testing.T) { - _, err := testHandler.testUpdateWithUser(nil, map[string]string{"list": "9999"}, `{"title":"TestLoremIpsum"}`) + _, err := testHandler.testUpdateWithUser(nil, map[string]string{"project": "9999"}, `{"title":"TestLoremIpsum"}`) assert.Error(t, err) - assertHandlerErrorCode(t, err, models.ErrCodeListDoesNotExist) + assertHandlerErrorCode(t, err, models.ErrCodeProjectDoesNotExist) }) t.Run("Normal with updating the description", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"list": "1"}, `{"title":"TestLoremIpsum","description":"Lorem Ipsum dolor sit amet","namespace_id":1}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"project": "1"}, `{"title":"TestLoremIpsum","description":"Lorem Ipsum dolor sit amet","namespace_id":1}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"TestLoremIpsum"`) assert.Contains(t, rec.Body.String(), `"description":"Lorem Ipsum dolor sit amet`) }) t.Run("Empty title", func(t *testing.T) { - _, err := testHandler.testUpdateWithUser(nil, map[string]string{"list": "1"}, `{"title":""}`) + _, err := testHandler.testUpdateWithUser(nil, map[string]string{"project": "1"}, `{"title":""}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message.(models.ValidationHTTPError).InvalidFields, "title: non zero value required") }) t.Run("Title too long", func(t *testing.T) { - _, err := testHandler.testUpdateWithUser(nil, map[string]string{"list": "1"}, `{"title":"Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea taki"}`) + _, err := testHandler.testUpdateWithUser(nil, map[string]string{"project": "1"}, `{"title":"Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea taki"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message.(models.ValidationHTTPError).InvalidFields[0], "does not validate as runelength(1|250)") }) t.Run("Rights check", func(t *testing.T) { t.Run("Forbidden", func(t *testing.T) { // Owned by user13 - _, err := testHandler.testUpdateWithUser(nil, map[string]string{"list": "20"}, `{"title":"TestLoremIpsum"}`) + _, err := testHandler.testUpdateWithUser(nil, map[string]string{"project": "20"}, `{"title":"TestLoremIpsum"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via Team readonly", func(t *testing.T) { - _, err := testHandler.testUpdateWithUser(nil, map[string]string{"list": "6"}, `{"title":"TestLoremIpsum"}`) + _, err := testHandler.testUpdateWithUser(nil, map[string]string{"project": "6"}, `{"title":"TestLoremIpsum"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via Team write", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"list": "7"}, `{"title":"TestLoremIpsum","namespace_id":6}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"project": "7"}, `{"title":"TestLoremIpsum","namespace_id":6}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"TestLoremIpsum"`) }) t.Run("Shared Via Team admin", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"list": "8"}, `{"title":"TestLoremIpsum","namespace_id":6}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"project": "8"}, `{"title":"TestLoremIpsum","namespace_id":6}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"TestLoremIpsum"`) }) t.Run("Shared Via User readonly", func(t *testing.T) { - _, err := testHandler.testUpdateWithUser(nil, map[string]string{"list": "9"}, `{"title":"TestLoremIpsum"}`) + _, err := testHandler.testUpdateWithUser(nil, map[string]string{"project": "9"}, `{"title":"TestLoremIpsum"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via User write", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"list": "10"}, `{"title":"TestLoremIpsum","namespace_id":6}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"project": "10"}, `{"title":"TestLoremIpsum","namespace_id":6}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"TestLoremIpsum"`) }) t.Run("Shared Via User admin", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"list": "11"}, `{"title":"TestLoremIpsum","namespace_id":6}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"project": "11"}, `{"title":"TestLoremIpsum","namespace_id":6}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"TestLoremIpsum"`) }) t.Run("Shared Via NamespaceTeam readonly", func(t *testing.T) { - _, err := testHandler.testUpdateWithUser(nil, map[string]string{"list": "12"}, `{"title":"TestLoremIpsum"}`) + _, err := testHandler.testUpdateWithUser(nil, map[string]string{"project": "12"}, `{"title":"TestLoremIpsum"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via NamespaceTeam write", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"list": "13"}, `{"title":"TestLoremIpsum","namespace_id":8}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"project": "13"}, `{"title":"TestLoremIpsum","namespace_id":8}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"TestLoremIpsum"`) }) t.Run("Shared Via NamespaceTeam admin", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"list": "14"}, `{"title":"TestLoremIpsum","namespace_id":9}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"project": "14"}, `{"title":"TestLoremIpsum","namespace_id":9}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"TestLoremIpsum"`) }) t.Run("Shared Via NamespaceUser readonly", func(t *testing.T) { - _, err := testHandler.testUpdateWithUser(nil, map[string]string{"list": "15"}, `{"title":"TestLoremIpsum"}`) + _, err := testHandler.testUpdateWithUser(nil, map[string]string{"project": "15"}, `{"title":"TestLoremIpsum"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via NamespaceUser write", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"list": "16"}, `{"title":"TestLoremIpsum","namespace_id":11}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"project": "16"}, `{"title":"TestLoremIpsum","namespace_id":11}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"TestLoremIpsum"`) }) t.Run("Shared Via NamespaceUser admin", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"list": "17"}, `{"title":"TestLoremIpsum","namespace_id":12}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"project": "17"}, `{"title":"TestLoremIpsum","namespace_id":12}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"TestLoremIpsum"`) }) @@ -272,82 +272,82 @@ func TestList(t *testing.T) { }) t.Run("Delete", func(t *testing.T) { t.Run("Normal", func(t *testing.T) { - rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"list": "1"}) + rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"project": "1"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"message":"Successfully deleted."`) }) t.Run("Nonexisting", func(t *testing.T) { - _, err := testHandler.testDeleteWithUser(nil, map[string]string{"list": "999"}) + _, err := testHandler.testDeleteWithUser(nil, map[string]string{"project": "999"}) assert.Error(t, err) - assertHandlerErrorCode(t, err, models.ErrCodeListDoesNotExist) + assertHandlerErrorCode(t, err, models.ErrCodeProjectDoesNotExist) }) t.Run("Rights check", func(t *testing.T) { t.Run("Forbidden", func(t *testing.T) { // Owned by user13 - _, err := testHandler.testDeleteWithUser(nil, map[string]string{"list": "20"}) + _, err := testHandler.testDeleteWithUser(nil, map[string]string{"project": "20"}) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via Team readonly", func(t *testing.T) { - _, err := testHandler.testDeleteWithUser(nil, map[string]string{"list": "6"}) + _, err := testHandler.testDeleteWithUser(nil, map[string]string{"project": "6"}) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via Team write", func(t *testing.T) { - _, err := testHandler.testDeleteWithUser(nil, map[string]string{"list": "7"}) + _, err := testHandler.testDeleteWithUser(nil, map[string]string{"project": "7"}) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via Team admin", func(t *testing.T) { - rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"list": "8"}) + rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"project": "8"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"message":"Successfully deleted."`) }) t.Run("Shared Via User readonly", func(t *testing.T) { - _, err := testHandler.testDeleteWithUser(nil, map[string]string{"list": "9"}) + _, err := testHandler.testDeleteWithUser(nil, map[string]string{"project": "9"}) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via User write", func(t *testing.T) { - _, err := testHandler.testDeleteWithUser(nil, map[string]string{"list": "10"}) + _, err := testHandler.testDeleteWithUser(nil, map[string]string{"project": "10"}) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via User admin", func(t *testing.T) { - rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"list": "11"}) + rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"project": "11"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"message":"Successfully deleted."`) }) t.Run("Shared Via NamespaceTeam readonly", func(t *testing.T) { - _, err := testHandler.testDeleteWithUser(nil, map[string]string{"list": "12"}) + _, err := testHandler.testDeleteWithUser(nil, map[string]string{"project": "12"}) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via NamespaceTeam write", func(t *testing.T) { - _, err := testHandler.testDeleteWithUser(nil, map[string]string{"list": "13"}) + _, err := testHandler.testDeleteWithUser(nil, map[string]string{"project": "13"}) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via NamespaceTeam admin", func(t *testing.T) { - rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"list": "14"}) + rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"project": "14"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"message":"Successfully deleted."`) }) t.Run("Shared Via NamespaceUser readonly", func(t *testing.T) { - _, err := testHandler.testDeleteWithUser(nil, map[string]string{"list": "15"}) + _, err := testHandler.testDeleteWithUser(nil, map[string]string{"project": "15"}) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via NamespaceUser write", func(t *testing.T) { - _, err := testHandler.testDeleteWithUser(nil, map[string]string{"list": "16"}) + _, err := testHandler.testDeleteWithUser(nil, map[string]string{"project": "16"}) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via NamespaceUser admin", func(t *testing.T) { - rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"list": "17"}) + rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"project": "17"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"message":"Successfully deleted."`) }) @@ -355,7 +355,7 @@ func TestList(t *testing.T) { }) t.Run("Create", func(t *testing.T) { t.Run("Normal", func(t *testing.T) { - // Check the list was loaded successfully after update, see testReadOneWithUser + // Check the project was loaded successfully after update, see testReadOneWithUser rec, err := testHandler.testCreateWithUser(nil, map[string]string{"namespace": "1"}, `{"title":"Lorem"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem"`) diff --git a/pkg/integrations/task_collection_test.go b/pkg/integrations/task_collection_test.go index 93ba86df0..d7d936868 100644 --- a/pkg/integrations/task_collection_test.go +++ b/pkg/integrations/task_collection_test.go @@ -33,9 +33,9 @@ func TestTaskCollection(t *testing.T) { }, t: t, } - t.Run("ReadAll on list", func(t *testing.T) { + t.Run("ReadAll on project", func(t *testing.T) { - urlParams := map[string]string{"list": "1"} + urlParams := map[string]string{"project": "1"} t.Run("Normal", func(t *testing.T) { rec, err := testHandler.testReadAllWithUser(nil, urlParams) @@ -113,49 +113,49 @@ func TestTaskCollection(t *testing.T) { t.Run("by priority", func(t *testing.T) { rec, err := testHandler.testReadAllWithUser(url.Values{"sort_by": []string{"priority"}}, urlParams) assert.NoError(t, err) - assert.Contains(t, rec.Body.String(), `{"id":33,"title":"task #33 with percent done","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"0001-01-01T00:00:00Z","reminder_dates":null,"list_id":1,"repeat_after":0,"repeat_mode":0,"priority":0,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0.5,"identifier":"test1-17","index":17,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":1,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}}]`) + assert.Contains(t, rec.Body.String(), `{"id":33,"title":"task #33 with percent done","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"0001-01-01T00:00:00Z","reminder_dates":null,"project_id":1,"repeat_after":0,"repeat_mode":0,"priority":0,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0.5,"identifier":"test1-17","index":17,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":1,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}}]`) }) t.Run("by priority desc", func(t *testing.T) { rec, err := testHandler.testReadAllWithUser(url.Values{"sort_by": []string{"priority"}, "order_by": []string{"desc"}}, urlParams) assert.NoError(t, err) - assert.Contains(t, rec.Body.String(), `[{"id":3,"title":"task #3 high prio","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"0001-01-01T00:00:00Z","reminder_dates":null,"list_id":1,"repeat_after":0,"repeat_mode":0,"priority":100,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0,"identifier":"test1-3","index":3,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":2,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}},{"id":4,"title":"task #4 low prio","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"0001-01-01T00:00:00Z","reminder_dates":null,"list_id":1,"repeat_after":0,"repeat_mode":0,"priority":1`) + assert.Contains(t, rec.Body.String(), `[{"id":3,"title":"task #3 high prio","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"0001-01-01T00:00:00Z","reminder_dates":null,"project_id":1,"repeat_after":0,"repeat_mode":0,"priority":100,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0,"identifier":"test1-3","index":3,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":2,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}},{"id":4,"title":"task #4 low prio","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"0001-01-01T00:00:00Z","reminder_dates":null,"project_id":1,"repeat_after":0,"repeat_mode":0,"priority":1`) }) t.Run("by priority asc", func(t *testing.T) { rec, err := testHandler.testReadAllWithUser(url.Values{"sort_by": []string{"priority"}, "order_by": []string{"asc"}}, urlParams) assert.NoError(t, err) - assert.Contains(t, rec.Body.String(), `{"id":33,"title":"task #33 with percent done","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"0001-01-01T00:00:00Z","reminder_dates":null,"list_id":1,"repeat_after":0,"repeat_mode":0,"priority":0,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0.5,"identifier":"test1-17","index":17,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":1,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}}]`) + assert.Contains(t, rec.Body.String(), `{"id":33,"title":"task #33 with percent done","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"0001-01-01T00:00:00Z","reminder_dates":null,"project_id":1,"repeat_after":0,"repeat_mode":0,"priority":0,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0.5,"identifier":"test1-17","index":17,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":1,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}}]`) }) // should equal duedate asc t.Run("by due_date", func(t *testing.T) { rec, err := testHandler.testReadAllWithUser(url.Values{"sort_by": []string{"due_date"}}, urlParams) assert.NoError(t, err) - assert.Contains(t, rec.Body.String(), `[{"id":6,"title":"task #6 lower due date","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"2018-11-30T22:25:24Z","reminder_dates":null,"list_id":1,"repeat_after":0,"repeat_mode":0,"priority":0,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0,"identifier":"test1-6","index":6,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":3,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}}`) + assert.Contains(t, rec.Body.String(), `[{"id":6,"title":"task #6 lower due date","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"2018-11-30T22:25:24Z","reminder_dates":null,"project_id":1,"repeat_after":0,"repeat_mode":0,"priority":0,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0,"identifier":"test1-6","index":6,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":3,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}}`) }) t.Run("by duedate desc", func(t *testing.T) { rec, err := testHandler.testReadAllWithUser(url.Values{"sort_by": []string{"due_date"}, "order_by": []string{"desc"}}, urlParams) assert.NoError(t, err) - assert.Contains(t, rec.Body.String(), `[{"id":5,"title":"task #5 higher due date","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"2018-12-01T03:58:44Z","reminder_dates":null,"list_id":1,"repeat_after":0,"repeat_mode":0,"priority":0,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0,"identifier":"test1-5","index":5,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":2,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}},{"id":6,"title":"task #6 lower due date`) + assert.Contains(t, rec.Body.String(), `[{"id":5,"title":"task #5 higher due date","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"2018-12-01T03:58:44Z","reminder_dates":null,"project_id":1,"repeat_after":0,"repeat_mode":0,"priority":0,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0,"identifier":"test1-5","index":5,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":2,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}},{"id":6,"title":"task #6 lower due date`) }) // Due date without unix suffix t.Run("by duedate asc without suffix", func(t *testing.T) { rec, err := testHandler.testReadAllWithUser(url.Values{"sort_by": []string{"due_date"}, "order_by": []string{"asc"}}, urlParams) assert.NoError(t, err) - assert.Contains(t, rec.Body.String(), `[{"id":6,"title":"task #6 lower due date","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"2018-11-30T22:25:24Z","reminder_dates":null,"list_id":1,"repeat_after":0,"repeat_mode":0,"priority":0,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0,"identifier":"test1-6","index":6,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":3,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}}`) + assert.Contains(t, rec.Body.String(), `[{"id":6,"title":"task #6 lower due date","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"2018-11-30T22:25:24Z","reminder_dates":null,"project_id":1,"repeat_after":0,"repeat_mode":0,"priority":0,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0,"identifier":"test1-6","index":6,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":3,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}}`) }) t.Run("by due_date without suffix", func(t *testing.T) { rec, err := testHandler.testReadAllWithUser(url.Values{"sort_by": []string{"due_date"}}, urlParams) assert.NoError(t, err) - assert.Contains(t, rec.Body.String(), `[{"id":6,"title":"task #6 lower due date","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"2018-11-30T22:25:24Z","reminder_dates":null,"list_id":1,"repeat_after":0,"repeat_mode":0,"priority":0,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0,"identifier":"test1-6","index":6,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":3,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}}`) + assert.Contains(t, rec.Body.String(), `[{"id":6,"title":"task #6 lower due date","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"2018-11-30T22:25:24Z","reminder_dates":null,"project_id":1,"repeat_after":0,"repeat_mode":0,"priority":0,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0,"identifier":"test1-6","index":6,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":3,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}}`) }) t.Run("by duedate desc without suffix", func(t *testing.T) { rec, err := testHandler.testReadAllWithUser(url.Values{"sort_by": []string{"due_date"}, "order_by": []string{"desc"}}, urlParams) assert.NoError(t, err) - assert.Contains(t, rec.Body.String(), `[{"id":5,"title":"task #5 higher due date","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"2018-12-01T03:58:44Z","reminder_dates":null,"list_id":1,"repeat_after":0,"repeat_mode":0,"priority":0,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0,"identifier":"test1-5","index":5,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":2,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}},{"id":6,"title":"task #6 lower due date`) + assert.Contains(t, rec.Body.String(), `[{"id":5,"title":"task #5 higher due date","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"2018-12-01T03:58:44Z","reminder_dates":null,"project_id":1,"repeat_after":0,"repeat_mode":0,"priority":0,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0,"identifier":"test1-5","index":5,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":2,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}},{"id":6,"title":"task #6 lower due date`) }) t.Run("by duedate asc", func(t *testing.T) { rec, err := testHandler.testReadAllWithUser(url.Values{"sort_by": []string{"due_date"}, "order_by": []string{"asc"}}, urlParams) assert.NoError(t, err) - assert.Contains(t, rec.Body.String(), `[{"id":6,"title":"task #6 lower due date","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"2018-11-30T22:25:24Z","reminder_dates":null,"list_id":1,"repeat_after":0,"repeat_mode":0,"priority":0,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0,"identifier":"test1-6","index":6,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":3,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}}`) + assert.Contains(t, rec.Body.String(), `[{"id":6,"title":"task #6 lower due date","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"2018-11-30T22:25:24Z","reminder_dates":null,"project_id":1,"repeat_after":0,"repeat_mode":0,"priority":0,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0,"identifier":"test1-6","index":6,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":3,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}}`) }) t.Run("invalid sort parameter", func(t *testing.T) { _, err := testHandler.testReadAllWithUser(url.Values{"sort_by": []string{"loremipsum"}}, urlParams) @@ -287,7 +287,7 @@ func TestTaskCollection(t *testing.T) { t.Run("date range", func(t *testing.T) { rec, err := testHandler.testReadAllWithUser( nil, - map[string]string{"list": "-2"}, // Actually a saved filter - contains the same filter arguments as the start and end date filter from above + map[string]string{"project": "-2"}, // Actually a saved filter - contains the same filter arguments as the start and end date filter from above ) assert.NoError(t, err) assert.NotContains(t, rec.Body.String(), `task #1`) @@ -341,7 +341,7 @@ func TestTaskCollection(t *testing.T) { assert.Contains(t, rec.Body.String(), `task #24`) // Shared via namespace user readonly assert.Contains(t, rec.Body.String(), `task #25`) // Shared via namespace user write assert.Contains(t, rec.Body.String(), `task #26`) // Shared via namespace user admin - // TODO: Add some cases where the user has access to the list, somhow shared + // TODO: Add some cases where the user has access to the project, somhow shared }) t.Run("Search", func(t *testing.T) { rec, err := testHandler.testReadAllWithUser(url.Values{"s": []string{"task #6"}}, nil) @@ -366,33 +366,33 @@ func TestTaskCollection(t *testing.T) { t.Run("by priority", func(t *testing.T) { rec, err := testHandler.testReadAllWithUser(url.Values{"sort_by": []string{"priority"}}, nil) assert.NoError(t, err) - assert.Contains(t, rec.Body.String(), `{"id":33,"title":"task #33 with percent done","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"0001-01-01T00:00:00Z","reminder_dates":null,"list_id":1,"repeat_after":0,"repeat_mode":0,"priority":0,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0.5,"identifier":"test1-17","index":17,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":1,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}}]`) + assert.Contains(t, rec.Body.String(), `{"id":33,"title":"task #33 with percent done","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"0001-01-01T00:00:00Z","reminder_dates":null,"project_id":1,"repeat_after":0,"repeat_mode":0,"priority":0,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0.5,"identifier":"test1-17","index":17,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":1,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}}]`) }) t.Run("by priority desc", func(t *testing.T) { rec, err := testHandler.testReadAllWithUser(url.Values{"sort_by": []string{"priority"}, "order_by": []string{"desc"}}, nil) assert.NoError(t, err) - assert.Contains(t, rec.Body.String(), `[{"id":3,"title":"task #3 high prio","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"0001-01-01T00:00:00Z","reminder_dates":null,"list_id":1,"repeat_after":0,"repeat_mode":0,"priority":100,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0,"identifier":"test1-3","index":3,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":2,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}},{"id":4,"title":"task #4 low prio","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"0001-01-01T00:00:00Z","reminder_dates":null,"list_id":1,"repeat_after":0,"repeat_mode":0,"priority":1`) + assert.Contains(t, rec.Body.String(), `[{"id":3,"title":"task #3 high prio","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"0001-01-01T00:00:00Z","reminder_dates":null,"project_id":1,"repeat_after":0,"repeat_mode":0,"priority":100,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0,"identifier":"test1-3","index":3,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":2,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}},{"id":4,"title":"task #4 low prio","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"0001-01-01T00:00:00Z","reminder_dates":null,"project_id":1,"repeat_after":0,"repeat_mode":0,"priority":1`) }) t.Run("by priority asc", func(t *testing.T) { rec, err := testHandler.testReadAllWithUser(url.Values{"sort_by": []string{"priority"}, "order_by": []string{"asc"}}, nil) assert.NoError(t, err) - assert.Contains(t, rec.Body.String(), `{"id":33,"title":"task #33 with percent done","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"0001-01-01T00:00:00Z","reminder_dates":null,"list_id":1,"repeat_after":0,"repeat_mode":0,"priority":0,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0.5,"identifier":"test1-17","index":17,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":1,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}}]`) + assert.Contains(t, rec.Body.String(), `{"id":33,"title":"task #33 with percent done","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"0001-01-01T00:00:00Z","reminder_dates":null,"project_id":1,"repeat_after":0,"repeat_mode":0,"priority":0,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0.5,"identifier":"test1-17","index":17,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":1,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}}]`) }) // should equal duedate asc t.Run("by due_date", func(t *testing.T) { rec, err := testHandler.testReadAllWithUser(url.Values{"sort_by": []string{"due_date"}}, nil) assert.NoError(t, err) - assert.Contains(t, rec.Body.String(), `[{"id":6,"title":"task #6 lower due date","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"2018-11-30T22:25:24Z","reminder_dates":null,"list_id":1,"repeat_after":0,"repeat_mode":0,"priority":0,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0,"identifier":"test1-6","index":6,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":3,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}},{"id":5,"title":"task #5 higher due date","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"2018-12-01T03:58:44Z","reminder_dates":null,"list_id":1,"repeat_after":0,"repeat_mode":0,"priority":0,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0,"identifier":"test1-5","index":5,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":2,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}}`) + assert.Contains(t, rec.Body.String(), `[{"id":6,"title":"task #6 lower due date","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"2018-11-30T22:25:24Z","reminder_dates":null,"project_id":1,"repeat_after":0,"repeat_mode":0,"priority":0,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0,"identifier":"test1-6","index":6,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":3,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}},{"id":5,"title":"task #5 higher due date","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"2018-12-01T03:58:44Z","reminder_dates":null,"project_id":1,"repeat_after":0,"repeat_mode":0,"priority":0,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0,"identifier":"test1-5","index":5,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":2,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}}`) }) t.Run("by duedate desc", func(t *testing.T) { rec, err := testHandler.testReadAllWithUser(url.Values{"sort_by": []string{"due_date"}, "order_by": []string{"desc"}}, nil) assert.NoError(t, err) - assert.Contains(t, rec.Body.String(), `[{"id":5,"title":"task #5 higher due date","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"2018-12-01T03:58:44Z","reminder_dates":null,"list_id":1,"repeat_after":0,"repeat_mode":0,"priority":0,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0,"identifier":"test1-5","index":5,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":2,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}},{"id":6,"title":"task #6 lower due date`) + assert.Contains(t, rec.Body.String(), `[{"id":5,"title":"task #5 higher due date","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"2018-12-01T03:58:44Z","reminder_dates":null,"project_id":1,"repeat_after":0,"repeat_mode":0,"priority":0,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0,"identifier":"test1-5","index":5,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":2,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}},{"id":6,"title":"task #6 lower due date`) }) t.Run("by duedate asc", func(t *testing.T) { rec, err := testHandler.testReadAllWithUser(url.Values{"sort_by": []string{"due_date"}, "order_by": []string{"asc"}}, nil) assert.NoError(t, err) - assert.Contains(t, rec.Body.String(), `[{"id":6,"title":"task #6 lower due date","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"2018-11-30T22:25:24Z","reminder_dates":null,"list_id":1,"repeat_after":0,"repeat_mode":0,"priority":0,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0,"identifier":"test1-6","index":6,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":3,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}},{"id":5,"title":"task #5 higher due date","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"2018-12-01T03:58:44Z","reminder_dates":null,"list_id":1,"repeat_after":0,"repeat_mode":0,"priority":0,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0,"identifier":"test1-5","index":5,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":2,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}}`) + assert.Contains(t, rec.Body.String(), `[{"id":6,"title":"task #6 lower due date","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"2018-11-30T22:25:24Z","reminder_dates":null,"project_id":1,"repeat_after":0,"repeat_mode":0,"priority":0,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0,"identifier":"test1-6","index":6,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":3,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}},{"id":5,"title":"task #5 higher due date","description":"","done":false,"done_at":"0001-01-01T00:00:00Z","due_date":"2018-12-01T03:58:44Z","reminder_dates":null,"project_id":1,"repeat_after":0,"repeat_mode":0,"priority":0,"start_date":"0001-01-01T00:00:00Z","end_date":"0001-01-01T00:00:00Z","assignees":null,"labels":null,"hex_color":"","percent_done":0,"identifier":"test1-5","index":5,"related_tasks":{},"attachments":null,"cover_image_attachment_id":0,"is_favorite":false,"created":"2018-12-01T01:12:04Z","updated":"2018-12-01T01:12:04Z","bucket_id":2,"position":0,"kanban_position":0,"created_by":{"id":1,"name":"","username":"user1","created":"2018-12-01T15:13:12Z","updated":"2018-12-02T15:13:12Z"}}`) }) t.Run("invalid parameter", func(t *testing.T) { // Invalid parameter should not sort at all diff --git a/pkg/integrations/task_comment_test.go b/pkg/integrations/task_comment_test.go index b90007047..6d1959e87 100644 --- a/pkg/integrations/task_comment_test.go +++ b/pkg/integrations/task_comment_test.go @@ -39,7 +39,7 @@ func TestTaskComments(t *testing.T) { linkShare: &models.LinkSharing{ ID: 2, Hash: "test2", - ListID: 2, + ProjectID: 2, Right: models.RightWrite, SharingType: models.SharingTypeWithoutPassword, SharedByID: 1, diff --git a/pkg/integrations/task_test.go b/pkg/integrations/task_test.go index 1a09f92c9..dc6c662cf 100644 --- a/pkg/integrations/task_test.go +++ b/pkg/integrations/task_test.go @@ -39,7 +39,7 @@ func TestTask(t *testing.T) { linkShare: &models.LinkSharing{ ID: 2, Hash: "test2", - ListID: 2, + ProjectID: 2, Right: models.RightWrite, SharingType: models.SharingTypeWithoutPassword, SharedByID: 1, @@ -54,157 +54,157 @@ func TestTask(t *testing.T) { t.Run("Update", func(t *testing.T) { t.Run("Update task items", func(t *testing.T) { t.Run("Title", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "1"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "1"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) assert.NotContains(t, rec.Body.String(), `"title":"task #1"`) }) t.Run("Description", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "1"}, `{"description":"Dolor sit amet"}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "1"}, `{"description":"Dolor sit amet"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"description":"Dolor sit amet"`) assert.NotContains(t, rec.Body.String(), `"description":"Lorem Ipsum"`) }) t.Run("Description to empty", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "1"}, `{"description":""}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "1"}, `{"description":""}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"description":""`) assert.NotContains(t, rec.Body.String(), `"description":"Lorem Ipsum"`) }) t.Run("Done", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "1"}, `{"done":true}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "1"}, `{"done":true}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"done":true`) assert.NotContains(t, rec.Body.String(), `"done":false`) }) t.Run("Undone", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "2"}, `{"done":false}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "2"}, `{"done":false}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"done":false`) assert.NotContains(t, rec.Body.String(), `"done":true`) }) t.Run("Due date", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "1"}, `{"due_date": "2020-02-10T10:00:00Z"}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "1"}, `{"due_date": "2020-02-10T10:00:00Z"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"due_date":"2020-02-10T10:00:00Z"`) assert.NotContains(t, rec.Body.String(), `"due_date":0`) }) t.Run("Due date unset", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "5"}, `{"due_date": null}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "5"}, `{"due_date": null}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"due_date":"0001-01-01T00:00:00Z"`) assert.NotContains(t, rec.Body.String(), `"due_date":"2020-02-10T10:00:00Z"`) }) t.Run("Reminders", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "1"}, `{"reminder_dates": ["2020-02-10T10:00:00Z","2020-02-11T10:00:00Z"]}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "1"}, `{"reminder_dates": ["2020-02-10T10:00:00Z","2020-02-11T10:00:00Z"]}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"reminder_dates":["2020-02-10T10:00:00Z","2020-02-11T10:00:00Z"]`) assert.NotContains(t, rec.Body.String(), `"reminder_dates": null`) }) t.Run("Reminders unset to empty array", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "27"}, `{"reminder_dates": []}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "27"}, `{"reminder_dates": []}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"reminder_dates":null`) assert.NotContains(t, rec.Body.String(), `"reminder_dates":[1543626724,1543626824]`) }) t.Run("Reminders unset to null", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "27"}, `{"reminder_dates": null}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "27"}, `{"reminder_dates": null}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"reminder_dates":null`) assert.NotContains(t, rec.Body.String(), `"reminder_dates":[1543626724,1543626824]`) }) t.Run("Repeat after", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "1"}, `{"repeat_after":3600}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "1"}, `{"repeat_after":3600}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"repeat_after":3600`) assert.NotContains(t, rec.Body.String(), `"repeat_after":0`) }) t.Run("Repeat after unset", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "28"}, `{"repeat_after":0}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "28"}, `{"repeat_after":0}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"repeat_after":0`) assert.NotContains(t, rec.Body.String(), `"repeat_after":3600`) }) t.Run("Repeat after update done", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "28"}, `{"done":true}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "28"}, `{"done":true}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"done":false`) assert.NotContains(t, rec.Body.String(), `"done":true`) }) t.Run("Assignees", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "1"}, `{"assignees":[{"id":1}]}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "1"}, `{"assignees":[{"id":1}]}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"assignees":[{"id":1`) assert.NotContains(t, rec.Body.String(), `"assignees":[]`) }) t.Run("Removing Assignees empty array", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "30"}, `{"assignees":[]}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "30"}, `{"assignees":[]}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"assignees":null`) assert.NotContains(t, rec.Body.String(), `"assignees":[{"id":1`) }) t.Run("Removing Assignees null", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "30"}, `{"assignees":null}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "30"}, `{"assignees":null}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"assignees":null`) assert.NotContains(t, rec.Body.String(), `"assignees":[{"id":1`) }) t.Run("Priority", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "1"}, `{"priority":100}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "1"}, `{"priority":100}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"priority":100`) assert.NotContains(t, rec.Body.String(), `"priority":0`) }) t.Run("Priority to 0", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "3"}, `{"priority":0}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "3"}, `{"priority":0}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"priority":0`) assert.NotContains(t, rec.Body.String(), `"priority":100`) }) t.Run("Start date", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "1"}, `{"start_date":"2020-02-10T10:00:00Z"}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "1"}, `{"start_date":"2020-02-10T10:00:00Z"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"start_date":"2020-02-10T10:00:00Z"`) assert.NotContains(t, rec.Body.String(), `"start_date":0`) }) t.Run("Start date unset", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "7"}, `{"start_date":"0001-01-01T00:00:00Z"}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "7"}, `{"start_date":"0001-01-01T00:00:00Z"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"start_date":"0001-01-01T00:00:00Z"`) assert.NotContains(t, rec.Body.String(), `"start_date":"2020-02-10T10:00:00Z"`) }) t.Run("End date", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "1"}, `{"end_date":"2020-02-10T12:00:00Z"}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "1"}, `{"end_date":"2020-02-10T12:00:00Z"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"end_date":"2020-02-10T12:00:00Z"`) assert.NotContains(t, rec.Body.String(), `"end_date":""`) }) t.Run("End date unset", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "8"}, `{"end_date":"0001-01-01T00:00:00Z"}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "8"}, `{"end_date":"0001-01-01T00:00:00Z"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"end_date":"0001-01-01T00:00:00Z"`) assert.NotContains(t, rec.Body.String(), `"end_date":"2020-02-10T10:00:00Z"`) }) t.Run("Color", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "1"}, `{"hex_color":"f0f0f0"}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "1"}, `{"hex_color":"f0f0f0"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"hex_color":"f0f0f0"`) assert.NotContains(t, rec.Body.String(), `"hex_color":""`) }) t.Run("Color unset", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "31"}, `{"hex_color":""}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "31"}, `{"hex_color":""}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"hex_color":""`) assert.NotContains(t, rec.Body.String(), `"hex_color":"f0f0f0"`) }) t.Run("Percent Done", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "1"}, `{"percent_done":0.1}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "1"}, `{"percent_done":0.1}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"percent_done":0.1`) assert.NotContains(t, rec.Body.String(), `"percent_done":0,`) }) t.Run("Percent Done unset", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "33"}, `{"percent_done":0}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "33"}, `{"percent_done":0}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"percent_done":0,`) assert.NotContains(t, rec.Body.String(), `"percent_done":0.1`) @@ -212,112 +212,112 @@ func TestTask(t *testing.T) { }) t.Run("Nonexisting", func(t *testing.T) { - _, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "99999"}, `{"title":"Lorem Ipsum"}`) + _, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "99999"}, `{"title":"Lorem Ipsum"}`) assert.Error(t, err) assertHandlerErrorCode(t, err, models.ErrCodeTaskDoesNotExist) }) t.Run("Rights check", func(t *testing.T) { t.Run("Forbidden", func(t *testing.T) { - _, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "14"}, `{"title":"Lorem Ipsum"}`) + _, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "14"}, `{"title":"Lorem Ipsum"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via Team readonly", func(t *testing.T) { - _, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "15"}, `{"title":"Lorem Ipsum"}`) + _, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "15"}, `{"title":"Lorem Ipsum"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via Team write", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "16"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "16"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) }) t.Run("Shared Via Team admin", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "17"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "17"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) }) t.Run("Shared Via User readonly", func(t *testing.T) { - _, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "18"}, `{"title":"Lorem Ipsum"}`) + _, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "18"}, `{"title":"Lorem Ipsum"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via User write", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "19"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "19"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) }) t.Run("Shared Via User admin", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "20"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "20"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) }) t.Run("Shared Via NamespaceTeam readonly", func(t *testing.T) { - _, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "21"}, `{"title":"Lorem Ipsum"}`) + _, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "21"}, `{"title":"Lorem Ipsum"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via NamespaceTeam write", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "22"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "22"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) }) t.Run("Shared Via NamespaceTeam admin", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "23"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "23"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) }) t.Run("Shared Via NamespaceUser readonly", func(t *testing.T) { - _, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "24"}, `{"title":"Lorem Ipsum"}`) + _, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "24"}, `{"title":"Lorem Ipsum"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via NamespaceUser write", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "25"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "25"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) }) t.Run("Shared Via NamespaceUser admin", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "26"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "26"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) }) }) - t.Run("Move to other list", func(t *testing.T) { + t.Run("Move to other project", func(t *testing.T) { t.Run("normal", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "1"}, `{"list_id":7}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "1"}, `{"project_id":7}`) assert.NoError(t, err) - assert.Contains(t, rec.Body.String(), `"list_id":7`) - assert.NotContains(t, rec.Body.String(), `"list_id":1`) + assert.Contains(t, rec.Body.String(), `"project_id":7`) + assert.NotContains(t, rec.Body.String(), `"project_id":1`) }) t.Run("Forbidden", func(t *testing.T) { - _, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "1"}, `{"list_id":20}`) + _, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "1"}, `{"project_id":20}`) assert.Error(t, err) assertHandlerErrorCode(t, err, models.ErrorCodeGenericForbidden) }) t.Run("Read Only", func(t *testing.T) { - _, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "1"}, `{"list_id":6}`) + _, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "1"}, `{"project_id":6}`) assert.Error(t, err) assertHandlerErrorCode(t, err, models.ErrorCodeGenericForbidden) }) }) t.Run("Bucket", func(t *testing.T) { t.Run("Normal", func(t *testing.T) { - rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "1"}, `{"bucket_id":3}`) + rec, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "1"}, `{"bucket_id":3}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"bucket_id":3`) assert.NotContains(t, rec.Body.String(), `"bucket_id":1`) }) - t.Run("Different List", func(t *testing.T) { - _, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "1"}, `{"bucket_id":4}`) + t.Run("Different Project", func(t *testing.T) { + _, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "1"}, `{"bucket_id":4}`) assert.Error(t, err) - assertHandlerErrorCode(t, err, models.ErrCodeBucketDoesNotBelongToList) + assertHandlerErrorCode(t, err, models.ErrCodeBucketDoesNotBelongToProject) }) t.Run("Nonexisting Bucket", func(t *testing.T) { - _, err := testHandler.testUpdateWithUser(nil, map[string]string{"listtask": "1"}, `{"bucket_id":9999}`) + _, err := testHandler.testUpdateWithUser(nil, map[string]string{"projecttask": "1"}, `{"bucket_id":9999}`) assert.Error(t, err) assertHandlerErrorCode(t, err, models.ErrCodeBucketDoesNotExist) }) @@ -325,81 +325,81 @@ func TestTask(t *testing.T) { }) t.Run("Delete", func(t *testing.T) { t.Run("Normal", func(t *testing.T) { - rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"listtask": "1"}) + rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"projecttask": "1"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `Successfully deleted.`) }) t.Run("Nonexisting", func(t *testing.T) { - _, err := testHandler.testDeleteWithUser(nil, map[string]string{"listtask": "99999"}) + _, err := testHandler.testDeleteWithUser(nil, map[string]string{"projecttask": "99999"}) assert.Error(t, err) assertHandlerErrorCode(t, err, models.ErrCodeTaskDoesNotExist) }) t.Run("Rights check", func(t *testing.T) { t.Run("Forbidden", func(t *testing.T) { - _, err := testHandler.testDeleteWithUser(nil, map[string]string{"listtask": "14"}) + _, err := testHandler.testDeleteWithUser(nil, map[string]string{"projecttask": "14"}) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via Team readonly", func(t *testing.T) { - _, err := testHandler.testDeleteWithUser(nil, map[string]string{"listtask": "15"}) + _, err := testHandler.testDeleteWithUser(nil, map[string]string{"projecttask": "15"}) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via Team write", func(t *testing.T) { - rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"listtask": "16"}) + rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"projecttask": "16"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `Successfully deleted.`) }) t.Run("Shared Via Team admin", func(t *testing.T) { - rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"listtask": "17"}) + rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"projecttask": "17"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `Successfully deleted.`) }) t.Run("Shared Via User readonly", func(t *testing.T) { - _, err := testHandler.testDeleteWithUser(nil, map[string]string{"listtask": "18"}) + _, err := testHandler.testDeleteWithUser(nil, map[string]string{"projecttask": "18"}) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via User write", func(t *testing.T) { - rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"listtask": "19"}) + rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"projecttask": "19"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `Successfully deleted.`) }) t.Run("Shared Via User admin", func(t *testing.T) { - rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"listtask": "20"}) + rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"projecttask": "20"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `Successfully deleted.`) }) t.Run("Shared Via NamespaceTeam readonly", func(t *testing.T) { - _, err := testHandler.testDeleteWithUser(nil, map[string]string{"listtask": "21"}) + _, err := testHandler.testDeleteWithUser(nil, map[string]string{"projecttask": "21"}) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via NamespaceTeam write", func(t *testing.T) { - rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"listtask": "22"}) + rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"projecttask": "22"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `Successfully deleted.`) }) t.Run("Shared Via NamespaceTeam admin", func(t *testing.T) { - rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"listtask": "23"}) + rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"projecttask": "23"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `Successfully deleted.`) }) t.Run("Shared Via NamespaceUser readonly", func(t *testing.T) { - _, err := testHandler.testDeleteWithUser(nil, map[string]string{"listtask": "24"}) + _, err := testHandler.testDeleteWithUser(nil, map[string]string{"projecttask": "24"}) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via NamespaceUser write", func(t *testing.T) { - rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"listtask": "25"}) + rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"projecttask": "25"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `Successfully deleted.`) }) t.Run("Shared Via NamespaceUser admin", func(t *testing.T) { - rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"listtask": "26"}) + rec, err := testHandler.testDeleteWithUser(nil, map[string]string{"projecttask": "26"}) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `Successfully deleted.`) }) @@ -407,110 +407,110 @@ func TestTask(t *testing.T) { }) t.Run("Create", func(t *testing.T) { t.Run("Normal", func(t *testing.T) { - rec, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "1"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "1"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) }) t.Run("Nonexisting", func(t *testing.T) { - _, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "9999"}, `{"title":"Lorem Ipsum"}`) + _, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "9999"}, `{"title":"Lorem Ipsum"}`) assert.Error(t, err) - assertHandlerErrorCode(t, err, models.ErrCodeListDoesNotExist) + assertHandlerErrorCode(t, err, models.ErrCodeProjectDoesNotExist) }) t.Run("Rights check", func(t *testing.T) { t.Run("Forbidden", func(t *testing.T) { // Owned by user13 - _, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "20"}, `{"title":"Lorem Ipsum"}`) + _, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "20"}, `{"title":"Lorem Ipsum"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via Team readonly", func(t *testing.T) { - _, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "6"}, `{"title":"Lorem Ipsum"}`) + _, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "6"}, `{"title":"Lorem Ipsum"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via Team write", func(t *testing.T) { - rec, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "7"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "7"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) }) t.Run("Shared Via Team admin", func(t *testing.T) { - rec, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "8"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "8"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) }) t.Run("Shared Via User readonly", func(t *testing.T) { - _, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "9"}, `{"title":"Lorem Ipsum"}`) + _, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "9"}, `{"title":"Lorem Ipsum"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via User write", func(t *testing.T) { - rec, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "10"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "10"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) }) t.Run("Shared Via User admin", func(t *testing.T) { - rec, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "11"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "11"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) }) t.Run("Shared Via NamespaceTeam readonly", func(t *testing.T) { - _, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "12"}, `{"title":"Lorem Ipsum"}`) + _, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "12"}, `{"title":"Lorem Ipsum"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via NamespaceTeam write", func(t *testing.T) { - rec, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "13"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "13"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) }) t.Run("Shared Via NamespaceTeam admin", func(t *testing.T) { - rec, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "14"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "14"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) }) t.Run("Shared Via NamespaceUser readonly", func(t *testing.T) { - _, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "15"}, `{"title":"Lorem Ipsum"}`) + _, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "15"}, `{"title":"Lorem Ipsum"}`) assert.Error(t, err) assert.Contains(t, err.(*echo.HTTPError).Message, `Forbidden`) }) t.Run("Shared Via NamespaceUser write", func(t *testing.T) { - rec, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "16"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "16"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) }) t.Run("Shared Via NamespaceUser admin", func(t *testing.T) { - rec, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "17"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "17"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) }) }) t.Run("Bucket", func(t *testing.T) { t.Run("Normal", func(t *testing.T) { - rec, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "1"}, `{"title":"Lorem Ipsum","bucket_id":3}`) + rec, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "1"}, `{"title":"Lorem Ipsum","bucket_id":3}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"bucket_id":3`) assert.NotContains(t, rec.Body.String(), `"bucket_id":1`) }) - t.Run("Different List", func(t *testing.T) { - _, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "1"}, `{"title":"Lorem Ipsum","bucket_id":4}`) + t.Run("Different Project", func(t *testing.T) { + _, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "1"}, `{"title":"Lorem Ipsum","bucket_id":4}`) assert.Error(t, err) - assertHandlerErrorCode(t, err, models.ErrCodeBucketDoesNotBelongToList) + assertHandlerErrorCode(t, err, models.ErrCodeBucketDoesNotBelongToProject) }) t.Run("Nonexisting Bucket", func(t *testing.T) { - _, err := testHandler.testCreateWithUser(nil, map[string]string{"list": "1"}, `{"title":"Lorem Ipsum","bucket_id":9999}`) + _, err := testHandler.testCreateWithUser(nil, map[string]string{"project": "1"}, `{"title":"Lorem Ipsum","bucket_id":9999}`) assert.Error(t, err) assertHandlerErrorCode(t, err, models.ErrCodeBucketDoesNotExist) }) }) t.Run("Link Share", func(t *testing.T) { - rec, err := testHandlerLinkShareWrite.testCreateWithLinkShare(nil, map[string]string{"list": "2"}, `{"title":"Lorem Ipsum"}`) + rec, err := testHandlerLinkShareWrite.testCreateWithLinkShare(nil, map[string]string{"project": "2"}, `{"title":"Lorem Ipsum"}`) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `"title":"Lorem Ipsum"`) db.AssertExists(t, "tasks", map[string]interface{}{ - "list_id": 2, + "project_id": 2, "title": "Lorem Ipsum", "created_by_id": -2, }, false) diff --git a/pkg/integrations/user_list_test.go b/pkg/integrations/user_list_test.go index 6850fa199..1e201d95f 100644 --- a/pkg/integrations/user_list_test.go +++ b/pkg/integrations/user_list_test.go @@ -24,14 +24,14 @@ import ( "github.com/stretchr/testify/assert" ) -func TestUserList(t *testing.T) { +func TestUserProject(t *testing.T) { t.Run("Normal test", func(t *testing.T) { - rec, err := newTestRequestWithUser(t, http.MethodPost, apiv1.UserList, &testuser1, "", nil, nil) + rec, err := newTestRequestWithUser(t, http.MethodPost, apiv1.UserProject, &testuser1, "", nil, nil) assert.NoError(t, err) assert.Equal(t, "null\n", rec.Body.String()) }) t.Run("Search for user3", func(t *testing.T) { - rec, err := newTestRequestWithUser(t, http.MethodPost, apiv1.UserList, &testuser1, "", map[string][]string{"s": {"user3"}}, nil) + rec, err := newTestRequestWithUser(t, http.MethodPost, apiv1.UserProject, &testuser1, "", map[string][]string{"s": {"user3"}}, nil) assert.NoError(t, err) assert.Contains(t, rec.Body.String(), `user3`) assert.NotContains(t, rec.Body.String(), `user1`) diff --git a/pkg/metrics/metrics.go b/pkg/metrics/metrics.go index 68dafc913..76dfe3201 100644 --- a/pkg/metrics/metrics.go +++ b/pkg/metrics/metrics.go @@ -28,8 +28,8 @@ import ( ) const ( - // ListCountKey is the name of the key in which we save the list count - ListCountKey = `listcount` + // ProjectCountKey is the name of the key in which we save the project count + ProjectCountKey = `projectcount` // UserCountKey is the name of the key we use to store total users in redis UserCountKey = `usercount` @@ -65,16 +65,16 @@ func InitMetrics() { GetRegistry() - // Register total list count metric + // Register total project count metric err := registry.Register(promauto.NewGaugeFunc(prometheus.GaugeOpts{ - Name: "vikunja_list_count", - Help: "The number of lists on this instance", + Name: "vikunja_project_count", + Help: "The number of projects on this instance", }, func() float64 { - count, _ := GetCount(ListCountKey) + count, _ := GetCount(ProjectCountKey) return float64(count) })) if err != nil { - log.Criticalf("Could not register metrics for %s: %s", ListCountKey, err) + log.Criticalf("Could not register metrics for %s: %s", ProjectCountKey, err) } // Register total user count metric @@ -147,7 +147,7 @@ func GetCount(key string) (count int64, err error) { return } -// SetCount sets the list count to a given value +// SetCount sets the project count to a given value func SetCount(count int64, key string) error { return keyvalue.Put(key, count) } diff --git a/pkg/models/bulk_task.go b/pkg/models/bulk_task.go index a4d3ee531..583984cf0 100644 --- a/pkg/models/bulk_task.go +++ b/pkg/models/bulk_task.go @@ -24,13 +24,13 @@ import ( // BulkTask is the definition of a bulk update task type BulkTask struct { - // A list of task ids to update + // A project of task ids to update IDs []int64 `json:"task_ids"` Tasks []*Task `json:"-"` Task } -func (bt *BulkTask) checkIfTasksAreOnTheSameList(s *xorm.Session) (err error) { +func (bt *BulkTask) checkIfTasksAreOnTheSameProject(s *xorm.Session) (err error) { // Get the tasks err = bt.GetTasksByIDs(s) if err != nil { @@ -41,11 +41,11 @@ func (bt *BulkTask) checkIfTasksAreOnTheSameList(s *xorm.Session) (err error) { return ErrBulkTasksNeedAtLeastOne{} } - // Check if all tasks are in the same list - var firstListID = bt.Tasks[0].ListID + // Check if all tasks are in the same project + var firstProjectID = bt.Tasks[0].ProjectID for _, t := range bt.Tasks { - if t.ListID != firstListID { - return ErrBulkTasksMustBeInSameList{firstListID, t.ListID} + if t.ProjectID != firstProjectID { + return ErrBulkTasksMustBeInSameProject{firstProjectID, t.ProjectID} } } @@ -55,13 +55,13 @@ func (bt *BulkTask) checkIfTasksAreOnTheSameList(s *xorm.Session) (err error) { // CanUpdate checks if a user is allowed to update a task func (bt *BulkTask) CanUpdate(s *xorm.Session, a web.Auth) (bool, error) { - err := bt.checkIfTasksAreOnTheSameList(s) + err := bt.checkIfTasksAreOnTheSameProject(s) if err != nil { return false, err } - // A user can update an task if he has write acces to its list - l := &List{ID: bt.Tasks[0].ListID} + // A user can update an task if he has write acces to its project + l := &Project{ID: bt.Tasks[0].ProjectID} return l.CanWrite(s, a) } @@ -72,10 +72,10 @@ func (bt *BulkTask) CanUpdate(s *xorm.Session, a web.Auth) (bool, error) { // @Accept json // @Produce json // @Security JWTKeyAuth -// @Param task body models.BulkTask true "The task object. Looks like a normal task, the only difference is it uses an array of list_ids to update." +// @Param task body models.BulkTask true "The task object. Looks like a normal task, the only difference is it uses an array of project_ids to update." // @Success 200 {object} models.Task "The updated task object." // @Failure 400 {object} web.HTTPError "Invalid task object provided." -// @Failure 403 {object} web.HTTPError "The user does not have access to the task (aka its list)" +// @Failure 403 {object} web.HTTPError "The user does not have access to the task (aka its project)" // @Failure 500 {object} models.Message "Internal error" // @Router /tasks/bulk [post] func (bt *BulkTask) Update(s *xorm.Session, a web.Auth) (err error) { diff --git a/pkg/models/bulk_task_test.go b/pkg/models/bulk_task_test.go index 7159302fc..9f38a1ba5 100644 --- a/pkg/models/bulk_task_test.go +++ b/pkg/models/bulk_task_test.go @@ -47,7 +47,7 @@ func TestBulkTask_Update(t *testing.T) { }, }, { - name: "Test with one task on different list", + name: "Test with one task on different project", fields: fields{ IDs: []int64{10, 11, 12, 13}, Task: Task{ diff --git a/pkg/models/error.go b/pkg/models/error.go index 580ba0551..12716b590 100644 --- a/pkg/models/error.go +++ b/pkg/models/error.go @@ -110,222 +110,222 @@ func (err ValidationHTTPError) Error() string { } // =========== -// List errors +// Project errors // =========== -// ErrListDoesNotExist represents a "ErrListDoesNotExist" kind of error. Used if the list does not exist. -type ErrListDoesNotExist struct { +// ErrProjectDoesNotExist represents a "ErrProjectDoesNotExist" kind of error. Used if the project does not exist. +type ErrProjectDoesNotExist struct { ID int64 } -// IsErrListDoesNotExist checks if an error is a ErrListDoesNotExist. -func IsErrListDoesNotExist(err error) bool { - _, ok := err.(ErrListDoesNotExist) +// IsErrProjectDoesNotExist checks if an error is a ErrProjectDoesNotExist. +func IsErrProjectDoesNotExist(err error) bool { + _, ok := err.(ErrProjectDoesNotExist) return ok } -func (err ErrListDoesNotExist) Error() string { - return fmt.Sprintf("List does not exist [ID: %d]", err.ID) +func (err ErrProjectDoesNotExist) Error() string { + return fmt.Sprintf("Project does not exist [ID: %d]", err.ID) } -// ErrCodeListDoesNotExist holds the unique world-error code of this error -const ErrCodeListDoesNotExist = 3001 +// ErrCodeProjectDoesNotExist holds the unique world-error code of this error +const ErrCodeProjectDoesNotExist = 3001 // HTTPError holds the http error description -func (err ErrListDoesNotExist) HTTPError() web.HTTPError { - return web.HTTPError{HTTPCode: http.StatusNotFound, Code: ErrCodeListDoesNotExist, Message: "This list does not exist."} +func (err ErrProjectDoesNotExist) HTTPError() web.HTTPError { + return web.HTTPError{HTTPCode: http.StatusNotFound, Code: ErrCodeProjectDoesNotExist, Message: "This project does not exist."} } -// ErrNeedToHaveListReadAccess represents an error, where the user dont has read access to that List -type ErrNeedToHaveListReadAccess struct { - ListID int64 - UserID int64 +// ErrNeedToHaveProjectReadAccess represents an error, where the user dont has read access to that Project +type ErrNeedToHaveProjectReadAccess struct { + ProjectID int64 + UserID int64 } -// IsErrNeedToHaveListReadAccess checks if an error is a ErrListDoesNotExist. -func IsErrNeedToHaveListReadAccess(err error) bool { - _, ok := err.(ErrNeedToHaveListReadAccess) +// IsErrNeedToHaveProjectReadAccess checks if an error is a ErrProjectDoesNotExist. +func IsErrNeedToHaveProjectReadAccess(err error) bool { + _, ok := err.(ErrNeedToHaveProjectReadAccess) return ok } -func (err ErrNeedToHaveListReadAccess) Error() string { - return fmt.Sprintf("User needs to have read access to that list [ListID: %d, UserID: %d]", err.ListID, err.UserID) +func (err ErrNeedToHaveProjectReadAccess) Error() string { + return fmt.Sprintf("User needs to have read access to that project [ProjectID: %d, UserID: %d]", err.ProjectID, err.UserID) } -// ErrCodeNeedToHaveListReadAccess holds the unique world-error code of this error -const ErrCodeNeedToHaveListReadAccess = 3004 +// ErrCodeNeedToHaveProjectReadAccess holds the unique world-error code of this error +const ErrCodeNeedToHaveProjectReadAccess = 3004 // HTTPError holds the http error description -func (err ErrNeedToHaveListReadAccess) HTTPError() web.HTTPError { - return web.HTTPError{HTTPCode: http.StatusForbidden, Code: ErrCodeNeedToHaveListReadAccess, Message: "You need to have read access to this list."} +func (err ErrNeedToHaveProjectReadAccess) HTTPError() web.HTTPError { + return web.HTTPError{HTTPCode: http.StatusForbidden, Code: ErrCodeNeedToHaveProjectReadAccess, Message: "You need to have read access to this project."} } -// ErrListTitleCannotBeEmpty represents a "ErrListTitleCannotBeEmpty" kind of error. Used if the list does not exist. -type ErrListTitleCannotBeEmpty struct{} +// ErrProjectTitleCannotBeEmpty represents a "ErrProjectTitleCannotBeEmpty" kind of error. Used if the project does not exist. +type ErrProjectTitleCannotBeEmpty struct{} -// IsErrListTitleCannotBeEmpty checks if an error is a ErrListTitleCannotBeEmpty. -func IsErrListTitleCannotBeEmpty(err error) bool { - _, ok := err.(ErrListTitleCannotBeEmpty) +// IsErrProjectTitleCannotBeEmpty checks if an error is a ErrProjectTitleCannotBeEmpty. +func IsErrProjectTitleCannotBeEmpty(err error) bool { + _, ok := err.(ErrProjectTitleCannotBeEmpty) return ok } -func (err ErrListTitleCannotBeEmpty) Error() string { - return "List title cannot be empty." +func (err ErrProjectTitleCannotBeEmpty) Error() string { + return "Project title cannot be empty." } -// ErrCodeListTitleCannotBeEmpty holds the unique world-error code of this error -const ErrCodeListTitleCannotBeEmpty = 3005 +// ErrCodeProjectTitleCannotBeEmpty holds the unique world-error code of this error +const ErrCodeProjectTitleCannotBeEmpty = 3005 // HTTPError holds the http error description -func (err ErrListTitleCannotBeEmpty) HTTPError() web.HTTPError { - return web.HTTPError{HTTPCode: http.StatusBadRequest, Code: ErrCodeListTitleCannotBeEmpty, Message: "You must provide at least a list title."} +func (err ErrProjectTitleCannotBeEmpty) HTTPError() web.HTTPError { + return web.HTTPError{HTTPCode: http.StatusBadRequest, Code: ErrCodeProjectTitleCannotBeEmpty, Message: "You must provide at least a project title."} } -// ErrListShareDoesNotExist represents a "ErrListShareDoesNotExist" kind of error. Used if the list share does not exist. -type ErrListShareDoesNotExist struct { +// ErrProjectShareDoesNotExist represents a "ErrProjectShareDoesNotExist" kind of error. Used if the project share does not exist. +type ErrProjectShareDoesNotExist struct { ID int64 Hash string } -// IsErrListShareDoesNotExist checks if an error is a ErrListShareDoesNotExist. -func IsErrListShareDoesNotExist(err error) bool { - _, ok := err.(ErrListShareDoesNotExist) +// IsErrProjectShareDoesNotExist checks if an error is a ErrProjectShareDoesNotExist. +func IsErrProjectShareDoesNotExist(err error) bool { + _, ok := err.(ErrProjectShareDoesNotExist) return ok } -func (err ErrListShareDoesNotExist) Error() string { - return "List share does not exist." +func (err ErrProjectShareDoesNotExist) Error() string { + return "Project share does not exist." } -// ErrCodeListShareDoesNotExist holds the unique world-error code of this error -const ErrCodeListShareDoesNotExist = 3006 +// ErrCodeProjectShareDoesNotExist holds the unique world-error code of this error +const ErrCodeProjectShareDoesNotExist = 3006 // HTTPError holds the http error description -func (err ErrListShareDoesNotExist) HTTPError() web.HTTPError { - return web.HTTPError{HTTPCode: http.StatusNotFound, Code: ErrCodeListShareDoesNotExist, Message: "The list share does not exist."} +func (err ErrProjectShareDoesNotExist) HTTPError() web.HTTPError { + return web.HTTPError{HTTPCode: http.StatusNotFound, Code: ErrCodeProjectShareDoesNotExist, Message: "The project share does not exist."} } -// ErrListIdentifierIsNotUnique represents a "ErrListIdentifierIsNotUnique" kind of error. Used if the provided list identifier is not unique. -type ErrListIdentifierIsNotUnique struct { +// ErrProjectIdentifierIsNotUnique represents a "ErrProjectIdentifierIsNotUnique" kind of error. Used if the provided project identifier is not unique. +type ErrProjectIdentifierIsNotUnique struct { Identifier string } -// IsErrListIdentifierIsNotUnique checks if an error is a ErrListIdentifierIsNotUnique. -func IsErrListIdentifierIsNotUnique(err error) bool { - _, ok := err.(ErrListIdentifierIsNotUnique) +// IsErrProjectIdentifierIsNotUnique checks if an error is a ErrProjectIdentifierIsNotUnique. +func IsErrProjectIdentifierIsNotUnique(err error) bool { + _, ok := err.(ErrProjectIdentifierIsNotUnique) return ok } -func (err ErrListIdentifierIsNotUnique) Error() string { - return "List identifier is not unique." +func (err ErrProjectIdentifierIsNotUnique) Error() string { + return "Project identifier is not unique." } -// ErrCodeListIdentifierIsNotUnique holds the unique world-error code of this error -const ErrCodeListIdentifierIsNotUnique = 3007 +// ErrCodeProjectIdentifierIsNotUnique holds the unique world-error code of this error +const ErrCodeProjectIdentifierIsNotUnique = 3007 // HTTPError holds the http error description -func (err ErrListIdentifierIsNotUnique) HTTPError() web.HTTPError { +func (err ErrProjectIdentifierIsNotUnique) HTTPError() web.HTTPError { return web.HTTPError{ HTTPCode: http.StatusBadRequest, - Code: ErrCodeListIdentifierIsNotUnique, - Message: "A list with this identifier already exists.", + Code: ErrCodeProjectIdentifierIsNotUnique, + Message: "A project with this identifier already exists.", } } -// ErrListIsArchived represents an error, where a list is archived -type ErrListIsArchived struct { - ListID int64 +// ErrProjectIsArchived represents an error, where a project is archived +type ErrProjectIsArchived struct { + ProjectID int64 } -// IsErrListIsArchived checks if an error is a list is archived error. -func IsErrListIsArchived(err error) bool { - _, ok := err.(ErrListIsArchived) +// IsErrProjectIsArchived checks if an error is a project is archived error. +func IsErrProjectIsArchived(err error) bool { + _, ok := err.(ErrProjectIsArchived) return ok } -func (err ErrListIsArchived) Error() string { - return fmt.Sprintf("List is archived [ListID: %d]", err.ListID) +func (err ErrProjectIsArchived) Error() string { + return fmt.Sprintf("Project is archived [ProjectID: %d]", err.ProjectID) } -// ErrCodeListIsArchived holds the unique world-error code of this error -const ErrCodeListIsArchived = 3008 +// ErrCodeProjectIsArchived holds the unique world-error code of this error +const ErrCodeProjectIsArchived = 3008 // HTTPError holds the http error description -func (err ErrListIsArchived) HTTPError() web.HTTPError { - return web.HTTPError{HTTPCode: http.StatusPreconditionFailed, Code: ErrCodeListIsArchived, Message: "This list is archived. Editing or creating new tasks is not possible."} +func (err ErrProjectIsArchived) HTTPError() web.HTTPError { + return web.HTTPError{HTTPCode: http.StatusPreconditionFailed, Code: ErrCodeProjectIsArchived, Message: "This project is archived. Editing or creating new tasks is not possible."} } -// ErrListCannotBelongToAPseudoNamespace represents an error where a list cannot belong to a pseudo namespace -type ErrListCannotBelongToAPseudoNamespace struct { - ListID int64 +// ErrProjectCannotBelongToAPseudoNamespace represents an error where a project cannot belong to a pseudo namespace +type ErrProjectCannotBelongToAPseudoNamespace struct { + ProjectID int64 NamespaceID int64 } -// IsErrListCannotBelongToAPseudoNamespace checks if an error is a list is archived error. -func IsErrListCannotBelongToAPseudoNamespace(err error) bool { - _, ok := err.(*ErrListCannotBelongToAPseudoNamespace) +// IsErrProjectCannotBelongToAPseudoNamespace checks if an error is a project is archived error. +func IsErrProjectCannotBelongToAPseudoNamespace(err error) bool { + _, ok := err.(*ErrProjectCannotBelongToAPseudoNamespace) return ok } -func (err *ErrListCannotBelongToAPseudoNamespace) Error() string { - return fmt.Sprintf("List cannot belong to a pseudo namespace [ListID: %d, NamespaceID: %d]", err.ListID, err.NamespaceID) +func (err *ErrProjectCannotBelongToAPseudoNamespace) Error() string { + return fmt.Sprintf("Project cannot belong to a pseudo namespace [ProjectID: %d, NamespaceID: %d]", err.ProjectID, err.NamespaceID) } -// ErrCodeListCannotBelongToAPseudoNamespace holds the unique world-error code of this error -const ErrCodeListCannotBelongToAPseudoNamespace = 3009 +// ErrCodeProjectCannotBelongToAPseudoNamespace holds the unique world-error code of this error +const ErrCodeProjectCannotBelongToAPseudoNamespace = 3009 // HTTPError holds the http error description -func (err *ErrListCannotBelongToAPseudoNamespace) HTTPError() web.HTTPError { +func (err *ErrProjectCannotBelongToAPseudoNamespace) HTTPError() web.HTTPError { return web.HTTPError{ HTTPCode: http.StatusPreconditionFailed, - Code: ErrCodeListCannotBelongToAPseudoNamespace, - Message: "This list cannot belong a dynamically generated namespace.", + Code: ErrCodeProjectCannotBelongToAPseudoNamespace, + Message: "This project cannot belong a dynamically generated namespace.", } } -// ErrListMustBelongToANamespace represents an error where a list must belong to a namespace -type ErrListMustBelongToANamespace struct { - ListID int64 +// ErrProjectMustBelongToANamespace represents an error where a project must belong to a namespace +type ErrProjectMustBelongToANamespace struct { + ProjectID int64 NamespaceID int64 } -// IsErrListMustBelongToANamespace checks if an error is a list must belong to a namespace error. -func IsErrListMustBelongToANamespace(err error) bool { - _, ok := err.(*ErrListMustBelongToANamespace) +// IsErrProjectMustBelongToANamespace checks if an error is a project must belong to a namespace error. +func IsErrProjectMustBelongToANamespace(err error) bool { + _, ok := err.(*ErrProjectMustBelongToANamespace) return ok } -func (err *ErrListMustBelongToANamespace) Error() string { - return fmt.Sprintf("List must belong to a namespace [ListID: %d, NamespaceID: %d]", err.ListID, err.NamespaceID) +func (err *ErrProjectMustBelongToANamespace) Error() string { + return fmt.Sprintf("Project must belong to a namespace [ProjectID: %d, NamespaceID: %d]", err.ProjectID, err.NamespaceID) } -// ErrCodeListMustBelongToANamespace holds the unique world-error code of this error -const ErrCodeListMustBelongToANamespace = 3010 +// ErrCodeProjectMustBelongToANamespace holds the unique world-error code of this error +const ErrCodeProjectMustBelongToANamespace = 3010 // HTTPError holds the http error description -func (err *ErrListMustBelongToANamespace) HTTPError() web.HTTPError { +func (err *ErrProjectMustBelongToANamespace) HTTPError() web.HTTPError { return web.HTTPError{ HTTPCode: http.StatusPreconditionFailed, - Code: ErrCodeListMustBelongToANamespace, - Message: "This list must belong to a namespace.", + Code: ErrCodeProjectMustBelongToANamespace, + Message: "This project must belong to a namespace.", } } // ================ -// List task errors +// Project task errors // ================ -// ErrTaskCannotBeEmpty represents a "ErrListDoesNotExist" kind of error. Used if the list does not exist. +// ErrTaskCannotBeEmpty represents a "ErrProjectDoesNotExist" kind of error. Used if the project does not exist. type ErrTaskCannotBeEmpty struct{} -// IsErrTaskCannotBeEmpty checks if an error is a ErrListDoesNotExist. +// IsErrTaskCannotBeEmpty checks if an error is a ErrProjectDoesNotExist. func IsErrTaskCannotBeEmpty(err error) bool { _, ok := err.(ErrTaskCannotBeEmpty) return ok } func (err ErrTaskCannotBeEmpty) Error() string { - return "List task title cannot be empty." + return "Project task title cannot be empty." } // ErrCodeTaskCannotBeEmpty holds the unique world-error code of this error @@ -333,22 +333,22 @@ const ErrCodeTaskCannotBeEmpty = 4001 // HTTPError holds the http error description func (err ErrTaskCannotBeEmpty) HTTPError() web.HTTPError { - return web.HTTPError{HTTPCode: http.StatusBadRequest, Code: ErrCodeTaskCannotBeEmpty, Message: "You must provide at least a list task title."} + return web.HTTPError{HTTPCode: http.StatusBadRequest, Code: ErrCodeTaskCannotBeEmpty, Message: "You must provide at least a project task title."} } -// ErrTaskDoesNotExist represents a "ErrListDoesNotExist" kind of error. Used if the list does not exist. +// ErrTaskDoesNotExist represents a "ErrProjectDoesNotExist" kind of error. Used if the project does not exist. type ErrTaskDoesNotExist struct { ID int64 } -// IsErrTaskDoesNotExist checks if an error is a ErrListDoesNotExist. +// IsErrTaskDoesNotExist checks if an error is a ErrProjectDoesNotExist. func IsErrTaskDoesNotExist(err error) bool { _, ok := err.(ErrTaskDoesNotExist) return ok } func (err ErrTaskDoesNotExist) Error() string { - return fmt.Sprintf("List task does not exist. [ID: %d]", err.ID) + return fmt.Sprintf("Project task does not exist. [ID: %d]", err.ID) } // ErrCodeTaskDoesNotExist holds the unique world-error code of this error @@ -359,28 +359,28 @@ func (err ErrTaskDoesNotExist) HTTPError() web.HTTPError { return web.HTTPError{HTTPCode: http.StatusNotFound, Code: ErrCodeTaskDoesNotExist, Message: "This task does not exist"} } -// ErrBulkTasksMustBeInSameList represents a "ErrBulkTasksMustBeInSameList" kind of error. -type ErrBulkTasksMustBeInSameList struct { +// ErrBulkTasksMustBeInSameProject represents a "ErrBulkTasksMustBeInSameProject" kind of error. +type ErrBulkTasksMustBeInSameProject struct { ShouldBeID int64 IsID int64 } -// IsErrBulkTasksMustBeInSameList checks if an error is a ErrBulkTasksMustBeInSameList. -func IsErrBulkTasksMustBeInSameList(err error) bool { - _, ok := err.(ErrBulkTasksMustBeInSameList) +// IsErrBulkTasksMustBeInSameProject checks if an error is a ErrBulkTasksMustBeInSameProject. +func IsErrBulkTasksMustBeInSameProject(err error) bool { + _, ok := err.(ErrBulkTasksMustBeInSameProject) return ok } -func (err ErrBulkTasksMustBeInSameList) Error() string { - return fmt.Sprintf("All bulk editing tasks must be in the same list. [Should be: %d, is: %d]", err.ShouldBeID, err.IsID) +func (err ErrBulkTasksMustBeInSameProject) Error() string { + return fmt.Sprintf("All bulk editing tasks must be in the same project. [Should be: %d, is: %d]", err.ShouldBeID, err.IsID) } -// ErrCodeBulkTasksMustBeInSameList holds the unique world-error code of this error -const ErrCodeBulkTasksMustBeInSameList = 4003 +// ErrCodeBulkTasksMustBeInSameProject holds the unique world-error code of this error +const ErrCodeBulkTasksMustBeInSameProject = 4003 // HTTPError holds the http error description -func (err ErrBulkTasksMustBeInSameList) HTTPError() web.HTTPError { - return web.HTTPError{HTTPCode: http.StatusBadRequest, Code: ErrCodeBulkTasksMustBeInSameList, Message: "All tasks must be in the same list."} +func (err ErrBulkTasksMustBeInSameProject) HTTPError() web.HTTPError { + return web.HTTPError{HTTPCode: http.StatusBadRequest, Code: ErrCodeBulkTasksMustBeInSameProject, Message: "All tasks must be in the same project."} } // ErrBulkTasksNeedAtLeastOne represents a "ErrBulkTasksNeedAtLeastOne" kind of error. @@ -1042,7 +1042,7 @@ const ErrCodeNamespaceIsArchived = 5012 // HTTPError holds the http error description func (err ErrNamespaceIsArchived) HTTPError() web.HTTPError { - return web.HTTPError{HTTPCode: http.StatusPreconditionFailed, Code: ErrCodeNamespaceIsArchived, Message: "This namespaces is archived. Editing or creating new lists is not possible."} + return web.HTTPError{HTTPCode: http.StatusPreconditionFailed, Code: ErrCodeNamespaceIsArchived, Message: "This namespaces is archived. Editing or creating new projects is not possible."} } // ============ @@ -1095,7 +1095,7 @@ func (err ErrTeamDoesNotExist) HTTPError() web.HTTPError { return web.HTTPError{HTTPCode: http.StatusNotFound, Code: ErrCodeTeamDoesNotExist, Message: "This team does not exist."} } -// ErrTeamAlreadyHasAccess represents an error where a team already has access to a list/namespace +// ErrTeamAlreadyHasAccess represents an error where a team already has access to a project/namespace type ErrTeamAlreadyHasAccess struct { TeamID int64 ID int64 @@ -1167,38 +1167,38 @@ func (err ErrCannotDeleteLastTeamMember) HTTPError() web.HTTPError { return web.HTTPError{HTTPCode: http.StatusBadRequest, Code: ErrCodeCannotDeleteLastTeamMember, Message: "You cannot delete the last member of a team."} } -// ErrTeamDoesNotHaveAccessToList represents an error, where the Team is not the owner of that List (used i.e. when deleting a List) -type ErrTeamDoesNotHaveAccessToList struct { - ListID int64 - TeamID int64 +// ErrTeamDoesNotHaveAccessToProject represents an error, where the Team is not the owner of that Project (used i.e. when deleting a Project) +type ErrTeamDoesNotHaveAccessToProject struct { + ProjectID int64 + TeamID int64 } -// IsErrTeamDoesNotHaveAccessToList checks if an error is a ErrListDoesNotExist. -func IsErrTeamDoesNotHaveAccessToList(err error) bool { - _, ok := err.(ErrTeamDoesNotHaveAccessToList) +// IsErrTeamDoesNotHaveAccessToProject checks if an error is a ErrProjectDoesNotExist. +func IsErrTeamDoesNotHaveAccessToProject(err error) bool { + _, ok := err.(ErrTeamDoesNotHaveAccessToProject) return ok } -func (err ErrTeamDoesNotHaveAccessToList) Error() string { - return fmt.Sprintf("Team does not have access to the list [ListID: %d, TeamID: %d]", err.ListID, err.TeamID) +func (err ErrTeamDoesNotHaveAccessToProject) Error() string { + return fmt.Sprintf("Team does not have access to the project [ProjectID: %d, TeamID: %d]", err.ProjectID, err.TeamID) } -// ErrCodeTeamDoesNotHaveAccessToList holds the unique world-error code of this error -const ErrCodeTeamDoesNotHaveAccessToList = 6007 +// ErrCodeTeamDoesNotHaveAccessToProject holds the unique world-error code of this error +const ErrCodeTeamDoesNotHaveAccessToProject = 6007 // HTTPError holds the http error description -func (err ErrTeamDoesNotHaveAccessToList) HTTPError() web.HTTPError { - return web.HTTPError{HTTPCode: http.StatusForbidden, Code: ErrCodeTeamDoesNotHaveAccessToList, Message: "This team does not have access to the list."} +func (err ErrTeamDoesNotHaveAccessToProject) HTTPError() web.HTTPError { + return web.HTTPError{HTTPCode: http.StatusForbidden, Code: ErrCodeTeamDoesNotHaveAccessToProject, Message: "This team does not have access to the project."} } // ==================== -// User <-> List errors +// User <-> Project errors // ==================== -// ErrUserAlreadyHasAccess represents an error where a user already has access to a list/namespace +// ErrUserAlreadyHasAccess represents an error where a user already has access to a project/namespace type ErrUserAlreadyHasAccess struct { - UserID int64 - ListID int64 + UserID int64 + ProjectID int64 } // IsErrUserAlreadyHasAccess checks if an error is ErrUserAlreadyHasAccess. @@ -1208,7 +1208,7 @@ func IsErrUserAlreadyHasAccess(err error) bool { } func (err ErrUserAlreadyHasAccess) Error() string { - return fmt.Sprintf("User already has access to that list. [User ID: %d, List ID: %d]", err.UserID, err.ListID) + return fmt.Sprintf("User already has access to that project. [User ID: %d, Project ID: %d]", err.UserID, err.ProjectID) } // ErrCodeUserAlreadyHasAccess holds the unique world-error code of this error @@ -1216,31 +1216,31 @@ const ErrCodeUserAlreadyHasAccess = 7002 // HTTPError holds the http error description func (err ErrUserAlreadyHasAccess) HTTPError() web.HTTPError { - return web.HTTPError{HTTPCode: http.StatusConflict, Code: ErrCodeUserAlreadyHasAccess, Message: "This user already has access to this list."} + return web.HTTPError{HTTPCode: http.StatusConflict, Code: ErrCodeUserAlreadyHasAccess, Message: "This user already has access to this project."} } -// ErrUserDoesNotHaveAccessToList represents an error, where the user is not the owner of that List (used i.e. when deleting a List) -type ErrUserDoesNotHaveAccessToList struct { - ListID int64 - UserID int64 +// ErrUserDoesNotHaveAccessToProject represents an error, where the user is not the owner of that Project (used i.e. when deleting a Project) +type ErrUserDoesNotHaveAccessToProject struct { + ProjectID int64 + UserID int64 } -// IsErrUserDoesNotHaveAccessToList checks if an error is a ErrListDoesNotExist. -func IsErrUserDoesNotHaveAccessToList(err error) bool { - _, ok := err.(ErrUserDoesNotHaveAccessToList) +// IsErrUserDoesNotHaveAccessToProject checks if an error is a ErrProjectDoesNotExist. +func IsErrUserDoesNotHaveAccessToProject(err error) bool { + _, ok := err.(ErrUserDoesNotHaveAccessToProject) return ok } -func (err ErrUserDoesNotHaveAccessToList) Error() string { - return fmt.Sprintf("User does not have access to the list [ListID: %d, UserID: %d]", err.ListID, err.UserID) +func (err ErrUserDoesNotHaveAccessToProject) Error() string { + return fmt.Sprintf("User does not have access to the project [ProjectID: %d, UserID: %d]", err.ProjectID, err.UserID) } -// ErrCodeUserDoesNotHaveAccessToList holds the unique world-error code of this error -const ErrCodeUserDoesNotHaveAccessToList = 7003 +// ErrCodeUserDoesNotHaveAccessToProject holds the unique world-error code of this error +const ErrCodeUserDoesNotHaveAccessToProject = 7003 // HTTPError holds the http error description -func (err ErrUserDoesNotHaveAccessToList) HTTPError() web.HTTPError { - return web.HTTPError{HTTPCode: http.StatusForbidden, Code: ErrCodeUserDoesNotHaveAccessToList, Message: "This user does not have access to the list."} +func (err ErrUserDoesNotHaveAccessToProject) HTTPError() web.HTTPError { + return web.HTTPError{HTTPCode: http.StatusForbidden, Code: ErrCodeUserDoesNotHaveAccessToProject, Message: "This user does not have access to the project."} } // ============= @@ -1392,38 +1392,38 @@ func (err ErrBucketDoesNotExist) HTTPError() web.HTTPError { } } -// ErrBucketDoesNotBelongToList represents an error where a kanban bucket does not belong to a list -type ErrBucketDoesNotBelongToList struct { - BucketID int64 - ListID int64 +// ErrBucketDoesNotBelongToProject represents an error where a kanban bucket does not belong to a project +type ErrBucketDoesNotBelongToProject struct { + BucketID int64 + ProjectID int64 } -// IsErrBucketDoesNotBelongToList checks if an error is ErrBucketDoesNotBelongToList. -func IsErrBucketDoesNotBelongToList(err error) bool { - _, ok := err.(ErrBucketDoesNotBelongToList) +// IsErrBucketDoesNotBelongToProject checks if an error is ErrBucketDoesNotBelongToProject. +func IsErrBucketDoesNotBelongToProject(err error) bool { + _, ok := err.(ErrBucketDoesNotBelongToProject) return ok } -func (err ErrBucketDoesNotBelongToList) Error() string { - return fmt.Sprintf("Bucket does not not belong to list [BucketID: %d, ListID: %d]", err.BucketID, err.ListID) +func (err ErrBucketDoesNotBelongToProject) Error() string { + return fmt.Sprintf("Bucket does not not belong to project [BucketID: %d, ProjectID: %d]", err.BucketID, err.ProjectID) } -// ErrCodeBucketDoesNotBelongToList holds the unique world-error code of this error -const ErrCodeBucketDoesNotBelongToList = 10002 +// ErrCodeBucketDoesNotBelongToProject holds the unique world-error code of this error +const ErrCodeBucketDoesNotBelongToProject = 10002 // HTTPError holds the http error description -func (err ErrBucketDoesNotBelongToList) HTTPError() web.HTTPError { +func (err ErrBucketDoesNotBelongToProject) HTTPError() web.HTTPError { return web.HTTPError{ HTTPCode: http.StatusBadRequest, - Code: ErrCodeBucketDoesNotBelongToList, - Message: "This bucket does not belong to that list.", + Code: ErrCodeBucketDoesNotBelongToProject, + Message: "This bucket does not belong to that project.", } } -// ErrCannotRemoveLastBucket represents an error where a kanban bucket is the last on a list and thus cannot be removed. +// ErrCannotRemoveLastBucket represents an error where a kanban bucket is the last on a project and thus cannot be removed. type ErrCannotRemoveLastBucket struct { - BucketID int64 - ListID int64 + BucketID int64 + ProjectID int64 } // IsErrCannotRemoveLastBucket checks if an error is ErrCannotRemoveLastBucket. @@ -1433,7 +1433,7 @@ func IsErrCannotRemoveLastBucket(err error) bool { } func (err ErrCannotRemoveLastBucket) Error() string { - return fmt.Sprintf("Cannot remove last bucket of list [BucketID: %d, ListID: %d]", err.BucketID, err.ListID) + return fmt.Sprintf("Cannot remove last bucket of project [BucketID: %d, ProjectID: %d]", err.BucketID, err.ProjectID) } // ErrCodeCannotRemoveLastBucket holds the unique world-error code of this error @@ -1444,7 +1444,7 @@ func (err ErrCannotRemoveLastBucket) HTTPError() web.HTTPError { return web.HTTPError{ HTTPCode: http.StatusPreconditionFailed, Code: ErrCodeCannotRemoveLastBucket, - Message: "You cannot remove the last bucket on this list.", + Message: "You cannot remove the last bucket on this project.", } } @@ -1477,32 +1477,32 @@ func (err ErrBucketLimitExceeded) HTTPError() web.HTTPError { } } -// ErrOnlyOneDoneBucketPerList represents an error where a bucket is set to the done bucket but one already exists for its list. -type ErrOnlyOneDoneBucketPerList struct { +// ErrOnlyOneDoneBucketPerProject represents an error where a bucket is set to the done bucket but one already exists for its project. +type ErrOnlyOneDoneBucketPerProject struct { BucketID int64 - ListID int64 + ProjectID int64 DoneBucketID int64 } -// IsErrOnlyOneDoneBucketPerList checks if an error is ErrBucketLimitExceeded. -func IsErrOnlyOneDoneBucketPerList(err error) bool { - _, ok := err.(*ErrOnlyOneDoneBucketPerList) +// IsErrOnlyOneDoneBucketPerProject checks if an error is ErrBucketLimitExceeded. +func IsErrOnlyOneDoneBucketPerProject(err error) bool { + _, ok := err.(*ErrOnlyOneDoneBucketPerProject) return ok } -func (err *ErrOnlyOneDoneBucketPerList) Error() string { - return fmt.Sprintf("There can be only one done bucket per list [BucketID: %d, ListID: %d]", err.BucketID, err.ListID) +func (err *ErrOnlyOneDoneBucketPerProject) Error() string { + return fmt.Sprintf("There can be only one done bucket per project [BucketID: %d, ProjectID: %d]", err.BucketID, err.ProjectID) } -// ErrCodeOnlyOneDoneBucketPerList holds the unique world-error code of this error -const ErrCodeOnlyOneDoneBucketPerList = 10005 +// ErrCodeOnlyOneDoneBucketPerProject holds the unique world-error code of this error +const ErrCodeOnlyOneDoneBucketPerProject = 10005 // HTTPError holds the http error description -func (err *ErrOnlyOneDoneBucketPerList) HTTPError() web.HTTPError { +func (err *ErrOnlyOneDoneBucketPerProject) HTTPError() web.HTTPError { return web.HTTPError{ HTTPCode: http.StatusPreconditionFailed, - Code: ErrCodeOnlyOneDoneBucketPerList, - Message: "There can be only one done bucket per list.", + Code: ErrCodeOnlyOneDoneBucketPerProject, + Message: "There can be only one done bucket per project.", } } diff --git a/pkg/models/events.go b/pkg/models/events.go index 820aba0c6..c1fcbcbe4 100644 --- a/pkg/models/events.go +++ b/pkg/models/events.go @@ -214,68 +214,68 @@ func (t *NamespaceDeletedEvent) Name() string { } ///////////////// -// List Events // +// Project Events // ///////////////// -// ListCreatedEvent represents an event where a list has been created -type ListCreatedEvent struct { - List *List - Doer *user.User +// ProjectCreatedEvent represents an event where a project has been created +type ProjectCreatedEvent struct { + Project *Project + Doer *user.User } -// Name defines the name for ListCreatedEvent -func (l *ListCreatedEvent) Name() string { - return "list.created" +// Name defines the name for ProjectCreatedEvent +func (l *ProjectCreatedEvent) Name() string { + return "project.created" } -// ListUpdatedEvent represents an event where a list has been updated -type ListUpdatedEvent struct { - List *List - Doer web.Auth +// ProjectUpdatedEvent represents an event where a project has been updated +type ProjectUpdatedEvent struct { + Project *Project + Doer web.Auth } -// Name defines the name for ListUpdatedEvent -func (l *ListUpdatedEvent) Name() string { - return "list.updated" +// Name defines the name for ProjectUpdatedEvent +func (l *ProjectUpdatedEvent) Name() string { + return "project.updated" } -// ListDeletedEvent represents an event where a list has been deleted -type ListDeletedEvent struct { - List *List - Doer web.Auth +// ProjectDeletedEvent represents an event where a project has been deleted +type ProjectDeletedEvent struct { + Project *Project + Doer web.Auth } -// Name defines the name for ListDeletedEvent -func (t *ListDeletedEvent) Name() string { - return "list.deleted" +// Name defines the name for ProjectDeletedEvent +func (t *ProjectDeletedEvent) Name() string { + return "project.deleted" } //////////////////// // Sharing Events // //////////////////// -// ListSharedWithUserEvent represents an event where a list has been shared with a user -type ListSharedWithUserEvent struct { - List *List - User *user.User - Doer web.Auth +// ProjectSharedWithUserEvent represents an event where a project has been shared with a user +type ProjectSharedWithUserEvent struct { + Project *Project + User *user.User + Doer web.Auth } -// Name defines the name for ListSharedWithUserEvent -func (l *ListSharedWithUserEvent) Name() string { - return "list.shared.user" +// Name defines the name for ProjectSharedWithUserEvent +func (l *ProjectSharedWithUserEvent) Name() string { + return "project.shared.user" } -// ListSharedWithTeamEvent represents an event where a list has been shared with a team -type ListSharedWithTeamEvent struct { - List *List - Team *Team - Doer web.Auth +// ProjectSharedWithTeamEvent represents an event where a project has been shared with a team +type ProjectSharedWithTeamEvent struct { + Project *Project + Team *Team + Doer web.Auth } -// Name defines the name for ListSharedWithTeamEvent -func (l *ListSharedWithTeamEvent) Name() string { - return "list.shared.team" +// Name defines the name for ProjectSharedWithTeamEvent +func (l *ProjectSharedWithTeamEvent) Name() string { + return "project.shared.team" } // NamespaceSharedWithUserEvent represents an event where a namespace has been shared with a user diff --git a/pkg/models/export.go b/pkg/models/export.go index b3b2fac3b..1ae87881d 100644 --- a/pkg/models/export.go +++ b/pkg/models/export.go @@ -57,7 +57,7 @@ func ExportUserData(s *xorm.Session, u *user.User) (err error) { defer dumpWriter.Close() // Get the data - err = exportListsAndTasks(s, u, dumpWriter) + err = exportProjectsAndTasks(s, u, dumpWriter) if err != nil { return err } @@ -72,7 +72,7 @@ func ExportUserData(s *xorm.Session, u *user.User) (err error) { return err } // Background files - err = exportListBackgrounds(s, u, dumpWriter) + err = exportProjectBackgrounds(s, u, dumpWriter) if err != nil { return err } @@ -121,7 +121,7 @@ func ExportUserData(s *xorm.Session, u *user.User) (err error) { }) } -func exportListsAndTasks(s *xorm.Session, u *user.User, wr *zip.Writer) (err error) { +func exportProjectsAndTasks(s *xorm.Session, u *user.User, wr *zip.Writer) (err error) { namspaces, _, _, err := (&Namespace{IsArchived: true}).ReadAll(s, u, "", -1, 0) if err != nil { @@ -129,29 +129,29 @@ func exportListsAndTasks(s *xorm.Session, u *user.User, wr *zip.Writer) (err err } namespaceIDs := []int64{} - namespaces := []*NamespaceWithListsAndTasks{} - listMap := make(map[int64]*ListWithTasksAndBuckets) - listIDs := []int64{} - for _, n := range namspaces.([]*NamespaceWithLists) { + namespaces := []*NamespaceWithProjectsAndTasks{} + projectMap := make(map[int64]*ProjectWithTasksAndBuckets) + projectIDs := []int64{} + for _, n := range namspaces.([]*NamespaceWithProjects) { if n.ID < 1 { // Don't include filters continue } - nn := &NamespaceWithListsAndTasks{ + nn := &NamespaceWithProjectsAndTasks{ Namespace: n.Namespace, - Lists: []*ListWithTasksAndBuckets{}, + Projects: []*ProjectWithTasksAndBuckets{}, } - for _, l := range n.Lists { - ll := &ListWithTasksAndBuckets{ - List: *l, + for _, l := range n.Projects { + ll := &ProjectWithTasksAndBuckets{ + Project: *l, BackgroundFileID: l.BackgroundFileID, Tasks: []*TaskWithComments{}, } - nn.Lists = append(nn.Lists, ll) - listMap[l.ID] = ll - listIDs = append(listIDs, l.ID) + nn.Projects = append(nn.Projects, ll) + projectMap[l.ID] = ll + projectIDs = append(projectIDs, l.ID) } namespaceIDs = append(namespaceIDs, n.ID) @@ -162,13 +162,13 @@ func exportListsAndTasks(s *xorm.Session, u *user.User, wr *zip.Writer) (err err return nil } - // Get all lists - lists, err := getListsForNamespaces(s, namespaceIDs, true) + // Get all projects + projects, err := getProjectsForNamespaces(s, namespaceIDs, true) if err != nil { return err } - tasks, _, _, err := getTasksForLists(s, lists, u, &taskOptions{ + tasks, _, _, err := getTasksForProjects(s, projects, u, &taskOptions{ page: 0, perPage: -1, }) @@ -181,17 +181,17 @@ func exportListsAndTasks(s *xorm.Session, u *user.User, wr *zip.Writer) (err err taskMap[t.ID] = &TaskWithComments{ Task: *t, } - if _, exists := listMap[t.ListID]; !exists { - log.Debugf("[User Data Export] List %d does not exist for task %d, omitting", t.ListID, t.ID) + if _, exists := projectMap[t.ProjectID]; !exists { + log.Debugf("[User Data Export] Project %d does not exist for task %d, omitting", t.ProjectID, t.ID) continue } - listMap[t.ListID].Tasks = append(listMap[t.ListID].Tasks, taskMap[t.ID]) + projectMap[t.ProjectID].Tasks = append(projectMap[t.ProjectID].Tasks, taskMap[t.ID]) } comments := []*TaskComment{} err = s. Join("LEFT", "tasks", "tasks.id = task_comments.task_id"). - In("tasks.list_id", listIDs). + In("tasks.project_id", projectIDs). Find(&comments) if err != nil { return @@ -206,17 +206,17 @@ func exportListsAndTasks(s *xorm.Session, u *user.User, wr *zip.Writer) (err err } buckets := []*Bucket{} - err = s.In("list_id", listIDs).Find(&buckets) + err = s.In("project_id", projectIDs).Find(&buckets) if err != nil { return } for _, b := range buckets { - if _, exists := listMap[b.ListID]; !exists { - log.Debugf("[User Data Export] List %d does not exist for bucket %d, omitting", b.ListID, b.ID) + if _, exists := projectMap[b.ProjectID]; !exists { + log.Debugf("[User Data Export] Project %d does not exist for bucket %d, omitting", b.ProjectID, b.ID) continue } - listMap[b.ListID].Buckets = append(listMap[b.ListID].Buckets, b) + projectMap[b.ProjectID].Buckets = append(projectMap[b.ProjectID].Buckets, b) } data, err := json.Marshal(namespaces) @@ -228,9 +228,9 @@ func exportListsAndTasks(s *xorm.Session, u *user.User, wr *zip.Writer) (err err } func exportTaskAttachments(s *xorm.Session, u *user.User, wr *zip.Writer) (err error) { - lists, _, _, err := getRawListsForUser( + projects, _, _, err := getRawProjectsForUser( s, - &listOptions{ + &projectOptions{ user: u, page: -1, }, @@ -239,7 +239,7 @@ func exportTaskAttachments(s *xorm.Session, u *user.User, wr *zip.Writer) (err e return err } - tasks, _, _, err := getRawTasksForLists(s, lists, u, &taskOptions{page: -1}) + tasks, _, _, err := getRawTasksForProjects(s, projects, u, &taskOptions{page: -1}) if err != nil { return err } @@ -279,10 +279,10 @@ func exportSavedFilters(s *xorm.Session, u *user.User, wr *zip.Writer) (err erro return utils.WriteBytesToZip("filters.json", data, wr) } -func exportListBackgrounds(s *xorm.Session, u *user.User, wr *zip.Writer) (err error) { - lists, _, _, err := getRawListsForUser( +func exportProjectBackgrounds(s *xorm.Session, u *user.User, wr *zip.Writer) (err error) { + projects, _, _, err := getRawProjectsForUser( s, - &listOptions{ + &projectOptions{ user: u, page: -1, }, @@ -292,7 +292,7 @@ func exportListBackgrounds(s *xorm.Session, u *user.User, wr *zip.Writer) (err e } fs := make(map[int64]io.ReadCloser) - for _, l := range lists { + for _, l := range projects { if l.BackgroundFileID == 0 { continue } diff --git a/pkg/models/favorites.go b/pkg/models/favorites.go index 35f74ac12..421ad4b1a 100644 --- a/pkg/models/favorites.go +++ b/pkg/models/favorites.go @@ -29,7 +29,7 @@ type FavoriteKind int const ( FavoriteKindUnknown FavoriteKind = iota FavoriteKindTask - FavoriteKindList + FavoriteKindProject ) // Favorite represents an entity which is a favorite to someone diff --git a/pkg/models/kanban.go b/pkg/models/kanban.go index 75a0a9f58..a7f3242f4 100644 --- a/pkg/models/kanban.go +++ b/pkg/models/kanban.go @@ -31,8 +31,8 @@ type Bucket struct { ID int64 `xorm:"bigint autoincr not null unique pk" json:"id" param:"bucket"` // The title of this bucket. Title string `xorm:"text not null" valid:"required" minLength:"1" json:"title"` - // The list this bucket belongs to. - ListID int64 `xorm:"bigint not null" json:"list_id" param:"list"` + // The project this bucket belongs to. + ProjectID int64 `xorm:"bigint not null" json:"project_id" param:"project"` // All tasks which belong to this bucket. Tasks []*Task `xorm:"-" json:"tasks"` @@ -77,19 +77,19 @@ func getBucketByID(s *xorm.Session, id int64) (b *Bucket, err error) { return } -func getDefaultBucket(s *xorm.Session, listID int64) (bucket *Bucket, err error) { +func getDefaultBucket(s *xorm.Session, projectID int64) (bucket *Bucket, err error) { bucket = &Bucket{} _, err = s. - Where("list_id = ?", listID). + Where("project_id = ?", projectID). OrderBy("position asc"). Get(bucket) return } -func getDoneBucketForList(s *xorm.Session, listID int64) (bucket *Bucket, err error) { +func getDoneBucketForProject(s *xorm.Session, projectID int64) (bucket *Bucket, err error) { bucket = &Bucket{} exists, err := s. - Where("list_id = ? and is_done_bucket = ?", listID, true). + Where("project_id = ? and is_done_bucket = ?", projectID, true). Get(bucket) if err != nil { return nil, err @@ -101,14 +101,14 @@ func getDoneBucketForList(s *xorm.Session, listID int64) (bucket *Bucket, err er return } -// ReadAll returns all buckets with their tasks for a certain list -// @Summary Get all kanban buckets of a list -// @Description Returns all kanban buckets with belong to a list including their tasks. +// ReadAll returns all buckets with their tasks for a certain project +// @Summary Get all kanban buckets of a project +// @Description Returns all kanban buckets with belong to a project including their tasks. // @tags task // @Accept json // @Produce json // @Security JWTKeyAuth -// @Param id path int true "List Id" +// @Param id path int true "Project Id" // @Param page query int false "The page number for tasks. Used for pagination. If not provided, the first page of results is returned." // @Param per_page query int false "The maximum number of tasks per bucket per page. This parameter is limited by the configured maximum of items per page." // @Param s query string false "Search tasks by task text." @@ -119,15 +119,15 @@ func getDoneBucketForList(s *xorm.Session, listID int64) (bucket *Bucket, err er // @Param filter_include_nulls query string false "If set to true the result will include filtered fields whose value is set to `null`. Available values are `true` or `false`. Defaults to `false`." // @Success 200 {array} models.Bucket "The buckets with their tasks" // @Failure 500 {object} models.Message "Internal server error" -// @Router /lists/{id}/buckets [get] +// @Router /projects/{id}/buckets [get] func (b *Bucket) ReadAll(s *xorm.Session, auth web.Auth, search string, page int, perPage int) (result interface{}, resultCount int, numberOfTotalItems int64, err error) { - list, err := GetListSimpleByID(s, b.ListID) + project, err := GetProjectSimpleByID(s, b.ProjectID) if err != nil { return nil, 0, 0, err } - can, _, err := list.CanRead(s, auth) + can, _, err := project.CanRead(s, auth) if err != nil { return nil, 0, 0, err } @@ -135,10 +135,10 @@ func (b *Bucket) ReadAll(s *xorm.Session, auth web.Auth, search string, page int return nil, 0, 0, ErrGenericForbidden{} } - // Get all buckets for this list + // Get all buckets for this project buckets := []*Bucket{} err = s. - Where("list_id = ?", b.ListID). + Where("project_id = ?", b.ProjectID). OrderBy("position"). Find(&buckets) if err != nil { @@ -202,7 +202,7 @@ func (b *Bucket) ReadAll(s *xorm.Session, auth web.Auth, search string, page int opts.filters[bucketFilterIndex].value = id - ts, _, _, err := getRawTasksForLists(s, []*List{{ID: bucket.ListID}}, auth, opts) + ts, _, _, err := getRawTasksForProjects(s, []*Project{{ID: bucket.ProjectID}}, auth, opts) if err != nil { return nil, 0, 0, err } @@ -226,7 +226,7 @@ func (b *Bucket) ReadAll(s *xorm.Session, auth web.Auth, search string, page int for _, task := range tasks { // Check if the bucket exists in the map to prevent nil pointer panics if _, exists := bucketMap[task.BucketID]; !exists { - log.Debugf("Tried to put task %d into bucket %d which does not exist in list %d", task.ID, task.BucketID, b.ListID) + log.Debugf("Tried to put task %d into bucket %d which does not exist in project %d", task.ID, task.BucketID, b.ProjectID) continue } bucketMap[task.BucketID].Tasks = append(bucketMap[task.BucketID].Tasks, task) @@ -237,18 +237,18 @@ func (b *Bucket) ReadAll(s *xorm.Session, auth web.Auth, search string, page int // Create creates a new bucket // @Summary Create a new bucket -// @Description Creates a new kanban bucket on a list. +// @Description Creates a new kanban bucket on a project. // @tags task // @Accept json // @Produce json // @Security JWTKeyAuth -// @Param id path int true "List Id" +// @Param id path int true "Project Id" // @Param bucket body models.Bucket true "The bucket object" // @Success 200 {object} models.Bucket "The created bucket object." // @Failure 400 {object} web.HTTPError "Invalid bucket object provided." -// @Failure 404 {object} web.HTTPError "The list does not exist." +// @Failure 404 {object} web.HTTPError "The project does not exist." // @Failure 500 {object} models.Message "Internal error" -// @Router /lists/{id}/buckets [put] +// @Router /projects/{id}/buckets [put] func (b *Bucket) Create(s *xorm.Session, a web.Auth) (err error) { b.CreatedBy, err = GetUserOrLinkShareUser(s, a) if err != nil { @@ -273,24 +273,24 @@ func (b *Bucket) Create(s *xorm.Session, a web.Auth) (err error) { // @Accept json // @Produce json // @Security JWTKeyAuth -// @Param listID path int true "List Id" +// @Param projectID path int true "Project Id" // @Param bucketID path int true "Bucket Id" // @Param bucket body models.Bucket true "The bucket object" // @Success 200 {object} models.Bucket "The created bucket object." // @Failure 400 {object} web.HTTPError "Invalid bucket object provided." // @Failure 404 {object} web.HTTPError "The bucket does not exist." // @Failure 500 {object} models.Message "Internal error" -// @Router /lists/{listID}/buckets/{bucketID} [post] +// @Router /projects/{projectID}/buckets/{bucketID} [post] func (b *Bucket) Update(s *xorm.Session, a web.Auth) (err error) { - doneBucket, err := getDoneBucketForList(s, b.ListID) + doneBucket, err := getDoneBucketForProject(s, b.ProjectID) if err != nil { return err } if doneBucket != nil && doneBucket.IsDoneBucket && b.IsDoneBucket && doneBucket.ID != b.ID { - return &ErrOnlyOneDoneBucketPerList{ + return &ErrOnlyOneDoneBucketPerProject{ BucketID: b.ID, - ListID: b.ListID, + ProjectID: b.ProjectID, DoneBucketID: doneBucket.ID, } } @@ -309,28 +309,28 @@ func (b *Bucket) Update(s *xorm.Session, a web.Auth) (err error) { // Delete removes a bucket, but no tasks // @Summary Deletes an existing bucket -// @Description Deletes an existing kanban bucket and dissociates all of its task. It does not delete any tasks. You cannot delete the last bucket on a list. +// @Description Deletes an existing kanban bucket and dissociates all of its task. It does not delete any tasks. You cannot delete the last bucket on a project. // @tags task // @Accept json // @Produce json // @Security JWTKeyAuth -// @Param listID path int true "List Id" +// @Param projectID path int true "Project Id" // @Param bucketID path int true "Bucket Id" // @Success 200 {object} models.Message "Successfully deleted." // @Failure 404 {object} web.HTTPError "The bucket does not exist." // @Failure 500 {object} models.Message "Internal error" -// @Router /lists/{listID}/buckets/{bucketID} [delete] +// @Router /projects/{projectID}/buckets/{bucketID} [delete] func (b *Bucket) Delete(s *xorm.Session, a web.Auth) (err error) { // Prevent removing the last bucket - total, err := s.Where("list_id = ?", b.ListID).Count(&Bucket{}) + total, err := s.Where("project_id = ?", b.ProjectID).Count(&Bucket{}) if err != nil { return } if total <= 1 { return ErrCannotRemoveLastBucket{ - BucketID: b.ID, - ListID: b.ListID, + BucketID: b.ID, + ProjectID: b.ProjectID, } } @@ -341,7 +341,7 @@ func (b *Bucket) Delete(s *xorm.Session, a web.Auth) (err error) { } // Get the default bucket - defaultBucket, err := getDefaultBucket(s, b.ListID) + defaultBucket, err := getDefaultBucket(s, b.ProjectID) if err != nil { return } diff --git a/pkg/models/kanban_rights.go b/pkg/models/kanban_rights.go index 8f82f90a3..68e498b8d 100644 --- a/pkg/models/kanban_rights.go +++ b/pkg/models/kanban_rights.go @@ -23,7 +23,7 @@ import ( // CanCreate checks if a user can create a new bucket func (b *Bucket) CanCreate(s *xorm.Session, a web.Auth) (bool, error) { - l := &List{ID: b.ListID} + l := &Project{ID: b.ProjectID} return l.CanWrite(s, a) } @@ -43,6 +43,6 @@ func (b *Bucket) canDoBucket(s *xorm.Session, a web.Auth) (bool, error) { if err != nil { return false, err } - l := &List{ID: bb.ListID} + l := &Project{ID: bb.ProjectID} return l.CanWrite(s, a) } diff --git a/pkg/models/kanban_test.go b/pkg/models/kanban_test.go index dd1dc759c..4ac30b1b0 100644 --- a/pkg/models/kanban_test.go +++ b/pkg/models/kanban_test.go @@ -33,7 +33,7 @@ func TestBucket_ReadAll(t *testing.T) { defer s.Close() testuser := &user.User{ID: 1} - b := &Bucket{ListID: 1} + b := &Bucket{ProjectID: 1} bucketsInterface, _, _, err := b.ReadAll(s, testuser, "", 0, 0) assert.NoError(t, err) @@ -53,7 +53,7 @@ func TestBucket_ReadAll(t *testing.T) { assert.Len(t, buckets[1].Tasks, 3) assert.Len(t, buckets[2].Tasks, 3) - // Assert we have bucket 1, 2, 3 but not 4 (that belongs to a different list) and their position + // Assert we have bucket 1, 2, 3 but not 4 (that belongs to a different project) and their position assert.Equal(t, int64(1), buckets[0].ID) assert.Equal(t, int64(2), buckets[1].ID) assert.Equal(t, int64(3), buckets[2].ID) @@ -77,7 +77,7 @@ func TestBucket_ReadAll(t *testing.T) { testuser := &user.User{ID: 1} b := &Bucket{ - ListID: 1, + ProjectID: 1, TaskCollection: TaskCollection{ FilterBy: []string{"title"}, FilterComparator: []string{"like"}, @@ -98,11 +98,11 @@ func TestBucket_ReadAll(t *testing.T) { defer s.Close() linkShare := &LinkSharing{ - ID: 1, - ListID: 1, - Right: RightRead, + ID: 1, + ProjectID: 1, + Right: RightRead, } - b := &Bucket{ListID: 1} + b := &Bucket{ProjectID: 1} result, _, _, err := b.ReadAll(s, linkShare, "", 0, 0) assert.NoError(t, err) buckets, _ := result.([]*Bucket) @@ -116,7 +116,7 @@ func TestBucket_ReadAll(t *testing.T) { defer s.Close() testuser := &user.User{ID: 12} - b := &Bucket{ListID: 23} + b := &Bucket{ProjectID: 23} result, _, _, err := b.ReadAll(s, testuser, "", 0, 0) assert.NoError(t, err) buckets, _ := result.([]*Bucket) @@ -135,8 +135,8 @@ func TestBucket_Delete(t *testing.T) { defer s.Close() b := &Bucket{ - ID: 2, // The second bucket only has 3 tasks - ListID: 1, + ID: 2, // The second bucket only has 3 tasks + ProjectID: 1, } err := b.Delete(s, user) assert.NoError(t, err) @@ -149,18 +149,18 @@ func TestBucket_Delete(t *testing.T) { assert.NoError(t, err) assert.Len(t, tasks, 16) db.AssertMissing(t, "buckets", map[string]interface{}{ - "id": 2, - "list_id": 1, + "id": 2, + "project_id": 1, }) }) - t.Run("last bucket in list", func(t *testing.T) { + t.Run("last bucket in project", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() defer s.Close() b := &Bucket{ - ID: 34, - ListID: 18, + ID: 34, + ProjectID: 18, } err := b.Delete(s, user) assert.Error(t, err) @@ -169,8 +169,8 @@ func TestBucket_Delete(t *testing.T) { assert.NoError(t, err) db.AssertExists(t, "buckets", map[string]interface{}{ - "id": 34, - "list_id": 18, + "id": 34, + "project_id": 18, }, false) }) } @@ -217,19 +217,19 @@ func TestBucket_Update(t *testing.T) { testAndAssertBucketUpdate(t, b, s) }) - t.Run("only one done bucket per list", func(t *testing.T) { + t.Run("only one done bucket per project", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() defer s.Close() b := &Bucket{ ID: 1, - ListID: 1, + ProjectID: 1, IsDoneBucket: true, } err := b.Update(s, &user.User{ID: 1}) assert.Error(t, err) - assert.True(t, IsErrOnlyOneDoneBucketPerList(err)) + assert.True(t, IsErrOnlyOneDoneBucketPerProject(err)) }) } diff --git a/pkg/models/label_rights.go b/pkg/models/label_rights.go index bb3136097..196dd10c5 100644 --- a/pkg/models/label_rights.go +++ b/pkg/models/label_rights.go @@ -77,7 +77,7 @@ func (l *Label) hasAccessToLabel(s *xorm.Session, a web.Auth) (has bool, maxRigh builder. Select("id"). From("tasks"). - Where(builder.In("list_id", getUserListsStatement(u.ID).Select("l.id"))), + Where(builder.In("project_id", getUserProjectsStatement(u.ID).Select("l.id"))), ) ll := &LabelTask{} diff --git a/pkg/models/label_task.go b/pkg/models/label_task.go index 73db42e75..13d7e462a 100644 --- a/pkg/models/label_task.go +++ b/pkg/models/label_task.go @@ -35,7 +35,7 @@ import ( type LabelTask struct { // The unique, numeric id of this label. ID int64 `xorm:"bigint autoincr not null unique pk" json:"-"` - TaskID int64 `xorm:"bigint INDEX not null" json:"-" param:"listtask"` + TaskID int64 `xorm:"bigint INDEX not null" json:"-" param:"projecttask"` // The label id you want to associate with a task. LabelID int64 `xorm:"bigint INDEX not null" json:"label_id" param:"label"` // A timestamp when this task was created. You cannot change this value. @@ -52,7 +52,7 @@ func (LabelTask) TableName() string { // Delete deletes a label on a task // @Summary Remove a label from a task -// @Description Remove a label from a task. The user needs to have write-access to the list to be able do this. +// @Description Remove a label from a task. The user needs to have write-access to the project to be able do this. // @tags labels // @Accept json // @Produce json @@ -71,7 +71,7 @@ func (lt *LabelTask) Delete(s *xorm.Session, a web.Auth) (err error) { // Create adds a label to a task // @Summary Add a label to a task -// @Description Add a label to a task. The user needs to have write-access to the list to be able do this. +// @Description Add a label to a task. The user needs to have write-access to the project to be able do this. // @tags labels // @Accept json // @Produce json @@ -100,7 +100,7 @@ func (lt *LabelTask) Create(s *xorm.Session, a web.Auth) (err error) { return err } - err = updateListByTaskID(s, lt.TaskID) + err = updateProjectByTaskID(s, lt.TaskID) return } @@ -180,7 +180,7 @@ func GetLabelsByTaskIDs(s *xorm.Session, opts *LabelByTaskIDsOptions) (ls []*Lab builder. Select("id"). From("tasks"). - Where(builder.In("list_id", getUserListsStatement(opts.GetForUser).Select("l.id"))), + Where(builder.In("project_id", getUserProjectsStatement(opts.GetForUser).Select("l.id"))), ), cond) } if opts.GetUnusedLabels { @@ -309,17 +309,17 @@ func (t *Task) UpdateTaskLabels(s *xorm.Session, creator web.Auth, labels []*Lab for _, oldLabel := range allLabels { found = false if newLabels[oldLabel.ID] != nil { - found = true // If a new label is already in the list with old labels + found = true // If a new label is already in the project with old labels } - // Put all labels which are only on the old list to the trash + // Put all labels which are only on the old project to the trash if !found { labelsToDelete = append(labelsToDelete, oldLabel.ID) } else { t.Labels = append(t.Labels, oldLabel) } - // Put it in a list with all old labels, just using the loop here + // Put it in a project with all old labels, just using the loop here oldLabels[oldLabel.ID] = oldLabel } @@ -365,7 +365,7 @@ func (t *Task) UpdateTaskLabels(s *xorm.Session, creator web.Auth, labels []*Lab t.Labels = append(t.Labels, label) } - err = updateListLastUpdated(s, &List{ID: t.ListID}) + err = updateProjectLastUpdated(s, &Project{ID: t.ProjectID}) return } @@ -373,7 +373,7 @@ func (t *Task) UpdateTaskLabels(s *xorm.Session, creator web.Auth, labels []*Lab type LabelTaskBulk struct { // All labels you want to update at once. Labels []*Label `json:"labels"` - TaskID int64 `json:"-" param:"listtask"` + TaskID int64 `json:"-" param:"projecttask"` web.CRUDable `json:"-"` web.Rights `json:"-"` diff --git a/pkg/models/link_sharing.go b/pkg/models/link_sharing.go index 249a0a121..a2f6208f8 100644 --- a/pkg/models/link_sharing.go +++ b/pkg/models/link_sharing.go @@ -42,17 +42,17 @@ const ( SharingTypeWithPassword ) -// LinkSharing represents a shared list +// LinkSharing represents a shared project type LinkSharing struct { // The ID of the shared thing ID int64 `xorm:"bigint autoincr not null unique pk" json:"id" param:"share"` - // The public id to get this shared list + // The public id to get this shared project Hash string `xorm:"varchar(40) not null unique" json:"hash" param:"hash"` // The name of this link share. All actions someone takes while being authenticated with that link will appear with that name. Name string `xorm:"text null" json:"name"` - // The ID of the shared list - ListID int64 `xorm:"bigint not null" json:"-" param:"list"` - // The right this list is shared with. 0 = Read only, 1 = Read & Write, 2 = Admin. See the docs for more details. + // The ID of the shared project + ProjectID int64 `xorm:"bigint not null" json:"-" param:"project"` + // The right this project is shared with. 0 = Read only, 1 = Read & Write, 2 = Admin. See the docs for more details. Right Right `xorm:"bigint INDEX not null default 0" json:"right" valid:"length(0|2)" maximum:"2" default:"0"` // The kind of this link. 0 = undefined, 1 = without password, 2 = with password. @@ -61,11 +61,11 @@ type LinkSharing struct { // The password of this link share. You can only set it, not retrieve it after the link share has been created. Password string `xorm:"text null" json:"password"` - // The user who shared this list + // The user who shared this project SharedBy *user.User `xorm:"-" json:"shared_by"` SharedByID int64 `xorm:"bigint INDEX not null" json:"-"` - // A timestamp when this list was shared. You cannot change this value. + // A timestamp when this project was shared. You cannot change this value. Created time.Time `xorm:"created not null" json:"created"` // A timestamp when this share was last updated. You cannot change this value. Updated time.Time `xorm:"updated not null" json:"updated"` @@ -89,7 +89,7 @@ func GetLinkShareFromClaims(claims jwt.MapClaims) (share *LinkSharing, err error share = &LinkSharing{} share.ID = int64(claims["id"].(float64)) share.Hash = claims["hash"].(string) - share.ListID = int64(claims["list_id"].(float64)) + share.ProjectID = int64(claims["project_id"].(float64)) share.Right = Right(claims["right"].(float64)) share.SharedByID = int64(claims["sharedByID"].(float64)) return @@ -114,21 +114,21 @@ func (share *LinkSharing) toUser() *user.User { } } -// Create creates a new link share for a given list -// @Summary Share a list via link -// @Description Share a list via link. The user needs to have write-access to the list to be able do this. +// Create creates a new link share for a given project +// @Summary Share a project via link +// @Description Share a project via link. The user needs to have write-access to the project to be able do this. // @tags sharing // @Accept json // @Produce json // @Security JWTKeyAuth -// @Param list path int true "List ID" +// @Param project path int true "Project ID" // @Param label body models.LinkSharing true "The new link share object" // @Success 201 {object} models.LinkSharing "The created link share object." // @Failure 400 {object} web.HTTPError "Invalid link share object provided." -// @Failure 403 {object} web.HTTPError "Not allowed to add the list share." -// @Failure 404 {object} web.HTTPError "The list does not exist." +// @Failure 403 {object} web.HTTPError "Not allowed to add the project share." +// @Failure 404 {object} web.HTTPError "The project does not exist." // @Failure 500 {object} models.Message "Internal error" -// @Router /lists/{list}/shares [put] +// @Router /projects/{project}/shares [put] func (share *LinkSharing) Create(s *xorm.Session, a web.Auth) (err error) { err = share.Right.isValid() @@ -156,48 +156,48 @@ func (share *LinkSharing) Create(s *xorm.Session, a web.Auth) (err error) { } // ReadOne returns one share -// @Summary Get one link shares for a list +// @Summary Get one link shares for a project // @Description Returns one link share by its ID. // @tags sharing // @Accept json // @Produce json -// @Param list path int true "List ID" +// @Param project path int true "Project ID" // @Param share path int true "Share ID" // @Security JWTKeyAuth // @Success 200 {object} models.LinkSharing "The share links" -// @Failure 403 {object} web.HTTPError "No access to the list" +// @Failure 403 {object} web.HTTPError "No access to the project" // @Failure 404 {object} web.HTTPError "Share Link not found." // @Failure 500 {object} models.Message "Internal error" -// @Router /lists/{list}/shares/{share} [get] +// @Router /projects/{project}/shares/{share} [get] func (share *LinkSharing) ReadOne(s *xorm.Session, a web.Auth) (err error) { exists, err := s.Where("id = ?", share.ID).Get(share) if err != nil { return err } if !exists { - return ErrListShareDoesNotExist{ID: share.ID, Hash: share.Hash} + return ErrProjectShareDoesNotExist{ID: share.ID, Hash: share.Hash} } share.Password = "" return } -// ReadAll returns all shares for a given list -// @Summary Get all link shares for a list -// @Description Returns all link shares which exist for a given list +// ReadAll returns all shares for a given project +// @Summary Get all link shares for a project +// @Description Returns all link shares which exist for a given project // @tags sharing // @Accept json // @Produce json -// @Param list path int true "List ID" +// @Param project path int true "Project ID" // @Param page query int false "The page number. Used for pagination. If not provided, the first page of results is returned." // @Param per_page query int false "The maximum number of items per page. Note this parameter is limited by the configured maximum of items per page." // @Param s query string false "Search shares by hash." // @Security JWTKeyAuth // @Success 200 {array} models.LinkSharing "The share links" // @Failure 500 {object} models.Message "Internal error" -// @Router /lists/{list}/shares [get] +// @Router /projects/{project}/shares [get] func (share *LinkSharing) ReadAll(s *xorm.Session, a web.Auth, search string, page int, perPage int) (result interface{}, resultCount int, totalItems int64, err error) { - list := &List{ID: share.ListID} - can, _, err := list.CanRead(s, a) + project := &Project{ID: share.ProjectID} + can, _, err := project.CanRead(s, a) if err != nil { return nil, 0, 0, err } @@ -210,7 +210,7 @@ func (share *LinkSharing) ReadAll(s *xorm.Session, a web.Auth, search string, pa var shares []*LinkSharing query := s. Where(builder.And( - builder.Eq{"list_id": share.ListID}, + builder.Eq{"project_id": share.ProjectID}, builder.Or( db.ILIKE("hash", search), db.ILIKE("name", search), @@ -246,7 +246,7 @@ func (share *LinkSharing) ReadAll(s *xorm.Session, a web.Auth, search string, pa // Total count totalItems, err = s. - Where("list_id = ? AND hash LIKE ?", share.ListID, "%"+search+"%"). + Where("project_id = ? AND hash LIKE ?", share.ProjectID, "%"+search+"%"). Count(&LinkSharing{}) if err != nil { return nil, 0, 0, err @@ -257,18 +257,18 @@ func (share *LinkSharing) ReadAll(s *xorm.Session, a web.Auth, search string, pa // Delete removes a link share // @Summary Remove a link share -// @Description Remove a link share. The user needs to have write-access to the list to be able do this. +// @Description Remove a link share. The user needs to have write-access to the project to be able do this. // @tags sharing // @Accept json // @Produce json // @Security JWTKeyAuth -// @Param list path int true "List ID" +// @Param project path int true "Project ID" // @Param share path int true "Share Link ID" // @Success 200 {object} models.Message "The link was successfully removed." // @Failure 403 {object} web.HTTPError "Not allowed to remove the link." // @Failure 404 {object} web.HTTPError "Share Link not found." // @Failure 500 {object} models.Message "Internal error" -// @Router /lists/{list}/shares/{share} [delete] +// @Router /projects/{project}/shares/{share} [delete] func (share *LinkSharing) Delete(s *xorm.Session, a web.Auth) (err error) { _, err = s.Where("id = ?", share.ID).Delete(share) return @@ -282,19 +282,19 @@ func GetLinkShareByHash(s *xorm.Session, hash string) (share *LinkSharing, err e return } if !has { - return share, ErrListShareDoesNotExist{Hash: hash} + return share, ErrProjectShareDoesNotExist{Hash: hash} } return } -// GetListByShareHash returns a link share by its hash -func GetListByShareHash(s *xorm.Session, hash string) (list *List, err error) { +// GetProjectByShareHash returns a link share by its hash +func GetProjectByShareHash(s *xorm.Session, hash string) (project *Project, err error) { share, err := GetLinkShareByHash(s, hash) if err != nil { return } - list, err = GetListSimpleByID(s, share.ListID) + project, err = GetProjectSimpleByID(s, share.ProjectID) return } @@ -306,7 +306,7 @@ func GetLinkShareByID(s *xorm.Session, id int64) (share *LinkSharing, err error) return } if !has { - return share, ErrListShareDoesNotExist{ID: id} + return share, ErrProjectShareDoesNotExist{ID: id} } return } diff --git a/pkg/models/link_sharing_rights.go b/pkg/models/link_sharing_rights.go index f909132d5..4abf583fe 100644 --- a/pkg/models/link_sharing_rights.go +++ b/pkg/models/link_sharing_rights.go @@ -28,7 +28,7 @@ func (share *LinkSharing) CanRead(s *xorm.Session, a web.Auth) (bool, int, error return false, 0, nil } - l, err := GetListByShareHash(s, share.Hash) + l, err := GetProjectByShareHash(s, share.Hash) if err != nil { return false, 0, err } @@ -56,7 +56,7 @@ func (share *LinkSharing) canDoLinkShare(s *xorm.Session, a web.Auth) (bool, err return false, nil } - l, err := GetListSimpleByID(s, share.ListID) + l, err := GetProjectSimpleByID(s, share.ProjectID) if err != nil { return false, err } diff --git a/pkg/models/link_sharing_test.go b/pkg/models/link_sharing_test.go index 8b3e6f2ee..e0af9a846 100644 --- a/pkg/models/link_sharing_test.go +++ b/pkg/models/link_sharing_test.go @@ -33,8 +33,8 @@ func TestLinkSharing_Create(t *testing.T) { defer s.Close() share := &LinkSharing{ - ListID: 1, - Right: RightRead, + ProjectID: 1, + Right: RightRead, } err := share.Create(s, doer) @@ -52,8 +52,8 @@ func TestLinkSharing_Create(t *testing.T) { defer s.Close() share := &LinkSharing{ - ListID: 1, - Right: Right(123), + ProjectID: 1, + Right: Right(123), } err := share.Create(s, doer) @@ -66,9 +66,9 @@ func TestLinkSharing_Create(t *testing.T) { defer s.Close() share := &LinkSharing{ - ListID: 1, - Right: RightRead, - Password: "somePassword", + ProjectID: 1, + Right: RightRead, + Password: "somePassword", } err := share.Create(s, doer) @@ -92,7 +92,7 @@ func TestLinkSharing_ReadAll(t *testing.T) { defer s.Close() share := &LinkSharing{ - ListID: 1, + ProjectID: 1, } all, _, _, err := share.ReadAll(s, doer, "", 1, -1) shares := all.([]*LinkSharing) @@ -109,7 +109,7 @@ func TestLinkSharing_ReadAll(t *testing.T) { defer s.Close() share := &LinkSharing{ - ListID: 1, + ProjectID: 1, } all, _, _, err := share.ReadAll(s, doer, "wITHPASS", 1, -1) shares := all.([]*LinkSharing) diff --git a/pkg/models/list.go b/pkg/models/list.go index 44812c7e9..3439efc93 100644 --- a/pkg/models/list.go +++ b/pkg/models/list.go @@ -33,123 +33,123 @@ import ( "xorm.io/xorm" ) -// List represents a list of tasks -type List struct { - // The unique, numeric id of this list. - ID int64 `xorm:"bigint autoincr not null unique pk" json:"id" param:"list"` - // The title of the list. You'll see this in the namespace overview. +// Project represents a project of tasks +type Project struct { + // The unique, numeric id of this project. + ID int64 `xorm:"bigint autoincr not null unique pk" json:"id" param:"project"` + // The title of the project. You'll see this in the namespace overview. Title string `xorm:"varchar(250) not null" json:"title" valid:"required,runelength(1|250)" minLength:"1" maxLength:"250"` - // The description of the list. + // The description of the project. Description string `xorm:"longtext null" json:"description"` - // The unique list short identifier. Used to build task identifiers. + // The unique project short identifier. Used to build task identifiers. Identifier string `xorm:"varchar(10) null" json:"identifier" valid:"runelength(0|10)" minLength:"0" maxLength:"10"` - // The hex color of this list + // The hex color of this project HexColor string `xorm:"varchar(6) null" json:"hex_color" valid:"runelength(0|6)" maxLength:"6"` OwnerID int64 `xorm:"bigint INDEX not null" json:"-"` NamespaceID int64 `xorm:"bigint INDEX not null" json:"namespace_id" param:"namespace"` - // The user who created this list. + // The user who created this project. Owner *user.User `xorm:"-" json:"owner" valid:"-"` - // Whether or not a list is archived. + // Whether or not a project is archived. IsArchived bool `xorm:"not null default false" json:"is_archived" query:"is_archived"` - // The id of the file this list has set as background + // The id of the file this project has set as background BackgroundFileID int64 `xorm:"null" json:"-"` - // Holds extra information about the background set since some background providers require attribution or similar. If not null, the background can be accessed at /lists/{listID}/background + // Holds extra information about the background set since some background providers require attribution or similar. If not null, the background can be accessed at /projects/{projectID}/background BackgroundInformation interface{} `xorm:"-" json:"background_information"` - // Contains a very small version of the list background to use as a blurry preview until the actual background is loaded. Check out https://blurha.sh/ to learn how it works. + // Contains a very small version of the project background to use as a blurry preview until the actual background is loaded. Check out https://blurha.sh/ to learn how it works. BackgroundBlurHash string `xorm:"varchar(50) null" json:"background_blur_hash"` - // True if a list is a favorite. Favorite lists show up in a separate namespace. This value depends on the user making the call to the api. + // True if a project is a favorite. Favorite projects show up in a separate namespace. This value depends on the user making the call to the api. IsFavorite bool `xorm:"-" json:"is_favorite"` - // The subscription status for the user reading this list. You can only read this property, use the subscription endpoints to modify it. - // Will only returned when retreiving one list. + // The subscription status for the user reading this project. You can only read this property, use the subscription endpoints to modify it. + // Will only returned when retreiving one project. Subscription *Subscription `xorm:"-" json:"subscription,omitempty"` - // The position this list has when querying all lists. See the tasks.position property on how to use this. + // The position this project has when querying all projects. See the tasks.position property on how to use this. Position float64 `xorm:"double null" json:"position"` - // A timestamp when this list was created. You cannot change this value. + // A timestamp when this project was created. You cannot change this value. Created time.Time `xorm:"created not null" json:"created"` - // A timestamp when this list was last updated. You cannot change this value. + // A timestamp when this project was last updated. You cannot change this value. Updated time.Time `xorm:"updated not null" json:"updated"` web.CRUDable `xorm:"-" json:"-"` web.Rights `xorm:"-" json:"-"` } -type ListWithTasksAndBuckets struct { - List - // An array of tasks which belong to the list. +type ProjectWithTasksAndBuckets struct { + Project + // An array of tasks which belong to the project. Tasks []*TaskWithComments `xorm:"-" json:"tasks"` // Only used for migration. Buckets []*Bucket `xorm:"-" json:"buckets"` BackgroundFileID int64 `xorm:"null" json:"background_file_id"` } -// TableName returns a better name for the lists table -func (l *List) TableName() string { - return "lists" +// TableName returns a better name for the projects table +func (l *Project) TableName() string { + return "projects" } -// ListBackgroundType holds a list background type -type ListBackgroundType struct { +// ProjectBackgroundType holds a project background type +type ProjectBackgroundType struct { Type string } -// ListBackgroundUpload represents the list upload background type -const ListBackgroundUpload string = "upload" +// ProjectBackgroundUpload represents the project upload background type +const ProjectBackgroundUpload string = "upload" -// FavoritesPseudoList holds all tasks marked as favorites -var FavoritesPseudoList = List{ +// FavoritesPseudoProject holds all tasks marked as favorites +var FavoritesPseudoProject = Project{ ID: -1, Title: "Favorites", - Description: "This list has all tasks marked as favorites.", + Description: "This project has all tasks marked as favorites.", NamespaceID: FavoritesPseudoNamespace.ID, IsFavorite: true, Created: time.Now(), Updated: time.Now(), } -// GetListsByNamespaceID gets all lists in a namespace -func GetListsByNamespaceID(s *xorm.Session, nID int64, doer *user.User) (lists []*List, err error) { +// GetProjectsByNamespaceID gets all projects in a namespace +func GetProjectsByNamespaceID(s *xorm.Session, nID int64, doer *user.User) (projects []*Project, err error) { switch nID { - case SharedListsPseudoNamespace.ID: - nnn, err := getSharedListsInNamespace(s, false, doer) + case SharedProjectsPseudoNamespace.ID: + nnn, err := getSharedProjectsInNamespace(s, false, doer) if err != nil { return nil, err } - if nnn != nil && nnn.Lists != nil { - lists = nnn.Lists + if nnn != nil && nnn.Projects != nil { + projects = nnn.Projects } case FavoritesPseudoNamespace.ID: - namespaces := make(map[int64]*NamespaceWithLists) - _, err := getNamespacesWithLists(s, &namespaces, "", false, 0, -1, doer.ID) + namespaces := make(map[int64]*NamespaceWithProjects) + _, err := getNamespacesWithProjects(s, &namespaces, "", false, 0, -1, doer.ID) if err != nil { return nil, err } namespaceIDs, _ := getNamespaceOwnerIDs(namespaces) - ls, err := getListsForNamespaces(s, namespaceIDs, false) + ls, err := getProjectsForNamespaces(s, namespaceIDs, false) if err != nil { return nil, err } - nnn, err := getFavoriteLists(s, ls, namespaceIDs, doer) + nnn, err := getFavoriteProjects(s, ls, namespaceIDs, doer) if err != nil { return nil, err } - if nnn != nil && nnn.Lists != nil { - lists = nnn.Lists + if nnn != nil && nnn.Projects != nil { + projects = nnn.Projects } case SavedFiltersPseudoNamespace.ID: nnn, err := getSavedFilters(s, doer) if err != nil { return nil, err } - if nnn != nil && nnn.Lists != nil { - lists = nnn.Lists + if nnn != nil && nnn.Projects != nil { + projects = nnn.Projects } default: err = s.Select("l.*"). @@ -158,48 +158,48 @@ func GetListsByNamespaceID(s *xorm.Session, nID int64, doer *user.User) (lists [ Where("l.is_archived = false"). Where("n.is_archived = false OR n.is_archived IS NULL"). Where("namespace_id = ?", nID). - Find(&lists) + Find(&projects) } if err != nil { return nil, err } - // get more list details - err = addListDetails(s, lists, doer) - return lists, err + // get more project details + err = addProjectDetails(s, projects, doer) + return projects, err } -// ReadAll gets all lists a user has access to -// @Summary Get all lists a user has access to -// @Description Returns all lists a user has access to. -// @tags list +// ReadAll gets all projects a user has access to +// @Summary Get all projects a user has access to +// @Description Returns all projects a user has access to. +// @tags project // @Accept json // @Produce json // @Param page query int false "The page number. Used for pagination. If not provided, the first page of results is returned." // @Param per_page query int false "The maximum number of items per page. Note this parameter is limited by the configured maximum of items per page." -// @Param s query string false "Search lists by title." -// @Param is_archived query bool false "If true, also returns all archived lists." +// @Param s query string false "Search projects by title." +// @Param is_archived query bool false "If true, also returns all archived projects." // @Security JWTKeyAuth -// @Success 200 {array} models.List "The lists" -// @Failure 403 {object} web.HTTPError "The user does not have access to the list" +// @Success 200 {array} models.Project "The projects" +// @Failure 403 {object} web.HTTPError "The user does not have access to the project" // @Failure 500 {object} models.Message "Internal error" -// @Router /lists [get] -func (l *List) ReadAll(s *xorm.Session, a web.Auth, search string, page int, perPage int) (result interface{}, resultCount int, totalItems int64, err error) { +// @Router /projects [get] +func (l *Project) ReadAll(s *xorm.Session, a web.Auth, search string, page int, perPage int) (result interface{}, resultCount int, totalItems int64, err error) { // Check if we're dealing with a share auth shareAuth, ok := a.(*LinkSharing) if ok { - list, err := GetListSimpleByID(s, shareAuth.ListID) + project, err := GetProjectSimpleByID(s, shareAuth.ProjectID) if err != nil { return nil, 0, 0, err } - lists := []*List{list} - err = addListDetails(s, lists, a) - return lists, 0, 0, err + projects := []*Project{project} + err = addProjectDetails(s, projects, a) + return projects, 0, 0, err } - lists, resultCount, totalItems, err := getRawListsForUser( + projects, resultCount, totalItems, err := getRawProjectsForUser( s, - &listOptions{ + &projectOptions{ search: search, user: &user.User{ID: a.GetID()}, page: page, @@ -210,33 +210,33 @@ func (l *List) ReadAll(s *xorm.Session, a web.Auth, search string, page int, per return nil, 0, 0, err } - // Add more list details - err = addListDetails(s, lists, a) - return lists, resultCount, totalItems, err + // Add more project details + err = addProjectDetails(s, projects, a) + return projects, resultCount, totalItems, err } -// ReadOne gets one list by its ID -// @Summary Gets one list -// @Description Returns a list by its ID. -// @tags list +// ReadOne gets one project by its ID +// @Summary Gets one project +// @Description Returns a project by its ID. +// @tags project // @Accept json // @Produce json // @Security JWTKeyAuth -// @Param id path int true "List ID" -// @Success 200 {object} models.List "The list" -// @Failure 403 {object} web.HTTPError "The user does not have access to the list" +// @Param id path int true "Project ID" +// @Success 200 {object} models.Project "The project" +// @Failure 403 {object} web.HTTPError "The user does not have access to the project" // @Failure 500 {object} models.Message "Internal error" -// @Router /lists/{id} [get] -func (l *List) ReadOne(s *xorm.Session, a web.Auth) (err error) { +// @Router /projects/{id} [get] +func (l *Project) ReadOne(s *xorm.Session, a web.Auth) (err error) { - if l.ID == FavoritesPseudoList.ID { - // Already "built" the list in CanRead + if l.ID == FavoritesPseudoProject.ID { + // Already "built" the project in CanRead return nil } // Check for saved filters - if getSavedFilterIDFromListID(l.ID) > 0 { - sf, err := getSavedFilterSimpleByID(s, getSavedFilterIDFromListID(l.ID)) + if getSavedFilterIDFromProjectID(l.ID) > 0 { + sf, err := getSavedFilterSimpleByID(s, getSavedFilterIDFromProjectID(l.ID)) if err != nil { return err } @@ -247,7 +247,7 @@ func (l *List) ReadOne(s *xorm.Session, a web.Auth) (err error) { l.OwnerID = sf.OwnerID } - // Get list owner + // Get project owner l.Owner, err = user.GetUserByID(s, l.OwnerID) if err != nil { return err @@ -256,7 +256,7 @@ func (l *List) ReadOne(s *xorm.Session, a web.Auth) (err error) { if !l.IsArchived { err = l.CheckIsArchived(s) if err != nil { - if !IsErrNamespaceIsArchived(err) && !IsErrListIsArchived(err) { + if !IsErrNamespaceIsArchived(err) && !IsErrProjectIsArchived(err) { return } l.IsArchived = true @@ -272,78 +272,78 @@ func (l *List) ReadOne(s *xorm.Session, a web.Auth) (err error) { } if err != nil && files.IsErrFileIsNotUnsplashFile(err) { - l.BackgroundInformation = &ListBackgroundType{Type: ListBackgroundUpload} + l.BackgroundInformation = &ProjectBackgroundType{Type: ProjectBackgroundUpload} } } - l.IsFavorite, err = isFavorite(s, l.ID, a, FavoriteKindList) + l.IsFavorite, err = isFavorite(s, l.ID, a, FavoriteKindProject) if err != nil { return } - l.Subscription, err = GetSubscription(s, SubscriptionEntityList, l.ID, a) + l.Subscription, err = GetSubscription(s, SubscriptionEntityProject, l.ID, a) return } -// GetListSimpleByID gets a list with only the basic items, aka no tasks or user objects. Returns an error if the list does not exist. -func GetListSimpleByID(s *xorm.Session, listID int64) (list *List, err error) { +// GetProjectSimpleByID gets a project with only the basic items, aka no tasks or user objects. Returns an error if the project does not exist. +func GetProjectSimpleByID(s *xorm.Session, projectID int64) (project *Project, err error) { - list = &List{} + project = &Project{} - if listID < 1 { - return nil, ErrListDoesNotExist{ID: listID} + if projectID < 1 { + return nil, ErrProjectDoesNotExist{ID: projectID} } exists, err := s. - Where("id = ?", listID). + Where("id = ?", projectID). OrderBy("position"). - Get(list) + Get(project) if err != nil { return } if !exists { - return nil, ErrListDoesNotExist{ID: listID} + return nil, ErrProjectDoesNotExist{ID: projectID} } return } -// GetListSimplByTaskID gets a list by a task id -func GetListSimplByTaskID(s *xorm.Session, taskID int64) (l *List, err error) { - // We need to re-init our list object, because otherwise xorm creates a "where for every item in that list object, +// GetProjectSimplByTaskID gets a project by a task id +func GetProjectSimplByTaskID(s *xorm.Session, taskID int64) (l *Project, err error) { + // We need to re-init our project object, because otherwise xorm creates a "where for every item in that project object, // leading to not finding anything if the id is good, but for example the title is different. - var list List + var project Project exists, err := s. - Select("lists.*"). - Table(List{}). - Join("INNER", "tasks", "lists.id = tasks.list_id"). + Select("projects.*"). + Table(Project{}). + Join("INNER", "tasks", "projects.id = tasks.project_id"). Where("tasks.id = ?", taskID). - Get(&list) + Get(&project) if err != nil { return } if !exists { - return &List{}, ErrListDoesNotExist{ID: l.ID} + return &Project{}, ErrProjectDoesNotExist{ID: l.ID} } - return &list, nil + return &project, nil } -// GetListsByIDs returns a map of lists from a slice with list ids -func GetListsByIDs(s *xorm.Session, listIDs []int64) (lists map[int64]*List, err error) { - lists = make(map[int64]*List, len(listIDs)) +// GetProjectsByIDs returns a map of projects from a slice with project ids +func GetProjectsByIDs(s *xorm.Session, projectIDs []int64) (projects map[int64]*Project, err error) { + projects = make(map[int64]*Project, len(projectIDs)) - if len(listIDs) == 0 { + if len(projectIDs) == 0 { return } - err = s.In("id", listIDs).Find(&lists) + err = s.In("id", projectIDs).Find(&projects) return } -type listOptions struct { +type projectOptions struct { search string user *user.User page int @@ -351,7 +351,7 @@ type listOptions struct { isArchived bool } -func getUserListsStatement(userID int64) *builder.Builder { +func getUserProjectsStatement(userID int64) *builder.Builder { dialect := config.DatabaseType.GetString() if dialect == "sqlite" { dialect = builder.SQLITE @@ -359,13 +359,13 @@ func getUserListsStatement(userID int64) *builder.Builder { return builder.Dialect(dialect). Select("l.*"). - From("lists", "l"). + From("projects", "l"). Join("INNER", "namespaces n", "l.namespace_id = n.id"). Join("LEFT", "team_namespaces tn", "tn.namespace_id = n.id"). Join("LEFT", "team_members tm", "tm.team_id = tn.team_id"). - Join("LEFT", "team_lists tl", "l.id = tl.list_id"). + Join("LEFT", "team_projects tl", "l.id = tl.project_id"). Join("LEFT", "team_members tm2", "tm2.team_id = tl.team_id"). - Join("LEFT", "users_lists ul", "ul.list_id = l.id"). + Join("LEFT", "users_projects ul", "ul.project_id = l.id"). Join("LEFT", "users_namespaces un", "un.namespace_id = l.namespace_id"). Where(builder.Or( builder.Eq{"tm.user_id": userID}, @@ -378,8 +378,8 @@ func getUserListsStatement(userID int64) *builder.Builder { GroupBy("l.id") } -// Gets the lists only, without any tasks or so -func getRawListsForUser(s *xorm.Session, opts *listOptions) (lists []*List, resultCount int, totalItems int64, err error) { +// Gets the projects only, without any tasks or so +func getRawProjectsForUser(s *xorm.Session, opts *projectOptions) (projects []*Project, resultCount int, totalItems int64, err error) { fullUser, err := user.GetUserByID(s, opts.user.ID) if err != nil { return nil, 0, 0, err @@ -403,7 +403,7 @@ func getRawListsForUser(s *xorm.Session, opts *listOptions) (lists []*List, resu for _, val := range vals { v, err := strconv.ParseInt(val, 10, 64) if err != nil { - log.Debugf("List search string part '%s' is not a number: %s", val, err) + log.Debugf("Project search string part '%s' is not a number: %s", val, err) continue } ids = append(ids, v) @@ -415,41 +415,41 @@ func getRawListsForUser(s *xorm.Session, opts *listOptions) (lists []*List, resu filterCond = builder.In("l.id", ids) } - // Gets all Lists where the user is either owner or in a team which has access to the list + // Gets all Projects where the user is either owner or in a team which has access to the project // Or in a team which has namespace read access - query := getUserListsStatement(fullUser.ID). + query := getUserProjectsStatement(fullUser.ID). Where(filterCond). Where(isArchivedCond) if limit > 0 { query = query.Limit(limit, start) } - err = s.SQL(query).Find(&lists) + err = s.SQL(query).Find(&projects) if err != nil { return nil, 0, 0, err } - query = getUserListsStatement(fullUser.ID). + query = getUserProjectsStatement(fullUser.ID). Where(filterCond). Where(isArchivedCond) totalItems, err = s. SQL(query.Select("count(*)")). - Count(&List{}) - return lists, len(lists), totalItems, err + Count(&Project{}) + return projects, len(projects), totalItems, err } -// addListDetails adds owner user objects and list tasks to all lists in the slice -func addListDetails(s *xorm.Session, lists []*List, a web.Auth) (err error) { - if len(lists) == 0 { +// addProjectDetails adds owner user objects and project tasks to all projects in the slice +func addProjectDetails(s *xorm.Session, projects []*Project, a web.Auth) (err error) { + if len(projects) == 0 { return } var ownerIDs []int64 - for _, l := range lists { + for _, l := range projects { ownerIDs = append(ownerIDs, l.OwnerID) } - // Get all list owners + // Get all project owners owners := map[int64]*user.User{} if len(ownerIDs) > 0 { err = s.In("id", ownerIDs).Find(&owners) @@ -459,38 +459,38 @@ func addListDetails(s *xorm.Session, lists []*List, a web.Auth) (err error) { } var fileIDs []int64 - var listIDs []int64 - for _, l := range lists { - listIDs = append(listIDs, l.ID) + var projectIDs []int64 + for _, l := range projects { + projectIDs = append(projectIDs, l.ID) if o, exists := owners[l.OwnerID]; exists { l.Owner = o } if l.BackgroundFileID != 0 { - l.BackgroundInformation = &ListBackgroundType{Type: ListBackgroundUpload} + l.BackgroundInformation = &ProjectBackgroundType{Type: ProjectBackgroundUpload} } fileIDs = append(fileIDs, l.BackgroundFileID) } - favs, err := getFavorites(s, listIDs, a, FavoriteKindList) + favs, err := getFavorites(s, projectIDs, a, FavoriteKindProject) if err != nil { return err } - subscriptions, err := GetSubscriptions(s, SubscriptionEntityList, listIDs, a) + subscriptions, err := GetSubscriptions(s, SubscriptionEntityProject, projectIDs, a) if err != nil { - log.Errorf("An error occurred while getting list subscriptions for a namespace item: %s", err.Error()) + log.Errorf("An error occurred while getting project subscriptions for a namespace item: %s", err.Error()) subscriptions = make(map[int64]*Subscription) } - for _, list := range lists { + for _, project := range projects { // Don't override the favorite state if it was already set from before (favorite saved filters do this) - if list.IsFavorite { + if project.IsFavorite { continue } - list.IsFavorite = favs[list.ID] + project.IsFavorite = favs[project.ID] - if subscription, exists := subscriptions[list.ID]; exists { - list.Subscription = subscription + if subscription, exists := subscriptions[project.ID]; exists { + project.Subscription = subscription } } @@ -509,8 +509,8 @@ func addListDetails(s *xorm.Session, lists []*List, a web.Auth) (err error) { unsplashPhotos[u.FileID] = u } - // Build it all into the lists slice - for _, l := range lists { + // Build it all into the projects slice + for _, l := range projects { // Only override the file info if we have info for unsplash backgrounds if _, exists := unsplashPhotos[l.BackgroundFileID]; exists { l.BackgroundInformation = unsplashPhotos[l.BackgroundFileID] @@ -520,31 +520,31 @@ func addListDetails(s *xorm.Session, lists []*List, a web.Auth) (err error) { return } -// NamespaceList is a meta type to be able to join a list with its namespace -type NamespaceList struct { - List List `xorm:"extends"` +// NamespaceProject is a meta type to be able to join a project with its namespace +type NamespaceProject struct { + Project Project `xorm:"extends"` Namespace Namespace `xorm:"extends"` } -// CheckIsArchived returns an ErrListIsArchived or ErrNamespaceIsArchived if the list or its namespace is archived. -func (l *List) CheckIsArchived(s *xorm.Session) (err error) { - // When creating a new list, we check if the namespace is archived +// CheckIsArchived returns an ErrProjectIsArchived or ErrNamespaceIsArchived if the project or its namespace is archived. +func (l *Project) CheckIsArchived(s *xorm.Session) (err error) { + // When creating a new project, we check if the namespace is archived if l.ID == 0 { n := &Namespace{ID: l.NamespaceID} return n.CheckIsArchived(s) } - nl := &NamespaceList{} + nl := &NamespaceProject{} exists, err := s. - Table("lists"). - Join("LEFT", "namespaces", "lists.namespace_id = namespaces.id"). - Where("lists.id = ? AND (lists.is_archived = true OR namespaces.is_archived = true)", l.ID). + Table("projects"). + Join("LEFT", "namespaces", "projects.namespace_id = namespaces.id"). + Where("projects.id = ? AND (projects.is_archived = true OR namespaces.is_archived = true)", l.ID). Get(nl) if err != nil { return } - if exists && nl.List.ID != 0 && nl.List.IsArchived { - return ErrListIsArchived{ListID: l.ID} + if exists && nl.Project.ID != 0 && nl.Project.IsArchived { + return ErrProjectIsArchived{ProjectID: l.ID} } if exists && nl.Namespace.ID != 0 && nl.Namespace.IsArchived { return ErrNamespaceIsArchived{NamespaceID: nl.Namespace.ID} @@ -552,38 +552,38 @@ func (l *List) CheckIsArchived(s *xorm.Session) (err error) { return nil } -func checkListBeforeUpdateOrDelete(s *xorm.Session, list *List) error { - if list.NamespaceID < 0 { - return &ErrListCannotBelongToAPseudoNamespace{ListID: list.ID, NamespaceID: list.NamespaceID} +func checkProjectBeforeUpdateOrDelete(s *xorm.Session, project *Project) error { + if project.NamespaceID < 0 { + return &ErrProjectCannotBelongToAPseudoNamespace{ProjectID: project.ID, NamespaceID: project.NamespaceID} } // Check if the namespace exists - if list.NamespaceID > 0 { - _, err := GetNamespaceByID(s, list.NamespaceID) + if project.NamespaceID > 0 { + _, err := GetNamespaceByID(s, project.NamespaceID) if err != nil { return err } } // Check if the identifier is unique and not empty - if list.Identifier != "" { + if project.Identifier != "" { exists, err := s. - Where("identifier = ?", list.Identifier). - And("id != ?", list.ID). - Exist(&List{}) + Where("identifier = ?", project.Identifier). + And("id != ?", project.ID). + Exist(&Project{}) if err != nil { return err } if exists { - return ErrListIdentifierIsNotUnique{Identifier: list.Identifier} + return ErrProjectIdentifierIsNotUnique{Identifier: project.Identifier} } } return nil } -func CreateList(s *xorm.Session, list *List, auth web.Auth) (err error) { - err = list.CheckIsArchived(s) +func CreateProject(s *xorm.Session, project *Project, auth web.Auth) (err error) { + err = project.CheckIsArchived(s) if err != nil { return err } @@ -593,61 +593,61 @@ func CreateList(s *xorm.Session, list *List, auth web.Auth) (err error) { return err } - list.OwnerID = doer.ID - list.Owner = doer - list.ID = 0 // Otherwise only the first time a new list would be created + project.OwnerID = doer.ID + project.Owner = doer + project.ID = 0 // Otherwise only the first time a new project would be created - err = checkListBeforeUpdateOrDelete(s, list) + err = checkProjectBeforeUpdateOrDelete(s, project) if err != nil { return } - _, err = s.Insert(list) + _, err = s.Insert(project) if err != nil { return } - list.Position = calculateDefaultPosition(list.ID, list.Position) - _, err = s.Where("id = ?", list.ID).Update(list) + project.Position = calculateDefaultPosition(project.ID, project.Position) + _, err = s.Where("id = ?", project.ID).Update(project) if err != nil { return } - if list.IsFavorite { - if err := addToFavorites(s, list.ID, auth, FavoriteKindList); err != nil { + if project.IsFavorite { + if err := addToFavorites(s, project.ID, auth, FavoriteKindProject); err != nil { return err } } - // Create a new first bucket for this list + // Create a new first bucket for this project b := &Bucket{ - ListID: list.ID, - Title: "Backlog", + ProjectID: project.ID, + Title: "Backlog", } err = b.Create(s, auth) if err != nil { return } - return events.Dispatch(&ListCreatedEvent{ - List: list, - Doer: doer, + return events.Dispatch(&ProjectCreatedEvent{ + Project: project, + Doer: doer, }) } -func UpdateList(s *xorm.Session, list *List, auth web.Auth, updateListBackground bool) (err error) { - err = checkListBeforeUpdateOrDelete(s, list) +func UpdateProject(s *xorm.Session, project *Project, auth web.Auth, updateProjectBackground bool) (err error) { + err = checkProjectBeforeUpdateOrDelete(s, project) if err != nil { return } - if list.NamespaceID == 0 { - return &ErrListMustBelongToANamespace{ - ListID: list.ID, - NamespaceID: list.NamespaceID, + if project.NamespaceID == 0 { + return &ErrProjectMustBelongToANamespace{ + ProjectID: project.ID, + NamespaceID: project.NamespaceID, } } - // We need to specify the cols we want to update here to be able to un-archive lists + // We need to specify the cols we want to update here to be able to un-archive projects colsToUpdate := []string{ "title", "is_archived", @@ -656,72 +656,72 @@ func UpdateList(s *xorm.Session, list *List, auth web.Auth, updateListBackground "namespace_id", "position", } - if list.Description != "" { + if project.Description != "" { colsToUpdate = append(colsToUpdate, "description") } - if updateListBackground { + if updateProjectBackground { colsToUpdate = append(colsToUpdate, "background_file_id", "background_blur_hash") } - wasFavorite, err := isFavorite(s, list.ID, auth, FavoriteKindList) + wasFavorite, err := isFavorite(s, project.ID, auth, FavoriteKindProject) if err != nil { return err } - if list.IsFavorite && !wasFavorite { - if err := addToFavorites(s, list.ID, auth, FavoriteKindList); err != nil { + if project.IsFavorite && !wasFavorite { + if err := addToFavorites(s, project.ID, auth, FavoriteKindProject); err != nil { return err } } - if !list.IsFavorite && wasFavorite { - if err := removeFromFavorite(s, list.ID, auth, FavoriteKindList); err != nil { + if !project.IsFavorite && wasFavorite { + if err := removeFromFavorite(s, project.ID, auth, FavoriteKindProject); err != nil { return err } } _, err = s. - ID(list.ID). + ID(project.ID). Cols(colsToUpdate...). - Update(list) + Update(project) if err != nil { return err } - err = events.Dispatch(&ListUpdatedEvent{ - List: list, - Doer: auth, + err = events.Dispatch(&ProjectUpdatedEvent{ + Project: project, + Doer: auth, }) if err != nil { return err } - l, err := GetListSimpleByID(s, list.ID) + l, err := GetProjectSimpleByID(s, project.ID) if err != nil { return err } - *list = *l - err = list.ReadOne(s, auth) + *project = *l + err = project.ReadOne(s, auth) return } // Update implements the update method of CRUDable -// @Summary Updates a list -// @Description Updates a list. This does not include adding a task (see below). -// @tags list +// @Summary Updates a project +// @Description Updates a project. This does not include adding a task (see below). +// @tags project // @Accept json // @Produce json // @Security JWTKeyAuth -// @Param id path int true "List ID" -// @Param list body models.List true "The list with updated values you want to update." -// @Success 200 {object} models.List "The updated list." -// @Failure 400 {object} web.HTTPError "Invalid list object provided." -// @Failure 403 {object} web.HTTPError "The user does not have access to the list" +// @Param id path int true "Project ID" +// @Param project body models.Project true "The project with updated values you want to update." +// @Success 200 {object} models.Project "The updated project." +// @Failure 400 {object} web.HTTPError "Invalid project object provided." +// @Failure 403 {object} web.HTTPError "The user does not have access to the project" // @Failure 500 {object} models.Message "Internal error" -// @Router /lists/{id} [post] -func (l *List) Update(s *xorm.Session, a web.Auth) (err error) { - fid := getSavedFilterIDFromListID(l.ID) +// @Router /projects/{id} [post] +func (l *Project) Update(s *xorm.Session, a web.Auth) (err error) { + fid := getSavedFilterIDFromProjectID(l.ID) if fid > 0 { f, err := getSavedFilterSimpleByID(s, fid) if err != nil { @@ -736,44 +736,44 @@ func (l *List) Update(s *xorm.Session, a web.Auth) (err error) { return err } - *l = *f.toList() + *l = *f.toProject() return nil } - return UpdateList(s, l, a, false) + return UpdateProject(s, l, a, false) } -func updateListLastUpdated(s *xorm.Session, list *List) error { - _, err := s.ID(list.ID).Cols("updated").Update(list) +func updateProjectLastUpdated(s *xorm.Session, project *Project) error { + _, err := s.ID(project.ID).Cols("updated").Update(project) return err } -func updateListByTaskID(s *xorm.Session, taskID int64) (err error) { - // need to get the task to update the list last updated timestamp +func updateProjectByTaskID(s *xorm.Session, taskID int64) (err error) { + // need to get the task to update the project last updated timestamp task, err := GetTaskByIDSimple(s, taskID) if err != nil { return err } - return updateListLastUpdated(s, &List{ID: task.ListID}) + return updateProjectLastUpdated(s, &Project{ID: task.ProjectID}) } // Create implements the create method of CRUDable -// @Summary Creates a new list -// @Description Creates a new list in a given namespace. The user needs write-access to the namespace. -// @tags list +// @Summary Creates a new project +// @Description Creates a new project in a given namespace. The user needs write-access to the namespace. +// @tags project // @Accept json // @Produce json // @Security JWTKeyAuth // @Param namespaceID path int true "Namespace ID" -// @Param list body models.List true "The list you want to create." -// @Success 201 {object} models.List "The created list." -// @Failure 400 {object} web.HTTPError "Invalid list object provided." -// @Failure 403 {object} web.HTTPError "The user does not have access to the list" +// @Param project body models.Project true "The project you want to create." +// @Success 201 {object} models.Project "The created project." +// @Failure 400 {object} web.HTTPError "Invalid project object provided." +// @Failure 403 {object} web.HTTPError "The user does not have access to the project" // @Failure 500 {object} models.Message "Internal error" -// @Router /namespaces/{namespaceID}/lists [put] -func (l *List) Create(s *xorm.Session, a web.Auth) (err error) { - err = CreateList(s, l, a) +// @Router /namespaces/{namespaceID}/projects [put] +func (l *Project) Create(s *xorm.Session, a web.Auth) (err error) { + err = CreateProject(s, l, a) if err != nil { return } @@ -782,33 +782,33 @@ func (l *List) Create(s *xorm.Session, a web.Auth) (err error) { } // Delete implements the delete method of CRUDable -// @Summary Deletes a list -// @Description Delets a list -// @tags list +// @Summary Deletes a project +// @Description Delets a project +// @tags project // @Produce json // @Security JWTKeyAuth -// @Param id path int true "List ID" -// @Success 200 {object} models.Message "The list was successfully deleted." -// @Failure 400 {object} web.HTTPError "Invalid list object provided." -// @Failure 403 {object} web.HTTPError "The user does not have access to the list" +// @Param id path int true "Project ID" +// @Success 200 {object} models.Message "The project was successfully deleted." +// @Failure 400 {object} web.HTTPError "Invalid project object provided." +// @Failure 403 {object} web.HTTPError "The user does not have access to the project" // @Failure 500 {object} models.Message "Internal error" -// @Router /lists/{id} [delete] -func (l *List) Delete(s *xorm.Session, a web.Auth) (err error) { +// @Router /projects/{id} [delete] +func (l *Project) Delete(s *xorm.Session, a web.Auth) (err error) { - fullList, err := GetListSimpleByID(s, l.ID) + fullList, err := GetProjectSimpleByID(s, l.ID) if err != nil { return } - // Delete the list - _, err = s.ID(l.ID).Delete(&List{}) + // Delete the project + _, err = s.ID(l.ID).Delete(&Project{}) if err != nil { return } - // Delete all tasks on that list + // Delete all tasks on that project // Using the loop to make sure all related entities to all tasks are properly deleted as well. - tasks, _, _, err := getRawTasksForLists(s, []*List{l}, a, &taskOptions{}) + tasks, _, _, err := getRawTasksForProjects(s, []*Project{l}, a, &taskOptions{}) if err != nil { return } @@ -825,15 +825,15 @@ func (l *List) Delete(s *xorm.Session, a web.Auth) (err error) { return } - return events.Dispatch(&ListDeletedEvent{ - List: l, - Doer: a, + return events.Dispatch(&ProjectDeletedEvent{ + Project: l, + Doer: a, }) } // DeleteBackgroundFileIfExists deletes the list's background file from the db and the filesystem, // if one exists -func (l *List) DeleteBackgroundFileIfExists() (err error) { +func (l *Project) DeleteBackgroundFileIfExists() (err error) { if l.BackgroundFileID == 0 { return } @@ -842,10 +842,10 @@ func (l *List) DeleteBackgroundFileIfExists() (err error) { return file.Delete() } -// SetListBackground sets a background file as list background in the db -func SetListBackground(s *xorm.Session, listID int64, background *files.File, blurHash string) (err error) { - l := &List{ - ID: listID, +// SetProjectBackground sets a background file as project background in the db +func SetProjectBackground(s *xorm.Session, projectID int64, background *files.File, blurHash string) (err error) { + l := &Project{ + ID: projectID, BackgroundFileID: background.ID, BackgroundBlurHash: blurHash, } diff --git a/pkg/models/list_duplicate.go b/pkg/models/list_duplicate.go index d5c75325a..3307935af 100644 --- a/pkg/models/list_duplicate.go +++ b/pkg/models/list_duplicate.go @@ -24,89 +24,89 @@ import ( "xorm.io/xorm" ) -// ListDuplicate holds everything needed to duplicate a list -type ListDuplicate struct { - // The list id of the list to duplicate - ListID int64 `json:"-" param:"listid"` +// ProjectDuplicate holds everything needed to duplicate a project +type ProjectDuplicate struct { + // The project id of the project to duplicate + ProjectID int64 `json:"-" param:"projectid"` // The target namespace ID NamespaceID int64 `json:"namespace_id,omitempty"` - // The copied list - List *List `json:",omitempty"` + // The copied project + Project *Project `json:",omitempty"` web.Rights `json:"-"` web.CRUDable `json:"-"` } -// CanCreate checks if a user has the right to duplicate a list -func (ld *ListDuplicate) CanCreate(s *xorm.Session, a web.Auth) (canCreate bool, err error) { - // List Exists + user has read access to list - ld.List = &List{ID: ld.ListID} - canRead, _, err := ld.List.CanRead(s, a) +// CanCreate checks if a user has the right to duplicate a project +func (ld *ProjectDuplicate) CanCreate(s *xorm.Session, a web.Auth) (canCreate bool, err error) { + // Project Exists + user has read access to project + ld.Project = &Project{ID: ld.ProjectID} + canRead, _, err := ld.Project.CanRead(s, a) if err != nil || !canRead { return canRead, err } - // Namespace exists + user has write access to is (-> can create new lists) - ld.List.NamespaceID = ld.NamespaceID - return ld.List.CanCreate(s, a) + // Namespace exists + user has write access to is (-> can create new projects) + ld.Project.NamespaceID = ld.NamespaceID + return ld.Project.CanCreate(s, a) } -// Create duplicates a list -// @Summary Duplicate an existing list -// @Description Copies the list, tasks, files, kanban data, assignees, comments, attachments, lables, relations, backgrounds, user/team rights and link shares from one list to a new namespace. The user needs read access in the list and write access in the namespace of the new list. -// @tags list +// Create duplicates a project +// @Summary Duplicate an existing project +// @Description Copies the project, tasks, files, kanban data, assignees, comments, attachments, lables, relations, backgrounds, user/team rights and link shares from one project to a new namespace. The user needs read access in the project and write access in the namespace of the new project. +// @tags project // @Accept json // @Produce json // @Security JWTKeyAuth -// @Param listID path int true "The list ID to duplicate" -// @Param list body models.ListDuplicate true "The target namespace which should hold the copied list." -// @Success 201 {object} models.ListDuplicate "The created list." -// @Failure 400 {object} web.HTTPError "Invalid list duplicate object provided." -// @Failure 403 {object} web.HTTPError "The user does not have access to the list or namespace" +// @Param projectID path int true "The project ID to duplicate" +// @Param project body models.ProjectDuplicate true "The target namespace which should hold the copied project." +// @Success 201 {object} models.ProjectDuplicate "The created project." +// @Failure 400 {object} web.HTTPError "Invalid project duplicate object provided." +// @Failure 403 {object} web.HTTPError "The user does not have access to the project or namespace" // @Failure 500 {object} models.Message "Internal error" -// @Router /lists/{listID}/duplicate [put] +// @Router /projects/{projectID}/duplicate [put] // //nolint:gocyclo -func (ld *ListDuplicate) Create(s *xorm.Session, doer web.Auth) (err error) { +func (ld *ProjectDuplicate) Create(s *xorm.Session, doer web.Auth) (err error) { - log.Debugf("Duplicating list %d", ld.ListID) + log.Debugf("Duplicating project %d", ld.ProjectID) - ld.List.ID = 0 - ld.List.Identifier = "" // Reset the identifier to trigger regenerating a new one + ld.Project.ID = 0 + ld.Project.Identifier = "" // Reset the identifier to trigger regenerating a new one // Set the owner to the current user - ld.List.OwnerID = doer.GetID() - if err := CreateList(s, ld.List, doer); err != nil { - // If there is no available unique list identifier, just reset it. - if IsErrListIdentifierIsNotUnique(err) { - ld.List.Identifier = "" + ld.Project.OwnerID = doer.GetID() + if err := CreateProject(s, ld.Project, doer); err != nil { + // If there is no available unique project identifier, just reset it. + if IsErrProjectIdentifierIsNotUnique(err) { + ld.Project.Identifier = "" } else { return err } } - log.Debugf("Duplicated list %d into new list %d", ld.ListID, ld.List.ID) + log.Debugf("Duplicated project %d into new project %d", ld.ProjectID, ld.Project.ID) // Duplicate kanban buckets // Old bucket ID as key, new id as value // Used to map the newly created tasks to their new buckets bucketMap := make(map[int64]int64) buckets := []*Bucket{} - err = s.Where("list_id = ?", ld.ListID).Find(&buckets) + err = s.Where("project_id = ?", ld.ProjectID).Find(&buckets) if err != nil { return } for _, b := range buckets { oldID := b.ID b.ID = 0 - b.ListID = ld.List.ID + b.ProjectID = ld.Project.ID if err := b.Create(s, doer); err != nil { return err } bucketMap[oldID] = b.ID } - log.Debugf("Duplicated all buckets from list %d into %d", ld.ListID, ld.List.ID) + log.Debugf("Duplicated all buckets from project %d into %d", ld.ProjectID, ld.Project.ID) err = duplicateTasks(s, doer, ld, bucketMap) if err != nil { @@ -114,11 +114,11 @@ func (ld *ListDuplicate) Create(s *xorm.Session, doer web.Auth) (err error) { } // Background files + unsplash info - if ld.List.BackgroundFileID != 0 { + if ld.Project.BackgroundFileID != 0 { - log.Debugf("Duplicating background %d from list %d into %d", ld.List.BackgroundFileID, ld.ListID, ld.List.ID) + log.Debugf("Duplicating background %d from project %d into %d", ld.Project.BackgroundFileID, ld.ProjectID, ld.Project.ID) - f := &files.File{ID: ld.List.BackgroundFileID} + f := &files.File{ID: ld.Project.BackgroundFileID} if err := f.LoadFileMetaByID(); err != nil { return err } @@ -133,7 +133,7 @@ func (ld *ListDuplicate) Create(s *xorm.Session, doer web.Auth) (err error) { } // Get unsplash info if applicable - up, err := GetUnsplashPhotoByFileID(s, ld.List.BackgroundFileID) + up, err := GetUnsplashPhotoByFileID(s, ld.Project.BackgroundFileID) if err != nil && files.IsErrFileIsNotUnsplashFile(err) { return err } @@ -145,38 +145,38 @@ func (ld *ListDuplicate) Create(s *xorm.Session, doer web.Auth) (err error) { } } - if err := SetListBackground(s, ld.List.ID, file, ld.List.BackgroundBlurHash); err != nil { + if err := SetProjectBackground(s, ld.Project.ID, file, ld.Project.BackgroundBlurHash); err != nil { return err } - log.Debugf("Duplicated list background from list %d into %d", ld.ListID, ld.List.ID) + log.Debugf("Duplicated project background from project %d into %d", ld.ProjectID, ld.Project.ID) } // Rights / Shares - // To keep it simple(r) we will only copy rights which are directly used with the list, no namespace changes. - users := []*ListUser{} - err = s.Where("list_id = ?", ld.ListID).Find(&users) + // To keep it simple(r) we will only copy rights which are directly used with the project, no namespace changes. + users := []*ProjectUser{} + err = s.Where("project_id = ?", ld.ProjectID).Find(&users) if err != nil { return } for _, u := range users { u.ID = 0 - u.ListID = ld.List.ID + u.ProjectID = ld.Project.ID if _, err := s.Insert(u); err != nil { return err } } - log.Debugf("Duplicated user shares from list %d into %d", ld.ListID, ld.List.ID) + log.Debugf("Duplicated user shares from project %d into %d", ld.ProjectID, ld.Project.ID) - teams := []*TeamList{} - err = s.Where("list_id = ?", ld.ListID).Find(&teams) + teams := []*TeamProject{} + err = s.Where("project_id = ?", ld.ProjectID).Find(&teams) if err != nil { return } for _, t := range teams { t.ID = 0 - t.ListID = ld.List.ID + t.ProjectID = ld.Project.ID if _, err := s.Insert(t); err != nil { return err } @@ -184,27 +184,27 @@ func (ld *ListDuplicate) Create(s *xorm.Session, doer web.Auth) (err error) { // Generate new link shares if any are available linkShares := []*LinkSharing{} - err = s.Where("list_id = ?", ld.ListID).Find(&linkShares) + err = s.Where("project_id = ?", ld.ProjectID).Find(&linkShares) if err != nil { return } for _, share := range linkShares { share.ID = 0 - share.ListID = ld.List.ID + share.ProjectID = ld.Project.ID share.Hash = utils.MakeRandomString(40) if _, err := s.Insert(share); err != nil { return err } } - log.Debugf("Duplicated all link shares from list %d into %d", ld.ListID, ld.List.ID) + log.Debugf("Duplicated all link shares from project %d into %d", ld.ProjectID, ld.Project.ID) return } -func duplicateTasks(s *xorm.Session, doer web.Auth, ld *ListDuplicate, bucketMap map[int64]int64) (err error) { +func duplicateTasks(s *xorm.Session, doer web.Auth, ld *ProjectDuplicate, bucketMap map[int64]int64) (err error) { // Get all tasks + all task details - tasks, _, _, err := getTasksForLists(s, []*List{{ID: ld.ListID}}, doer, &taskOptions{}) + tasks, _, _, err := getTasksForProjects(s, []*Project{{ID: ld.ProjectID}}, doer, &taskOptions{}) if err != nil { return err } @@ -221,7 +221,7 @@ func duplicateTasks(s *xorm.Session, doer web.Auth, ld *ListDuplicate, bucketMap for _, t := range tasks { oldID := t.ID t.ID = 0 - t.ListID = ld.List.ID + t.ProjectID = ld.Project.ID t.BucketID = bucketMap[t.BucketID] t.UID = "" err := createTask(s, t, doer, false) @@ -232,11 +232,11 @@ func duplicateTasks(s *xorm.Session, doer web.Auth, ld *ListDuplicate, bucketMap oldTaskIDs = append(oldTaskIDs, oldID) } - log.Debugf("Duplicated all tasks from list %d into %d", ld.ListID, ld.List.ID) + log.Debugf("Duplicated all tasks from project %d into %d", ld.ProjectID, ld.Project.ID) // Save all attachments - // We also duplicate all underlying files since they could be modified in one list which would result in - // file changes in the other list which is not something we want. + // We also duplicate all underlying files since they could be modified in one project which would result in + // file changes in the other project which is not something we want. attachments, err := getTaskAttachmentsByTaskIDs(s, oldTaskIDs) if err != nil { return err @@ -254,7 +254,7 @@ func duplicateTasks(s *xorm.Session, doer web.Auth, ld *ListDuplicate, bucketMap attachment.File = &files.File{ID: attachment.FileID} if err := attachment.File.LoadFileMetaByID(); err != nil { if files.IsErrFileDoesNotExist(err) { - log.Debugf("Not duplicating attachment %d (file %d) because it does not exist from list %d into %d", oldAttachmentID, attachment.FileID, ld.ListID, ld.List.ID) + log.Debugf("Not duplicating attachment %d (file %d) because it does not exist from project %d into %d", oldAttachmentID, attachment.FileID, ld.ProjectID, ld.Project.ID) continue } return err @@ -272,10 +272,10 @@ func duplicateTasks(s *xorm.Session, doer web.Auth, ld *ListDuplicate, bucketMap _ = attachment.File.File.Close() } - log.Debugf("Duplicated attachment %d into %d from list %d into %d", oldAttachmentID, attachment.ID, ld.ListID, ld.List.ID) + log.Debugf("Duplicated attachment %d into %d from project %d into %d", oldAttachmentID, attachment.ID, ld.ProjectID, ld.Project.ID) } - log.Debugf("Duplicated all attachments from list %d into %d", ld.ListID, ld.List.ID) + log.Debugf("Duplicated all attachments from project %d into %d", ld.ProjectID, ld.Project.ID) // Copy label tasks (not the labels) labelTasks := []*LabelTask{} @@ -292,7 +292,7 @@ func duplicateTasks(s *xorm.Session, doer web.Auth, ld *ListDuplicate, bucketMap } } - log.Debugf("Duplicated all labels from list %d into %d", ld.ListID, ld.List.ID) + log.Debugf("Duplicated all labels from project %d into %d", ld.ProjectID, ld.Project.ID) // Assignees // Only copy those assignees who have access to the task @@ -303,18 +303,18 @@ func duplicateTasks(s *xorm.Session, doer web.Auth, ld *ListDuplicate, bucketMap } for _, a := range assignees { t := &Task{ - ID: taskMap[a.TaskID], - ListID: ld.List.ID, + ID: taskMap[a.TaskID], + ProjectID: ld.Project.ID, } - if err := t.addNewAssigneeByID(s, a.UserID, ld.List, doer); err != nil { - if IsErrUserDoesNotHaveAccessToList(err) { + if err := t.addNewAssigneeByID(s, a.UserID, ld.Project, doer); err != nil { + if IsErrUserDoesNotHaveAccessToProject(err) { continue } return err } } - log.Debugf("Duplicated all assignees from list %d into %d", ld.ListID, ld.List.ID) + log.Debugf("Duplicated all assignees from project %d into %d", ld.ProjectID, ld.Project.ID) // Comments comments := []*TaskComment{} @@ -330,10 +330,10 @@ func duplicateTasks(s *xorm.Session, doer web.Auth, ld *ListDuplicate, bucketMap } } - log.Debugf("Duplicated all comments from list %d into %d", ld.ListID, ld.List.ID) + log.Debugf("Duplicated all comments from project %d into %d", ld.ProjectID, ld.Project.ID) - // Relations in that list - // Low-Effort: Only copy those relations which are between tasks in the same list + // Relations in that project + // Low-Effort: Only copy those relations which are between tasks in the same project // because we can do that without a lot of hassle relations := []*TaskRelation{} err = s.In("task_id", oldTaskIDs).Find(&relations) @@ -353,7 +353,7 @@ func duplicateTasks(s *xorm.Session, doer web.Auth, ld *ListDuplicate, bucketMap } } - log.Debugf("Duplicated all task relations from list %d into %d", ld.ListID, ld.List.ID) + log.Debugf("Duplicated all task relations from project %d into %d", ld.ProjectID, ld.Project.ID) return nil } diff --git a/pkg/models/list_duplicate_test.go b/pkg/models/list_duplicate_test.go index 14fbb90dc..70ff0f95e 100644 --- a/pkg/models/list_duplicate_test.go +++ b/pkg/models/list_duplicate_test.go @@ -25,7 +25,7 @@ import ( "github.com/stretchr/testify/assert" ) -func TestListDuplicate(t *testing.T) { +func TestProjectDuplicate(t *testing.T) { db.LoadAndAssertFixtures(t) files.InitTestFileFixtures(t) @@ -36,8 +36,8 @@ func TestListDuplicate(t *testing.T) { ID: 1, } - l := &ListDuplicate{ - ListID: 1, + l := &ProjectDuplicate{ + ProjectID: 1, NamespaceID: 1, } can, err := l.CanCreate(s, u) diff --git a/pkg/models/list_rights.go b/pkg/models/list_rights.go index 4f18a92df..da8285fb2 100644 --- a/pkg/models/list_rights.go +++ b/pkg/models/list_rights.go @@ -23,35 +23,35 @@ import ( "xorm.io/xorm" ) -// CanWrite return whether the user can write on that list or not -func (l *List) CanWrite(s *xorm.Session, a web.Auth) (bool, error) { +// CanWrite return whether the user can write on that project or not +func (l *Project) CanWrite(s *xorm.Session, a web.Auth) (bool, error) { - // The favorite list can't be edited - if l.ID == FavoritesPseudoList.ID { + // The favorite project can't be edited + if l.ID == FavoritesPseudoProject.ID { return false, nil } - // Get the list and check the right - originalList, err := GetListSimpleByID(s, l.ID) + // Get the project and check the right + originalProject, err := GetProjectSimpleByID(s, l.ID) if err != nil { return false, err } // We put the result of the is archived check in a separate variable to be able to return it later without // needing to recheck it again - errIsArchived := originalList.CheckIsArchived(s) + errIsArchived := originalProject.CheckIsArchived(s) var canWrite bool // Check if we're dealing with a share auth shareAuth, ok := a.(*LinkSharing) if ok { - return originalList.ID == shareAuth.ListID && + return originalProject.ID == shareAuth.ProjectID && (shareAuth.Right == RightWrite || shareAuth.Right == RightAdmin), errIsArchived } - // Check if the user is either owner or can write to the list - if originalList.isOwner(&user.User{ID: a.GetID()}) { + // Check if the user is either owner or can write to the project + if originalProject.isOwner(&user.User{ID: a.GetID()}) { canWrite = true } @@ -59,47 +59,47 @@ func (l *List) CanWrite(s *xorm.Session, a web.Auth) (bool, error) { return canWrite, errIsArchived } - canWrite, _, err = originalList.checkRight(s, a, RightWrite, RightAdmin) + canWrite, _, err = originalProject.checkRight(s, a, RightWrite, RightAdmin) if err != nil { return false, err } return canWrite, errIsArchived } -// CanRead checks if a user has read access to a list -func (l *List) CanRead(s *xorm.Session, a web.Auth) (bool, int, error) { +// CanRead checks if a user has read access to a project +func (l *Project) CanRead(s *xorm.Session, a web.Auth) (bool, int, error) { - // The favorite list needs a special treatment - if l.ID == FavoritesPseudoList.ID { + // The favorite project needs a special treatment + if l.ID == FavoritesPseudoProject.ID { owner, err := user.GetFromAuth(a) if err != nil { return false, 0, err } - *l = FavoritesPseudoList + *l = FavoritesPseudoProject l.Owner = owner return true, int(RightRead), nil } - // Saved Filter Lists need a special case - if getSavedFilterIDFromListID(l.ID) > 0 { - sf := &SavedFilter{ID: getSavedFilterIDFromListID(l.ID)} + // Saved Filter Projects need a special case + if getSavedFilterIDFromProjectID(l.ID) > 0 { + sf := &SavedFilter{ID: getSavedFilterIDFromProjectID(l.ID)} return sf.CanRead(s, a) } // Check if the user is either owner or can read var err error - originalList, err := GetListSimpleByID(s, l.ID) + originalProject, err := GetProjectSimpleByID(s, l.ID) if err != nil { return false, 0, err } - *l = *originalList + *l = *originalProject // Check if we're dealing with a share auth shareAuth, ok := a.(*LinkSharing) if ok { - return l.ID == shareAuth.ListID && + return l.ID == shareAuth.ProjectID && (shareAuth.Right == RightRead || shareAuth.Right == RightWrite || shareAuth.Right == RightAdmin), int(shareAuth.Right), nil } @@ -109,20 +109,20 @@ func (l *List) CanRead(s *xorm.Session, a web.Auth) (bool, int, error) { return l.checkRight(s, a, RightRead, RightWrite, RightAdmin) } -// CanUpdate checks if the user can update a list -func (l *List) CanUpdate(s *xorm.Session, a web.Auth) (canUpdate bool, err error) { - // The favorite list can't be edited - if l.ID == FavoritesPseudoList.ID { +// CanUpdate checks if the user can update a project +func (l *Project) CanUpdate(s *xorm.Session, a web.Auth) (canUpdate bool, err error) { + // The favorite project can't be edited + if l.ID == FavoritesPseudoProject.ID { return false, nil } - // Get the list - ol, err := GetListSimpleByID(s, l.ID) + // Get the project + ol, err := GetProjectSimpleByID(s, l.ID) if err != nil { return false, err } - // Check if we're moving the list into a different namespace. + // Check if we're moving the project into a different namespace. // If that is the case, we need to verify permissions to do so. if l.NamespaceID != 0 && l.NamespaceID != ol.NamespaceID { newNamespace := &Namespace{ID: l.NamespaceID} @@ -135,7 +135,7 @@ func (l *List) CanUpdate(s *xorm.Session, a web.Auth) (canUpdate bool, err error } } - fid := getSavedFilterIDFromListID(l.ID) + fid := getSavedFilterIDFromProjectID(l.ID) if fid > 0 { sf, err := getSavedFilterSimpleByID(s, fid) if err != nil { @@ -146,33 +146,33 @@ func (l *List) CanUpdate(s *xorm.Session, a web.Auth) (canUpdate bool, err error } canUpdate, err = l.CanWrite(s, a) - // If the list is archived and the user tries to un-archive it, let the request through - if IsErrListIsArchived(err) && !l.IsArchived { + // If the project is archived and the user tries to un-archive it, let the request through + if IsErrProjectIsArchived(err) && !l.IsArchived { err = nil } return canUpdate, err } -// CanDelete checks if the user can delete a list -func (l *List) CanDelete(s *xorm.Session, a web.Auth) (bool, error) { +// CanDelete checks if the user can delete a project +func (l *Project) CanDelete(s *xorm.Session, a web.Auth) (bool, error) { return l.IsAdmin(s, a) } -// CanCreate checks if the user can create a list -func (l *List) CanCreate(s *xorm.Session, a web.Auth) (bool, error) { - // A user can create a list if they have write access to the namespace +// CanCreate checks if the user can create a project +func (l *Project) CanCreate(s *xorm.Session, a web.Auth) (bool, error) { + // A user can create a project if they have write access to the namespace n := &Namespace{ID: l.NamespaceID} return n.CanWrite(s, a) } -// IsAdmin returns whether the user has admin rights on the list or not -func (l *List) IsAdmin(s *xorm.Session, a web.Auth) (bool, error) { - // The favorite list can't be edited - if l.ID == FavoritesPseudoList.ID { +// IsAdmin returns whether the user has admin rights on the project or not +func (l *Project) IsAdmin(s *xorm.Session, a web.Auth) (bool, error) { + // The favorite project can't be edited + if l.ID == FavoritesPseudoProject.ID { return false, nil } - originalList, err := GetListSimpleByID(s, l.ID) + originalProject, err := GetProjectSimpleByID(s, l.ID) if err != nil { return false, err } @@ -180,26 +180,26 @@ func (l *List) IsAdmin(s *xorm.Session, a web.Auth) (bool, error) { // Check if we're dealing with a share auth shareAuth, ok := a.(*LinkSharing) if ok { - return originalList.ID == shareAuth.ListID && shareAuth.Right == RightAdmin, nil + return originalProject.ID == shareAuth.ProjectID && shareAuth.Right == RightAdmin, nil } // Check all the things - // Check if the user is either owner or can write to the list + // Check if the user is either owner or can write to the project // Owners are always admins - if originalList.isOwner(&user.User{ID: a.GetID()}) { + if originalProject.isOwner(&user.User{ID: a.GetID()}) { return true, nil } - is, _, err := originalList.checkRight(s, a, RightAdmin) + is, _, err := originalProject.checkRight(s, a, RightAdmin) return is, err } -// Little helper function to check if a user is list owner -func (l *List) isOwner(u *user.User) bool { +// Little helper function to check if a user is project owner +func (l *Project) isOwner(u *user.User) bool { return l.OwnerID == u.ID } // Checks n different rights for any given user -func (l *List) checkRight(s *xorm.Session, a web.Auth, rights ...Right) (bool, int, error) { +func (l *Project) checkRight(s *xorm.Session, a web.Auth, rights ...Right) (bool, int, error) { /* The following loop creates a sql condition like this one: @@ -208,30 +208,30 @@ func (l *List) checkRight(s *xorm.Session, a web.Auth, rights ...Right) (bool, i (tm.user_id = 1 AND tn.right = 1) OR (tm2.user_id = 1 AND tl.right = 1) OR for each passed right. That way, we can check with a single sql query (instead if 8) - if the user has the right to see the list or not. + if the user has the right to see the project or not. */ var conds []builder.Cond for _, r := range rights { // User conditions - // If the list was shared directly with the user and the user has the right + // If the project was shared directly with the user and the user has the right conds = append(conds, builder.And( builder.Eq{"ul.user_id": a.GetID()}, builder.Eq{"ul.right": r}, )) - // If the namespace this list belongs to was shared directly with the user and the user has the right + // If the namespace this project belongs to was shared directly with the user and the user has the right conds = append(conds, builder.And( builder.Eq{"un.user_id": a.GetID()}, builder.Eq{"un.right": r}, )) // Team rights - // If the list was shared directly with the team and the team has the right + // If the project was shared directly with the team and the team has the right conds = append(conds, builder.And( builder.Eq{"tm2.user_id": a.GetID()}, builder.Eq{"tl.right": r}, )) - // If the namespace this list belongs to was shared directly with the team and the team has the right + // If the namespace this project belongs to was shared directly with the team and the team has the right conds = append(conds, builder.And( builder.Eq{"tm.user_id": a.GetID()}, builder.Eq{"tn.right": r}, @@ -241,30 +241,30 @@ func (l *List) checkRight(s *xorm.Session, a web.Auth, rights ...Right) (bool, i // If the user is the owner of a namespace, it has any right, all the time conds = append(conds, builder.Eq{"n.owner_id": a.GetID()}) - type allListRights struct { + type allProjectRights struct { UserNamespace *NamespaceUser `xorm:"extends"` - UserList *ListUser `xorm:"extends"` + UserProject *ProjectUser `xorm:"extends"` TeamNamespace *TeamNamespace `xorm:"extends"` - TeamList *TeamList `xorm:"extends"` + TeamProject *TeamProject `xorm:"extends"` NamespaceOwnerID int64 `xorm:"namespaces_owner_id"` } - r := &allListRights{} + r := &allProjectRights{} var maxRight = 0 exists, err := s. Select("l.*, un.right, ul.right, tn.right, tl.right, n.owner_id as namespaces_owner_id"). - Table("lists"). + Table("projects"). Alias("l"). // User stuff Join("LEFT", []string{"users_namespaces", "un"}, "un.namespace_id = l.namespace_id"). - Join("LEFT", []string{"users_lists", "ul"}, "ul.list_id = l.id"). + Join("LEFT", []string{"users_projects", "ul"}, "ul.project_id = l.id"). Join("LEFT", []string{"namespaces", "n"}, "n.id = l.namespace_id"). // Team stuff Join("LEFT", []string{"team_namespaces", "tn"}, " l.namespace_id = tn.namespace_id"). Join("LEFT", []string{"team_members", "tm"}, "tm.team_id = tn.team_id"). - Join("LEFT", []string{"team_lists", "tl"}, "l.id = tl.list_id"). + Join("LEFT", []string{"team_projects", "tl"}, "l.id = tl.project_id"). Join("LEFT", []string{"team_members", "tm2"}, "tm2.team_id = tl.team_id"). // The actual condition Where(builder.And( @@ -279,14 +279,14 @@ func (l *List) checkRight(s *xorm.Session, a web.Auth, rights ...Right) (bool, i if int(r.UserNamespace.Right) > maxRight { maxRight = int(r.UserNamespace.Right) } - if int(r.UserList.Right) > maxRight { - maxRight = int(r.UserList.Right) + if int(r.UserProject.Right) > maxRight { + maxRight = int(r.UserProject.Right) } if int(r.TeamNamespace.Right) > maxRight { maxRight = int(r.TeamNamespace.Right) } - if int(r.TeamList.Right) > maxRight { - maxRight = int(r.TeamList.Right) + if int(r.TeamProject.Right) > maxRight { + maxRight = int(r.TeamProject.Right) } if r.NamespaceOwnerID == a.GetID() { maxRight = int(RightAdmin) diff --git a/pkg/models/list_team.go b/pkg/models/list_team.go index 4ec979fd1..6032f2ba4 100644 --- a/pkg/models/list_team.go +++ b/pkg/models/list_team.go @@ -27,14 +27,14 @@ import ( "xorm.io/xorm" ) -// TeamList defines the relation between a team and a list -type TeamList struct { - // The unique, numeric id of this list <-> team relation. +// TeamProject defines the relation between a team and a project +type TeamProject struct { + // The unique, numeric id of this project <-> team relation. ID int64 `xorm:"bigint autoincr not null unique pk" json:"id"` // The team id. TeamID int64 `xorm:"bigint not null INDEX" json:"team_id" param:"team"` - // The list id. - ListID int64 `xorm:"bigint not null INDEX" json:"-" param:"list"` + // The project id. + ProjectID int64 `xorm:"bigint not null INDEX" json:"-" param:"project"` // The right this team has. 0 = Read only, 1 = Read & Write, 2 = Admin. See the docs for more details. Right Right `xorm:"bigint INDEX not null default 0" json:"right" valid:"length(0|2)" maximum:"2" default:"0"` @@ -48,8 +48,8 @@ type TeamList struct { } // TableName makes beautiful table names -func (TeamList) TableName() string { - return "team_lists" +func (TeamProject) TableName() string { + return "team_projects" } // TeamWithRight represents a team, combined with rights. @@ -58,22 +58,22 @@ type TeamWithRight struct { Right Right `json:"right"` } -// Create creates a new team <-> list relation -// @Summary Add a team to a list -// @Description Gives a team access to a list. +// Create creates a new team <-> project relation +// @Summary Add a team to a project +// @Description Gives a team access to a project. // @tags sharing // @Accept json // @Produce json // @Security JWTKeyAuth -// @Param id path int true "List ID" -// @Param list body models.TeamList true "The team you want to add to the list." -// @Success 201 {object} models.TeamList "The created team<->list relation." -// @Failure 400 {object} web.HTTPError "Invalid team list object provided." +// @Param id path int true "Project ID" +// @Param project body models.TeamProject true "The team you want to add to the project." +// @Success 201 {object} models.TeamProject "The created team<->project relation." +// @Failure 400 {object} web.HTTPError "Invalid team project object provided." // @Failure 404 {object} web.HTTPError "The team does not exist." -// @Failure 403 {object} web.HTTPError "The user does not have access to the list" +// @Failure 403 {object} web.HTTPError "The user does not have access to the project" // @Failure 500 {object} models.Message "Internal error" -// @Router /lists/{id}/teams [put] -func (tl *TeamList) Create(s *xorm.Session, a web.Auth) (err error) { +// @Router /projects/{id}/teams [put] +func (tl *TeamProject) Create(s *xorm.Session, a web.Auth) (err error) { // Check if the rights are valid if err = tl.Right.isValid(); err != nil { @@ -86,21 +86,21 @@ func (tl *TeamList) Create(s *xorm.Session, a web.Auth) (err error) { return err } - // Check if the list exists - l, err := GetListSimpleByID(s, tl.ListID) + // Check if the project exists + l, err := GetProjectSimpleByID(s, tl.ProjectID) if err != nil { return err } - // Check if the team is already on the list + // Check if the team is already on the project exists, err := s.Where("team_id = ?", tl.TeamID). - And("list_id = ?", tl.ListID). - Get(&TeamList{}) + And("project_id = ?", tl.ProjectID). + Get(&TeamProject{}) if err != nil { return } if exists { - return ErrTeamAlreadyHasAccess{tl.TeamID, tl.ListID} + return ErrTeamAlreadyHasAccess{tl.TeamID, tl.ProjectID} } // Insert the new team @@ -109,33 +109,33 @@ func (tl *TeamList) Create(s *xorm.Session, a web.Auth) (err error) { return err } - err = events.Dispatch(&ListSharedWithTeamEvent{ - List: l, - Team: team, - Doer: a, + err = events.Dispatch(&ProjectSharedWithTeamEvent{ + Project: l, + Team: team, + Doer: a, }) if err != nil { return err } - err = updateListLastUpdated(s, l) + err = updateProjectLastUpdated(s, l) return } -// Delete deletes a team <-> list relation based on the list & team id -// @Summary Delete a team from a list -// @Description Delets a team from a list. The team won't have access to the list anymore. +// Delete deletes a team <-> project relation based on the project & team id +// @Summary Delete a team from a project +// @Description Delets a team from a project. The team won't have access to the project anymore. // @tags sharing // @Produce json // @Security JWTKeyAuth -// @Param listID path int true "List ID" +// @Param projectID path int true "Project ID" // @Param teamID path int true "Team ID" // @Success 200 {object} models.Message "The team was successfully deleted." -// @Failure 403 {object} web.HTTPError "The user does not have access to the list" -// @Failure 404 {object} web.HTTPError "Team or list does not exist." +// @Failure 403 {object} web.HTTPError "The user does not have access to the project" +// @Failure 404 {object} web.HTTPError "Team or project does not exist." // @Failure 500 {object} models.Message "Internal error" -// @Router /lists/{listID}/teams/{teamID} [delete] -func (tl *TeamList) Delete(s *xorm.Session, a web.Auth) (err error) { +// @Router /projects/{projectID}/teams/{teamID} [delete] +func (tl *TeamProject) Delete(s *xorm.Session, a web.Auth) (err error) { // Check if the team exists _, err = GetTeamByID(s, tl.TeamID) @@ -143,53 +143,53 @@ func (tl *TeamList) Delete(s *xorm.Session, a web.Auth) (err error) { return } - // Check if the team has access to the list + // Check if the team has access to the project has, err := s. - Where("team_id = ? AND list_id = ?", tl.TeamID, tl.ListID). - Get(&TeamList{}) + Where("team_id = ? AND project_id = ?", tl.TeamID, tl.ProjectID). + Get(&TeamProject{}) if err != nil { return } if !has { - return ErrTeamDoesNotHaveAccessToList{TeamID: tl.TeamID, ListID: tl.ListID} + return ErrTeamDoesNotHaveAccessToProject{TeamID: tl.TeamID, ProjectID: tl.ProjectID} } // Delete the relation _, err = s.Where("team_id = ?", tl.TeamID). - And("list_id = ?", tl.ListID). - Delete(TeamList{}) + And("project_id = ?", tl.ProjectID). + Delete(TeamProject{}) if err != nil { return err } - err = updateListLastUpdated(s, &List{ID: tl.ListID}) + err = updateProjectLastUpdated(s, &Project{ID: tl.ProjectID}) return } -// ReadAll implements the method to read all teams of a list -// @Summary Get teams on a list -// @Description Returns a list with all teams which have access on a given list. +// ReadAll implements the method to read all teams of a project +// @Summary Get teams on a project +// @Description Returns a project with all teams which have access on a given project. // @tags sharing // @Accept json // @Produce json -// @Param id path int true "List ID" +// @Param id path int true "Project ID" // @Param page query int false "The page number. Used for pagination. If not provided, the first page of results is returned." // @Param per_page query int false "The maximum number of items per page. Note this parameter is limited by the configured maximum of items per page." // @Param s query string false "Search teams by its name." // @Security JWTKeyAuth // @Success 200 {array} models.TeamWithRight "The teams with their right." -// @Failure 403 {object} web.HTTPError "No right to see the list." +// @Failure 403 {object} web.HTTPError "No right to see the project." // @Failure 500 {object} models.Message "Internal error" -// @Router /lists/{id}/teams [get] -func (tl *TeamList) ReadAll(s *xorm.Session, a web.Auth, search string, page int, perPage int) (result interface{}, resultCount int, totalItems int64, err error) { +// @Router /projects/{id}/teams [get] +func (tl *TeamProject) ReadAll(s *xorm.Session, a web.Auth, search string, page int, perPage int) (result interface{}, resultCount int, totalItems int64, err error) { // Check if the user can read the namespace - l := &List{ID: tl.ListID} + l := &Project{ID: tl.ProjectID} canRead, _, err := l.CanRead(s, a) if err != nil { return nil, 0, 0, err } if !canRead { - return nil, 0, 0, ErrNeedToHaveListReadAccess{ListID: tl.ListID, UserID: a.GetID()} + return nil, 0, 0, ErrNeedToHaveProjectReadAccess{ProjectID: tl.ProjectID, UserID: a.GetID()} } limit, start := getLimitFromPageIndex(page, perPage) @@ -198,8 +198,8 @@ func (tl *TeamList) ReadAll(s *xorm.Session, a web.Auth, search string, page int all := []*TeamWithRight{} query := s. Table("teams"). - Join("INNER", "team_lists", "team_id = teams.id"). - Where("team_lists.list_id = ?", tl.ListID). + Join("INNER", "team_projects", "team_id = teams.id"). + Where("team_projects.project_id = ?", tl.ProjectID). Where(db.ILIKE("teams.name", search)) if limit > 0 { query = query.Limit(limit, start) @@ -221,8 +221,8 @@ func (tl *TeamList) ReadAll(s *xorm.Session, a web.Auth, search string, page int totalItems, err = s. Table("teams"). - Join("INNER", "team_lists", "team_id = teams.id"). - Where("team_lists.list_id = ?", tl.ListID). + Join("INNER", "team_projects", "team_id = teams.id"). + Where("team_projects.project_id = ?", tl.ProjectID). Where("teams.name LIKE ?", "%"+search+"%"). Count(&TeamWithRight{}) if err != nil { @@ -232,22 +232,22 @@ func (tl *TeamList) ReadAll(s *xorm.Session, a web.Auth, search string, page int return all, len(all), totalItems, err } -// Update updates a team <-> list relation -// @Summary Update a team <-> list relation -// @Description Update a team <-> list relation. Mostly used to update the right that team has. +// Update updates a team <-> project relation +// @Summary Update a team <-> project relation +// @Description Update a team <-> project relation. Mostly used to update the right that team has. // @tags sharing // @Accept json // @Produce json -// @Param listID path int true "List ID" +// @Param projectID path int true "Project ID" // @Param teamID path int true "Team ID" -// @Param list body models.TeamList true "The team you want to update." +// @Param project body models.TeamProject true "The team you want to update." // @Security JWTKeyAuth -// @Success 200 {object} models.TeamList "The updated team <-> list relation." -// @Failure 403 {object} web.HTTPError "The user does not have admin-access to the list" -// @Failure 404 {object} web.HTTPError "Team or list does not exist." +// @Success 200 {object} models.TeamProject "The updated team <-> project relation." +// @Failure 403 {object} web.HTTPError "The user does not have admin-access to the project" +// @Failure 404 {object} web.HTTPError "Team or project does not exist." // @Failure 500 {object} models.Message "Internal error" -// @Router /lists/{listID}/teams/{teamID} [post] -func (tl *TeamList) Update(s *xorm.Session, a web.Auth) (err error) { +// @Router /projects/{projectID}/teams/{teamID} [post] +func (tl *TeamProject) Update(s *xorm.Session, a web.Auth) (err error) { // Check if the right is valid if err := tl.Right.isValid(); err != nil { @@ -255,13 +255,13 @@ func (tl *TeamList) Update(s *xorm.Session, a web.Auth) (err error) { } _, err = s. - Where("list_id = ? AND team_id = ?", tl.ListID, tl.TeamID). + Where("project_id = ? AND team_id = ?", tl.ProjectID, tl.TeamID). Cols("right"). Update(tl) if err != nil { return err } - err = updateListLastUpdated(s, &List{ID: tl.ListID}) + err = updateProjectLastUpdated(s, &Project{ID: tl.ProjectID}) return } diff --git a/pkg/models/list_team_rights.go b/pkg/models/list_team_rights.go index 588b9faa1..bdd1841d3 100644 --- a/pkg/models/list_team_rights.go +++ b/pkg/models/list_team_rights.go @@ -21,27 +21,27 @@ import ( "xorm.io/xorm" ) -// CanCreate checks if the user can create a team <-> list relation -func (tl *TeamList) CanCreate(s *xorm.Session, a web.Auth) (bool, error) { - return tl.canDoTeamList(s, a) +// CanCreate checks if the user can create a team <-> project relation +func (tl *TeamProject) CanCreate(s *xorm.Session, a web.Auth) (bool, error) { + return tl.canDoTeamProject(s, a) } -// CanDelete checks if the user can delete a team <-> list relation -func (tl *TeamList) CanDelete(s *xorm.Session, a web.Auth) (bool, error) { - return tl.canDoTeamList(s, a) +// CanDelete checks if the user can delete a team <-> project relation +func (tl *TeamProject) CanDelete(s *xorm.Session, a web.Auth) (bool, error) { + return tl.canDoTeamProject(s, a) } -// CanUpdate checks if the user can update a team <-> list relation -func (tl *TeamList) CanUpdate(s *xorm.Session, a web.Auth) (bool, error) { - return tl.canDoTeamList(s, a) +// CanUpdate checks if the user can update a team <-> project relation +func (tl *TeamProject) CanUpdate(s *xorm.Session, a web.Auth) (bool, error) { + return tl.canDoTeamProject(s, a) } -func (tl *TeamList) canDoTeamList(s *xorm.Session, a web.Auth) (bool, error) { +func (tl *TeamProject) canDoTeamProject(s *xorm.Session, a web.Auth) (bool, error) { // Link shares aren't allowed to do anything if _, is := a.(*LinkSharing); is { return false, nil } - l := List{ID: tl.ListID} + l := Project{ID: tl.ProjectID} return l.IsAdmin(s, a) } diff --git a/pkg/models/list_team_test.go b/pkg/models/list_team_test.go index fa5da4a93..0b56e93e0 100644 --- a/pkg/models/list_team_test.go +++ b/pkg/models/list_team_test.go @@ -28,13 +28,13 @@ import ( "github.com/stretchr/testify/assert" ) -func TestTeamList_ReadAll(t *testing.T) { +func TestTeamProject_ReadAll(t *testing.T) { u := &user.User{ID: 1} t.Run("normal", func(t *testing.T) { - tl := TeamList{ - TeamID: 1, - ListID: 3, + tl := TeamProject{ + TeamID: 1, + ProjectID: 3, } db.LoadAndAssertFixtures(t) s := db.NewSession() @@ -45,22 +45,22 @@ func TestTeamList_ReadAll(t *testing.T) { assert.Equal(t, ts.Len(), 1) _ = s.Close() }) - t.Run("nonexistant list", func(t *testing.T) { - tl := TeamList{ - ListID: 99999, + t.Run("nonexistant project", func(t *testing.T) { + tl := TeamProject{ + ProjectID: 99999, } db.LoadAndAssertFixtures(t) s := db.NewSession() _, _, _, err := tl.ReadAll(s, u, "", 1, 50) assert.Error(t, err) - assert.True(t, IsErrListDoesNotExist(err)) + assert.True(t, IsErrProjectDoesNotExist(err)) _ = s.Close() }) t.Run("namespace owner", func(t *testing.T) { - tl := TeamList{ - TeamID: 1, - ListID: 2, - Right: RightAdmin, + tl := TeamProject{ + TeamID: 1, + ProjectID: 2, + Right: RightAdmin, } db.LoadAndAssertFixtures(t) s := db.NewSession() @@ -69,21 +69,21 @@ func TestTeamList_ReadAll(t *testing.T) { _ = s.Close() }) t.Run("no access", func(t *testing.T) { - tl := TeamList{ - TeamID: 1, - ListID: 5, - Right: RightAdmin, + tl := TeamProject{ + TeamID: 1, + ProjectID: 5, + Right: RightAdmin, } db.LoadAndAssertFixtures(t) s := db.NewSession() _, _, _, err := tl.ReadAll(s, u, "", 1, 50) assert.Error(t, err) - assert.True(t, IsErrNeedToHaveListReadAccess(err)) + assert.True(t, IsErrNeedToHaveProjectReadAccess(err)) _ = s.Close() }) t.Run("search", func(t *testing.T) { - tl := TeamList{ - ListID: 19, + tl := TeamProject{ + ProjectID: 19, } db.LoadAndAssertFixtures(t) s := db.NewSession() @@ -97,15 +97,15 @@ func TestTeamList_ReadAll(t *testing.T) { }) } -func TestTeamList_Create(t *testing.T) { +func TestTeamProject_Create(t *testing.T) { u := &user.User{ID: 1} t.Run("normal", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() - tl := TeamList{ - TeamID: 1, - ListID: 1, - Right: RightAdmin, + tl := TeamProject{ + TeamID: 1, + ProjectID: 1, + Right: RightAdmin, } allowed, _ := tl.CanCreate(s, u) assert.True(t, allowed) @@ -113,19 +113,19 @@ func TestTeamList_Create(t *testing.T) { assert.NoError(t, err) err = s.Commit() assert.NoError(t, err) - db.AssertExists(t, "team_lists", map[string]interface{}{ - "team_id": 1, - "list_id": 1, - "right": RightAdmin, + db.AssertExists(t, "team_projects", map[string]interface{}{ + "team_id": 1, + "project_id": 1, + "right": RightAdmin, }, false) }) t.Run("team already has access", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() - tl := TeamList{ - TeamID: 1, - ListID: 3, - Right: RightAdmin, + tl := TeamProject{ + TeamID: 1, + ProjectID: 3, + Right: RightAdmin, } err := tl.Create(s, u) assert.Error(t, err) @@ -135,10 +135,10 @@ func TestTeamList_Create(t *testing.T) { t.Run("wrong rights", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() - tl := TeamList{ - TeamID: 1, - ListID: 1, - Right: RightUnknown, + tl := TeamProject{ + TeamID: 1, + ProjectID: 1, + Right: RightUnknown, } err := tl.Create(s, u) assert.Error(t, err) @@ -148,84 +148,84 @@ func TestTeamList_Create(t *testing.T) { t.Run("nonexistant team", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() - tl := TeamList{ - TeamID: 9999, - ListID: 1, + tl := TeamProject{ + TeamID: 9999, + ProjectID: 1, } err := tl.Create(s, u) assert.Error(t, err) assert.True(t, IsErrTeamDoesNotExist(err)) _ = s.Close() }) - t.Run("nonexistant list", func(t *testing.T) { + t.Run("nonexistant project", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() - tl := TeamList{ - TeamID: 1, - ListID: 9999, + tl := TeamProject{ + TeamID: 1, + ProjectID: 9999, } err := tl.Create(s, u) assert.Error(t, err) - assert.True(t, IsErrListDoesNotExist(err)) + assert.True(t, IsErrProjectDoesNotExist(err)) _ = s.Close() }) } -func TestTeamList_Delete(t *testing.T) { +func TestTeamProject_Delete(t *testing.T) { user := &user.User{ID: 1} t.Run("normal", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() - tl := TeamList{ - TeamID: 1, - ListID: 3, + tl := TeamProject{ + TeamID: 1, + ProjectID: 3, } err := tl.Delete(s, user) assert.NoError(t, err) err = s.Commit() assert.NoError(t, err) - db.AssertMissing(t, "team_lists", map[string]interface{}{ - "team_id": 1, - "list_id": 3, + db.AssertMissing(t, "team_projects", map[string]interface{}{ + "team_id": 1, + "project_id": 3, }) }) t.Run("nonexistant team", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() - tl := TeamList{ - TeamID: 9999, - ListID: 1, + tl := TeamProject{ + TeamID: 9999, + ProjectID: 1, } err := tl.Delete(s, user) assert.Error(t, err) assert.True(t, IsErrTeamDoesNotExist(err)) _ = s.Close() }) - t.Run("nonexistant list", func(t *testing.T) { + t.Run("nonexistant project", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() - tl := TeamList{ - TeamID: 1, - ListID: 9999, + tl := TeamProject{ + TeamID: 1, + ProjectID: 9999, } err := tl.Delete(s, user) assert.Error(t, err) - assert.True(t, IsErrTeamDoesNotHaveAccessToList(err)) + assert.True(t, IsErrTeamDoesNotHaveAccessToProject(err)) _ = s.Close() }) } -func TestTeamList_Update(t *testing.T) { +func TestTeamProject_Update(t *testing.T) { type fields struct { - ID int64 - TeamID int64 - ListID int64 - Right Right - Created time.Time - Updated time.Time - CRUDable web.CRUDable - Rights web.Rights + ID int64 + TeamID int64 + ProjectID int64 + Right Right + Created time.Time + Updated time.Time + CRUDable web.CRUDable + Rights web.Rights } tests := []struct { name string @@ -236,33 +236,33 @@ func TestTeamList_Update(t *testing.T) { { name: "Test Update Normally", fields: fields{ - ListID: 3, - TeamID: 1, - Right: RightAdmin, + ProjectID: 3, + TeamID: 1, + Right: RightAdmin, }, }, { name: "Test Update to write", fields: fields{ - ListID: 3, - TeamID: 1, - Right: RightWrite, + ProjectID: 3, + TeamID: 1, + Right: RightWrite, }, }, { name: "Test Update to Read", fields: fields{ - ListID: 3, - TeamID: 1, - Right: RightRead, + ProjectID: 3, + TeamID: 1, + Right: RightRead, }, }, { name: "Test Update with invalid right", fields: fields{ - ListID: 3, - TeamID: 1, - Right: 500, + ProjectID: 3, + TeamID: 1, + Right: 500, }, wantErr: true, errType: IsErrInvalidRight, @@ -273,30 +273,30 @@ func TestTeamList_Update(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() - tl := &TeamList{ - ID: tt.fields.ID, - TeamID: tt.fields.TeamID, - ListID: tt.fields.ListID, - Right: tt.fields.Right, - Created: tt.fields.Created, - Updated: tt.fields.Updated, - CRUDable: tt.fields.CRUDable, - Rights: tt.fields.Rights, + tl := &TeamProject{ + ID: tt.fields.ID, + TeamID: tt.fields.TeamID, + ProjectID: tt.fields.ProjectID, + Right: tt.fields.Right, + Created: tt.fields.Created, + Updated: tt.fields.Updated, + CRUDable: tt.fields.CRUDable, + Rights: tt.fields.Rights, } err := tl.Update(s, &user.User{ID: 1}) if (err != nil) != tt.wantErr { - t.Errorf("TeamList.Update() error = %v, wantErr %v", err, tt.wantErr) + t.Errorf("TeamProject.Update() error = %v, wantErr %v", err, tt.wantErr) } if (err != nil) && tt.wantErr && !tt.errType(err) { - t.Errorf("TeamList.Update() Wrong error type! Error = %v, want = %v", err, runtime.FuncForPC(reflect.ValueOf(tt.errType).Pointer()).Name()) + t.Errorf("TeamProject.Update() Wrong error type! Error = %v, want = %v", err, runtime.FuncForPC(reflect.ValueOf(tt.errType).Pointer()).Name()) } err = s.Commit() assert.NoError(t, err) if !tt.wantErr { - db.AssertExists(t, "team_lists", map[string]interface{}{ - "list_id": tt.fields.ListID, - "team_id": tt.fields.TeamID, - "right": tt.fields.Right, + db.AssertExists(t, "team_projects", map[string]interface{}{ + "project_id": tt.fields.ProjectID, + "team_id": tt.fields.TeamID, + "right": tt.fields.Right, }, false) } }) diff --git a/pkg/models/list_test.go b/pkg/models/list_test.go index f908ef88d..0757c38cf 100644 --- a/pkg/models/list_test.go +++ b/pkg/models/list_test.go @@ -1,4 +1,4 @@ -// Vikunja is a to-do list application to facilitate your life. +// Vikunja is a to-do project application to facilitate your life. // Copyright 2018-2021 Vikunja and contributors. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -26,7 +26,7 @@ import ( "github.com/stretchr/testify/assert" ) -func TestList_CreateOrUpdate(t *testing.T) { +func TestProject_CreateOrUpdate(t *testing.T) { usr := &user.User{ ID: 1, Username: "user1", @@ -37,31 +37,31 @@ func TestList_CreateOrUpdate(t *testing.T) { t.Run("normal", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() - list := List{ + project := Project{ Title: "test", Description: "Lorem Ipsum", NamespaceID: 1, } - err := list.Create(s, usr) + err := project.Create(s, usr) assert.NoError(t, err) err = s.Commit() assert.NoError(t, err) - db.AssertExists(t, "lists", map[string]interface{}{ - "id": list.ID, - "title": list.Title, - "description": list.Description, - "namespace_id": list.NamespaceID, + db.AssertExists(t, "projects", map[string]interface{}{ + "id": project.ID, + "title": project.Title, + "description": project.Description, + "namespace_id": project.NamespaceID, }, false) }) t.Run("nonexistant namespace", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() - list := List{ + project := Project{ Title: "test", Description: "Lorem Ipsum", NamespaceID: 999999, } - err := list.Create(s, usr) + err := project.Create(s, usr) assert.Error(t, err) assert.True(t, IsErrNamespaceDoesNotExist(err)) _ = s.Close() @@ -70,12 +70,12 @@ func TestList_CreateOrUpdate(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() usr := &user.User{ID: 9482385} - list := List{ + project := Project{ Title: "test", Description: "Lorem Ipsum", NamespaceID: 1, } - err := list.Create(s, usr) + err := project.Create(s, usr) assert.Error(t, err) assert.True(t, user.IsErrUserDoesNotExist(err)) _ = s.Close() @@ -83,34 +83,34 @@ func TestList_CreateOrUpdate(t *testing.T) { t.Run("existing identifier", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() - list := List{ + project := Project{ Title: "test", Description: "Lorem Ipsum", Identifier: "test1", NamespaceID: 1, } - err := list.Create(s, usr) + err := project.Create(s, usr) assert.Error(t, err) - assert.True(t, IsErrListIdentifierIsNotUnique(err)) + assert.True(t, IsErrProjectIdentifierIsNotUnique(err)) _ = s.Close() }) t.Run("non ascii characters", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() - list := List{ + project := Project{ Title: "приффки фсем", Description: "Lorem Ipsum", NamespaceID: 1, } - err := list.Create(s, usr) + err := project.Create(s, usr) assert.NoError(t, err) err = s.Commit() assert.NoError(t, err) - db.AssertExists(t, "lists", map[string]interface{}{ - "id": list.ID, - "title": list.Title, - "description": list.Description, - "namespace_id": list.NamespaceID, + db.AssertExists(t, "projects", map[string]interface{}{ + "id": project.ID, + "title": project.Title, + "description": project.Description, + "namespace_id": project.NamespaceID, }, false) }) }) @@ -119,50 +119,50 @@ func TestList_CreateOrUpdate(t *testing.T) { t.Run("normal", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() - list := List{ + project := Project{ ID: 1, Title: "test", Description: "Lorem Ipsum", NamespaceID: 1, } - list.Description = "Lorem Ipsum dolor sit amet." - err := list.Update(s, usr) + project.Description = "Lorem Ipsum dolor sit amet." + err := project.Update(s, usr) assert.NoError(t, err) err = s.Commit() assert.NoError(t, err) - db.AssertExists(t, "lists", map[string]interface{}{ - "id": list.ID, - "title": list.Title, - "description": list.Description, - "namespace_id": list.NamespaceID, + db.AssertExists(t, "projects", map[string]interface{}{ + "id": project.ID, + "title": project.Title, + "description": project.Description, + "namespace_id": project.NamespaceID, }, false) }) t.Run("nonexistant", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() - list := List{ + project := Project{ ID: 99999999, Title: "test", NamespaceID: 1, } - err := list.Update(s, usr) + err := project.Update(s, usr) assert.Error(t, err) - assert.True(t, IsErrListDoesNotExist(err)) + assert.True(t, IsErrProjectDoesNotExist(err)) _ = s.Close() }) t.Run("existing identifier", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() - list := List{ + project := Project{ Title: "test", Description: "Lorem Ipsum", Identifier: "test1", NamespaceID: 1, } - err := list.Create(s, usr) + err := project.Create(s, usr) assert.Error(t, err) - assert.True(t, IsErrListIdentifierIsNotUnique(err)) + assert.True(t, IsErrProjectIdentifierIsNotUnique(err)) _ = s.Close() }) t.Run("change namespace", func(t *testing.T) { @@ -175,37 +175,37 @@ func TestList_CreateOrUpdate(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() - list := List{ + project := Project{ ID: 6, Title: "Test6", Description: "Lorem Ipsum", NamespaceID: 7, // from 6 } - can, err := list.CanUpdate(s, usr) + can, err := project.CanUpdate(s, usr) assert.NoError(t, err) assert.True(t, can) - err = list.Update(s, usr) + err = project.Update(s, usr) assert.NoError(t, err) err = s.Commit() assert.NoError(t, err) - db.AssertExists(t, "lists", map[string]interface{}{ - "id": list.ID, - "title": list.Title, - "description": list.Description, - "namespace_id": list.NamespaceID, + db.AssertExists(t, "projects", map[string]interface{}{ + "id": project.ID, + "title": project.Title, + "description": project.Description, + "namespace_id": project.NamespaceID, }, false) }) // FIXME: The check for whether the namespace is archived is missing in namespace.CanWrite // t.Run("archived own", func(t *testing.T) { // db.LoadAndAssertFixtures(t) // s := db.NewSession() - // list := List{ + // project := Project{ // ID: 1, // Title: "Test1", // Description: "Lorem Ipsum", // NamespaceID: 16, // from 1 // } - // can, err := list.CanUpdate(s, usr) + // can, err := project.CanUpdate(s, usr) // assert.NoError(t, err) // assert.False(t, can) // namespace is archived and thus not writeable // _ = s.Close() @@ -213,13 +213,13 @@ func TestList_CreateOrUpdate(t *testing.T) { t.Run("others", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() - list := List{ + project := Project{ ID: 1, Title: "Test1", Description: "Lorem Ipsum", NamespaceID: 2, // from 1 } - can, _ := list.CanUpdate(s, usr) + can, _ := project.CanUpdate(s, usr) assert.False(t, can) // namespace is not writeable by us _ = s.Close() }) @@ -232,32 +232,32 @@ func TestList_CreateOrUpdate(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() - list := List{ + project := Project{ ID: 6, Title: "Test6", Description: "Lorem Ipsum", NamespaceID: -1, } - err := list.Update(s, usr) + err := project.Update(s, usr) assert.Error(t, err) - assert.True(t, IsErrListCannotBelongToAPseudoNamespace(err)) + assert.True(t, IsErrProjectCannotBelongToAPseudoNamespace(err)) }) }) }) } -func TestList_Delete(t *testing.T) { +func TestProject_Delete(t *testing.T) { t.Run("normal", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() - list := List{ + project := Project{ ID: 1, } - err := list.Delete(s, &user.User{ID: 1}) + err := project.Delete(s, &user.User{ID: 1}) assert.NoError(t, err) err = s.Commit() assert.NoError(t, err) - db.AssertMissing(t, "lists", map[string]interface{}{ + db.AssertMissing(t, "projects", map[string]interface{}{ "id": 1, }) }) @@ -265,14 +265,14 @@ func TestList_Delete(t *testing.T) { db.LoadAndAssertFixtures(t) files.InitTestFileFixtures(t) s := db.NewSession() - list := List{ + project := Project{ ID: 25, } - err := list.Delete(s, &user.User{ID: 6}) + err := project.Delete(s, &user.User{ID: 6}) assert.NoError(t, err) err = s.Commit() assert.NoError(t, err) - db.AssertMissing(t, "lists", map[string]interface{}{ + db.AssertMissing(t, "projects", map[string]interface{}{ "id": 25, }) db.AssertMissing(t, "files", map[string]interface{}{ @@ -281,77 +281,77 @@ func TestList_Delete(t *testing.T) { }) } -func TestList_DeleteBackgroundFileIfExists(t *testing.T) { - t.Run("list with background", func(t *testing.T) { +func TestProject_DeleteBackgroundFileIfExists(t *testing.T) { + t.Run("project with background", func(t *testing.T) { db.LoadAndAssertFixtures(t) files.InitTestFileFixtures(t) s := db.NewSession() file := &files.File{ID: 1} - list := List{ + project := Project{ ID: 1, BackgroundFileID: file.ID, } - err := SetListBackground(s, list.ID, file, "") + err := SetProjectBackground(s, project.ID, file, "") assert.NoError(t, err) - err = list.DeleteBackgroundFileIfExists() + err = project.DeleteBackgroundFileIfExists() assert.NoError(t, err) }) - t.Run("list with invalid background", func(t *testing.T) { + t.Run("project with invalid background", func(t *testing.T) { db.LoadAndAssertFixtures(t) files.InitTestFileFixtures(t) s := db.NewSession() file := &files.File{ID: 9999} - list := List{ + project := Project{ ID: 1, BackgroundFileID: file.ID, } - err := SetListBackground(s, list.ID, file, "") + err := SetProjectBackground(s, project.ID, file, "") assert.NoError(t, err) - err = list.DeleteBackgroundFileIfExists() + err = project.DeleteBackgroundFileIfExists() assert.Error(t, err) assert.True(t, files.IsErrFileDoesNotExist(err)) }) - t.Run("list without background", func(t *testing.T) { + t.Run("project without background", func(t *testing.T) { db.LoadAndAssertFixtures(t) files.InitTestFileFixtures(t) - list := List{ID: 1} - err := list.DeleteBackgroundFileIfExists() + project := Project{ID: 1} + err := project.DeleteBackgroundFileIfExists() assert.NoError(t, err) }) } -func TestList_ReadAll(t *testing.T) { +func TestProject_ReadAll(t *testing.T) { t.Run("all in namespace", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() - // Get all lists for our namespace - lists, err := GetListsByNamespaceID(s, 1, &user.User{}) + // Get all projects for our namespace + projects, err := GetProjectsByNamespaceID(s, 1, &user.User{}) assert.NoError(t, err) - assert.Equal(t, len(lists), 2) + assert.Equal(t, len(projects), 2) _ = s.Close() }) - t.Run("all lists for user", func(t *testing.T) { + t.Run("all projects for user", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() u := &user.User{ID: 1} - list := List{} - lists3, _, _, err := list.ReadAll(s, u, "", 1, 50) + project := Project{} + projects3, _, _, err := project.ReadAll(s, u, "", 1, 50) assert.NoError(t, err) - assert.Equal(t, reflect.TypeOf(lists3).Kind(), reflect.Slice) - ls := lists3.([]*List) + assert.Equal(t, reflect.TypeOf(projects3).Kind(), reflect.Slice) + ls := projects3.([]*Project) assert.Equal(t, 16, len(ls)) - assert.Equal(t, int64(3), ls[0].ID) // List 3 has a position of 1 and should be sorted first + assert.Equal(t, int64(3), ls[0].ID) // Project 3 has a position of 1 and should be sorted first assert.Equal(t, int64(1), ls[1].ID) assert.Equal(t, int64(4), ls[2].ID) _ = s.Close() }) - t.Run("lists for nonexistant user", func(t *testing.T) { + t.Run("projects for nonexistant user", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() usr := &user.User{ID: 999999} - list := List{} - _, _, _, err := list.ReadAll(s, usr, "", 1, 50) + project := Project{} + _, _, _, err := project.ReadAll(s, usr, "", 1, 50) assert.Error(t, err) assert.True(t, user.IsErrUserDoesNotExist(err)) _ = s.Close() @@ -360,25 +360,25 @@ func TestList_ReadAll(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() u := &user.User{ID: 1} - list := List{} - lists3, _, _, err := list.ReadAll(s, u, "TEST10", 1, 50) + project := Project{} + projects3, _, _, err := project.ReadAll(s, u, "TEST10", 1, 50) assert.NoError(t, err) - ls := lists3.([]*List) + ls := projects3.([]*Project) assert.Equal(t, 1, len(ls)) assert.Equal(t, int64(10), ls[0].ID) _ = s.Close() }) } -func TestList_ReadOne(t *testing.T) { +func TestProject_ReadOne(t *testing.T) { t.Run("normal", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() defer s.Close() u := &user.User{ID: 1} - l := &List{ID: 1} + l := &Project{ID: 1} can, _, err := l.CanRead(s, u) assert.NoError(t, err) assert.True(t, can) @@ -392,7 +392,7 @@ func TestList_ReadOne(t *testing.T) { defer s.Close() u := &user.User{ID: 6} - l := &List{ID: 12} + l := &Project{ID: 12} can, _, err := l.CanRead(s, u) assert.NoError(t, err) assert.True(t, can) diff --git a/pkg/models/list_users.go b/pkg/models/list_users.go index 810894ee6..e9053dd94 100644 --- a/pkg/models/list_users.go +++ b/pkg/models/list_users.go @@ -28,16 +28,16 @@ import ( "xorm.io/xorm" ) -// ListUser represents a list <-> user relation -type ListUser struct { - // The unique, numeric id of this list <-> user relation. +// ProjectUser represents a project <-> user relation +type ProjectUser struct { + // The unique, numeric id of this project <-> user relation. ID int64 `xorm:"bigint autoincr not null unique pk" json:"id" param:"namespace"` // The username. Username string `xorm:"-" json:"user_id" param:"user"` // Used internally to reference the user UserID int64 `xorm:"bigint not null INDEX" json:"-"` - // The list id. - ListID int64 `xorm:"bigint not null INDEX" json:"-" param:"list"` + // The project id. + ProjectID int64 `xorm:"bigint not null INDEX" json:"-" param:"project"` // The right this user has. 0 = Read only, 1 = Read & Write, 2 = Admin. See the docs for more details. Right Right `xorm:"bigint INDEX not null default 0" json:"right" valid:"length(0|2)" maximum:"2" default:"0"` @@ -50,41 +50,41 @@ type ListUser struct { web.Rights `xorm:"-" json:"-"` } -// TableName is the table name for ListUser -func (ListUser) TableName() string { - return "users_lists" +// TableName is the table name for ProjectUser +func (ProjectUser) TableName() string { + return "users_projects" } -// UserWithRight represents a user in combination with the right it can have on a list/namespace +// UserWithRight represents a user in combination with the right it can have on a project/namespace type UserWithRight struct { user.User `xorm:"extends"` Right Right `json:"right"` } -// Create creates a new list <-> user relation -// @Summary Add a user to a list -// @Description Gives a user access to a list. +// Create creates a new project <-> user relation +// @Summary Add a user to a project +// @Description Gives a user access to a project. // @tags sharing // @Accept json // @Produce json // @Security JWTKeyAuth -// @Param id path int true "List ID" -// @Param list body models.ListUser true "The user you want to add to the list." -// @Success 201 {object} models.ListUser "The created user<->list relation." -// @Failure 400 {object} web.HTTPError "Invalid user list object provided." +// @Param id path int true "Project ID" +// @Param project body models.ProjectUser true "The user you want to add to the project." +// @Success 201 {object} models.ProjectUser "The created user<->project relation." +// @Failure 400 {object} web.HTTPError "Invalid user project object provided." // @Failure 404 {object} web.HTTPError "The user does not exist." -// @Failure 403 {object} web.HTTPError "The user does not have access to the list" +// @Failure 403 {object} web.HTTPError "The user does not have access to the project" // @Failure 500 {object} models.Message "Internal error" -// @Router /lists/{id}/users [put] -func (lu *ListUser) Create(s *xorm.Session, a web.Auth) (err error) { +// @Router /projects/{id}/users [put] +func (lu *ProjectUser) Create(s *xorm.Session, a web.Auth) (err error) { // Check if the right is valid if err := lu.Right.isValid(); err != nil { return err } - // Check if the list exists - l, err := GetListSimpleByID(s, lu.ListID) + // Check if the project exists + l, err := GetProjectSimpleByID(s, lu.ProjectID) if err != nil { return } @@ -96,53 +96,53 @@ func (lu *ListUser) Create(s *xorm.Session, a web.Auth) (err error) { } lu.UserID = u.ID - // Check if the user already has access or is owner of that list + // Check if the user already has access or is owner of that project // We explicitly DONT check for teams here if l.OwnerID == lu.UserID { - return ErrUserAlreadyHasAccess{UserID: lu.UserID, ListID: lu.ListID} + return ErrUserAlreadyHasAccess{UserID: lu.UserID, ProjectID: lu.ProjectID} } - exist, err := s.Where("list_id = ? AND user_id = ?", lu.ListID, lu.UserID).Get(&ListUser{}) + exist, err := s.Where("project_id = ? AND user_id = ?", lu.ProjectID, lu.UserID).Get(&ProjectUser{}) if err != nil { return } if exist { - return ErrUserAlreadyHasAccess{UserID: lu.UserID, ListID: lu.ListID} + return ErrUserAlreadyHasAccess{UserID: lu.UserID, ProjectID: lu.ProjectID} } - // Insert user <-> list relation + // Insert user <-> project relation _, err = s.Insert(lu) if err != nil { return err } - err = events.Dispatch(&ListSharedWithUserEvent{ - List: l, - User: u, - Doer: a, + err = events.Dispatch(&ProjectSharedWithUserEvent{ + Project: l, + User: u, + Doer: a, }) if err != nil { return err } - err = updateListLastUpdated(s, l) + err = updateProjectLastUpdated(s, l) return } -// Delete deletes a list <-> user relation -// @Summary Delete a user from a list -// @Description Delets a user from a list. The user won't have access to the list anymore. +// Delete deletes a project <-> user relation +// @Summary Delete a user from a project +// @Description Delets a user from a project. The user won't have access to the project anymore. // @tags sharing // @Produce json // @Security JWTKeyAuth -// @Param listID path int true "List ID" +// @Param projectID path int true "Project ID" // @Param userID path int true "User ID" -// @Success 200 {object} models.Message "The user was successfully removed from the list." -// @Failure 403 {object} web.HTTPError "The user does not have access to the list" -// @Failure 404 {object} web.HTTPError "user or list does not exist." +// @Success 200 {object} models.Message "The user was successfully removed from the project." +// @Failure 403 {object} web.HTTPError "The user does not have access to the project" +// @Failure 404 {object} web.HTTPError "user or project does not exist." // @Failure 500 {object} models.Message "Internal error" -// @Router /lists/{listID}/users/{userID} [delete] -func (lu *ListUser) Delete(s *xorm.Session, a web.Auth) (err error) { +// @Router /projects/{projectID}/users/{userID} [delete] +func (lu *ProjectUser) Delete(s *xorm.Session, a web.Auth) (err error) { // Check if the user exists u, err := user.GetUserByUsername(s, lu.Username) @@ -151,52 +151,52 @@ func (lu *ListUser) Delete(s *xorm.Session, a web.Auth) (err error) { } lu.UserID = u.ID - // Check if the user has access to the list + // Check if the user has access to the project has, err := s. - Where("user_id = ? AND list_id = ?", lu.UserID, lu.ListID). - Get(&ListUser{}) + Where("user_id = ? AND project_id = ?", lu.UserID, lu.ProjectID). + Get(&ProjectUser{}) if err != nil { return } if !has { - return ErrUserDoesNotHaveAccessToList{ListID: lu.ListID, UserID: lu.UserID} + return ErrUserDoesNotHaveAccessToProject{ProjectID: lu.ProjectID, UserID: lu.UserID} } _, err = s. - Where("user_id = ? AND list_id = ?", lu.UserID, lu.ListID). - Delete(&ListUser{}) + Where("user_id = ? AND project_id = ?", lu.UserID, lu.ProjectID). + Delete(&ProjectUser{}) if err != nil { return err } - err = updateListLastUpdated(s, &List{ID: lu.ListID}) + err = updateProjectLastUpdated(s, &Project{ID: lu.ProjectID}) return } -// ReadAll gets all users who have access to a list -// @Summary Get users on a list -// @Description Returns a list with all users which have access on a given list. +// ReadAll gets all users who have access to a project +// @Summary Get users on a project +// @Description Returns a project with all users which have access on a given project. // @tags sharing // @Accept json // @Produce json -// @Param id path int true "List ID" +// @Param id path int true "Project ID" // @Param page query int false "The page number. Used for pagination. If not provided, the first page of results is returned." // @Param per_page query int false "The maximum number of items per page. Note this parameter is limited by the configured maximum of items per page." // @Param s query string false "Search users by its name." // @Security JWTKeyAuth // @Success 200 {array} models.UserWithRight "The users with the right they have." -// @Failure 403 {object} web.HTTPError "No right to see the list." +// @Failure 403 {object} web.HTTPError "No right to see the project." // @Failure 500 {object} models.Message "Internal error" -// @Router /lists/{id}/users [get] -func (lu *ListUser) ReadAll(s *xorm.Session, a web.Auth, search string, page int, perPage int) (result interface{}, resultCount int, numberOfTotalItems int64, err error) { - // Check if the user has access to the list - l := &List{ID: lu.ListID} +// @Router /projects/{id}/users [get] +func (lu *ProjectUser) ReadAll(s *xorm.Session, a web.Auth, search string, page int, perPage int) (result interface{}, resultCount int, numberOfTotalItems int64, err error) { + // Check if the user has access to the project + l := &Project{ID: lu.ProjectID} canRead, _, err := l.CanRead(s, a) if err != nil { return nil, 0, 0, err } if !canRead { - return nil, 0, 0, ErrNeedToHaveListReadAccess{UserID: a.GetID(), ListID: lu.ListID} + return nil, 0, 0, ErrNeedToHaveProjectReadAccess{UserID: a.GetID(), ProjectID: lu.ProjectID} } limit, start := getLimitFromPageIndex(page, perPage) @@ -204,8 +204,8 @@ func (lu *ListUser) ReadAll(s *xorm.Session, a web.Auth, search string, page int // Get all users all := []*UserWithRight{} query := s. - Join("INNER", "users_lists", "user_id = users.id"). - Where("users_lists.list_id = ?", lu.ListID). + Join("INNER", "users_projects", "user_id = users.id"). + Where("users_projects.project_id = ?", lu.ProjectID). Where(db.ILIKE("users.username", search)) if limit > 0 { query = query.Limit(limit, start) @@ -221,30 +221,30 @@ func (lu *ListUser) ReadAll(s *xorm.Session, a web.Auth, search string, page int } numberOfTotalItems, err = s. - Join("INNER", "users_lists", "user_id = users.id"). - Where("users_lists.list_id = ?", lu.ListID). + Join("INNER", "users_projects", "user_id = users.id"). + Where("users_projects.project_id = ?", lu.ProjectID). Where("users.username LIKE ?", "%"+search+"%"). Count(&UserWithRight{}) return all, len(all), numberOfTotalItems, err } -// Update updates a user <-> list relation -// @Summary Update a user <-> list relation -// @Description Update a user <-> list relation. Mostly used to update the right that user has. +// Update updates a user <-> project relation +// @Summary Update a user <-> project relation +// @Description Update a user <-> project relation. Mostly used to update the right that user has. // @tags sharing // @Accept json // @Produce json -// @Param listID path int true "List ID" +// @Param projectID path int true "Project ID" // @Param userID path int true "User ID" -// @Param list body models.ListUser true "The user you want to update." +// @Param project body models.ProjectUser true "The user you want to update." // @Security JWTKeyAuth -// @Success 200 {object} models.ListUser "The updated user <-> list relation." -// @Failure 403 {object} web.HTTPError "The user does not have admin-access to the list" -// @Failure 404 {object} web.HTTPError "User or list does not exist." +// @Success 200 {object} models.ProjectUser "The updated user <-> project relation." +// @Failure 403 {object} web.HTTPError "The user does not have admin-access to the project" +// @Failure 404 {object} web.HTTPError "User or project does not exist." // @Failure 500 {object} models.Message "Internal error" -// @Router /lists/{listID}/users/{userID} [post] -func (lu *ListUser) Update(s *xorm.Session, a web.Auth) (err error) { +// @Router /projects/{projectID}/users/{userID} [post] +func (lu *ProjectUser) Update(s *xorm.Session, a web.Auth) (err error) { // Check if the right is valid if err := lu.Right.isValid(); err != nil { @@ -259,13 +259,13 @@ func (lu *ListUser) Update(s *xorm.Session, a web.Auth) (err error) { lu.UserID = u.ID _, err = s. - Where("list_id = ? AND user_id = ?", lu.ListID, lu.UserID). + Where("project_id = ? AND user_id = ?", lu.ProjectID, lu.UserID). Cols("right"). Update(lu) if err != nil { return err } - err = updateListLastUpdated(s, &List{ID: lu.ListID}) + err = updateProjectLastUpdated(s, &Project{ID: lu.ProjectID}) return } diff --git a/pkg/models/list_users_rights.go b/pkg/models/list_users_rights.go index 3acbe7615..8c0ea5004 100644 --- a/pkg/models/list_users_rights.go +++ b/pkg/models/list_users_rights.go @@ -21,28 +21,28 @@ import ( "xorm.io/xorm" ) -// CanCreate checks if the user can create a new user <-> list relation -func (lu *ListUser) CanCreate(s *xorm.Session, a web.Auth) (bool, error) { - return lu.canDoListUser(s, a) +// CanCreate checks if the user can create a new user <-> project relation +func (lu *ProjectUser) CanCreate(s *xorm.Session, a web.Auth) (bool, error) { + return lu.canDoProjectUser(s, a) } -// CanDelete checks if the user can delete a user <-> list relation -func (lu *ListUser) CanDelete(s *xorm.Session, a web.Auth) (bool, error) { - return lu.canDoListUser(s, a) +// CanDelete checks if the user can delete a user <-> project relation +func (lu *ProjectUser) CanDelete(s *xorm.Session, a web.Auth) (bool, error) { + return lu.canDoProjectUser(s, a) } -// CanUpdate checks if the user can update a user <-> list relation -func (lu *ListUser) CanUpdate(s *xorm.Session, a web.Auth) (bool, error) { - return lu.canDoListUser(s, a) +// CanUpdate checks if the user can update a user <-> project relation +func (lu *ProjectUser) CanUpdate(s *xorm.Session, a web.Auth) (bool, error) { + return lu.canDoProjectUser(s, a) } -func (lu *ListUser) canDoListUser(s *xorm.Session, a web.Auth) (bool, error) { +func (lu *ProjectUser) canDoProjectUser(s *xorm.Session, a web.Auth) (bool, error) { // Link shares aren't allowed to do anything if _, is := a.(*LinkSharing); is { return false, nil } - // Get the list and check if the user has write access on it - l := List{ID: lu.ListID} + // Get the project and check if the user has write access on it + l := Project{ID: lu.ProjectID} return l.IsAdmin(s, a) } diff --git a/pkg/models/list_users_rights_test.go b/pkg/models/list_users_rights_test.go index d979881ee..c0b96bb7a 100644 --- a/pkg/models/list_users_rights_test.go +++ b/pkg/models/list_users_rights_test.go @@ -26,16 +26,16 @@ import ( "code.vikunja.io/web" ) -func TestListUser_CanDoSomething(t *testing.T) { +func TestProjectUser_CanDoSomething(t *testing.T) { type fields struct { - ID int64 - UserID int64 - ListID int64 - Right Right - Created time.Time - Updated time.Time - CRUDable web.CRUDable - Rights web.Rights + ID int64 + UserID int64 + ProjectID int64 + Right Right + Created time.Time + Updated time.Time + CRUDable web.CRUDable + Rights web.Rights } type args struct { a web.Auth @@ -49,7 +49,7 @@ func TestListUser_CanDoSomething(t *testing.T) { { name: "CanDoSomething Normally", fields: fields{ - ListID: 3, + ProjectID: 3, }, args: args{ a: &user.User{ID: 3}, @@ -57,9 +57,9 @@ func TestListUser_CanDoSomething(t *testing.T) { want: map[string]bool{"CanCreate": true, "CanDelete": true, "CanUpdate": true}, }, { - name: "CanDoSomething for a nonexistant list", + name: "CanDoSomething for a nonexistant project", fields: fields{ - ListID: 300, + ProjectID: 300, }, args: args{ a: &user.User{ID: 3}, @@ -69,7 +69,7 @@ func TestListUser_CanDoSomething(t *testing.T) { { name: "CanDoSomething where the user does not have the rights", fields: fields{ - ListID: 3, + ProjectID: 3, }, args: args{ a: &user.User{ID: 4}, @@ -82,24 +82,24 @@ func TestListUser_CanDoSomething(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() - lu := &ListUser{ - ID: tt.fields.ID, - UserID: tt.fields.UserID, - ListID: tt.fields.ListID, - Right: tt.fields.Right, - Created: tt.fields.Created, - Updated: tt.fields.Updated, - CRUDable: tt.fields.CRUDable, - Rights: tt.fields.Rights, + lu := &ProjectUser{ + ID: tt.fields.ID, + UserID: tt.fields.UserID, + ProjectID: tt.fields.ProjectID, + Right: tt.fields.Right, + Created: tt.fields.Created, + Updated: tt.fields.Updated, + CRUDable: tt.fields.CRUDable, + Rights: tt.fields.Rights, } if got, _ := lu.CanCreate(s, tt.args.a); got != tt.want["CanCreate"] { - t.Errorf("ListUser.CanCreate() = %v, want %v", got, tt.want["CanCreate"]) + t.Errorf("ProjectUser.CanCreate() = %v, want %v", got, tt.want["CanCreate"]) } if got, _ := lu.CanDelete(s, tt.args.a); got != tt.want["CanDelete"] { - t.Errorf("ListUser.CanDelete() = %v, want %v", got, tt.want["CanDelete"]) + t.Errorf("ProjectUser.CanDelete() = %v, want %v", got, tt.want["CanDelete"]) } if got, _ := lu.CanUpdate(s, tt.args.a); got != tt.want["CanUpdate"] { - t.Errorf("ListUser.CanUpdate() = %v, want %v", got, tt.want["CanUpdate"]) + t.Errorf("ProjectUser.CanUpdate() = %v, want %v", got, tt.want["CanUpdate"]) } _ = s.Close() }) diff --git a/pkg/models/list_users_test.go b/pkg/models/list_users_test.go index 7ba9d4437..69d2d97a7 100644 --- a/pkg/models/list_users_test.go +++ b/pkg/models/list_users_test.go @@ -29,17 +29,17 @@ import ( "gopkg.in/d4l3k/messagediff.v1" ) -func TestListUser_Create(t *testing.T) { +func TestProjectUser_Create(t *testing.T) { type fields struct { - ID int64 - UserID int64 - Username string - ListID int64 - Right Right - Created time.Time - Updated time.Time - CRUDable web.CRUDable - Rights web.Rights + ID int64 + UserID int64 + Username string + ProjectID int64 + Right Right + Created time.Time + Updated time.Time + CRUDable web.CRUDable + Rights web.Rights } type args struct { a web.Auth @@ -52,54 +52,54 @@ func TestListUser_Create(t *testing.T) { errType func(err error) bool }{ { - name: "ListUsers Create normally", + name: "ProjectUsers Create normally", fields: fields{ - Username: "user1", - ListID: 2, + Username: "user1", + ProjectID: 2, }, }, { - name: "ListUsers Create for duplicate", + name: "ProjectUsers Create for duplicate", fields: fields{ - Username: "user1", - ListID: 3, + Username: "user1", + ProjectID: 3, }, wantErr: true, errType: IsErrUserAlreadyHasAccess, }, { - name: "ListUsers Create with invalid right", + name: "ProjectUsers Create with invalid right", fields: fields{ - Username: "user1", - ListID: 2, - Right: 500, + Username: "user1", + ProjectID: 2, + Right: 500, }, wantErr: true, errType: IsErrInvalidRight, }, { - name: "ListUsers Create with inexisting list", + name: "ProjectUsers Create with inexisting project", fields: fields{ - Username: "user1", - ListID: 2000, + Username: "user1", + ProjectID: 2000, }, wantErr: true, - errType: IsErrListDoesNotExist, + errType: IsErrProjectDoesNotExist, }, { - name: "ListUsers Create with inexisting user", + name: "ProjectUsers Create with inexisting user", fields: fields{ - Username: "user500", - ListID: 2, + Username: "user500", + ProjectID: 2, }, wantErr: true, errType: user.IsErrUserDoesNotExist, }, { - name: "ListUsers Create with the owner as shared user", + name: "ProjectUsers Create with the owner as shared user", fields: fields{ - Username: "user1", - ListID: 1, + Username: "user1", + ProjectID: 1, }, wantErr: true, errType: IsErrUserAlreadyHasAccess, @@ -110,39 +110,39 @@ func TestListUser_Create(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() - ul := &ListUser{ - ID: tt.fields.ID, - UserID: tt.fields.UserID, - Username: tt.fields.Username, - ListID: tt.fields.ListID, - Right: tt.fields.Right, - Created: tt.fields.Created, - Updated: tt.fields.Updated, - CRUDable: tt.fields.CRUDable, - Rights: tt.fields.Rights, + ul := &ProjectUser{ + ID: tt.fields.ID, + UserID: tt.fields.UserID, + Username: tt.fields.Username, + ProjectID: tt.fields.ProjectID, + Right: tt.fields.Right, + Created: tt.fields.Created, + Updated: tt.fields.Updated, + CRUDable: tt.fields.CRUDable, + Rights: tt.fields.Rights, } err := ul.Create(s, tt.args.a) if (err != nil) != tt.wantErr { - t.Errorf("ListUser.Create() error = %v, wantErr %v", err, tt.wantErr) + t.Errorf("ProjectUser.Create() error = %v, wantErr %v", err, tt.wantErr) } if (err != nil) && tt.wantErr && !tt.errType(err) { - t.Errorf("ListUser.Create() Wrong error type! Error = %v, want = %v", err, runtime.FuncForPC(reflect.ValueOf(tt.errType).Pointer()).Name()) + t.Errorf("ProjectUser.Create() Wrong error type! Error = %v, want = %v", err, runtime.FuncForPC(reflect.ValueOf(tt.errType).Pointer()).Name()) } err = s.Commit() assert.NoError(t, err) if !tt.wantErr { - db.AssertExists(t, "users_lists", map[string]interface{}{ - "user_id": ul.UserID, - "list_id": tt.fields.ListID, + db.AssertExists(t, "users_projects", map[string]interface{}{ + "user_id": ul.UserID, + "project_id": tt.fields.ProjectID, }, false) } }) } } -func TestListUser_ReadAll(t *testing.T) { +func TestProjectUser_ReadAll(t *testing.T) { user1Read := &UserWithRight{ User: user.User{ ID: 1, @@ -173,14 +173,14 @@ func TestListUser_ReadAll(t *testing.T) { } type fields struct { - ID int64 - UserID int64 - ListID int64 - Right Right - Created time.Time - Updated time.Time - CRUDable web.CRUDable - Rights web.Rights + ID int64 + UserID int64 + ProjectID int64 + Right Right + Created time.Time + Updated time.Time + CRUDable web.CRUDable + Rights web.Rights } type args struct { search string @@ -198,7 +198,7 @@ func TestListUser_ReadAll(t *testing.T) { { name: "Test readall normal", fields: fields{ - ListID: 3, + ProjectID: 3, }, args: args{ a: &user.User{ID: 3}, @@ -209,20 +209,20 @@ func TestListUser_ReadAll(t *testing.T) { }, }, { - name: "Test ReadAll by a user who does not have access to the list", + name: "Test ReadAll by a user who does not have access to the project", fields: fields{ - ListID: 3, + ProjectID: 3, }, args: args{ a: &user.User{ID: 4}, }, wantErr: true, - errType: IsErrNeedToHaveListReadAccess, + errType: IsErrNeedToHaveProjectReadAccess, }, { name: "Search", fields: fields{ - ListID: 3, + ProjectID: 3, }, args: args{ a: &user.User{ID: 3}, @@ -238,41 +238,41 @@ func TestListUser_ReadAll(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() - ul := &ListUser{ - ID: tt.fields.ID, - UserID: tt.fields.UserID, - ListID: tt.fields.ListID, - Right: tt.fields.Right, - Created: tt.fields.Created, - Updated: tt.fields.Updated, - CRUDable: tt.fields.CRUDable, - Rights: tt.fields.Rights, + ul := &ProjectUser{ + ID: tt.fields.ID, + UserID: tt.fields.UserID, + ProjectID: tt.fields.ProjectID, + Right: tt.fields.Right, + Created: tt.fields.Created, + Updated: tt.fields.Updated, + CRUDable: tt.fields.CRUDable, + Rights: tt.fields.Rights, } got, _, _, err := ul.ReadAll(s, tt.args.a, tt.args.search, tt.args.page, 50) if (err != nil) != tt.wantErr { - t.Errorf("ListUser.ReadAll() error = %v, wantErr %v", err, tt.wantErr) + t.Errorf("ProjectUser.ReadAll() error = %v, wantErr %v", err, tt.wantErr) } if (err != nil) && tt.wantErr && !tt.errType(err) { - t.Errorf("ListUser.ReadAll() Wrong error type! Error = %v, want = %v", err, runtime.FuncForPC(reflect.ValueOf(tt.errType).Pointer()).Name()) + t.Errorf("ProjectUser.ReadAll() Wrong error type! Error = %v, want = %v", err, runtime.FuncForPC(reflect.ValueOf(tt.errType).Pointer()).Name()) } if diff, equal := messagediff.PrettyDiff(got, tt.want); !equal { - t.Errorf("ListUser.ReadAll() = %v, want %v, diff: %v", got, tt.want, diff) + t.Errorf("ProjectUser.ReadAll() = %v, want %v, diff: %v", got, tt.want, diff) } _ = s.Close() }) } } -func TestListUser_Update(t *testing.T) { +func TestProjectUser_Update(t *testing.T) { type fields struct { - ID int64 - Username string - ListID int64 - Right Right - Created time.Time - Updated time.Time - CRUDable web.CRUDable - Rights web.Rights + ID int64 + Username string + ProjectID int64 + Right Right + Created time.Time + Updated time.Time + CRUDable web.CRUDable + Rights web.Rights } tests := []struct { name string @@ -283,33 +283,33 @@ func TestListUser_Update(t *testing.T) { { name: "Test Update Normally", fields: fields{ - ListID: 3, - Username: "user1", - Right: RightAdmin, + ProjectID: 3, + Username: "user1", + Right: RightAdmin, }, }, { name: "Test Update to write", fields: fields{ - ListID: 3, - Username: "user1", - Right: RightWrite, + ProjectID: 3, + Username: "user1", + Right: RightWrite, }, }, { name: "Test Update to Read", fields: fields{ - ListID: 3, - Username: "user1", - Right: RightRead, + ProjectID: 3, + Username: "user1", + Right: RightRead, }, }, { name: "Test Update with invalid right", fields: fields{ - ListID: 3, - Username: "user1", - Right: 500, + ProjectID: 3, + Username: "user1", + Right: 500, }, wantErr: true, errType: IsErrInvalidRight, @@ -320,49 +320,49 @@ func TestListUser_Update(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() - lu := &ListUser{ - ID: tt.fields.ID, - Username: tt.fields.Username, - ListID: tt.fields.ListID, - Right: tt.fields.Right, - Created: tt.fields.Created, - Updated: tt.fields.Updated, - CRUDable: tt.fields.CRUDable, - Rights: tt.fields.Rights, + lu := &ProjectUser{ + ID: tt.fields.ID, + Username: tt.fields.Username, + ProjectID: tt.fields.ProjectID, + Right: tt.fields.Right, + Created: tt.fields.Created, + Updated: tt.fields.Updated, + CRUDable: tt.fields.CRUDable, + Rights: tt.fields.Rights, } err := lu.Update(s, &user.User{ID: 1}) if (err != nil) != tt.wantErr { - t.Errorf("ListUser.Update() error = %v, wantErr %v", err, tt.wantErr) + t.Errorf("ProjectUser.Update() error = %v, wantErr %v", err, tt.wantErr) } if (err != nil) && tt.wantErr && !tt.errType(err) { - t.Errorf("ListUser.Update() Wrong error type! Error = %v, want = %v", err, runtime.FuncForPC(reflect.ValueOf(tt.errType).Pointer()).Name()) + t.Errorf("ProjectUser.Update() Wrong error type! Error = %v, want = %v", err, runtime.FuncForPC(reflect.ValueOf(tt.errType).Pointer()).Name()) } err = s.Commit() assert.NoError(t, err) if !tt.wantErr { - db.AssertExists(t, "users_lists", map[string]interface{}{ - "list_id": tt.fields.ListID, - "user_id": lu.UserID, - "right": tt.fields.Right, + db.AssertExists(t, "users_projects", map[string]interface{}{ + "project_id": tt.fields.ProjectID, + "user_id": lu.UserID, + "right": tt.fields.Right, }, false) } }) } } -func TestListUser_Delete(t *testing.T) { +func TestProjectUser_Delete(t *testing.T) { type fields struct { - ID int64 - Username string - UserID int64 - ListID int64 - Right Right - Created time.Time - Updated time.Time - CRUDable web.CRUDable - Rights web.Rights + ID int64 + Username string + UserID int64 + ProjectID int64 + Right Right + Created time.Time + Updated time.Time + CRUDable web.CRUDable + Rights web.Rights } tests := []struct { name string @@ -373,8 +373,8 @@ func TestListUser_Delete(t *testing.T) { { name: "Try deleting some unexistant user", fields: fields{ - Username: "user1000", - ListID: 2, + Username: "user1000", + ProjectID: 2, }, wantErr: true, errType: user.IsErrUserDoesNotExist, @@ -382,18 +382,18 @@ func TestListUser_Delete(t *testing.T) { { name: "Try deleting a user which does not has access but exists", fields: fields{ - Username: "user1", - ListID: 4, + Username: "user1", + ProjectID: 4, }, wantErr: true, - errType: IsErrUserDoesNotHaveAccessToList, + errType: IsErrUserDoesNotHaveAccessToProject, }, { name: "Try deleting normally", fields: fields{ - Username: "user1", - UserID: 1, - ListID: 3, + Username: "user1", + UserID: 1, + ProjectID: 3, }, }, } @@ -402,31 +402,31 @@ func TestListUser_Delete(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() - lu := &ListUser{ - ID: tt.fields.ID, - Username: tt.fields.Username, - ListID: tt.fields.ListID, - Right: tt.fields.Right, - Created: tt.fields.Created, - Updated: tt.fields.Updated, - CRUDable: tt.fields.CRUDable, - Rights: tt.fields.Rights, + lu := &ProjectUser{ + ID: tt.fields.ID, + Username: tt.fields.Username, + ProjectID: tt.fields.ProjectID, + Right: tt.fields.Right, + Created: tt.fields.Created, + Updated: tt.fields.Updated, + CRUDable: tt.fields.CRUDable, + Rights: tt.fields.Rights, } err := lu.Delete(s, &user.User{ID: 1}) if (err != nil) != tt.wantErr { - t.Errorf("ListUser.Delete() error = %v, wantErr %v", err, tt.wantErr) + t.Errorf("ProjectUser.Delete() error = %v, wantErr %v", err, tt.wantErr) } if (err != nil) && tt.wantErr && !tt.errType(err) { - t.Errorf("ListUser.Delete() Wrong error type! Error = %v, want = %v", err, runtime.FuncForPC(reflect.ValueOf(tt.errType).Pointer()).Name()) + t.Errorf("ProjectUser.Delete() Wrong error type! Error = %v, want = %v", err, runtime.FuncForPC(reflect.ValueOf(tt.errType).Pointer()).Name()) } err = s.Commit() assert.NoError(t, err) if !tt.wantErr { - db.AssertMissing(t, "users_lists", map[string]interface{}{ - "user_id": tt.fields.UserID, - "list_id": tt.fields.ListID, + db.AssertMissing(t, "users_projects", map[string]interface{}{ + "user_id": tt.fields.UserID, + "project_id": tt.fields.ProjectID, }) } }) diff --git a/pkg/models/listeners.go b/pkg/models/listeners.go index d07de9ab4..f4dcfcd91 100644 --- a/pkg/models/listeners.go +++ b/pkg/models/listeners.go @@ -33,8 +33,8 @@ import ( // RegisterListeners registers all event listeners func RegisterListeners() { - events.RegisterListener((&ListCreatedEvent{}).Name(), &IncreaseListCounter{}) - events.RegisterListener((&ListDeletedEvent{}).Name(), &DecreaseListCounter{}) + events.RegisterListener((&ProjectCreatedEvent{}).Name(), &IncreaseProjectCounter{}) + events.RegisterListener((&ProjectDeletedEvent{}).Name(), &DecreaseProjectCounter{}) events.RegisterListener((&NamespaceCreatedEvent{}).Name(), &IncreaseNamespaceCounter{}) events.RegisterListener((&NamespaceDeletedEvent{}).Name(), &DecreaseNamespaceCounter{}) events.RegisterListener((&TaskCreatedEvent{}).Name(), &IncreaseTaskCounter{}) @@ -44,7 +44,7 @@ func RegisterListeners() { events.RegisterListener((&TaskCommentCreatedEvent{}).Name(), &SendTaskCommentNotification{}) events.RegisterListener((&TaskAssigneeCreatedEvent{}).Name(), &SendTaskAssignedNotification{}) events.RegisterListener((&TaskDeletedEvent{}).Name(), &SendTaskDeletedNotification{}) - events.RegisterListener((&ListCreatedEvent{}).Name(), &SendListCreatedNotification{}) + events.RegisterListener((&ProjectCreatedEvent{}).Name(), &SendProjectCreatedNotification{}) events.RegisterListener((&TaskAssigneeCreatedEvent{}).Name(), &SubscribeAssigneeToTask{}) events.RegisterListener((&TeamMemberAddedEvent{}).Name(), &SendTeamMemberAddedNotification{}) events.RegisterListener((&TaskCommentUpdatedEvent{}).Name(), &HandleTaskCommentEditMentions{}) @@ -471,42 +471,42 @@ func (s *HandleTaskUpdateLastUpdated) Handle(msg *message.Message) (err error) { } /////// -// List Event Listeners +// Project Event Listeners -type IncreaseListCounter struct { +type IncreaseProjectCounter struct { } -func (s *IncreaseListCounter) Name() string { - return "list.counter.increase" +func (s *IncreaseProjectCounter) Name() string { + return "project.counter.increase" } -func (s *IncreaseListCounter) Handle(msg *message.Message) (err error) { - return keyvalue.IncrBy(metrics.ListCountKey, 1) +func (s *IncreaseProjectCounter) Handle(msg *message.Message) (err error) { + return keyvalue.IncrBy(metrics.ProjectCountKey, 1) } -type DecreaseListCounter struct { +type DecreaseProjectCounter struct { } -func (s *DecreaseListCounter) Name() string { - return "list.counter.decrease" +func (s *DecreaseProjectCounter) Name() string { + return "project.counter.decrease" } -func (s *DecreaseListCounter) Handle(msg *message.Message) (err error) { - return keyvalue.DecrBy(metrics.ListCountKey, 1) +func (s *DecreaseProjectCounter) Handle(msg *message.Message) (err error) { + return keyvalue.DecrBy(metrics.ProjectCountKey, 1) } -// SendListCreatedNotification represents a listener -type SendListCreatedNotification struct { +// SendProjectCreatedNotification represents a listener +type SendProjectCreatedNotification struct { } -// Name defines the name for the SendListCreatedNotification listener -func (s *SendListCreatedNotification) Name() string { - return "send.list.created.notification" +// Name defines the name for the SendProjectCreatedNotification listener +func (s *SendProjectCreatedNotification) Name() string { + return "send.project.created.notification" } -// Handle is executed when the event SendListCreatedNotification listens on is fired -func (s *SendListCreatedNotification) Handle(msg *message.Message) (err error) { - event := &ListCreatedEvent{} +// Handle is executed when the event SendProjectCreatedNotification listens on is fired +func (s *SendProjectCreatedNotification) Handle(msg *message.Message) (err error) { + event := &ProjectCreatedEvent{} err = json.Unmarshal(msg.Payload, event) if err != nil { return err @@ -515,21 +515,21 @@ func (s *SendListCreatedNotification) Handle(msg *message.Message) (err error) { sess := db.NewSession() defer sess.Close() - subscribers, err := getSubscribersForEntity(sess, SubscriptionEntityList, event.List.ID) + subscribers, err := getSubscribersForEntity(sess, SubscriptionEntityProject, event.Project.ID) if err != nil { return err } - log.Debugf("Sending list created notifications to %d subscribers for list %d", len(subscribers), event.List.ID) + log.Debugf("Sending project created notifications to %d subscribers for project %d", len(subscribers), event.Project.ID) for _, subscriber := range subscribers { if subscriber.UserID == event.Doer.ID { continue } - n := &ListCreatedNotification{ - Doer: event.Doer, - List: event.List, + n := &ProjectCreatedNotification{ + Doer: event.Doer, + Project: event.Project, } err = notifications.Notify(subscriber.User, n) if err != nil { diff --git a/pkg/models/mentions_test.go b/pkg/models/mentions_test.go index d42e639b1..e608ec239 100644 --- a/pkg/models/mentions_test.go +++ b/pkg/models/mentions_test.go @@ -103,7 +103,7 @@ func TestSendingMentionNotification(t *testing.T) { assert.NoError(t, err) tc := &TaskComment{ Comment: "Lorem Ipsum @user1 @user2 @user3 @user4 @user5 @user6", - TaskID: 32, // user2 has access to the list that task belongs to + TaskID: 32, // user2 has access to the project that task belongs to } err = tc.Create(s, u) assert.NoError(t, err) @@ -156,7 +156,7 @@ func TestSendingMentionNotification(t *testing.T) { assert.NoError(t, err) tc := &TaskComment{ Comment: "Lorem Ipsum @user2", - TaskID: 32, // user2 has access to the list that task belongs to + TaskID: 32, // user2 has access to the project that task belongs to } err = tc.Create(s, u) assert.NoError(t, err) diff --git a/pkg/models/models.go b/pkg/models/models.go index 6f5e96395..66191e1f0 100644 --- a/pkg/models/models.go +++ b/pkg/models/models.go @@ -39,14 +39,14 @@ var ( // GetTables returns all structs which are also a table. func GetTables() []interface{} { return []interface{}{ - &List{}, + &Project{}, &Task{}, &Team{}, &TeamMember{}, - &TeamList{}, + &TeamProject{}, &TeamNamespace{}, &Namespace{}, - &ListUser{}, + &ProjectUser{}, &NamespaceUser{}, &TaskAssginee{}, &Label{}, diff --git a/pkg/models/namespace.go b/pkg/models/namespace.go index d8c78847f..c78a23096 100644 --- a/pkg/models/namespace.go +++ b/pkg/models/namespace.go @@ -61,27 +61,27 @@ type Namespace struct { // A timestamp when this namespace was last updated. You cannot change this value. Updated time.Time `xorm:"updated not null" json:"updated"` - // If set to true, will only return the namespaces, not their lists. + // If set to true, will only return the namespaces, not their projects. NamespacesOnly bool `xorm:"-" json:"-" query:"namespaces_only"` web.CRUDable `xorm:"-" json:"-"` web.Rights `xorm:"-" json:"-"` } -// SharedListsPseudoNamespace is a pseudo namespace used to hold shared lists -var SharedListsPseudoNamespace = Namespace{ +// SharedProjectsPseudoNamespace is a pseudo namespace used to hold shared projects +var SharedProjectsPseudoNamespace = Namespace{ ID: -1, - Title: "Shared Lists", - Description: "Lists of other users shared with you via teams or directly.", + Title: "Shared Projects", + Description: "Projects of other users shared with you via teams or directly.", Created: time.Now(), Updated: time.Now(), } -// FavoritesPseudoNamespace is a pseudo namespace used to hold favorited lists and tasks +// FavoritesPseudoNamespace is a pseudo namespace used to hold favorited projects and tasks var FavoritesPseudoNamespace = Namespace{ ID: -2, Title: "Favorites", - Description: "Favorite lists and tasks.", + Description: "Favorite projects and tasks.", Created: time.Now(), Updated: time.Now(), } @@ -106,9 +106,9 @@ func getNamespaceSimpleByID(s *xorm.Session, id int64) (namespace *Namespace, er return nil, ErrNamespaceDoesNotExist{ID: id} } - // Get the namesapce with shared lists + // Get the namesapce with shared projects if id == -1 { - return &SharedListsPseudoNamespace, nil + return &SharedProjectsPseudoNamespace, nil } if id == FavoritesPseudoNamespace.ID { @@ -181,24 +181,24 @@ func (n *Namespace) ReadOne(s *xorm.Session, a web.Auth) (err error) { return } -// NamespaceWithLists represents a namespace with list meta informations -type NamespaceWithLists struct { +// NamespaceWithProjects represents a namespace with project meta informations +type NamespaceWithProjects struct { Namespace `xorm:"extends"` - Lists []*List `xorm:"-" json:"lists"` + Projects []*Project `xorm:"-" json:"projects"` } -type NamespaceWithListsAndTasks struct { +type NamespaceWithProjectsAndTasks struct { Namespace - Lists []*ListWithTasksAndBuckets `xorm:"-" json:"lists"` + Projects []*ProjectWithTasksAndBuckets `xorm:"-" json:"projects"` } -func makeNamespaceSlice(namespaces map[int64]*NamespaceWithLists, userMap map[int64]*user.User, subscriptions map[int64]*Subscription) []*NamespaceWithLists { - all := make([]*NamespaceWithLists, 0, len(namespaces)) +func makeNamespaceSlice(namespaces map[int64]*NamespaceWithProjects, userMap map[int64]*user.User, subscriptions map[int64]*Subscription) []*NamespaceWithProjects { + all := make([]*NamespaceWithProjects, 0, len(namespaces)) for _, n := range namespaces { n.Owner = userMap[n.OwnerID] n.Subscription = subscriptions[n.ID] all = append(all, n) - for _, l := range n.Lists { + for _, l := range n.Projects { if n.Subscription != nil && l.Subscription == nil { l.Subscription = n.Subscription } @@ -253,7 +253,7 @@ func getNamespaceArchivedCond(archived bool) builder.Cond { return isArchivedCond } -func getNamespacesWithLists(s *xorm.Session, namespaces *map[int64]*NamespaceWithLists, search string, isArchived bool, page, perPage int, userID int64) (numberOfTotalItems int64, err error) { +func getNamespacesWithProjects(s *xorm.Session, namespaces *map[int64]*NamespaceWithProjects, search string, isArchived bool, page, perPage int, userID int64) (numberOfTotalItems int64, err error) { isArchivedCond := getNamespaceArchivedCond(isArchived) filterCond := getNamespaceFilterCond(search) @@ -289,11 +289,11 @@ func getNamespacesWithLists(s *xorm.Session, namespaces *map[int64]*NamespaceWit GroupBy("namespaces.id"). Where(filterCond). Where(isArchivedCond). - Count(&NamespaceWithLists{}) + Count(&NamespaceWithProjects{}) return numberOfTotalItems, err } -func getNamespaceOwnerIDs(namespaces map[int64]*NamespaceWithLists) (namespaceIDs, ownerIDs []int64) { +func getNamespaceOwnerIDs(namespaces map[int64]*NamespaceWithProjects) (namespaceIDs, ownerIDs []int64) { for _, nsp := range namespaces { namespaceIDs = append(namespaceIDs, nsp.ID) ownerIDs = append(ownerIDs, nsp.OwnerID) @@ -324,36 +324,36 @@ func getNamespaceSubscriptions(s *xorm.Session, namespaceIDs []int64, userID int return subscriptionsMap, err } -func getListsForNamespaces(s *xorm.Session, namespaceIDs []int64, archived bool) ([]*List, error) { - lists := []*List{} - listQuery := s. +func getProjectsForNamespaces(s *xorm.Session, namespaceIDs []int64, archived bool) ([]*Project, error) { + projects := []*Project{} + projectQuery := s. OrderBy("position"). In("namespace_id", namespaceIDs) if !archived { - listQuery.And("is_archived = false") + projectQuery.And("is_archived = false") } - err := listQuery.Find(&lists) - return lists, err + err := projectQuery.Find(&projects) + return projects, err } -func getSharedListsInNamespace(s *xorm.Session, archived bool, doer *user.User) (sharedListsNamespace *NamespaceWithLists, err error) { - // Create our pseudo namespace to hold the shared lists - sharedListsPseudonamespace := SharedListsPseudoNamespace - sharedListsPseudonamespace.OwnerID = doer.ID - sharedListsNamespace = &NamespaceWithLists{ - sharedListsPseudonamespace, - []*List{}, +func getSharedProjectsInNamespace(s *xorm.Session, archived bool, doer *user.User) (sharedProjectsNamespace *NamespaceWithProjects, err error) { + // Create our pseudo namespace to hold the shared projects + sharedProjectsPseudonamespace := SharedProjectsPseudoNamespace + sharedProjectsPseudonamespace.OwnerID = doer.ID + sharedProjectsNamespace = &NamespaceWithProjects{ + sharedProjectsPseudonamespace, + []*Project{}, } - // Get all lists individually shared with our user (not via a namespace) - individualLists := []*List{} - iListQuery := s.Select("l.*"). - Table("lists"). + // Get all projects individually shared with our user (not via a namespace) + individualProjects := []*Project{} + iProjectQuery := s.Select("l.*"). + Table("projects"). Alias("l"). - Join("LEFT", []string{"team_lists", "tl"}, "l.id = tl.list_id"). + Join("LEFT", []string{"team_projects", "tl"}, "l.id = tl.project_id"). Join("LEFT", []string{"team_members", "tm"}, "tm.team_id = tl.team_id"). - Join("LEFT", []string{"users_lists", "ul"}, "ul.list_id = l.id"). + Join("LEFT", []string{"users_projects", "ul"}, "ul.project_id = l.id"). Where(builder.And( builder.Eq{"tm.user_id": doer.ID}, builder.Neq{"l.owner_id": doer.ID}, @@ -364,53 +364,53 @@ func getSharedListsInNamespace(s *xorm.Session, archived bool, doer *user.User) )). GroupBy("l.id") if !archived { - iListQuery.And("l.is_archived = false") + iProjectQuery.And("l.is_archived = false") } - err = iListQuery.Find(&individualLists) + err = iProjectQuery.Find(&individualProjects) if err != nil { return } // Make the namespace -1 so we now later which one it was - // + Append it to all lists we already have - for _, l := range individualLists { - l.NamespaceID = sharedListsNamespace.ID + // + Append it to all projects we already have + for _, l := range individualProjects { + l.NamespaceID = sharedProjectsNamespace.ID } - sharedListsNamespace.Lists = individualLists + sharedProjectsNamespace.Projects = individualProjects - // Remove the sharedListsPseudonamespace if we don't have any shared lists - if len(individualLists) == 0 { - sharedListsNamespace = nil + // Remove the sharedProjectsPseudonamespace if we don't have any shared projects + if len(individualProjects) == 0 { + sharedProjectsNamespace = nil } return } -func getFavoriteLists(s *xorm.Session, lists []*List, namespaceIDs []int64, doer *user.User) (favoriteNamespace *NamespaceWithLists, err error) { - // Create our pseudo namespace with favorite lists +func getFavoriteProjects(s *xorm.Session, projects []*Project, namespaceIDs []int64, doer *user.User) (favoriteNamespace *NamespaceWithProjects, err error) { + // Create our pseudo namespace with favorite projects pseudoFavoriteNamespace := FavoritesPseudoNamespace pseudoFavoriteNamespace.OwnerID = doer.ID - favoriteNamespace = &NamespaceWithLists{ + favoriteNamespace = &NamespaceWithProjects{ Namespace: pseudoFavoriteNamespace, - Lists: []*List{{}}, + Projects: []*Project{{}}, } - *favoriteNamespace.Lists[0] = FavoritesPseudoList // Copying the list to be able to modify it later - favoriteNamespace.Lists[0].Owner = doer + *favoriteNamespace.Projects[0] = FavoritesPseudoProject // Copying the project to be able to modify it later + favoriteNamespace.Projects[0].Owner = doer - for _, list := range lists { - if !list.IsFavorite { + for _, project := range projects { + if !project.IsFavorite { continue } - favoriteNamespace.Lists = append(favoriteNamespace.Lists, list) + favoriteNamespace.Projects = append(favoriteNamespace.Projects, project) } - // Check if we have any favorites or favorited lists and remove the favorites namespace from the list if not + // Check if we have any favorites or favorited projects and remove the favorites namespace from the project if not cond := builder. Select("tasks.id"). From("tasks"). - Join("INNER", "lists", "tasks.list_id = lists.id"). - Join("INNER", "namespaces", "lists.namespace_id = namespaces.id"). + Join("INNER", "projects", "tasks.project_id = projects.id"). + Join("INNER", "namespaces", "projects.namespace_id = namespaces.id"). Where(builder.In("namespaces.id", namespaceIDs)) var favoriteCount int64 @@ -425,25 +425,25 @@ func getFavoriteLists(s *xorm.Session, lists []*List, namespaceIDs []int64, doer return } - // If we don't have any favorites in the favorites pseudo list, remove that pseudo list from the namespace + // If we don't have any favorites in the favorites pseudo project, remove that pseudo project from the namespace if favoriteCount == 0 { - for in, l := range favoriteNamespace.Lists { - if l.ID == FavoritesPseudoList.ID { - favoriteNamespace.Lists = append(favoriteNamespace.Lists[:in], favoriteNamespace.Lists[in+1:]...) + for in, l := range favoriteNamespace.Projects { + if l.ID == FavoritesPseudoProject.ID { + favoriteNamespace.Projects = append(favoriteNamespace.Projects[:in], favoriteNamespace.Projects[in+1:]...) break } } } // If we don't have any favorites in the namespace, remove it - if len(favoriteNamespace.Lists) == 0 { + if len(favoriteNamespace.Projects) == 0 { return nil, nil } return } -func getSavedFilters(s *xorm.Session, doer *user.User) (savedFiltersNamespace *NamespaceWithLists, err error) { +func getSavedFilters(s *xorm.Session, doer *user.User) (savedFiltersNamespace *NamespaceWithProjects, err error) { savedFilters, err := getSavedFiltersForUser(s, doer) if err != nil { return @@ -455,16 +455,16 @@ func getSavedFilters(s *xorm.Session, doer *user.User) (savedFiltersNamespace *N savedFiltersPseudoNamespace := SavedFiltersPseudoNamespace savedFiltersPseudoNamespace.OwnerID = doer.ID - savedFiltersNamespace = &NamespaceWithLists{ + savedFiltersNamespace = &NamespaceWithProjects{ Namespace: savedFiltersPseudoNamespace, - Lists: make([]*List, 0, len(savedFilters)), + Projects: make([]*Project, 0, len(savedFilters)), } for _, filter := range savedFilters { - filterList := filter.toList() - filterList.NamespaceID = savedFiltersNamespace.ID - filterList.Owner = doer - savedFiltersNamespace.Lists = append(savedFiltersNamespace.Lists, filterList) + filterProject := filter.toProject() + filterProject.NamespaceID = savedFiltersNamespace.ID + filterProject.Owner = doer + savedFiltersNamespace.Projects = append(savedFiltersNamespace.Projects, filterProject) } return @@ -480,9 +480,9 @@ func getSavedFilters(s *xorm.Session, doer *user.User) (savedFiltersNamespace *N // @Param per_page query int false "The maximum number of items per page. Note this parameter is limited by the configured maximum of items per page." // @Param s query string false "Search namespaces by name." // @Param is_archived query bool false "If true, also returns all archived namespaces." -// @Param namespaces_only query bool false "If true, also returns only namespaces without their lists." +// @Param namespaces_only query bool false "If true, also returns only namespaces without their projects." // @Security JWTKeyAuth -// @Success 200 {array} models.NamespaceWithLists "The Namespaces." +// @Success 200 {array} models.NamespaceWithProjects "The Namespaces." // @Failure 500 {object} models.Message "Internal error" // @Router /namespaces [get] // @@ -492,19 +492,19 @@ func (n *Namespace) ReadAll(s *xorm.Session, a web.Auth, search string, page int return nil, 0, 0, ErrGenericForbidden{} } - // This map will hold all namespaces and their lists. The key is usually the id of the namespace. - // We're using a map here because it makes a few things like adding lists or removing pseudo namespaces easier. - namespaces := make(map[int64]*NamespaceWithLists) + // This map will hold all namespaces and their projects. The key is usually the id of the namespace. + // We're using a map here because it makes a few things like adding projects or removing pseudo namespaces easier. + namespaces := make(map[int64]*NamespaceWithProjects) ////////////////////////////// - // Lists with their namespaces + // Projects with their namespaces doer, err := user.GetFromAuth(a) if err != nil { return nil, 0, 0, err } - numberOfTotalItems, err = getNamespacesWithLists(s, &namespaces, search, n.IsArchived, page, perPage, doer.ID) + numberOfTotalItems, err = getNamespacesWithProjects(s, &namespaces, search, n.IsArchived, page, perPage, doer.ID) if err != nil { return nil, 0, 0, err } @@ -531,23 +531,23 @@ func (n *Namespace) ReadAll(s *xorm.Session, a web.Auth, search string, page int return all, len(all), numberOfTotalItems, nil } - // Get all lists - lists, err := getListsForNamespaces(s, namespaceIDs, n.IsArchived) + // Get all projects + projects, err := getProjectsForNamespaces(s, namespaceIDs, n.IsArchived) if err != nil { return nil, 0, 0, err } /////////////// - // Shared Lists + // Shared Projects - sharedListsNamespace, err := getSharedListsInNamespace(s, n.IsArchived, doer) + sharedProjectsNamespace, err := getSharedProjectsInNamespace(s, n.IsArchived, doer) if err != nil { return nil, 0, 0, err } - if sharedListsNamespace != nil { - namespaces[sharedListsNamespace.ID] = sharedListsNamespace - lists = append(lists, sharedListsNamespace.Lists...) + if sharedProjectsNamespace != nil { + namespaces[sharedProjectsNamespace.ID] = sharedProjectsNamespace + projects = append(projects, sharedProjectsNamespace.Projects...) } ///////////////// @@ -560,20 +560,20 @@ func (n *Namespace) ReadAll(s *xorm.Session, a web.Auth, search string, page int if savedFiltersNamespace != nil { namespaces[savedFiltersNamespace.ID] = savedFiltersNamespace - lists = append(lists, savedFiltersNamespace.Lists...) + projects = append(projects, savedFiltersNamespace.Projects...) } ///////////////// - // Add list details (favorite state, among other things) - err = addListDetails(s, lists, a) + // Add project details (favorite state, among other things) + err = addProjectDetails(s, projects, a) if err != nil { return } ///////////////// - // Favorite lists + // Favorite projects - favoritesNamespace, err := getFavoriteLists(s, lists, namespaceIDs, doer) + favoritesNamespace, err := getFavoriteProjects(s, projects, namespaceIDs, doer) if err != nil { return nil, 0, 0, err } @@ -585,12 +585,12 @@ func (n *Namespace) ReadAll(s *xorm.Session, a web.Auth, search string, page int ////////////////////// // Put it all together - for _, list := range lists { - if list.NamespaceID == SharedListsPseudoNamespace.ID || list.NamespaceID == SavedFiltersPseudoNamespace.ID { - // Shared lists and filtered lists are already in the namespace + for _, project := range projects { + if project.NamespaceID == SharedProjectsPseudoNamespace.ID || project.NamespaceID == SavedFiltersPseudoNamespace.ID { + // Shared projects and filtered projects are already in the namespace continue } - namespaces[list.NamespaceID].Lists = append(namespaces[list.NamespaceID].Lists, list) + namespaces[project.NamespaceID].Projects = append(namespaces[project.NamespaceID].Projects, project) } all := makeNamespaceSlice(namespaces, ownerMap, subscriptionsMap) @@ -663,7 +663,7 @@ func (n *Namespace) Delete(s *xorm.Session, a web.Auth) (err error) { return deleteNamespace(s, n, a, true) } -func deleteNamespace(s *xorm.Session, n *Namespace, a web.Auth, withLists bool) (err error) { +func deleteNamespace(s *xorm.Session, n *Namespace, a web.Auth, withProjects bool) (err error) { // Check if the namespace exists _, err = GetNamespaceByID(s, n.ID) if err != nil { @@ -681,23 +681,23 @@ func deleteNamespace(s *xorm.Session, n *Namespace, a web.Auth, withLists bool) Doer: a, } - if !withLists { + if !withProjects { return events.Dispatch(namespaceDeleted) } - // Delete all lists with their tasks - lists, err := GetListsByNamespaceID(s, n.ID, &user.User{}) + // Delete all projects with their tasks + projects, err := GetProjectsByNamespaceID(s, n.ID, &user.User{}) if err != nil { return } - if len(lists) == 0 { + if len(projects) == 0 { return events.Dispatch(namespaceDeleted) } - // Looping over all lists to let the list handle properly cleaning up the tasks and everything else associated with it. - for _, list := range lists { - err = list.Delete(s, a) + // Looping over all projects to let the project handle properly cleaning up the tasks and everything else associated with it. + for _, project := range projects { + err = project.Delete(s, a) if err != nil { return err } @@ -748,7 +748,7 @@ func (n *Namespace) Update(s *xorm.Session, a web.Auth) (err error) { } } - // We need to specify the cols we want to update here to be able to un-archive lists + // We need to specify the cols we want to update here to be able to un-archive projects colsToUpdate := []string{ "title", "is_archived", diff --git a/pkg/models/namespace_rights.go b/pkg/models/namespace_rights.go index 0d03202cb..36d964897 100644 --- a/pkg/models/namespace_rights.go +++ b/pkg/models/namespace_rights.go @@ -73,7 +73,7 @@ func (n *Namespace) checkRight(s *xorm.Session, a web.Auth, rights ...Right) (bo } if a.GetID() == nn.OwnerID || - nn.ID == SharedListsPseudoNamespace.ID || + nn.ID == SharedProjectsPseudoNamespace.ID || nn.ID == FavoritesPseudoNamespace.ID || nn.ID == SavedFiltersPseudoNamespace.ID { return true, int(RightAdmin), nil @@ -88,7 +88,7 @@ func (n *Namespace) checkRight(s *xorm.Session, a web.Auth, rights ...Right) (bo for each passed right. That way, we can check with a single sql query (instead if 8) - if the user has the right to see the list or not. + if the user has the right to see the project or not. */ var conds []builder.Cond diff --git a/pkg/models/namespace_team_test.go b/pkg/models/namespace_team_test.go index df9323f78..9417df459 100644 --- a/pkg/models/namespace_team_test.go +++ b/pkg/models/namespace_team_test.go @@ -72,7 +72,7 @@ func TestTeamNamespace_ReadAll(t *testing.T) { } db.LoadAndAssertFixtures(t) s := db.NewSession() - teams, _, _, err := tn.ReadAll(s, u, "READ_only_on_list6", 1, 50) + teams, _, _, err := tn.ReadAll(s, u, "READ_only_on_project6", 1, 50) assert.NoError(t, err) assert.Equal(t, reflect.TypeOf(teams).Kind(), reflect.Slice) ts := teams.([]*TeamWithRight) diff --git a/pkg/models/namespace_test.go b/pkg/models/namespace_test.go index cbd4f28a6..3b6e54f51 100644 --- a/pkg/models/namespace_test.go +++ b/pkg/models/namespace_test.go @@ -207,21 +207,21 @@ func TestNamespace_ReadAll(t *testing.T) { n := &Namespace{} nn, _, _, err := n.ReadAll(s, user1, "", 1, -1) assert.NoError(t, err) - namespaces := nn.([]*NamespaceWithLists) + namespaces := nn.([]*NamespaceWithProjects) assert.NotNil(t, namespaces) assert.Len(t, namespaces, 11) // Total of 11 including shared, favorites and saved filters assert.Equal(t, int64(-3), namespaces[0].ID) // The first one should be the one with saved filters assert.Equal(t, int64(-2), namespaces[1].ID) // The second one should be the one with favorites assert.Equal(t, int64(-1), namespaces[2].ID) // The third one should be the one with the shared namespaces - // Ensure every list and namespace are not archived + // Ensure every project and namespace are not archived for _, namespace := range namespaces { assert.False(t, namespace.IsArchived) - for _, list := range namespace.Lists { - assert.False(t, list.IsArchived) + for _, project := range namespace.Projects { + assert.False(t, project.IsArchived) } } }) - t.Run("no own shared lists", func(t *testing.T) { + t.Run("no own shared projects", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() defer s.Close() @@ -229,18 +229,18 @@ func TestNamespace_ReadAll(t *testing.T) { n := &Namespace{} nn, _, _, err := n.ReadAll(s, user6, "", 1, -1) assert.NoError(t, err) - namespaces := nn.([]*NamespaceWithLists) + namespaces := nn.([]*NamespaceWithProjects) assert.NotNil(t, namespaces) assert.Equal(t, int64(-1), namespaces[1].ID) // The third one should be the one with the shared namespaces - sharedListOccurences := make(map[int64]int64) - for _, list := range namespaces[1].Lists { - assert.NotEqual(t, user1.ID, list.OwnerID) - sharedListOccurences[list.ID]++ + sharedProjectOccurences := make(map[int64]int64) + for _, project := range namespaces[1].Projects { + assert.NotEqual(t, user1.ID, project.OwnerID) + sharedProjectOccurences[project.ID]++ } - for listID, occ := range sharedListOccurences { - assert.Equal(t, int64(1), occ, "shared list %d is present %d times, should be 1", listID, occ) + for projectID, occ := range sharedProjectOccurences { + assert.Equal(t, int64(1), occ, "shared project %d is present %d times, should be 1", projectID, occ) } }) t.Run("namespaces only", func(t *testing.T) { @@ -253,12 +253,12 @@ func TestNamespace_ReadAll(t *testing.T) { } nn, _, _, err := n.ReadAll(s, user1, "", 1, -1) assert.NoError(t, err) - namespaces := nn.([]*NamespaceWithLists) + namespaces := nn.([]*NamespaceWithProjects) assert.NotNil(t, namespaces) assert.Len(t, namespaces, 8) // Total of 8 - excluding shared, favorites and saved filters (normally 11) - // Ensure every namespace does not contain lists + // Ensure every namespace does not contain projects for _, namespace := range namespaces { - assert.Nil(t, namespace.Lists) + assert.Nil(t, namespace.Projects) } }) t.Run("ids only", func(t *testing.T) { @@ -271,7 +271,7 @@ func TestNamespace_ReadAll(t *testing.T) { } nn, _, _, err := n.ReadAll(s, user7, "13,14", 1, -1) assert.NoError(t, err) - namespaces := nn.([]*NamespaceWithLists) + namespaces := nn.([]*NamespaceWithProjects) assert.NotNil(t, namespaces) assert.Len(t, namespaces, 2) assert.Equal(t, int64(13), namespaces[0].ID) @@ -287,7 +287,7 @@ func TestNamespace_ReadAll(t *testing.T) { } nn, _, _, err := n.ReadAll(s, user1, "1,w", 1, -1) assert.NoError(t, err) - namespaces := nn.([]*NamespaceWithLists) + namespaces := nn.([]*NamespaceWithProjects) assert.NotNil(t, namespaces) assert.Len(t, namespaces, 1) assert.Equal(t, int64(1), namespaces[0].ID) @@ -301,7 +301,7 @@ func TestNamespace_ReadAll(t *testing.T) { IsArchived: true, } nn, _, _, err := n.ReadAll(s, user1, "", 1, -1) - namespaces := nn.([]*NamespaceWithLists) + namespaces := nn.([]*NamespaceWithProjects) assert.NoError(t, err) assert.NotNil(t, namespaces) assert.Len(t, namespaces, 12) // Total of 12 including shared & favorites, one is archived @@ -316,7 +316,7 @@ func TestNamespace_ReadAll(t *testing.T) { n := &Namespace{} nn, _, _, err := n.ReadAll(s, user11, "", 1, -1) - namespaces := nn.([]*NamespaceWithLists) + namespaces := nn.([]*NamespaceWithProjects) assert.NoError(t, err) // Assert the first namespace is not the favorites namespace assert.NotEqual(t, FavoritesPseudoNamespace.ID, namespaces[0].ID) @@ -328,11 +328,11 @@ func TestNamespace_ReadAll(t *testing.T) { n := &Namespace{} nn, _, _, err := n.ReadAll(s, user12, "", 1, -1) - namespaces := nn.([]*NamespaceWithLists) + namespaces := nn.([]*NamespaceWithProjects) assert.NoError(t, err) - // Assert the first namespace is the favorites namespace and contains lists + // Assert the first namespace is the favorites namespace and contains projects assert.Equal(t, FavoritesPseudoNamespace.ID, namespaces[0].ID) - assert.NotEqual(t, 0, namespaces[0].Lists) + assert.NotEqual(t, 0, namespaces[0].Projects) }) t.Run("no saved filters", func(t *testing.T) { db.LoadAndAssertFixtures(t) @@ -341,7 +341,7 @@ func TestNamespace_ReadAll(t *testing.T) { n := &Namespace{} nn, _, _, err := n.ReadAll(s, user11, "", 1, -1) - namespaces := nn.([]*NamespaceWithLists) + namespaces := nn.([]*NamespaceWithProjects) assert.NoError(t, err) // Assert the first namespace is not the favorites namespace assert.NotEqual(t, SavedFiltersPseudoNamespace.ID, namespaces[0].ID) @@ -364,7 +364,7 @@ func TestNamespace_ReadAll(t *testing.T) { n := &Namespace{} nn, _, _, err := n.ReadAll(s, user6, "NamespACE7", 1, -1) assert.NoError(t, err) - namespaces := nn.([]*NamespaceWithLists) + namespaces := nn.([]*NamespaceWithProjects) assert.NotNil(t, namespaces) assert.Len(t, namespaces, 2) assert.Equal(t, int64(7), namespaces[1].ID) diff --git a/pkg/models/namespace_users_test.go b/pkg/models/namespace_users_test.go index 32f4d8b9d..634e796b8 100644 --- a/pkg/models/namespace_users_test.go +++ b/pkg/models/namespace_users_test.go @@ -79,7 +79,7 @@ func TestNamespaceUser_Create(t *testing.T) { errType: IsErrInvalidRight, }, { - name: "NamespaceUsers Create with inexisting list", + name: "NamespaceUsers Create with inexisting project", fields: fields{ Username: "user1", NamespaceID: 2000, @@ -208,7 +208,7 @@ func TestNamespaceUser_ReadAll(t *testing.T) { }, }, { - name: "Test ReadAll by a user who does not have access to the list", + name: "Test ReadAll by a user who does not have access to the project", fields: fields{ NamespaceID: 3, }, diff --git a/pkg/models/notifications.go b/pkg/models/notifications.go index 8867d0dfd..9daa5d735 100644 --- a/pkg/models/notifications.go +++ b/pkg/models/notifications.go @@ -150,28 +150,28 @@ func (n *TaskDeletedNotification) Name() string { return "task.deleted" } -// ListCreatedNotification represents a ListCreatedNotification notification -type ListCreatedNotification struct { - Doer *user.User `json:"doer"` - List *List `json:"list"` +// ProjectCreatedNotification represents a ProjectCreatedNotification notification +type ProjectCreatedNotification struct { + Doer *user.User `json:"doer"` + Project *Project `json:"project"` } -// ToMail returns the mail notification for ListCreatedNotification -func (n *ListCreatedNotification) ToMail() *notifications.Mail { +// ToMail returns the mail notification for ProjectCreatedNotification +func (n *ProjectCreatedNotification) ToMail() *notifications.Mail { return notifications.NewMail(). - Subject(n.Doer.GetName()+` created the list "`+n.List.Title+`"`). - Line(n.Doer.GetName()+` created the list "`+n.List.Title+`"`). - Action("View List", config.ServiceFrontendurl.GetString()+"lists/") + Subject(n.Doer.GetName()+` created the project "`+n.Project.Title+`"`). + Line(n.Doer.GetName()+` created the project "`+n.Project.Title+`"`). + Action("View Project", config.ServiceFrontendurl.GetString()+"projects/") } -// ToDB returns the ListCreatedNotification notification in a format which can be saved in the db -func (n *ListCreatedNotification) ToDB() interface{} { +// ToDB returns the ProjectCreatedNotification notification in a format which can be saved in the db +func (n *ProjectCreatedNotification) ToDB() interface{} { return n } // Name returns the name of the notification -func (n *ListCreatedNotification) Name() string { - return "list.created" +func (n *ProjectCreatedNotification) Name() string { + return "project.created" } // TeamMemberAddedNotification represents a TeamMemberAddedNotification notification diff --git a/pkg/models/rights.go b/pkg/models/rights.go index f4b62a67e..67f3585ec 100644 --- a/pkg/models/rights.go +++ b/pkg/models/rights.go @@ -16,7 +16,7 @@ package models -// Right defines the rights users/teams can have for lists/namespaces +// Right defines the rights users/teams can have for projects/namespaces type Right int // define unknown right @@ -26,11 +26,11 @@ const ( // Enumerate all the team rights const ( - // Can read lists in a + // Can read projects in a RightRead Right = iota - // Can write in a like lists and tasks. Cannot create new lists. + // Can write in a like projects and tasks. Cannot create new projects. RightWrite - // Can manage a list/namespace, can do everything + // Can manage a project/namespace, can do everything RightAdmin ) diff --git a/pkg/models/saved_filters.go b/pkg/models/saved_filters.go index 89f24671c..9c12f62f0 100644 --- a/pkg/models/saved_filters.go +++ b/pkg/models/saved_filters.go @@ -39,7 +39,7 @@ type SavedFilter struct { // The user who owns this filter Owner *user.User `xorm:"-" json:"owner" valid:"-"` - // True if the filter is a favorite. Favorite filters show up in a separate namespace together with favorite lists. + // True if the filter is a favorite. Favorite filters show up in a separate namespace together with favorite projects. IsFavorite bool `xorm:"default false" json:"is_favorite"` // A timestamp when this filter was created. You cannot change this value. @@ -57,28 +57,28 @@ func (sf *SavedFilter) TableName() string { } func (sf *SavedFilter) getTaskCollection() *TaskCollection { - // We're resetting the listID to return tasks from all lists - sf.Filters.ListID = 0 + // We're resetting the projectID to return tasks from all projects + sf.Filters.ProjectID = 0 return sf.Filters } -// Returns the saved filter ID from a list ID. Will not check if the filter actually exists. +// Returns the saved filter ID from a project ID. Will not check if the filter actually exists. // If the returned ID is zero, means that it is probably invalid. -func getSavedFilterIDFromListID(listID int64) (filterID int64) { - // We get the id of the saved filter by multiplying the ListID with -1 and subtracting one - filterID = listID*-1 - 1 - // FilterIDs from listIDs are always positive +func getSavedFilterIDFromProjectID(projectID int64) (filterID int64) { + // We get the id of the saved filter by multiplying the ProjectID with -1 and subtracting one + filterID = projectID*-1 - 1 + // FilterIDs from projectIDs are always positive if filterID < 0 { filterID = 0 } return } -func getListIDFromSavedFilterID(filterID int64) (listID int64) { - listID = filterID*-1 - 1 - // ListIDs from saved filters are always negative - if listID > 0 { - listID = 0 +func getProjectIDFromSavedFilterID(filterID int64) (projectID int64) { + projectID = filterID*-1 - 1 + // ProjectIDs from saved filters are always negative + if projectID > 0 { + projectID = 0 } return } @@ -93,9 +93,9 @@ func getSavedFiltersForUser(s *xorm.Session, auth web.Auth) (filters []*SavedFil return } -func (sf *SavedFilter) toList() *List { - return &List{ - ID: getListIDFromSavedFilterID(sf.ID), +func (sf *SavedFilter) toProject() *Project { + return &Project{ + ID: getProjectIDFromSavedFilterID(sf.ID), Title: sf.Title, Description: sf.Description, IsFavorite: sf.IsFavorite, diff --git a/pkg/models/saved_filters_test.go b/pkg/models/saved_filters_test.go index f72031c25..1a865bed4 100644 --- a/pkg/models/saved_filters_test.go +++ b/pkg/models/saved_filters_test.go @@ -25,21 +25,21 @@ import ( "xorm.io/xorm/schemas" ) -func TestSavedFilter_getListIDFromFilter(t *testing.T) { +func TestSavedFilter_getProjectIDFromFilter(t *testing.T) { t.Run("normal", func(t *testing.T) { - assert.Equal(t, int64(-2), getListIDFromSavedFilterID(1)) + assert.Equal(t, int64(-2), getProjectIDFromSavedFilterID(1)) }) t.Run("invalid", func(t *testing.T) { - assert.Equal(t, int64(0), getListIDFromSavedFilterID(-1)) + assert.Equal(t, int64(0), getProjectIDFromSavedFilterID(-1)) }) } -func TestSavedFilter_getFilterIDFromListID(t *testing.T) { +func TestSavedFilter_getFilterIDFromProjectID(t *testing.T) { t.Run("normal", func(t *testing.T) { - assert.Equal(t, int64(1), getSavedFilterIDFromListID(-2)) + assert.Equal(t, int64(1), getSavedFilterIDFromProjectID(-2)) }) t.Run("invalid", func(t *testing.T) { - assert.Equal(t, int64(0), getSavedFilterIDFromListID(2)) + assert.Equal(t, int64(0), getSavedFilterIDFromProjectID(2)) }) } diff --git a/pkg/models/subscription.go b/pkg/models/subscription.go index 23d80376c..51aac4874 100644 --- a/pkg/models/subscription.go +++ b/pkg/models/subscription.go @@ -32,13 +32,13 @@ type SubscriptionEntityType int const ( SubscriptionEntityUnknown = iota SubscriptionEntityNamespace - SubscriptionEntityList + SubscriptionEntityProject SubscriptionEntityTask ) const ( entityNamespace = `namespace` - entityList = `list` + entityProject = `project` entityTask = `task` ) @@ -72,8 +72,8 @@ func getEntityTypeFromString(entityType string) SubscriptionEntityType { switch entityType { case entityNamespace: return SubscriptionEntityNamespace - case entityList: - return SubscriptionEntityList + case entityProject: + return SubscriptionEntityProject case entityTask: return SubscriptionEntityTask } @@ -86,8 +86,8 @@ func (et SubscriptionEntityType) String() string { switch et { case SubscriptionEntityNamespace: return entityNamespace - case SubscriptionEntityList: - return entityList + case SubscriptionEntityProject: + return entityProject case SubscriptionEntityTask: return entityTask } @@ -97,7 +97,7 @@ func (et SubscriptionEntityType) String() string { func (et SubscriptionEntityType) validate() error { if et == SubscriptionEntityNamespace || - et == SubscriptionEntityList || + et == SubscriptionEntityProject || et == SubscriptionEntityTask { return nil } @@ -112,7 +112,7 @@ func (et SubscriptionEntityType) validate() error { // @Accept json // @Produce json // @Security JWTKeyAuth -// @Param entity path string true "The entity the user subscribes to. Can be either `namespace`, `list` or `task`." +// @Param entity path string true "The entity the user subscribes to. Can be either `namespace`, `project` or `task`." // @Param entityID path string true "The numeric id of the entity to subscribe to." // @Success 201 {object} models.Subscription "The subscription" // @Failure 403 {object} web.HTTPError "The user does not have access to subscribe to this entity." @@ -153,7 +153,7 @@ func (sb *Subscription) Create(s *xorm.Session, auth web.Auth) (err error) { // @Accept json // @Produce json // @Security JWTKeyAuth -// @Param entity path string true "The entity the user subscribed to. Can be either `namespace`, `list` or `task`." +// @Param entity path string true "The entity the user subscribed to. Can be either `namespace`, `project` or `task`." // @Param entityID path string true "The numeric id of the subscribed entity to." // @Success 200 {object} models.Subscription "The subscription" // @Failure 403 {object} web.HTTPError "The user does not have access to subscribe to this entity." @@ -177,16 +177,16 @@ func getSubscriberCondForEntity(entityType SubscriptionEntityType, entityID int6 ) } - if entityType == SubscriptionEntityList { + if entityType == SubscriptionEntityProject { cond = builder.Or( builder.And( builder.Eq{"entity_id": entityID}, - builder.Eq{"entity_type": SubscriptionEntityList}, + builder.Eq{"entity_type": SubscriptionEntityProject}, ), builder.And( builder.Eq{"entity_id": builder. Select("namespace_id"). - From("lists"). + From("projects"). Where(builder.Eq{"id": entityID}), }, builder.Eq{"entity_type": SubscriptionEntityNamespace}, @@ -203,19 +203,19 @@ func getSubscriberCondForEntity(entityType SubscriptionEntityType, entityID int6 builder.And( builder.Eq{"entity_id": builder. Select("namespace_id"). - From("lists"). - Join("INNER", "tasks", "lists.id = tasks.list_id"). + From("projects"). + Join("INNER", "tasks", "projects.id = tasks.project_id"). Where(builder.Eq{"tasks.id": entityID}), }, builder.Eq{"entity_type": SubscriptionEntityNamespace}, ), builder.And( builder.Eq{"entity_id": builder. - Select("list_id"). + Select("project_id"). From("tasks"). Where(builder.Eq{"id": entityID}), }, - builder.Eq{"entity_type": SubscriptionEntityList}, + builder.Eq{"entity_type": SubscriptionEntityProject}, ), ) } @@ -225,8 +225,8 @@ func getSubscriberCondForEntity(entityType SubscriptionEntityType, entityID int6 // GetSubscription returns a matching subscription for an entity and user. // It will return the next parent of a subscription. That means for tasks, it will first look for a subscription for -// that task, if there is none it will look for a subscription on the list the task belongs to and if that also -// doesn't exist it will check for a subscription for the namespace the list is belonging to. +// that task, if there is none it will look for a subscription on the project the task belongs to and if that also +// doesn't exist it will check for a subscription for the namespace the project is belonging to. func GetSubscription(s *xorm.Session, entityType SubscriptionEntityType, entityID int64, a web.Auth) (subscription *Subscription, err error) { subs, err := GetSubscriptions(s, entityType, []int64{entityID}, a) if err != nil || len(subs) == 0 { @@ -242,7 +242,7 @@ func GetSubscription(s *xorm.Session, entityType SubscriptionEntityType, entityI } // GetSubscriptions returns a map of subscriptions to a set of given entity IDs -func GetSubscriptions(s *xorm.Session, entityType SubscriptionEntityType, entityIDs []int64, a web.Auth) (listsToSubscriptions map[int64]*Subscription, err error) { +func GetSubscriptions(s *xorm.Session, entityType SubscriptionEntityType, entityIDs []int64, a web.Auth) (projectsToSubscriptions map[int64]*Subscription, err error) { u, is := a.(*user.User) if !is { return @@ -269,12 +269,12 @@ func GetSubscriptions(s *xorm.Session, entityType SubscriptionEntityType, entity return nil, err } - listsToSubscriptions = make(map[int64]*Subscription) + projectsToSubscriptions = make(map[int64]*Subscription) for _, sub := range subscriptions { sub.Entity = sub.EntityType.String() - listsToSubscriptions[sub.EntityID] = sub + projectsToSubscriptions[sub.EntityID] = sub } - return listsToSubscriptions, nil + return projectsToSubscriptions, nil } func getSubscribersForEntity(s *xorm.Session, entityType SubscriptionEntityType, entityID int64) (subscriptions []*Subscription, err error) { diff --git a/pkg/models/subscription_rights.go b/pkg/models/subscription_rights.go index 8b8fedc19..88f45438a 100644 --- a/pkg/models/subscription_rights.go +++ b/pkg/models/subscription_rights.go @@ -33,8 +33,8 @@ func (sb *Subscription) CanCreate(s *xorm.Session, a web.Auth) (can bool, err er case SubscriptionEntityNamespace: n := &Namespace{ID: sb.EntityID} can, _, err = n.CanRead(s, a) - case SubscriptionEntityList: - l := &List{ID: sb.EntityID} + case SubscriptionEntityProject: + l := &Project{ID: sb.EntityID} can, _, err = l.CanRead(s, a) case SubscriptionEntityTask: t := &Task{ID: sb.EntityID} diff --git a/pkg/models/subscription_test.go b/pkg/models/subscription_test.go index 3485c993f..1b23e1f24 100644 --- a/pkg/models/subscription_test.go +++ b/pkg/models/subscription_test.go @@ -29,9 +29,9 @@ func TestSubscriptionGetTypeFromString(t *testing.T) { entityType := getEntityTypeFromString("namespace") assert.Equal(t, SubscriptionEntityType(SubscriptionEntityNamespace), entityType) }) - t.Run("list", func(t *testing.T) { - entityType := getEntityTypeFromString("list") - assert.Equal(t, SubscriptionEntityType(SubscriptionEntityList), entityType) + t.Run("project", func(t *testing.T) { + entityType := getEntityTypeFromString("project") + assert.Equal(t, SubscriptionEntityType(SubscriptionEntityProject), entityType) }) t.Run("task", func(t *testing.T) { entityType := getEntityTypeFromString("task") @@ -104,20 +104,20 @@ func TestSubscription_Create(t *testing.T) { assert.True(t, IsErrNamespaceDoesNotExist(err)) assert.False(t, can) }) - t.Run("noneixsting list", func(t *testing.T) { + t.Run("noneixsting project", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() defer s.Close() sb := &Subscription{ - Entity: "list", + Entity: "project", EntityID: 99999999, UserID: u.ID, } can, err := sb.CanCreate(s, u) assert.Error(t, err) - assert.True(t, IsErrListDoesNotExist(err)) + assert.True(t, IsErrProjectDoesNotExist(err)) assert.False(t, can) }) t.Run("noneixsting task", func(t *testing.T) { @@ -151,13 +151,13 @@ func TestSubscription_Create(t *testing.T) { assert.NoError(t, err) assert.False(t, can) }) - t.Run("no rights to see list", func(t *testing.T) { + t.Run("no rights to see project", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() defer s.Close() sb := &Subscription{ - Entity: "list", + Entity: "project", EntityID: 20, UserID: u.ID, } @@ -278,12 +278,12 @@ func TestSubscriptionGet(t *testing.T) { assert.NotNil(t, sub) assert.Equal(t, int64(2), sub.ID) }) - t.Run("list", func(t *testing.T) { + t.Run("project", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() defer s.Close() - sub, err := GetSubscription(s, SubscriptionEntityList, 12, u) + sub, err := GetSubscription(s, SubscriptionEntityProject, 12, u) assert.NoError(t, err) assert.NotNil(t, sub) assert.Equal(t, int64(3), sub.ID) @@ -300,13 +300,13 @@ func TestSubscriptionGet(t *testing.T) { }) }) t.Run("inherited", func(t *testing.T) { - t.Run("list from namespace", func(t *testing.T) { + t.Run("project from namespace", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() defer s.Close() - // List 6 belongs to namespace 6 where user 6 has subscribed to - sub, err := GetSubscription(s, SubscriptionEntityList, 6, u) + // Project 6 belongs to namespace 6 where user 6 has subscribed to + sub, err := GetSubscription(s, SubscriptionEntityProject, 6, u) assert.NoError(t, err) assert.NotNil(t, sub) assert.Equal(t, int64(2), sub.ID) @@ -316,18 +316,18 @@ func TestSubscriptionGet(t *testing.T) { s := db.NewSession() defer s.Close() - // Task 20 belongs to list 11 which belongs to namespace 6 where the user has subscribed + // Task 20 belongs to project 11 which belongs to namespace 6 where the user has subscribed sub, err := GetSubscription(s, SubscriptionEntityTask, 20, u) assert.NoError(t, err) assert.NotNil(t, sub) assert.Equal(t, int64(2), sub.ID) }) - t.Run("task from list", func(t *testing.T) { + t.Run("task from project", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() defer s.Close() - // Task 21 belongs to list 12 which the user has subscribed to + // Task 21 belongs to project 12 which the user has subscribed to sub, err := GetSubscription(s, SubscriptionEntityTask, 21, u) assert.NoError(t, err) assert.NotNil(t, sub) diff --git a/pkg/models/task_assignees.go b/pkg/models/task_assignees.go index 3993a5da8..add702f80 100644 --- a/pkg/models/task_assignees.go +++ b/pkg/models/task_assignees.go @@ -33,7 +33,7 @@ import ( // TaskAssginee represents an assignment of a user to a task type TaskAssginee struct { ID int64 `xorm:"bigint autoincr not null unique pk" json:"-"` - TaskID int64 `xorm:"bigint INDEX not null" json:"-" param:"listtask"` + TaskID int64 `xorm:"bigint INDEX not null" json:"-" param:"projecttask"` UserID int64 `xorm:"bigint INDEX not null" json:"user_id" param:"user"` Created time.Time `xorm:"created not null"` @@ -102,10 +102,10 @@ func (t *Task) updateTaskAssignees(s *xorm.Session, assignees []*user.User, doer for _, oldAssignee := range t.Assignees { found = false if newAssignees[oldAssignee.ID] != nil { - found = true // If a new assignee is already in the list with old assignees + found = true // If a new assignee is already in the project with old assignees } - // Put all assignees which are only on the old list to the trash + // Put all assignees which are only on the old project to the trash if !found { assigneesToDelete = append(assigneesToDelete, oldAssignee.ID) } @@ -123,8 +123,8 @@ func (t *Task) updateTaskAssignees(s *xorm.Session, assignees []*user.User, doer } } - // Get the list to perform later checks - list, err := GetListSimpleByID(s, t.ListID) + // Get the project to perform later checks + project, err := GetProjectSimpleByID(s, t.ProjectID) if err != nil { return } @@ -138,7 +138,7 @@ func (t *Task) updateTaskAssignees(s *xorm.Session, assignees []*user.User, doer } // Add the new assignee - err = t.addNewAssigneeByID(s, u.ID, list, doer) + err = t.addNewAssigneeByID(s, u.ID, project, doer) if err != nil { return err } @@ -146,7 +146,7 @@ func (t *Task) updateTaskAssignees(s *xorm.Session, assignees []*user.User, doer t.setTaskAssignees(assignees) - err = updateListLastUpdated(s, &List{ID: t.ListID}) + err = updateProjectLastUpdated(s, &Project{ID: t.ProjectID}) return } @@ -178,7 +178,7 @@ func (la *TaskAssginee) Delete(s *xorm.Session, a web.Auth) (err error) { return err } - err = updateListByTaskID(s, la.TaskID) + err = updateProjectByTaskID(s, la.TaskID) if err != nil { return err } @@ -193,7 +193,7 @@ func (la *TaskAssginee) Delete(s *xorm.Session, a web.Auth) (err error) { // Create adds a new assignee to a task // @Summary Add a new assignee to a task -// @Description Adds a new assignee to a task. The assignee needs to have access to the list, the doer must be able to edit this task. +// @Description Adds a new assignee to a task. The assignee needs to have access to the project, the doer must be able to edit this task. // @tags assignees // @Accept json // @Produce json @@ -206,28 +206,28 @@ func (la *TaskAssginee) Delete(s *xorm.Session, a web.Auth) (err error) { // @Router /tasks/{taskID}/assignees [put] func (la *TaskAssginee) Create(s *xorm.Session, a web.Auth) (err error) { - // Get the list to perform later checks - list, err := GetListSimplByTaskID(s, la.TaskID) + // Get the project to perform later checks + project, err := GetProjectSimplByTaskID(s, la.TaskID) if err != nil { return } task := &Task{ID: la.TaskID} - return task.addNewAssigneeByID(s, la.UserID, list, a) + return task.addNewAssigneeByID(s, la.UserID, project, a) } -func (t *Task) addNewAssigneeByID(s *xorm.Session, newAssigneeID int64, list *List, auth web.Auth) (err error) { - // Check if the user exists and has access to the list +func (t *Task) addNewAssigneeByID(s *xorm.Session, newAssigneeID int64, project *Project, auth web.Auth) (err error) { + // Check if the user exists and has access to the project newAssignee, err := user.GetUserByID(s, newAssigneeID) if err != nil { return err } - canRead, _, err := list.CanRead(s, newAssignee) + canRead, _, err := project.CanRead(s, newAssignee) if err != nil { return err } if !canRead { - return ErrUserDoesNotHaveAccessToList{list.ID, newAssigneeID} + return ErrUserDoesNotHaveAccessToProject{project.ID, newAssigneeID} } exist, err := s. @@ -261,7 +261,7 @@ func (t *Task) addNewAssigneeByID(s *xorm.Session, newAssigneeID int64, list *Li return err } - err = updateListLastUpdated(s, &List{ID: t.ListID}) + err = updateProjectLastUpdated(s, &Project{ID: t.ProjectID}) return } @@ -280,7 +280,7 @@ func (t *Task) addNewAssigneeByID(s *xorm.Session, newAssigneeID int64, list *Li // @Failure 500 {object} models.Message "Internal error" // @Router /tasks/{taskID}/assignees [get] func (la *TaskAssginee) ReadAll(s *xorm.Session, a web.Auth, search string, page int, perPage int) (result interface{}, resultCount int, numberOfTotalItems int64, err error) { - task, err := GetListSimplByTaskID(s, la.TaskID) + task, err := GetProjectSimplByTaskID(s, la.TaskID) if err != nil { return nil, 0, 0, err } @@ -319,9 +319,9 @@ func (la *TaskAssginee) ReadAll(s *xorm.Session, a web.Auth, search string, page // BulkAssignees is a helper struct used to update multiple assignees at once. type BulkAssignees struct { - // A list with all assignees + // A project with all assignees Assignees []*user.User `json:"assignees"` - TaskID int64 `json:"-" param:"listtask"` + TaskID int64 `json:"-" param:"projecttask"` web.CRUDable `json:"-"` web.Rights `json:"-"` @@ -329,7 +329,7 @@ type BulkAssignees struct { // Create adds new assignees to a task // @Summary Add multiple new assignees to a task -// @Description Adds multiple new assignees to a task. The assignee needs to have access to the list, the doer must be able to edit this task. Every user not in the list will be unassigned from the task, pass an empty array to unassign everyone. +// @Description Adds multiple new assignees to a task. The assignee needs to have access to the project, the doer must be able to edit this task. Every user not in the project will be unassigned from the task, pass an empty array to unassign everyone. // @tags assignees // @Accept json // @Produce json diff --git a/pkg/models/task_assignees_rights.go b/pkg/models/task_assignees_rights.go index bb91ce707..88ec66931 100644 --- a/pkg/models/task_assignees_rights.go +++ b/pkg/models/task_assignees_rights.go @@ -37,10 +37,10 @@ func (la *TaskAssginee) CanDelete(s *xorm.Session, a web.Auth) (bool, error) { } func canDoTaskAssingee(s *xorm.Session, taskID int64, a web.Auth) (bool, error) { - // Check if the current user can edit the list - list, err := GetListSimplByTaskID(s, taskID) + // Check if the current user can edit the project + project, err := GetProjectSimplByTaskID(s, taskID) if err != nil { return false, err } - return list.CanUpdate(s, a) + return project.CanUpdate(s, a) } diff --git a/pkg/models/task_attachment.go b/pkg/models/task_attachment.go index 02976f884..0251bed0f 100644 --- a/pkg/models/task_attachment.go +++ b/pkg/models/task_attachment.go @@ -112,7 +112,7 @@ func (ta *TaskAttachment) ReadOne(s *xorm.Session, a web.Auth) (err error) { return } -// ReadAll returns a list with all attachments +// ReadAll returns a project with all attachments // @Summary Get all attachments for one task. // @Description Get all task attachments for one task. // @tags task diff --git a/pkg/models/task_collection.go b/pkg/models/task_collection.go index c2936ff70..52263c5dd 100644 --- a/pkg/models/task_collection.go +++ b/pkg/models/task_collection.go @@ -24,8 +24,8 @@ import ( // TaskCollection is a struct used to hold filter details and not clutter the Task struct with information not related to actual tasks. type TaskCollection struct { - ListID int64 `param:"list" json:"-"` - Lists []*List `json:"-"` + ProjectID int64 `param:"project" json:"-"` + Projects []*Project `json:"-"` // The query parameter to sort by. This is for ex. done, priority, etc. SortBy []string `query:"sort_by" json:"sort_by"` @@ -62,7 +62,7 @@ func validateTaskField(fieldName string) error { taskPropertyDoneAt, taskPropertyDueDate, taskPropertyCreatedByID, - taskPropertyListID, + taskPropertyProjectID, taskPropertyRepeatAfter, taskPropertyPriority, taskPropertyStartDate, @@ -120,16 +120,16 @@ func getTaskFilterOptsFromCollection(tf *TaskCollection) (opts *taskOptions, err } // ReadAll gets all tasks for a collection -// @Summary Get tasks in a list -// @Description Returns all tasks for the current list. +// @Summary Get tasks in a project +// @Description Returns all tasks for the current project. // @tags task // @Accept json // @Produce json -// @Param listID path int true "The list ID." +// @Param projectID path int true "The project ID." // @Param page query int false "The page number. Used for pagination. If not provided, the first page of results is returned." // @Param per_page query int false "The maximum number of items per page. Note this parameter is limited by the configured maximum of items per page." // @Param s query string false "Search tasks by task text." -// @Param sort_by query string false "The sorting parameter. You can pass this multiple times to get the tasks ordered by multiple different parametes, along with `order_by`. Possible values to sort by are `id`, `title`, `description`, `done`, `done_at`, `due_date`, `created_by_id`, `list_id`, `repeat_after`, `priority`, `start_date`, `end_date`, `hex_color`, `percent_done`, `uid`, `created`, `updated`. Default is `id`." +// @Param sort_by query string false "The sorting parameter. You can pass this multiple times to get the tasks ordered by multiple different parametes, along with `order_by`. Possible values to sort by are `id`, `title`, `description`, `done`, `done_at`, `due_date`, `created_by_id`, `project_id`, `repeat_after`, `priority`, `start_date`, `end_date`, `hex_color`, `percent_done`, `uid`, `created`, `updated`. Default is `id`." // @Param order_by query string false "The ordering parameter. Possible values to order by are `asc` or `desc`. Default is `asc`." // @Param filter_by query string false "The name of the field to filter by. Allowed values are all task properties. Task properties which are their own object require passing in the id of that entity. Accepts an array for multiple filters which will be chanied together, all supplied filter must match." // @Param filter_value query string false "The value to filter for. You can use [grafana](https://grafana.com/docs/grafana/latest/dashboards/time-range-controls)- or [elasticsearch](https://www.elastic.co/guide/en/elasticsearch/reference/7.3/common-options.html#date-math)-style relative dates for all date fields like `due_date`, `start_date`, `end_date`, etc." @@ -139,13 +139,13 @@ func getTaskFilterOptsFromCollection(tf *TaskCollection) (opts *taskOptions, err // @Security JWTKeyAuth // @Success 200 {array} models.Task "The tasks" // @Failure 500 {object} models.Message "Internal error" -// @Router /lists/{listID}/tasks [get] +// @Router /projects/{projectID}/tasks [get] func (tf *TaskCollection) ReadAll(s *xorm.Session, a web.Auth, search string, page int, perPage int) (result interface{}, resultCount int, totalItems int64, err error) { - // If the list id is < -1 this means we're dealing with a saved filter - in that case we get and populate the filter - // -1 is the favorites list which works as intended - if tf.ListID < -1 { - sf, err := getSavedFilterSimpleByID(s, getSavedFilterIDFromListID(tf.ListID)) + // If the project id is < -1 this means we're dealing with a saved filter - in that case we get and populate the filter + // -1 is the favorites project which works as intended + if tf.ProjectID < -1 { + sf, err := getSavedFilterSimpleByID(s, getSavedFilterIDFromProjectID(tf.ProjectID)) if err != nil { return nil, 0, 0, err } @@ -169,19 +169,19 @@ func (tf *TaskCollection) ReadAll(s *xorm.Session, a web.Auth, search string, pa shareAuth, is := a.(*LinkSharing) if is { - list, err := GetListSimpleByID(s, shareAuth.ListID) + project, err := GetProjectSimpleByID(s, shareAuth.ProjectID) if err != nil { return nil, 0, 0, err } - return getTasksForLists(s, []*List{list}, a, taskopts) + return getTasksForProjects(s, []*Project{project}, a, taskopts) } - // If the list ID is not set, we get all tasks for the user. + // If the project ID is not set, we get all tasks for the user. // This allows to use this function in Task.ReadAll with a possibility to deprecate the latter at some point. - if tf.ListID == 0 { - tf.Lists, _, _, err = getRawListsForUser( + if tf.ProjectID == 0 { + tf.Projects, _, _, err = getRawProjectsForUser( s, - &listOptions{ + &projectOptions{ user: &user.User{ID: a.GetID()}, page: -1, }, @@ -190,17 +190,17 @@ func (tf *TaskCollection) ReadAll(s *xorm.Session, a web.Auth, search string, pa return nil, 0, 0, err } } else { - // Check the list exists and the user has acess on it - list := &List{ID: tf.ListID} - canRead, _, err := list.CanRead(s, a) + // Check the project exists and the user has acess on it + project := &Project{ID: tf.ProjectID} + canRead, _, err := project.CanRead(s, a) if err != nil { return nil, 0, 0, err } if !canRead { - return nil, 0, 0, ErrUserDoesNotHaveAccessToList{ListID: tf.ListID} + return nil, 0, 0, ErrUserDoesNotHaveAccessToProject{ProjectID: tf.ProjectID} } - tf.Lists = []*List{{ID: tf.ListID}} + tf.Projects = []*Project{{ID: tf.ProjectID}} } - return getTasksForLists(s, tf.Lists, a, taskopts) + return getTasksForProjects(s, tf.Projects, a, taskopts) } diff --git a/pkg/models/task_collection_sort.go b/pkg/models/task_collection_sort.go index 4badd799b..b5ec1e79a 100644 --- a/pkg/models/task_collection_sort.go +++ b/pkg/models/task_collection_sort.go @@ -33,7 +33,7 @@ const ( taskPropertyDoneAt string = "done_at" taskPropertyDueDate string = "due_date" taskPropertyCreatedByID string = "created_by_id" - taskPropertyListID string = "list_id" + taskPropertyProjectID string = "project_id" taskPropertyRepeatAfter string = "repeat_after" taskPropertyPriority string = "priority" taskPropertyStartDate string = "start_date" diff --git a/pkg/models/task_collection_sort_test.go b/pkg/models/task_collection_sort_test.go index 685a66971..5d7cb0d69 100644 --- a/pkg/models/task_collection_sort_test.go +++ b/pkg/models/task_collection_sort_test.go @@ -50,7 +50,7 @@ func TestSortParamValidation(t *testing.T) { taskPropertyDoneAt, taskPropertyDueDate, taskPropertyCreatedByID, - taskPropertyListID, + taskPropertyProjectID, taskPropertyRepeatAfter, taskPropertyPriority, taskPropertyStartDate, diff --git a/pkg/models/task_collection_test.go b/pkg/models/task_collection_test.go index 7429ab5af..d00cd3bdb 100644 --- a/pkg/models/task_collection_test.go +++ b/pkg/models/task_collection_test.go @@ -90,7 +90,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { Index: 1, CreatedByID: 1, CreatedBy: user1, - ListID: 1, + ProjectID: 1, BucketID: 1, IsFavorite: true, Position: 2, @@ -104,7 +104,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { Title: "task #29 with parent task (1)", Index: 14, CreatedByID: 1, - ListID: 1, + ProjectID: 1, BucketID: 1, Created: time.Unix(1543626724, 0).In(loc), Updated: time.Unix(1543626724, 0).In(loc), @@ -162,7 +162,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { Done: true, CreatedByID: 1, CreatedBy: user1, - ListID: 1, + ProjectID: 1, BucketID: 1, Position: 4, Labels: []*Label{ @@ -182,7 +182,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { Index: 3, CreatedByID: 1, CreatedBy: user1, - ListID: 1, + ProjectID: 1, RelatedTasks: map[RelationKind][]*Task{}, Created: time.Unix(1543626724, 0).In(loc), Updated: time.Unix(1543626724, 0).In(loc), @@ -196,7 +196,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { Index: 4, CreatedByID: 1, CreatedBy: user1, - ListID: 1, + ProjectID: 1, RelatedTasks: map[RelationKind][]*Task{}, Created: time.Unix(1543626724, 0).In(loc), Updated: time.Unix(1543626724, 0).In(loc), @@ -210,7 +210,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { Index: 5, CreatedByID: 1, CreatedBy: user1, - ListID: 1, + ProjectID: 1, RelatedTasks: map[RelationKind][]*Task{}, Created: time.Unix(1543626724, 0).In(loc), Updated: time.Unix(1543626724, 0).In(loc), @@ -224,7 +224,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { Index: 6, CreatedByID: 1, CreatedBy: user1, - ListID: 1, + ProjectID: 1, RelatedTasks: map[RelationKind][]*Task{}, Created: time.Unix(1543626724, 0).In(loc), Updated: time.Unix(1543626724, 0).In(loc), @@ -238,7 +238,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { Index: 7, CreatedByID: 1, CreatedBy: user1, - ListID: 1, + ProjectID: 1, RelatedTasks: map[RelationKind][]*Task{}, Created: time.Unix(1543626724, 0).In(loc), Updated: time.Unix(1543626724, 0).In(loc), @@ -252,7 +252,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { Index: 8, CreatedByID: 1, CreatedBy: user1, - ListID: 1, + ProjectID: 1, RelatedTasks: map[RelationKind][]*Task{}, Created: time.Unix(1543626724, 0).In(loc), Updated: time.Unix(1543626724, 0).In(loc), @@ -266,7 +266,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { Index: 9, CreatedByID: 1, CreatedBy: user1, - ListID: 1, + ProjectID: 1, RelatedTasks: map[RelationKind][]*Task{}, BucketID: 1, Created: time.Unix(1543626724, 0).In(loc), @@ -281,7 +281,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { Index: 10, CreatedByID: 1, CreatedBy: user1, - ListID: 1, + ProjectID: 1, RelatedTasks: map[RelationKind][]*Task{}, BucketID: 1, Created: time.Unix(1543626724, 0).In(loc), @@ -294,7 +294,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { Index: 11, CreatedByID: 1, CreatedBy: user1, - ListID: 1, + ProjectID: 1, RelatedTasks: map[RelationKind][]*Task{}, BucketID: 1, Created: time.Unix(1543626724, 0).In(loc), @@ -307,7 +307,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { Index: 12, CreatedByID: 1, CreatedBy: user1, - ListID: 1, + ProjectID: 1, RelatedTasks: map[RelationKind][]*Task{}, BucketID: 1, Created: time.Unix(1543626724, 0).In(loc), @@ -320,7 +320,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { Index: 1, CreatedByID: 6, CreatedBy: user6, - ListID: 6, + ProjectID: 6, IsFavorite: true, RelatedTasks: map[RelationKind][]*Task{}, BucketID: 6, @@ -334,7 +334,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { Index: 1, CreatedByID: 6, CreatedBy: user6, - ListID: 7, + ProjectID: 7, RelatedTasks: map[RelationKind][]*Task{}, BucketID: 7, Created: time.Unix(1543626724, 0).In(loc), @@ -347,7 +347,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { Index: 1, CreatedByID: 6, CreatedBy: user6, - ListID: 8, + ProjectID: 8, RelatedTasks: map[RelationKind][]*Task{}, BucketID: 8, Created: time.Unix(1543626724, 0).In(loc), @@ -360,7 +360,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { Index: 1, CreatedByID: 6, CreatedBy: user6, - ListID: 9, + ProjectID: 9, RelatedTasks: map[RelationKind][]*Task{}, BucketID: 9, Created: time.Unix(1543626724, 0).In(loc), @@ -373,7 +373,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { Index: 1, CreatedByID: 6, CreatedBy: user6, - ListID: 10, + ProjectID: 10, RelatedTasks: map[RelationKind][]*Task{}, BucketID: 10, Created: time.Unix(1543626724, 0).In(loc), @@ -386,7 +386,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { Index: 1, CreatedByID: 6, CreatedBy: user6, - ListID: 11, + ProjectID: 11, RelatedTasks: map[RelationKind][]*Task{}, BucketID: 11, Created: time.Unix(1543626724, 0).In(loc), @@ -399,7 +399,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { Index: 1, CreatedByID: 6, CreatedBy: user6, - ListID: 12, + ProjectID: 12, RelatedTasks: map[RelationKind][]*Task{}, BucketID: 12, Created: time.Unix(1543626724, 0).In(loc), @@ -412,7 +412,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { Index: 1, CreatedByID: 6, CreatedBy: user6, - ListID: 13, + ProjectID: 13, RelatedTasks: map[RelationKind][]*Task{}, BucketID: 13, Created: time.Unix(1543626724, 0).In(loc), @@ -425,7 +425,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { Index: 1, CreatedByID: 6, CreatedBy: user6, - ListID: 14, + ProjectID: 14, RelatedTasks: map[RelationKind][]*Task{}, BucketID: 14, Created: time.Unix(1543626724, 0).In(loc), @@ -438,7 +438,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { Index: 1, CreatedByID: 6, CreatedBy: user6, - ListID: 15, + ProjectID: 15, RelatedTasks: map[RelationKind][]*Task{}, BucketID: 15, Created: time.Unix(1543626724, 0).In(loc), @@ -451,7 +451,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { Index: 1, CreatedByID: 6, CreatedBy: user6, - ListID: 16, + ProjectID: 16, RelatedTasks: map[RelationKind][]*Task{}, BucketID: 16, Created: time.Unix(1543626724, 0).In(loc), @@ -464,7 +464,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { Index: 1, CreatedByID: 6, CreatedBy: user6, - ListID: 17, + ProjectID: 17, RelatedTasks: map[RelationKind][]*Task{}, BucketID: 17, Created: time.Unix(1543626724, 0).In(loc), @@ -481,7 +481,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { time.Unix(1543626724, 0).In(loc), time.Unix(1543626824, 0).In(loc), }, - ListID: 1, + ProjectID: 1, BucketID: 1, RelatedTasks: map[RelationKind][]*Task{}, Created: time.Unix(1543626724, 0).In(loc), @@ -494,7 +494,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { Index: 13, CreatedByID: 1, CreatedBy: user1, - ListID: 1, + ProjectID: 1, RelatedTasks: map[RelationKind][]*Task{}, RepeatAfter: 3600, BucketID: 1, @@ -508,7 +508,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { Index: 14, CreatedByID: 1, CreatedBy: user1, - ListID: 1, + ProjectID: 1, RelatedTasks: map[RelationKind][]*Task{ RelationKindParenttask: { { @@ -517,7 +517,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { Description: "Lorem Ipsum", Index: 1, CreatedByID: 1, - ListID: 1, + ProjectID: 1, IsFavorite: true, Created: time.Unix(1543626724, 0).In(loc), Updated: time.Unix(1543626724, 0).In(loc), @@ -537,7 +537,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { Index: 15, CreatedByID: 1, CreatedBy: user1, - ListID: 1, + ProjectID: 1, Assignees: []*user.User{ user1, user2, @@ -555,7 +555,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { HexColor: "f0f0f0", CreatedByID: 1, CreatedBy: user1, - ListID: 1, + ProjectID: 1, RelatedTasks: map[RelationKind][]*Task{}, BucketID: 1, Created: time.Unix(1543626724, 0).In(loc), @@ -568,7 +568,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { Index: 1, CreatedByID: 1, CreatedBy: user1, - ListID: 3, + ProjectID: 3, RelatedTasks: map[RelationKind][]*Task{}, BucketID: 21, Created: time.Unix(1543626724, 0).In(loc), @@ -581,7 +581,7 @@ func TestTaskCollection_ReadAll(t *testing.T) { Index: 17, CreatedByID: 1, CreatedBy: user1, - ListID: 1, + ProjectID: 1, PercentDone: 0.5, RelatedTasks: map[RelationKind][]*Task{}, BucketID: 1, @@ -590,10 +590,10 @@ func TestTaskCollection_ReadAll(t *testing.T) { } type fields struct { - ListID int64 - Lists []*List - SortBy []string // Is a string, since this is the place where a query string comes from the user - OrderBy []string + ProjectID int64 + Projects []*Project + SortBy []string // Is a string, since this is the place where a query string comes from the user + OrderBy []string FilterBy []string FilterValue []string @@ -876,12 +876,12 @@ func TestTaskCollection_ReadAll(t *testing.T) { name: "favorited tasks", args: defaultArgs, fields: fields{ - ListID: FavoritesPseudoList.ID, + ProjectID: FavoritesPseudoProject.ID, }, want: []*Task{ task1, task15, - // Task 34 is also a favorite, but on a list user 1 has no access to. + // Task 34 is also a favorite, but on a project user 1 has no access to. }, }, { @@ -1042,9 +1042,9 @@ func TestTaskCollection_ReadAll(t *testing.T) { wantErr: false, }, { - name: "filter list", + name: "filter project", fields: fields{ - FilterBy: []string{"list_id"}, + FilterBy: []string{"project_id"}, FilterValue: []string{"6"}, FilterComparator: []string{"equals"}, }, @@ -1200,9 +1200,9 @@ func TestTaskCollection_ReadAll(t *testing.T) { { name: "saved filter with sort order", fields: fields{ - ListID: -2, - SortBy: []string{"title", "id"}, - OrderBy: []string{"desc", "asc"}, + ProjectID: -2, + SortBy: []string{"title", "id"}, + OrderBy: []string{"desc", "asc"}, }, args: args{ a: &user.User{ID: 1}, @@ -1224,9 +1224,9 @@ func TestTaskCollection_ReadAll(t *testing.T) { defer s.Close() lt := &TaskCollection{ - ListID: tt.fields.ListID, - SortBy: tt.fields.SortBy, - OrderBy: tt.fields.OrderBy, + ProjectID: tt.fields.ProjectID, + SortBy: tt.fields.SortBy, + OrderBy: tt.fields.OrderBy, FilterBy: tt.fields.FilterBy, FilterValue: tt.fields.FilterValue, diff --git a/pkg/models/task_comments_test.go b/pkg/models/task_comments_test.go index 8befded20..5f7c6c640 100644 --- a/pkg/models/task_comments_test.go +++ b/pkg/models/task_comments_test.go @@ -74,7 +74,7 @@ func TestTaskComment_Create(t *testing.T) { assert.NoError(t, err) tc := &TaskComment{ Comment: "Lorem Ipsum @user2", - TaskID: 32, // user2 has access to the list that task belongs to + TaskID: 32, // user2 has access to the project that task belongs to } err = tc.Create(s, u) assert.NoError(t, err) diff --git a/pkg/models/task_overdue_reminder.go b/pkg/models/task_overdue_reminder.go index e68fb92f2..8cefb9af2 100644 --- a/pkg/models/task_overdue_reminder.go +++ b/pkg/models/task_overdue_reminder.go @@ -80,7 +80,7 @@ func getUndoneOverdueTasks(s *xorm.Session, now time.Time) (usersWithTasks map[i tzs[t.User.Timezone] = tz } - // If it is time for that current user, add the task to their list of overdue tasks + // If it is time for that current user, add the task to their project of overdue tasks tm, err := time.Parse("15:04", t.User.OverdueTasksRemindersTime) if err != nil { return nil, err diff --git a/pkg/models/task_relation.go b/pkg/models/task_relation.go index afd0c1a08..0ae9b1db0 100644 --- a/pkg/models/task_relation.go +++ b/pkg/models/task_relation.go @@ -110,7 +110,7 @@ type RelatedTaskMap map[RelationKind][]*Task // Create creates a new task relation // @Summary Create a new relation between two tasks -// @Description Creates a new relation between two tasks. The user needs to have update rights on the base task and at least read rights on the other task. Both tasks do not need to be on the same list. Take a look at the docs for available task relation kinds. +// @Description Creates a new relation between two tasks. The user needs to have update rights on the base task and at least read rights on the other task. Both tasks do not need to be on the same project. Take a look at the docs for available task relation kinds. // @tags task // @Accept json // @Produce json diff --git a/pkg/models/task_relation_rights.go b/pkg/models/task_relation_rights.go index fb815a5ae..0fcd07bca 100644 --- a/pkg/models/task_relation_rights.go +++ b/pkg/models/task_relation_rights.go @@ -42,7 +42,7 @@ func (rel *TaskRelation) CanCreate(s *xorm.Session, a web.Auth) (bool, error) { return false, err } - // We explicitly don't check if the two tasks are on the same list. + // We explicitly don't check if the two tasks are on the same project. otherTask := &Task{ID: rel.OtherTaskID} has, _, err = otherTask.CanRead(s, a) if err != nil { diff --git a/pkg/models/task_relation_test.go b/pkg/models/task_relation_test.go index 219d56ff4..b037d224d 100644 --- a/pkg/models/task_relation_test.go +++ b/pkg/models/task_relation_test.go @@ -46,7 +46,7 @@ func TestTaskRelation_Create(t *testing.T) { "created_by_id": 1, }, false) }) - t.Run("Two Tasks In Different Lists", func(t *testing.T) { + t.Run("Two Tasks In Different Projects", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() defer s.Close() @@ -150,7 +150,7 @@ func TestTaskRelation_CanCreate(t *testing.T) { assert.NoError(t, err) assert.True(t, can) }) - t.Run("Two tasks on different lists", func(t *testing.T) { + t.Run("Two tasks on different projects", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() defer s.Close() diff --git a/pkg/models/tasks.go b/pkg/models/tasks.go index 0c79961cb..0d14e89c3 100644 --- a/pkg/models/tasks.go +++ b/pkg/models/tasks.go @@ -47,11 +47,11 @@ const ( TaskRepeatModeFromCurrentDate ) -// Task represents an task in a todolist +// Task represents an task in a project type Task struct { // The unique, numeric id of this task. - ID int64 `xorm:"bigint autoincr not null unique pk" json:"id" param:"listtask"` - // The task text. This is what you'll see in the list. + ID int64 `xorm:"bigint autoincr not null unique pk" json:"id" param:"projecttask"` + // The task text. This is what you'll see in the project. Title string `xorm:"TEXT not null" json:"title" valid:"minstringlength(1)" minLength:"1"` // The task description. Description string `xorm:"longtext null" json:"description"` @@ -63,8 +63,8 @@ type Task struct { DueDate time.Time `xorm:"DATETIME INDEX null 'due_date'" json:"due_date"` // An array of datetimes when the user wants to be reminded of the task. Reminders []time.Time `xorm:"-" json:"reminder_dates"` - // The list this task belongs to. - ListID int64 `xorm:"bigint INDEX not null" json:"list_id" param:"list"` + // The project this task belongs to. + ProjectID int64 `xorm:"bigint INDEX not null" json:"project_id" param:"project"` // An amount in seconds this task repeats itself. If this is set, when marking the task as done, it will mark itself as "undone" and then increase all remindes and the due date by its amount. RepeatAfter int64 `xorm:"bigint INDEX null" json:"repeat_after" valid:"range(0|9223372036854775807)"` // Can have three possible values which will trigger when the task is marked as done: 0 = repeats after the amount specified in repeat_after, 1 = repeats all dates each months (ignoring repeat_after), 3 = repeats from the current date rather than the last set date. @@ -84,9 +84,9 @@ type Task struct { // Determines how far a task is left from being done PercentDone float64 `xorm:"DOUBLE null" json:"percent_done"` - // The task identifier, based on the list identifier and the task's index + // The task identifier, based on the project identifier and the task's index Identifier string `xorm:"-" json:"identifier"` - // The task index, calculated per list + // The task index, calculated per project Index int64 `xorm:"bigint not null default 0" json:"index"` // The UID is currently not used for anything other than caldav, which is why we don't expose it over json @@ -101,7 +101,7 @@ type Task struct { // If this task has a cover image, the field will return the id of the attachment that is the cover image. CoverImageAttachmentID int64 `xorm:"bigint default 0" json:"cover_image_attachment_id"` - // True if a task is a favorite task. Favorite tasks show up in a separate "Important" list. This value depends on the user making the call to the api. + // True if a task is a favorite task. Favorite tasks show up in a separate "Important" project. This value depends on the user making the call to the api. IsFavorite bool `xorm:"-" json:"is_favorite"` // The subscription status for the user reading this task. You can only read this property, use the subscription endpoints to modify it. @@ -116,7 +116,7 @@ type Task struct { // BucketID is the ID of the kanban bucket this task belongs to. BucketID int64 `xorm:"bigint null" json:"bucket_id"` - // The position of the task - any task list can be sorted as usual by this parameter. + // The position of the task - any task project can be sorted as usual by this parameter. // When accessing tasks via kanban buckets, this is primarily used to sort them based on a range // We're using a float64 here to make it possible to put any task within any two other tasks (by changing the number). // You would calculate the new position between two tasks with something like task3.position = (task2.position - task1.position) / 2. @@ -128,7 +128,7 @@ type Task struct { // The user who initially created the task. CreatedBy *user.User `xorm:"-" json:"created_by" valid:"-"` - CreatedByID int64 `xorm:"bigint not null" json:"-"` // ID of the user who put that task on the list + CreatedByID int64 `xorm:"bigint not null" json:"-"` // ID of the user who put that task on the project web.CRUDable `xorm:"-" json:"-"` web.Rights `xorm:"-" json:"-"` @@ -139,7 +139,7 @@ type TaskWithComments struct { Comments []*TaskComment `xorm:"-" json:"comments"` } -// TableName returns the table name for listtasks +// TableName returns the table name for tasks func (*Task) TableName() string { return "tasks" } @@ -176,14 +176,14 @@ type taskOptions struct { // ReadAll is a dummy function to still have that endpoint documented // @Summary Get tasks -// @Description Returns all tasks on any list the user has access to. +// @Description Returns all tasks on any project the user has access to. // @tags task // @Accept json // @Produce json // @Param page query int false "The page number. Used for pagination. If not provided, the first page of results is returned." // @Param per_page query int false "The maximum number of items per page. Note this parameter is limited by the configured maximum of items per page." // @Param s query string false "Search tasks by task text." -// @Param sort_by query string false "The sorting parameter. You can pass this multiple times to get the tasks ordered by multiple different parametes, along with `order_by`. Possible values to sort by are `id`, `title`, `description`, `done`, `done_at`, `due_date`, `created_by_id`, `list_id`, `repeat_after`, `priority`, `start_date`, `end_date`, `hex_color`, `percent_done`, `uid`, `created`, `updated`. Default is `id`." +// @Param sort_by query string false "The sorting parameter. You can pass this multiple times to get the tasks ordered by multiple different parametes, along with `order_by`. Possible values to sort by are `id`, `title`, `description`, `done`, `done_at`, `due_date`, `created_by_id`, `project_id`, `repeat_after`, `priority`, `start_date`, `end_date`, `hex_color`, `percent_done`, `uid`, `created`, `updated`. Default is `id`." // @Param order_by query string false "The ordering parameter. Possible values to order by are `asc` or `desc`. Default is `asc`." // @Param filter_by query string false "The name of the field to filter by. Allowed values are all task properties. Task properties which are their own object require passing in the id of that entity. Accepts an array for multiple filters which will be chanied together, all supplied filter must match." // @Param filter_value query string false "The value to filter for." @@ -263,10 +263,10 @@ func getTaskIndexFromSearchString(s string) (index int64) { } //nolint:gocyclo -func getRawTasksForLists(s *xorm.Session, lists []*List, a web.Auth, opts *taskOptions) (tasks []*Task, resultCount int, totalItems int64, err error) { +func getRawTasksForProjects(s *xorm.Session, projects []*Project, a web.Auth, opts *taskOptions) (tasks []*Task, resultCount int, totalItems int64, err error) { - // If the user does not have any lists, don't try to get any tasks - if len(lists) == 0 { + // If the user does not have any projects, don't try to get any tasks + if len(projects) == 0 { return nil, 0, 0, nil } @@ -275,15 +275,15 @@ func getRawTasksForLists(s *xorm.Session, lists []*List, a web.Auth, opts *taskO opts.filterConcat = filterConcatOr } - // Get all list IDs and get the tasks - var listIDs []int64 - var hasFavoritesList bool - for _, l := range lists { - if l.ID == FavoritesPseudoList.ID { - hasFavoritesList = true + // Get all project IDs and get the tasks + var projectIDs []int64 + var hasFavoritesProject bool + for _, l := range projects { + if l.ID == FavoritesPseudoProject.ID { + hasFavoritesProject = true continue } - listIDs = append(listIDs, l.ID) + projectIDs = append(projectIDs, l.ID) } // Add the id parameter as the last parameter to sorty by default, but only if it is not already passed as the last parameter. @@ -384,7 +384,7 @@ func getRawTasksForLists(s *xorm.Session, lists []*List, a web.Auth, opts *taskO filters = append(filters, filter) } - // Then return all tasks for that lists + // Then return all tasks for that projects var where builder.Cond if opts.search != "" { @@ -396,18 +396,18 @@ func getRawTasksForLists(s *xorm.Session, lists []*List, a web.Auth, opts *taskO } } - var listIDCond builder.Cond - var listCond builder.Cond - if len(listIDs) > 0 { - listIDCond = builder.In("list_id", listIDs) - listCond = listIDCond + var projectIDCond builder.Cond + var projectCond builder.Cond + if len(projectIDs) > 0 { + projectIDCond = builder.In("project_id", projectIDs) + projectCond = projectIDCond } - if hasFavoritesList { + if hasFavoritesProject { // Make sure users can only see their favorites - userLists, _, _, err := getRawListsForUser( + userProjects, _, _, err := getRawProjectsForUser( s, - &listOptions{ + &projectOptions{ user: &user.User{ID: a.GetID()}, page: -1, }, @@ -416,9 +416,9 @@ func getRawTasksForLists(s *xorm.Session, lists []*List, a web.Auth, opts *taskO return nil, 0, 0, err } - userListIDs := make([]int64, 0, len(userLists)) - for _, l := range userLists { - userListIDs = append(userListIDs, l.ID) + userProjectIDs := make([]int64, 0, len(userProjects)) + for _, l := range userProjects { + userProjectIDs = append(userProjectIDs, l.ID) } // All favorite tasks for that user @@ -431,7 +431,7 @@ func getRawTasksForLists(s *xorm.Session, lists []*List, a web.Auth, opts *taskO builder.Eq{"kind": FavoriteKindTask}, )) - listCond = builder.And(listCond, builder.And(builder.In("id", favCond), builder.In("list_id", userListIDs))) + projectCond = builder.And(projectCond, builder.And(builder.In("id", favCond), builder.In("project_id", userProjectIDs))) } if len(reminderFilters) > 0 { @@ -462,10 +462,10 @@ func getRawTasksForLists(s *xorm.Session, lists []*List, a web.Auth, opts *taskO } cond := builder.In( - "list_id", + "project_id", builder. Select("id"). - From("lists"). + From("projects"). Where(filtercond), ) filters = append(filters, cond) @@ -482,7 +482,7 @@ func getRawTasksForLists(s *xorm.Session, lists []*List, a web.Auth, opts *taskO } limit, start := getLimitFromPageIndex(opts.page, opts.perPage) - cond := builder.And(listCond, where, filterCond) + cond := builder.And(projectCond, where, filterCond) query := s.Where(cond) if limit > 0 { @@ -505,9 +505,9 @@ func getRawTasksForLists(s *xorm.Session, lists []*List, a web.Auth, opts *taskO return tasks, len(tasks), totalItems, nil } -func getTasksForLists(s *xorm.Session, lists []*List, a web.Auth, opts *taskOptions) (tasks []*Task, resultCount int, totalItems int64, err error) { +func getTasksForProjects(s *xorm.Session, projects []*Project, a web.Auth, opts *taskOptions) (tasks []*Task, resultCount int, totalItems int64, err error) { - tasks, resultCount, totalItems, err = getRawTasksForLists(s, lists, a, opts) + tasks, resultCount, totalItems, err = getRawTasksForProjects(s, projects, a, opts) if err != nil { return nil, 0, 0, err } @@ -548,7 +548,7 @@ func GetTaskSimple(s *xorm.Session, t *Task) (task Task, err error) { return } -// GetTasksByIDs returns all tasks for a list of ids +// GetTasksByIDs returns all tasks for a project of ids func (bt *BulkTask) GetTasksByIDs(s *xorm.Session) (err error) { for _, id := range bt.IDs { if id < 1 { @@ -589,8 +589,8 @@ func getRemindersForTasks(s *xorm.Session, taskIDs []int64) (reminders []*TaskRe return } -func (t *Task) setIdentifier(list *List) { - t.Identifier = list.Identifier + "-" + strconv.FormatInt(t.Index, 10) +func (t *Task) setIdentifier(project *Project) { + t.Identifier = project.Identifier + "-" + strconv.FormatInt(t.Index, 10) } // Get all assignees @@ -715,7 +715,7 @@ func addRelatedTasksToTasks(s *xorm.Session, taskIDs []int64, taskMap map[int64] // It adds more stuff like assignees/labels/etc to a bunch of tasks func addMoreInfoToTasks(s *xorm.Session, taskMap map[int64]*Task, a web.Auth) (err error) { - // No need to iterate over users and stuff if the list doesn't have tasks + // No need to iterate over users and stuff if the project doesn't have tasks if len(taskMap) == 0 { return } @@ -723,11 +723,11 @@ func addMoreInfoToTasks(s *xorm.Session, taskMap map[int64]*Task, a web.Auth) (e // Get all users & task ids and put them into the array var userIDs []int64 var taskIDs []int64 - var listIDs []int64 + var projectIDs []int64 for _, i := range taskMap { taskIDs = append(taskIDs, i.ID) userIDs = append(userIDs, i.CreatedByID) - listIDs = append(listIDs, i.ListID) + projectIDs = append(projectIDs, i.ProjectID) } err = addAssigneesToTasks(s, taskIDs, taskMap) @@ -761,7 +761,7 @@ func addMoreInfoToTasks(s *xorm.Session, taskMap map[int64]*Task, a web.Auth) (e } // Get all identifiers - lists, err := GetListsByIDs(s, listIDs) + projects, err := GetProjectsByIDs(s, projectIDs) if err != nil { return err } @@ -778,8 +778,8 @@ func addMoreInfoToTasks(s *xorm.Session, taskMap map[int64]*Task, a web.Auth) (e // Prepare the subtasks task.RelatedTasks = make(RelatedTaskMap) - // Build the task identifier from the list identifier and task index - task.setIdentifier(lists[task.ListID]) + // Build the task identifier from the project identifier and task index + task.setIdentifier(projects[task.ProjectID]) task.IsFavorite = taskFavorites[task.ID] } @@ -789,11 +789,11 @@ func addMoreInfoToTasks(s *xorm.Session, taskMap map[int64]*Task, a web.Auth) (e return } -func checkBucketAndTaskBelongToSameList(fullTask *Task, bucket *Bucket) (err error) { - if fullTask.ListID != bucket.ListID { - return ErrBucketDoesNotBelongToList{ - ListID: fullTask.ListID, - BucketID: fullTask.BucketID, +func checkBucketAndTaskBelongToSameProject(fullTask *Task, bucket *Bucket) (err error) { + if fullTask.ProjectID != bucket.ProjectID { + return ErrBucketDoesNotBelongToProject{ + ProjectID: fullTask.ProjectID, + BucketID: fullTask.BucketID, } } @@ -821,7 +821,7 @@ func setTaskBucket(s *xorm.Session, task *Task, originalTask *Task, doCheckBucke // Make sure we have a bucket var bucket *Bucket if task.Done && originalTask != nil && !originalTask.Done { - bucket, err := getDoneBucketForList(s, task.ListID) + bucket, err := getDoneBucketForProject(s, task.ProjectID) if err != nil { return nil, err } @@ -834,9 +834,9 @@ func setTaskBucket(s *xorm.Session, task *Task, originalTask *Task, doCheckBucke task.BucketID = originalTask.BucketID } - // Either no bucket was provided or the task was moved between lists - if task.BucketID == 0 || (originalTask != nil && task.ListID != 0 && originalTask.ListID != task.ListID) { - bucket, err = getDefaultBucket(s, task.ListID) + // Either no bucket was provided or the task was moved between projects + if task.BucketID == 0 || (originalTask != nil && task.ProjectID != 0 && originalTask.ProjectID != task.ProjectID) { + bucket, err = getDefaultBucket(s, task.ProjectID) if err != nil { return } @@ -850,8 +850,8 @@ func setTaskBucket(s *xorm.Session, task *Task, originalTask *Task, doCheckBucke } } - // If there is a bucket set, make sure they belong to the same list as the task - err = checkBucketAndTaskBelongToSameList(task, bucket) + // If there is a bucket set, make sure they belong to the same project as the task + err = checkBucketAndTaskBelongToSameProject(task, bucket) if err != nil { return } @@ -879,10 +879,10 @@ func calculateDefaultPosition(entityID int64, position float64) float64 { return position } -func getNextTaskIndex(s *xorm.Session, listID int64) (nextIndex int64, err error) { +func getNextTaskIndex(s *xorm.Session, projectID int64) (nextIndex int64, err error) { latestTask := &Task{} _, err = s. - Where("list_id = ?", listID). + Where("project_id = ?", projectID). OrderBy("`index` desc"). Get(latestTask) if err != nil { @@ -892,20 +892,20 @@ func getNextTaskIndex(s *xorm.Session, listID int64) (nextIndex int64, err error return latestTask.Index + 1, nil } -// Create is the implementation to create a list task +// Create is the implementation to create a project task // @Summary Create a task -// @Description Inserts a task into a list. +// @Description Inserts a task into a project. // @tags task // @Accept json // @Produce json // @Security JWTKeyAuth -// @Param id path int true "List ID" +// @Param id path int true "Project ID" // @Param task body models.Task true "The task object" // @Success 201 {object} models.Task "The created task object." // @Failure 400 {object} web.HTTPError "Invalid task object provided." -// @Failure 403 {object} web.HTTPError "The user does not have access to the list" +// @Failure 403 {object} web.HTTPError "The user does not have access to the project" // @Failure 500 {object} models.Message "Internal error" -// @Router /lists/{id} [put] +// @Router /projects/{id} [put] func (t *Task) Create(s *xorm.Session, a web.Auth) (err error) { return createTask(s, t, a, true) } @@ -919,8 +919,8 @@ func createTask(s *xorm.Session, t *Task, a web.Auth, updateAssignees bool) (err return ErrTaskCannotBeEmpty{} } - // Check if the list exists - l, err := GetListSimpleByID(s, t.ListID) + // Check if the project exists + l, err := GetProjectSimpleByID(s, t.ProjectID) if err != nil { return err } @@ -943,7 +943,7 @@ func createTask(s *xorm.Session, t *Task, a web.Auth, updateAssignees bool) (err } // Get the index for this task - t.Index, err = getNextTaskIndex(s, t.ListID) + t.Index, err = getNextTaskIndex(s, t.ProjectID) if err != nil { return err } @@ -985,11 +985,11 @@ func createTask(s *xorm.Session, t *Task, a web.Auth, updateAssignees bool) (err return err } - err = updateListLastUpdated(s, &List{ID: t.ListID}) + err = updateProjectLastUpdated(s, &Project{ID: t.ProjectID}) return } -// Update updates a list task +// Update updates a project task // @Summary Update a task // @Description Updates a task. This includes marking it as done. Assignees you pass will be updated, see their individual endpoints for more details on how this is done. To update labels, see the description of the endpoint. // @tags task @@ -1000,7 +1000,7 @@ func createTask(s *xorm.Session, t *Task, a web.Auth, updateAssignees bool) (err // @Param task body models.Task true "The task object" // @Success 200 {object} models.Task "The updated task object." // @Failure 400 {object} web.HTTPError "Invalid task object provided." -// @Failure 403 {object} web.HTTPError "The user does not have access to the task (aka its list)" +// @Failure 403 {object} web.HTTPError "The user does not have access to the task (aka its project)" // @Failure 500 {object} models.Message "Internal error" // @Router /tasks/{id} [post] // @@ -1013,8 +1013,8 @@ func (t *Task) Update(s *xorm.Session, a web.Auth) (err error) { return } - if t.ListID == 0 { - t.ListID = ot.ListID + if t.ProjectID == 0 { + t.ProjectID = ot.ProjectID } // Get the reminders @@ -1066,7 +1066,7 @@ func (t *Task) Update(s *xorm.Session, a web.Auth) (err error) { "hex_color", "done_at", "percent_done", - "list_id", + "project_id", "bucket_id", "position", "repeat_mode", @@ -1074,9 +1074,9 @@ func (t *Task) Update(s *xorm.Session, a web.Auth) (err error) { "cover_image_attachment_id", } - // If the task is being moved between lists, make sure to move the bucket + index as well - if t.ListID != 0 && ot.ListID != t.ListID { - t.Index, err = getNextTaskIndex(s, t.ListID) + // If the task is being moved between projects, make sure to move the bucket + index as well + if t.ProjectID != 0 && ot.ProjectID != t.ProjectID { + t.Index, err = getNextTaskIndex(s, t.ProjectID) if err != nil { return err } @@ -1242,7 +1242,7 @@ func (t *Task) Update(s *xorm.Session, a web.Auth) (err error) { return err } - return updateListLastUpdated(s, &List{ID: t.ListID}) + return updateProjectLastUpdated(s, &Project{ID: t.ProjectID}) } func recalculateTaskKanbanPositions(s *xorm.Session, bucketID int64) (err error) { @@ -1510,7 +1510,7 @@ func (t *Task) updateReminders(s *xorm.Session, reminders []time.Time) (err erro t.Reminders = nil } - err = updateListLastUpdated(s, &List{ID: t.ListID}) + err = updateProjectLastUpdated(s, &Project{ID: t.ProjectID}) return } @@ -1519,16 +1519,16 @@ func updateTaskLastUpdated(s *xorm.Session, task *Task) error { return err } -// Delete implements the delete method for listTask +// Delete implements the delete method for a task // @Summary Delete a task -// @Description Deletes a task from a list. This does not mean "mark it done". +// @Description Deletes a task from a project. This does not mean "mark it done". // @tags task // @Produce json // @Security JWTKeyAuth // @Param id path int true "Task ID" // @Success 200 {object} models.Message "The created task object." // @Failure 400 {object} web.HTTPError "Invalid task ID provided." -// @Failure 403 {object} web.HTTPError "The user does not have access to the list" +// @Failure 403 {object} web.HTTPError "The user does not have access to the project" // @Failure 500 {object} models.Message "Internal error" // @Router /tasks/{id} [delete] func (t *Task) Delete(s *xorm.Session, a web.Auth) (err error) { @@ -1594,7 +1594,7 @@ func (t *Task) Delete(s *xorm.Session, a web.Auth) (err error) { return } - err = updateListLastUpdated(s, &List{ID: t.ListID}) + err = updateProjectLastUpdated(s, &Project{ID: t.ProjectID}) return } diff --git a/pkg/models/tasks_rights.go b/pkg/models/tasks_rights.go index eef78492b..d60267b45 100644 --- a/pkg/models/tasks_rights.go +++ b/pkg/models/tasks_rights.go @@ -26,15 +26,15 @@ func (t *Task) CanDelete(s *xorm.Session, a web.Auth) (bool, error) { return t.canDoTask(s, a) } -// CanUpdate determines if a user has the right to update a list task +// CanUpdate determines if a user has the right to update a project task func (t *Task) CanUpdate(s *xorm.Session, a web.Auth) (bool, error) { return t.canDoTask(s, a) } -// CanCreate determines if a user has the right to create a list task +// CanCreate determines if a user has the right to create a project task func (t *Task) CanCreate(s *xorm.Session, a web.Auth) (bool, error) { - // A user can do a task if he has write acces to its list - l := &List{ID: t.ListID} + // A user can do a task if he has write acces to its project + l := &Project{ID: t.ProjectID} return l.CanWrite(s, a) } @@ -46,8 +46,8 @@ func (t *Task) CanRead(s *xorm.Session, a web.Auth) (canRead bool, maxRight int, return } - // A user can read a task if it has access to the list - l := &List{ID: t.ListID} + // A user can read a task if it has access to the project + l := &Project{ID: t.ProjectID} return l.CanRead(s, a) } @@ -56,7 +56,7 @@ func (t *Task) CanWrite(s *xorm.Session, a web.Auth) (canWrite bool, err error) return t.canDoTask(s, a) } -// Helper function to check if a user can do stuff on a list task +// Helper function to check if a user can do stuff on a project task func (t *Task) canDoTask(s *xorm.Session, a web.Auth) (bool, error) { // Get the task ot, err := GetTaskByIDSimple(s, t.ID) @@ -64,10 +64,10 @@ func (t *Task) canDoTask(s *xorm.Session, a web.Auth) (bool, error) { return false, err } - // Check if we're moving the task into a different list to check if the user has sufficient rights for that on the new list - if t.ListID != 0 && t.ListID != ot.ListID { - newList := &List{ID: t.ListID} - can, err := newList.CanWrite(s, a) + // Check if we're moving the task into a different project to check if the user has sufficient rights for that on the new project + if t.ProjectID != 0 && t.ProjectID != ot.ProjectID { + newProject := &Project{ID: t.ProjectID} + can, err := newProject.CanWrite(s, a) if err != nil { return false, err } @@ -76,7 +76,7 @@ func (t *Task) canDoTask(s *xorm.Session, a web.Auth) (bool, error) { } } - // A user can do a task if it has write acces to its list - l := &List{ID: ot.ListID} + // A user can do a task if it has write acces to its project + l := &Project{ID: ot.ProjectID} return l.CanWrite(s, a) } diff --git a/pkg/models/tasks_test.go b/pkg/models/tasks_test.go index a6bbc71c4..fb712eb06 100644 --- a/pkg/models/tasks_test.go +++ b/pkg/models/tasks_test.go @@ -45,7 +45,7 @@ func TestTask_Create(t *testing.T) { task := &Task{ Title: "Lorem", Description: "Lorem Ipsum Dolor", - ListID: 1, + ProjectID: 1, } err := task.Create(s, usr) assert.NoError(t, err) @@ -63,7 +63,7 @@ func TestTask_Create(t *testing.T) { "id": task.ID, "title": "Lorem", "description": "Lorem Ipsum Dolor", - "list_id": 1, + "project_id": 1, "created_by_id": 1, "bucket_id": 1, }, false) @@ -78,13 +78,13 @@ func TestTask_Create(t *testing.T) { task := &Task{ Title: "", Description: "Lorem Ipsum Dolor", - ListID: 1, + ProjectID: 1, } err := task.Create(s, usr) assert.Error(t, err) assert.True(t, IsErrTaskCannotBeEmpty(err)) }) - t.Run("nonexistant list", func(t *testing.T) { + t.Run("nonexistant project", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() defer s.Close() @@ -92,11 +92,11 @@ func TestTask_Create(t *testing.T) { task := &Task{ Title: "Test", Description: "Lorem Ipsum Dolor", - ListID: 9999999, + ProjectID: 9999999, } err := task.Create(s, usr) assert.Error(t, err) - assert.True(t, IsErrListDoesNotExist(err)) + assert.True(t, IsErrProjectDoesNotExist(err)) }) t.Run("noneixtant user", func(t *testing.T) { db.LoadAndAssertFixtures(t) @@ -107,7 +107,7 @@ func TestTask_Create(t *testing.T) { task := &Task{ Title: "Test", Description: "Lorem Ipsum Dolor", - ListID: 1, + ProjectID: 1, } err := task.Create(s, nUser) assert.Error(t, err) @@ -121,7 +121,7 @@ func TestTask_Create(t *testing.T) { task := &Task{ Title: "Lorem", Description: "Lorem Ipsum Dolor", - ListID: 1, + ProjectID: 1, BucketID: 2, // Bucket 2 already has 3 tasks and a limit of 3 } err := task.Create(s, usr) @@ -142,7 +142,7 @@ func TestTask_Update(t *testing.T) { ID: 1, Title: "test10000", Description: "Lorem Ipsum Dolor", - ListID: 1, + ProjectID: 1, } err := task.Update(s, u) assert.NoError(t, err) @@ -153,7 +153,7 @@ func TestTask_Update(t *testing.T) { "id": 1, "title": "test10000", "description": "Lorem Ipsum Dolor", - "list_id": 1, + "project_id": 1, }, false) }) t.Run("nonexistant task", func(t *testing.T) { @@ -165,7 +165,7 @@ func TestTask_Update(t *testing.T) { ID: 9999999, Title: "test10000", Description: "Lorem Ipsum Dolor", - ListID: 1, + ProjectID: 1, } err := task.Update(s, u) assert.Error(t, err) @@ -180,7 +180,7 @@ func TestTask_Update(t *testing.T) { ID: 1, Title: "test10000", Description: "Lorem Ipsum Dolor", - ListID: 1, + ProjectID: 1, BucketID: 2, // Bucket 2 already has 3 tasks and a limit of 3 } err := task.Update(s, u) @@ -197,13 +197,13 @@ func TestTask_Update(t *testing.T) { Title: "test10000", Description: "Lorem Ipsum Dolor", KanbanPosition: 10, - ListID: 1, + ProjectID: 1, BucketID: 2, // Bucket 2 already has 3 tasks and a limit of 3 } err := task.Update(s, u) assert.NoError(t, err) }) - t.Run("bucket on other list", func(t *testing.T) { + t.Run("bucket on other project", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() defer s.Close() @@ -212,12 +212,12 @@ func TestTask_Update(t *testing.T) { ID: 1, Title: "test10000", Description: "Lorem Ipsum Dolor", - ListID: 1, - BucketID: 4, // Bucket 4 belongs to list 2 + ProjectID: 1, + BucketID: 4, // Bucket 4 belongs to project 2 } err := task.Update(s, u) assert.Error(t, err) - assert.True(t, IsErrBucketDoesNotBelongToList(err)) + assert.True(t, IsErrBucketDoesNotBelongToProject(err)) }) t.Run("moving a task to the done bucket", func(t *testing.T) { db.LoadAndAssertFixtures(t) @@ -225,10 +225,10 @@ func TestTask_Update(t *testing.T) { defer s.Close() task := &Task{ - ID: 1, - Title: "test", - ListID: 1, - BucketID: 3, // Bucket 3 is the done bucket + ID: 1, + Title: "test", + ProjectID: 1, + BucketID: 3, // Bucket 3 is the done bucket } err := task.Update(s, u) assert.NoError(t, err) @@ -237,11 +237,11 @@ func TestTask_Update(t *testing.T) { assert.True(t, task.Done) db.AssertExists(t, "tasks", map[string]interface{}{ - "id": 1, - "done": true, - "title": "test", - "list_id": 1, - "bucket_id": 3, + "id": 1, + "done": true, + "title": "test", + "project_id": 1, + "bucket_id": 3, }, false) }) t.Run("moving a repeating task to the done bucket", func(t *testing.T) { @@ -252,7 +252,7 @@ func TestTask_Update(t *testing.T) { task := &Task{ ID: 28, Title: "test updated", - ListID: 1, + ProjectID: 1, BucketID: 3, // Bucket 3 is the done bucket RepeatAfter: 3600, } @@ -271,21 +271,21 @@ func TestTask_Update(t *testing.T) { "bucket_id": 1, }, false) }) - t.Run("default bucket when moving a task between lists", func(t *testing.T) { + t.Run("default bucket when moving a task between projects", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() defer s.Close() task := &Task{ - ID: 1, - ListID: 2, + ID: 1, + ProjectID: 2, } err := task.Update(s, u) assert.NoError(t, err) err = s.Commit() assert.NoError(t, err) - assert.Equal(t, int64(4), task.BucketID) // bucket 4 is the default bucket on list 2 + assert.Equal(t, int64(4), task.BucketID) // bucket 4 is the default bucket on project 2 assert.True(t, task.Done) // bucket 4 is the done bucket, so the task should be marked as done as well }) t.Run("marking a task as done should move it to the done bucket", func(t *testing.T) { @@ -310,14 +310,14 @@ func TestTask_Update(t *testing.T) { "bucket_id": 3, }, false) }) - t.Run("move task to another list", func(t *testing.T) { + t.Run("move task to another project", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() defer s.Close() task := &Task{ - ID: 1, - ListID: 2, + ID: 1, + ProjectID: 2, } err := task.Update(s, u) assert.NoError(t, err) @@ -325,9 +325,9 @@ func TestTask_Update(t *testing.T) { assert.NoError(t, err) db.AssertExists(t, "tasks", map[string]interface{}{ - "id": 1, - "list_id": 2, - "bucket_id": 4, + "id": 1, + "project_id": 2, + "bucket_id": 4, }, false) }) t.Run("repeating tasks should not be moved to the done bucket", func(t *testing.T) { @@ -353,14 +353,14 @@ func TestTask_Update(t *testing.T) { "bucket_id": 1, }, false) }) - t.Run("moving a task between lists should give it a correct index", func(t *testing.T) { + t.Run("moving a task between projects should give it a correct index", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() defer s.Close() task := &Task{ - ID: 12, - ListID: 2, // From list 1 + ID: 12, + ProjectID: 2, // From project 1 } err := task.Update(s, u) assert.NoError(t, err) diff --git a/pkg/models/team_members_rights.go b/pkg/models/team_members_rights.go index b1a3db2b4..d87fd088d 100644 --- a/pkg/models/team_members_rights.go +++ b/pkg/models/team_members_rights.go @@ -46,7 +46,7 @@ func (tm *TeamMember) CanUpdate(s *xorm.Session, a web.Auth) (bool, error) { // IsAdmin checks if the user is team admin func (tm *TeamMember) IsAdmin(s *xorm.Session, a web.Auth) (bool, error) { - // Don't allow anything if we're dealing with a list share here + // Don't allow anything if we're dealing with a project share here if _, is := a.(*LinkSharing); is { return false, nil } diff --git a/pkg/models/teams.go b/pkg/models/teams.go index 0b21a5bd9..12a39095f 100644 --- a/pkg/models/teams.go +++ b/pkg/models/teams.go @@ -163,7 +163,7 @@ func addMoreInfoToTeams(s *xorm.Session, teams []*Team) (err error) { teamMap[u.TeamID].Members = append(teamMap[u.TeamID].Members, u) } - // We need to do this in a second loop as owners might not be the last ones in the list + // We need to do this in a second loop as owners might not be the last ones in the project for _, team := range teamMap { if teamUser, has := users[team.CreatedByID]; has { team.CreatedBy = &teamUser.User @@ -313,8 +313,8 @@ func (t *Team) Delete(s *xorm.Session, a web.Auth) (err error) { return } - // Delete team <-> lists relations - _, err = s.Where("team_id = ?", t.ID).Delete(&TeamList{}) + // Delete team <-> projects relations + _, err = s.Where("team_id = ?", t.ID).Delete(&TeamProject{}) if err != nil { return } diff --git a/pkg/models/teams_test.go b/pkg/models/teams_test.go index 590dc4de6..5bbaf6518 100644 --- a/pkg/models/teams_test.go +++ b/pkg/models/teams_test.go @@ -117,7 +117,7 @@ func TestTeam_ReadAll(t *testing.T) { defer s.Close() team := &Team{} - teams, _, _, err := team.ReadAll(s, doer, "READ_only_on_list6", 1, 50) + teams, _, _, err := team.ReadAll(s, doer, "READ_only_on_project6", 1, 50) assert.NoError(t, err) assert.Equal(t, reflect.TypeOf(teams).Kind(), reflect.Slice) ts := teams.([]*Team) diff --git a/pkg/models/unit_tests.go b/pkg/models/unit_tests.go index 2597bd12e..ce9b80714 100644 --- a/pkg/models/unit_tests.go +++ b/pkg/models/unit_tests.go @@ -47,7 +47,7 @@ func SetupTests() { "label_tasks", "labels", "link_shares", - "lists", + "projects", "namespaces", "task_assignees", "task_attachments", @@ -55,13 +55,13 @@ func SetupTests() { "task_relations", "task_reminders", "tasks", - "team_lists", + "team_projects", "team_members", "team_namespaces", "teams", "users", "user_tokens", - "users_lists", + "users_projects", "users_namespaces", "buckets", "saved_filters", diff --git a/pkg/models/user_delete.go b/pkg/models/user_delete.go index cd168804f..55858c149 100644 --- a/pkg/models/user_delete.go +++ b/pkg/models/user_delete.go @@ -99,7 +99,7 @@ func getNamespacesToDelete(s *xorm.Session, u *user.User) (namespacesToDelete [] return nil, nil } - namespaces := res.([]*NamespaceWithLists) + namespaces := res.([]*NamespaceWithProjects) for _, n := range namespaces { if n.ID < 0 { continue @@ -126,9 +126,9 @@ func getNamespacesToDelete(s *xorm.Session, u *user.User) (namespacesToDelete [] return } -func getListsToDelete(s *xorm.Session, u *user.User) (listsToDelete []*List, err error) { - listsToDelete = []*List{} - lm := &List{IsArchived: true} +func getProjectsToDelete(s *xorm.Session, u *user.User) (projectsToDelete []*Project, err error) { + projectsToDelete = []*Project{} + lm := &Project{IsArchived: true} res, _, _, err := lm.ReadAll(s, u, "", 0, -1) if err != nil { return nil, err @@ -138,20 +138,20 @@ func getListsToDelete(s *xorm.Session, u *user.User) (listsToDelete []*List, err return nil, nil } - lists := res.([]*List) - for _, l := range lists { + projects := res.([]*Project) + for _, l := range projects { if l.ID < 0 { continue } - hadUsers, err := ensureListAdminUser(s, l) + hadUsers, err := ensureProjectAdminUser(s, l) if err != nil { return nil, err } if hadUsers { continue } - hadTeams, err := ensureListAdminTeam(s, l) + hadTeams, err := ensureProjectAdminTeam(s, l) if err != nil { return nil, err } @@ -160,13 +160,13 @@ func getListsToDelete(s *xorm.Session, u *user.User) (listsToDelete []*List, err continue } - listsToDelete = append(listsToDelete, l) + projectsToDelete = append(projectsToDelete, l) } return } -// DeleteUser completely removes a user and all their associated lists, namespaces and tasks. +// DeleteUser completely removes a user and all their associated projects, namespaces and tasks. // This action is irrevocable. // Public to allow deletion from the CLI. func DeleteUser(s *xorm.Session, u *user.User) (err error) { @@ -175,7 +175,7 @@ func DeleteUser(s *xorm.Session, u *user.User) (err error) { return err } - listsToDelete, err := getListsToDelete(s, u) + projectsToDelete, err := getProjectsToDelete(s, u) if err != nil { return err } @@ -188,7 +188,7 @@ func DeleteUser(s *xorm.Session, u *user.User) (err error) { } } - for _, l := range listsToDelete { + for _, l := range projectsToDelete { err = l.Delete(s, u) if err != nil { return err @@ -218,7 +218,7 @@ func ensureNamespaceAdminUser(s *xorm.Session, n *Namespace) (hadUsers bool, err for _, lu := range namespaceUsers { if lu.Right == RightAdmin { - // List already has more than one admin, no need to do anything + // Project already has more than one admin, no need to do anything return true, nil } } @@ -244,7 +244,7 @@ func ensureNamespaceAdminTeam(s *xorm.Session, n *Namespace) (hadTeams bool, err for _, lu := range namespaceTeams { if lu.Right == RightAdmin { - // List already has more than one admin, no need to do anything + // Project already has more than one admin, no need to do anything return true, nil } } @@ -257,25 +257,25 @@ func ensureNamespaceAdminTeam(s *xorm.Session, n *Namespace) (hadTeams bool, err return true, err } -func ensureListAdminUser(s *xorm.Session, l *List) (hadUsers bool, err error) { - listUsers := []*ListUser{} - err = s.Where("list_id = ?", l.ID).Find(&listUsers) +func ensureProjectAdminUser(s *xorm.Session, l *Project) (hadUsers bool, err error) { + projectUsers := []*ProjectUser{} + err = s.Where("project_id = ?", l.ID).Find(&projectUsers) if err != nil { return } - if len(listUsers) == 0 { + if len(projectUsers) == 0 { return false, nil } - for _, lu := range listUsers { + for _, lu := range projectUsers { if lu.Right == RightAdmin { - // List already has more than one admin, no need to do anything + // Project already has more than one admin, no need to do anything return true, nil } } - firstUser := listUsers[0] + firstUser := projectUsers[0] firstUser.Right = RightAdmin _, err = s.Where("id = ?", firstUser.ID). Cols("right"). @@ -283,25 +283,25 @@ func ensureListAdminUser(s *xorm.Session, l *List) (hadUsers bool, err error) { return true, err } -func ensureListAdminTeam(s *xorm.Session, l *List) (hadTeams bool, err error) { - listTeams := []*TeamList{} - err = s.Where("list_id = ?", l.ID).Find(&listTeams) +func ensureProjectAdminTeam(s *xorm.Session, l *Project) (hadTeams bool, err error) { + projectTeams := []*TeamProject{} + err = s.Where("project_id = ?", l.ID).Find(&projectTeams) if err != nil { return } - if len(listTeams) == 0 { + if len(projectTeams) == 0 { return false, nil } - for _, lu := range listTeams { + for _, lu := range projectTeams { if lu.Right == RightAdmin { - // List already has more than one admin, no need to do anything + // Project already has more than one admin, no need to do anything return true, nil } } - firstTeam := listTeams[0] + firstTeam := projectTeams[0] firstTeam.Right = RightAdmin _, err = s.Where("id = ?", firstTeam.ID). Cols("right"). diff --git a/pkg/models/user_delete_test.go b/pkg/models/user_delete_test.go index bed04ffd7..0d1811b08 100644 --- a/pkg/models/user_delete_test.go +++ b/pkg/models/user_delete_test.go @@ -38,13 +38,13 @@ func TestDeleteUser(t *testing.T) { assert.NoError(t, err) db.AssertMissing(t, "users", map[string]interface{}{"id": u.ID}) - db.AssertMissing(t, "lists", map[string]interface{}{"id": 24}) // only user6 had access to this list - db.AssertExists(t, "lists", map[string]interface{}{"id": 6}, false) - db.AssertExists(t, "lists", map[string]interface{}{"id": 7}, false) - db.AssertExists(t, "lists", map[string]interface{}{"id": 8}, false) - db.AssertExists(t, "lists", map[string]interface{}{"id": 9}, false) - db.AssertExists(t, "lists", map[string]interface{}{"id": 10}, false) - db.AssertExists(t, "lists", map[string]interface{}{"id": 11}, false) + db.AssertMissing(t, "projects", map[string]interface{}{"id": 24}) // only user6 had access to this project + db.AssertExists(t, "projects", map[string]interface{}{"id": 6}, false) + db.AssertExists(t, "projects", map[string]interface{}{"id": 7}, false) + db.AssertExists(t, "projects", map[string]interface{}{"id": 8}, false) + db.AssertExists(t, "projects", map[string]interface{}{"id": 9}, false) + db.AssertExists(t, "projects", map[string]interface{}{"id": 10}, false) + db.AssertExists(t, "projects", map[string]interface{}{"id": 11}, false) }) t.Run("user with no namespaces", func(t *testing.T) { db.LoadAndAssertFixtures(t) @@ -56,6 +56,6 @@ func TestDeleteUser(t *testing.T) { err := DeleteUser(s, u) assert.NoError(t, err) - // No assertions for deleted lists and namespaces since that user doesn't have any + // No assertions for deleted projects and namespaces since that user doesn't have any }) } diff --git a/pkg/models/user_list.go b/pkg/models/user_list.go index b4efa2c32..fb7a54620 100644 --- a/pkg/models/user_list.go +++ b/pkg/models/user_list.go @@ -22,38 +22,38 @@ import ( "xorm.io/xorm" ) -// ListUIDs hold all kinds of user IDs from accounts who have somehow access to a list -type ListUIDs struct { - ListOwnerID int64 `xorm:"listOwner"` +// ProjectUIDs hold all kinds of user IDs from accounts who have somehow access to a project +type ProjectUIDs struct { + ProjectOwnerID int64 `xorm:"projectOwner"` NamespaceUserID int64 `xorm:"unID"` - ListUserID int64 `xorm:"ulID"` + ProjectUserID int64 `xorm:"ulID"` NamespaceOwnerUserID int64 `xorm:"nOwner"` TeamNamespaceUserID int64 `xorm:"tnUID"` - TeamListUserID int64 `xorm:"tlUID"` + TeamProjectUserID int64 `xorm:"tlUID"` } -// ListUsersFromList returns a list with all users who have access to a list, regardless of the method which gave them access -func ListUsersFromList(s *xorm.Session, l *List, search string) (users []*user.User, err error) { +// ProjectUsersFromProject returns a project with all users who have access to a project, regardless of the method which gave them access +func ProjectUsersFromProject(s *xorm.Session, l *Project, search string) (users []*user.User, err error) { - userids := []*ListUIDs{} + userids := []*ProjectUIDs{} err = s. - Select(`l.owner_id as listOwner, + Select(`l.owner_id as projectOwner, un.user_id as unID, ul.user_id as ulID, n.owner_id as nOwner, tm.user_id as tnUID, tm2.user_id as tlUID`). - Table("lists"). + Table("projects"). Alias("l"). // User stuff Join("LEFT", []string{"users_namespaces", "un"}, "un.namespace_id = l.namespace_id"). - Join("LEFT", []string{"users_lists", "ul"}, "ul.list_id = l.id"). + Join("LEFT", []string{"users_projects", "ul"}, "ul.project_id = l.id"). Join("LEFT", []string{"namespaces", "n"}, "n.id = l.namespace_id"). // Team stuff Join("LEFT", []string{"team_namespaces", "tn"}, " l.namespace_id = tn.namespace_id"). Join("LEFT", []string{"team_members", "tm"}, "tm.team_id = tn.team_id"). - Join("LEFT", []string{"team_lists", "tl"}, "l.id = tl.list_id"). + Join("LEFT", []string{"team_projects", "tl"}, "l.id = tl.project_id"). Join("LEFT", []string{"team_members", "tm2"}, "tm2.team_id = tl.team_id"). // The actual condition Where( @@ -80,14 +80,14 @@ func ListUsersFromList(s *xorm.Session, l *List, search string) (users []*user.U return } - // Remove duplicates from the list of ids and make it a slice + // Remove duplicates from the project of ids and make it a slice uidmap := make(map[int64]bool) uidmap[l.OwnerID] = true for _, u := range userids { - uidmap[u.ListUserID] = true + uidmap[u.ProjectUserID] = true uidmap[u.NamespaceOwnerUserID] = true uidmap[u.NamespaceUserID] = true - uidmap[u.TeamListUserID] = true + uidmap[u.TeamProjectUserID] = true uidmap[u.TeamNamespaceUserID] = true } @@ -102,7 +102,7 @@ func ListUsersFromList(s *xorm.Session, l *List, search string) (users []*user.U cond = builder.In("id", uids) } - users, err = user.ListUsers(s, search, &user.ListUserOpts{ + users, err = user.ProjectUsers(s, search, &user.ProjectUserOpts{ AdditionalCond: cond, ReturnAllIfNoSearchProvided: true, }) diff --git a/pkg/models/users_list_test.go b/pkg/models/users_list_test.go index a98356071..1ec039ee9 100644 --- a/pkg/models/users_list_test.go +++ b/pkg/models/users_list_test.go @@ -24,7 +24,7 @@ import ( "gopkg.in/d4l3k/messagediff.v1" ) -func TestListUsersFromList(t *testing.T) { +func TestProjectUsersFromProject(t *testing.T) { testuser1 := &user.User{ ID: 1, Username: "user1", @@ -176,7 +176,7 @@ func TestListUsersFromList(t *testing.T) { } type args struct { - l *List + l *Project search string } tests := []struct { @@ -187,13 +187,13 @@ func TestListUsersFromList(t *testing.T) { }{ { name: "Check owner only", - args: args{l: &List{ID: 18, OwnerID: 7}}, + args: args{l: &Project{ID: 18, OwnerID: 7}}, wantUsers: []*user.User{testuser7}, }, { - // This list has another different user shared for each possible method + // This project has another different user shared for each possible method name: "Check with owner and other users", - args: args{l: &List{ID: 19, OwnerID: 7}}, + args: args{l: &Project{ID: 19, OwnerID: 7}}, wantUsers: []*user.User{ testuser1, // Shared Via Team readonly testuser2, // Shared Via Team write @@ -216,7 +216,7 @@ func TestListUsersFromList(t *testing.T) { }, { name: "search for user1", - args: args{l: &List{ID: 19, OwnerID: 7}, search: "user1"}, + args: args{l: &Project{ID: 19, OwnerID: 7}, search: "user1"}, wantUsers: []*user.User{ testuser1, // Shared Via Team readonly }, @@ -228,9 +228,9 @@ func TestListUsersFromList(t *testing.T) { s := db.NewSession() defer s.Close() - gotUsers, err := ListUsersFromList(s, tt.args.l, tt.args.search) + gotUsers, err := ProjectUsersFromProject(s, tt.args.l, tt.args.search) if (err != nil) != tt.wantErr { - t.Errorf("ListUsersFromList() error = %v, wantErr %v", err, tt.wantErr) + t.Errorf("ProjectUsersFromProject() error = %v, wantErr %v", err, tt.wantErr) return } if diff, equal := messagediff.PrettyDiff(tt.wantUsers, gotUsers); !equal { diff --git a/pkg/modules/auth/auth.go b/pkg/modules/auth/auth.go index 54c6ba721..2faada9a1 100644 --- a/pkg/modules/auth/auth.go +++ b/pkg/modules/auth/auth.go @@ -89,7 +89,7 @@ func NewLinkShareJWTAuthtoken(share *models.LinkSharing) (token string, err erro claims["type"] = AuthTypeLinkShare claims["id"] = share.ID claims["hash"] = share.Hash - claims["list_id"] = share.ListID + claims["project_id"] = share.ProjectID claims["right"] = share.Right claims["sharedByID"] = share.SharedByID claims["exp"] = exp diff --git a/pkg/modules/background/background.go b/pkg/modules/background/background.go index bd6cc2ab1..4bbc1f55f 100644 --- a/pkg/modules/background/background.go +++ b/pkg/modules/background/background.go @@ -22,7 +22,7 @@ import ( "xorm.io/xorm" ) -// Image represents an image which can be used as a list background +// Image represents an image which can be used as a project background type Image struct { ID string `json:"id"` URL string `json:"url"` @@ -32,10 +32,10 @@ type Image struct { Info interface{} `json:"info,omitempty"` } -// Provider represents something that is able to get a list of images and set one of them as background +// Provider represents something that is able to get a project of images and set one of them as background type Provider interface { - // Search is used to either return a pre-defined list of Image or let the user search for an image + // Search is used to either return a pre-defined project of Image or let the user search for an image Search(s *xorm.Session, search string, page int64) (result []*Image, err error) - // Set sets an image which was most likely previously obtained by Search as list background - Set(s *xorm.Session, image *Image, list *models.List, auth web.Auth) (err error) + // Set sets an image which was most likely previously obtained by Search as project background + Set(s *xorm.Session, image *Image, project *models.Project, auth web.Auth) (err error) } diff --git a/pkg/modules/background/handler/background.go b/pkg/modules/background/handler/background.go index f5c3fc243..a0e9f175f 100644 --- a/pkg/modules/background/handler/background.go +++ b/pkg/modules/background/handler/background.go @@ -92,38 +92,38 @@ func (bp *BackgroundProvider) SearchBackgrounds(c echo.Context) error { } // This function does all kinds of preparations for setting and uploading a background -func (bp *BackgroundProvider) setBackgroundPreparations(s *xorm.Session, c echo.Context) (list *models.List, auth web.Auth, err error) { +func (bp *BackgroundProvider) setBackgroundPreparations(s *xorm.Session, c echo.Context) (project *models.Project, auth web.Auth, err error) { auth, err = auth2.GetAuthFromClaims(c) if err != nil { return nil, nil, echo.NewHTTPError(http.StatusBadRequest, "Invalid auth token: "+err.Error()) } - listID, err := strconv.ParseInt(c.Param("list"), 10, 64) + projectID, err := strconv.ParseInt(c.Param("project"), 10, 64) if err != nil { - return nil, nil, echo.NewHTTPError(http.StatusBadRequest, "Invalid list ID: "+err.Error()) + return nil, nil, echo.NewHTTPError(http.StatusBadRequest, "Invalid project ID: "+err.Error()) } - // Check if the user has the right to change the list background - list = &models.List{ID: listID} - can, err := list.CanUpdate(s, auth) + // Check if the user has the right to change the project background + project = &models.Project{ID: projectID} + can, err := project.CanUpdate(s, auth) if err != nil { return } if !can { - log.Infof("Tried to update list background of list %d while not having the rights for it (User: %v)", listID, auth) - return list, auth, models.ErrGenericForbidden{} + log.Infof("Tried to update project background of project %d while not having the rights for it (User: %v)", projectID, auth) + return project, auth, models.ErrGenericForbidden{} } - // Load the list - list, err = models.GetListSimpleByID(s, list.ID) + // Load the project + project, err = models.GetProjectSimpleByID(s, project.ID) return } -// SetBackground sets an Image as list background +// SetBackground sets an Image as project background func (bp *BackgroundProvider) SetBackground(c echo.Context) error { s := db.NewSession() defer s.Close() - list, auth, err := bp.setBackgroundPreparations(s, c) + project, auth, err := bp.setBackgroundPreparations(s, c) if err != nil { _ = s.Rollback() return handler.HandleHTTPError(err, c) @@ -138,12 +138,12 @@ func (bp *BackgroundProvider) SetBackground(c echo.Context) error { return echo.NewHTTPError(http.StatusBadRequest, "No or invalid model provided: "+err.Error()) } - err = p.Set(s, image, list, auth) + err = p.Set(s, image, project, auth) if err != nil { _ = s.Rollback() return handler.HandleHTTPError(err, c) } - return c.JSON(http.StatusOK, list) + return c.JSON(http.StatusOK, project) } func CreateBlurHash(srcf io.Reader) (hash string, err error) { @@ -163,7 +163,7 @@ func (bp *BackgroundProvider) UploadBackground(c echo.Context) error { s := db.NewSession() defer s.Close() - list, auth, err := bp.setBackgroundPreparations(s, c) + project, auth, err := bp.setBackgroundPreparations(s, c) if err != nil { _ = s.Rollback() return handler.HandleHTTPError(err, c) @@ -193,7 +193,7 @@ func (bp *BackgroundProvider) UploadBackground(c echo.Context) error { return c.JSON(http.StatusBadRequest, models.Message{Message: "Uploaded file is no image."}) } - err = SaveBackgroundFile(s, auth, list, srcf, file.Filename, uint64(file.Size)) + err = SaveBackgroundFile(s, auth, project, srcf, file.Filename, uint64(file.Size)) if err != nil { _ = s.Rollback() if files.IsErrFileIsTooLarge(err) { @@ -208,10 +208,10 @@ func (bp *BackgroundProvider) UploadBackground(c echo.Context) error { return handler.HandleHTTPError(err, c) } - return c.JSON(http.StatusOK, list) + return c.JSON(http.StatusOK, project) } -func SaveBackgroundFile(s *xorm.Session, auth web.Auth, list *models.List, srcf io.ReadSeeker, filename string, filesize uint64) (err error) { +func SaveBackgroundFile(s *xorm.Session, auth web.Auth, project *models.Project, srcf io.ReadSeeker, filename string, filesize uint64) (err error) { _, _ = srcf.Seek(0, io.SeekStart) f, err := files.Create(srcf, filename, filesize, auth) if err != nil { @@ -220,7 +220,7 @@ func SaveBackgroundFile(s *xorm.Session, auth web.Auth, list *models.List, srcf // Generate a blurHash _, _ = srcf.Seek(0, io.SeekStart) - list.BackgroundBlurHash, err = CreateBlurHash(srcf) + project.BackgroundBlurHash, err = CreateBlurHash(srcf) if err != nil { return err } @@ -228,68 +228,68 @@ func SaveBackgroundFile(s *xorm.Session, auth web.Auth, list *models.List, srcf // Save it p := upload.Provider{} img := &background.Image{ID: strconv.FormatInt(f.ID, 10)} - err = p.Set(s, img, list, auth) + err = p.Set(s, img, project, auth) return err } -func checkListBackgroundRights(s *xorm.Session, c echo.Context) (list *models.List, auth web.Auth, err error) { +func checkProjectBackgroundRights(s *xorm.Session, c echo.Context) (project *models.Project, auth web.Auth, err error) { auth, err = auth2.GetAuthFromClaims(c) if err != nil { return nil, auth, echo.NewHTTPError(http.StatusBadRequest, "Invalid auth token: "+err.Error()) } - listID, err := strconv.ParseInt(c.Param("list"), 10, 64) + projectID, err := strconv.ParseInt(c.Param("project"), 10, 64) if err != nil { - return nil, auth, echo.NewHTTPError(http.StatusBadRequest, "Invalid list ID: "+err.Error()) + return nil, auth, echo.NewHTTPError(http.StatusBadRequest, "Invalid project ID: "+err.Error()) } - // Check if a background for this list exists + Rights - list = &models.List{ID: listID} - can, _, err := list.CanRead(s, auth) + // Check if a background for this project exists + Rights + project = &models.Project{ID: projectID} + can, _, err := project.CanRead(s, auth) if err != nil { _ = s.Rollback() return nil, auth, handler.HandleHTTPError(err, c) } if !can { _ = s.Rollback() - log.Infof("Tried to get list background of list %d while not having the rights for it (User: %v)", listID, auth) + log.Infof("Tried to get project background of project %d while not having the rights for it (User: %v)", projectID, auth) return nil, auth, echo.NewHTTPError(http.StatusForbidden) } return } -// GetListBackground serves a previously set background from a list +// GetProjectBackground serves a previously set background from a project // It has no knowledge of the provider that was responsible for setting the background. -// @Summary Get the list background -// @Description Get the list background of a specific list. **Returns json on error.** -// @tags list +// @Summary Get the project background +// @Description Get the project background of a specific project. **Returns json on error.** +// @tags project // @Produce octet-stream -// @Param id path int true "List ID" +// @Param id path int true "Project ID" // @Security JWTKeyAuth -// @Success 200 {} string "The list background file." -// @Failure 403 {object} models.Message "No access to this list." -// @Failure 404 {object} models.Message "The list does not exist." +// @Success 200 {} string "The project background file." +// @Failure 403 {object} models.Message "No access to this project." +// @Failure 404 {object} models.Message "The project does not exist." // @Failure 500 {object} models.Message "Internal error" -// @Router /lists/{id}/background [get] -func GetListBackground(c echo.Context) error { +// @Router /projects/{id}/background [get] +func GetProjectBackground(c echo.Context) error { s := db.NewSession() defer s.Close() - list, _, err := checkListBackgroundRights(s, c) + project, _, err := checkProjectBackgroundRights(s, c) if err != nil { return err } - if list.BackgroundFileID == 0 { + if project.BackgroundFileID == 0 { _ = s.Rollback() return echo.NotFoundHandler(c) } // Get the file bgFile := &files.File{ - ID: list.BackgroundFileID, + ID: project.BackgroundFileID, } if err := bgFile.LoadFileByID(); err != nil { _ = s.Rollback() @@ -320,23 +320,23 @@ func GetListBackground(c echo.Context) error { return c.Stream(http.StatusOK, "image/jpg", bgFile.File) } -// RemoveListBackground removes a list background, no matter the background provider -// @Summary Remove a list background -// @Description Removes a previously set list background, regardless of the list provider used to set the background. It does not throw an error if the list does not have a background. -// @tags list +// RemoveProjectBackground removes a project background, no matter the background provider +// @Summary Remove a project background +// @Description Removes a previously set project background, regardless of the project provider used to set the background. It does not throw an error if the project does not have a background. +// @tags project // @Produce json -// @Param id path int true "List ID" +// @Param id path int true "Project ID" // @Security JWTKeyAuth -// @Success 200 {object} models.List "The list" -// @Failure 403 {object} models.Message "No access to this list." -// @Failure 404 {object} models.Message "The list does not exist." +// @Success 200 {object} models.Project "The project" +// @Failure 403 {object} models.Message "No access to this project." +// @Failure 404 {object} models.Message "The project does not exist." // @Failure 500 {object} models.Message "Internal error" -// @Router /lists/{id}/background [delete] -func RemoveListBackground(c echo.Context) error { +// @Router /projects/{id}/background [delete] +func RemoveProjectBackground(c echo.Context) error { s := db.NewSession() defer s.Close() - list, auth, err := checkListBackgroundRights(s, c) + project, auth, err := checkProjectBackgroundRights(s, c) if err != nil { return err } @@ -346,13 +346,13 @@ func RemoveListBackground(c echo.Context) error { return err } - list.BackgroundFileID = 0 - list.BackgroundInformation = nil - list.BackgroundBlurHash = "" - err = models.UpdateList(s, list, auth, true) + project.BackgroundFileID = 0 + project.BackgroundInformation = nil + project.BackgroundBlurHash = "" + err = models.UpdateProject(s, project, auth, true) if err != nil { return err } - return c.JSON(http.StatusOK, list) + return c.JSON(http.StatusOK, project) } diff --git a/pkg/modules/background/unsplash/proxy.go b/pkg/modules/background/unsplash/proxy.go index 7259a42f2..0bbee208b 100644 --- a/pkg/modules/background/unsplash/proxy.go +++ b/pkg/modules/background/unsplash/proxy.go @@ -45,7 +45,7 @@ func unsplashImage(url string, c echo.Context) error { // ProxyUnsplashImage proxies a thumbnail from unsplash for privacy reasons. // @Summary Get an unsplash image // @Description Get an unsplash image. **Returns json on error.** -// @tags list +// @tags project // @Produce octet-stream // @Param image path int true "Unsplash Image ID" // @Security JWTKeyAuth @@ -65,7 +65,7 @@ func ProxyUnsplashImage(c echo.Context) error { // ProxyUnsplashThumb proxies a thumbnail from unsplash for privacy reasons. // @Summary Get an unsplash thumbnail image // @Description Get an unsplash thumbnail image. The thumbnail is cropped to a max width of 200px. **Returns json on error.** -// @tags list +// @tags project // @Produce octet-stream // @Param image path int true "Unsplash Image ID" // @Security JWTKeyAuth diff --git a/pkg/modules/background/unsplash/unsplash.go b/pkg/modules/background/unsplash/unsplash.go index 1ee15ea5f..a10cadfa0 100644 --- a/pkg/modules/background/unsplash/unsplash.go +++ b/pkg/modules/background/unsplash/unsplash.go @@ -142,8 +142,8 @@ func getUnsplashPhotoInfoByID(photoID string) (photo *Photo, err error) { // Search is the implementation to search on unsplash // @Summary Search for a background from unsplash -// @Description Search for a list background from unsplash -// @tags list +// @Description Search for a project background from unsplash +// @tags project // @Produce json // @Security JWTKeyAuth // @Param s query string false "Search backgrounds from unsplash with this search term." @@ -232,21 +232,21 @@ func (p *Provider) Search(s *xorm.Session, search string, page int64) (result [] return } -// Set sets an unsplash photo as list background -// @Summary Set an unsplash photo as list background -// @Description Sets a photo from unsplash as list background. -// @tags list +// Set sets an unsplash photo as project background +// @Summary Set an unsplash photo as project background +// @Description Sets a photo from unsplash as project background. +// @tags project // @Accept json // @Produce json // @Security JWTKeyAuth -// @Param id path int true "List ID" -// @Param list body background.Image true "The image you want to set as background" -// @Success 200 {object} models.List "The background has been successfully set." +// @Param id path int true "Project ID" +// @Param project body background.Image true "The image you want to set as background" +// @Success 200 {object} models.Project "The background has been successfully set." // @Failure 400 {object} web.HTTPError "Invalid image object provided." -// @Failure 403 {object} web.HTTPError "The user does not have access to the list" +// @Failure 403 {object} web.HTTPError "The user does not have access to the project" // @Failure 500 {object} models.Message "Internal error" -// @Router /lists/{id}/backgrounds/unsplash [post] -func (p *Provider) Set(s *xorm.Session, image *background.Image, list *models.List, auth web.Auth) (err error) { +// @Router /projects/{id}/backgrounds/unsplash [post] +func (p *Provider) Set(s *xorm.Session, image *background.Image, project *models.Project, auth web.Auth) (err error) { // Find the photo photo, err := getUnsplashPhotoInfoByID(image.ID) @@ -289,13 +289,13 @@ func (p *Provider) Set(s *xorm.Session, image *background.Image, list *models.Li } // Remove the old background if one exists - if list.BackgroundFileID != 0 { - file := files.File{ID: list.BackgroundFileID} + if project.BackgroundFileID != 0 { + file := files.File{ID: project.BackgroundFileID} if err := file.Delete(); err != nil { return err } - if err := models.RemoveUnsplashPhoto(s, list.BackgroundFileID); err != nil { + if err := models.RemoveUnsplashPhoto(s, project.BackgroundFileID); err != nil { return err } } @@ -313,12 +313,12 @@ func (p *Provider) Set(s *xorm.Session, image *background.Image, list *models.Li } log.Debugf("Saved unsplash photo %s as file %d with new entry %d", image.ID, file.ID, unsplashPhoto.ID) - // Set the file in the list - list.BackgroundFileID = file.ID - list.BackgroundInformation = unsplashPhoto + // Set the file in the project + project.BackgroundFileID = file.ID + project.BackgroundInformation = unsplashPhoto - // Set it as the list background - return models.SetListBackground(s, list.ID, file, photo.BlurHash) + // Set it as the project background + return models.SetProjectBackground(s, project.ID, file, photo.BlurHash) } // Pingback pings the unsplash api if an unsplash photo has been accessed. diff --git a/pkg/modules/background/upload/upload.go b/pkg/modules/background/upload/upload.go index dac3eb229..072c0c5bd 100644 --- a/pkg/modules/background/upload/upload.go +++ b/pkg/modules/background/upload/upload.go @@ -37,24 +37,24 @@ func (p *Provider) Search(s *xorm.Session, search string, page int64) (result [] } // Set handles setting a background through a file upload -// @Summary Upload a list background -// @Description Upload a list background. -// @tags list +// @Summary Upload a project background +// @Description Upload a project background. +// @tags project // @Accept mpfd // @Produce json -// @Param id path int true "List ID" +// @Param id path int true "Project ID" // @Param background formData string true "The file as single file." // @Security JWTKeyAuth // @Success 200 {object} models.Message "The background was set successfully." // @Failure 400 {object} models.Message "File is no image." -// @Failure 403 {object} models.Message "No access to the list." +// @Failure 403 {object} models.Message "No access to the project." // @Failure 403 {object} models.Message "File too large." -// @Failure 404 {object} models.Message "The list does not exist." +// @Failure 404 {object} models.Message "The project does not exist." // @Failure 500 {object} models.Message "Internal error" -// @Router /lists/{id}/backgrounds/upload [put] -func (p *Provider) Set(s *xorm.Session, img *background.Image, list *models.List, auth web.Auth) (err error) { +// @Router /projects/{id}/backgrounds/upload [put] +func (p *Provider) Set(s *xorm.Session, img *background.Image, project *models.Project, auth web.Auth) (err error) { // Remove the old background if one exists - err = list.DeleteBackgroundFileIfExists() + err = project.DeleteBackgroundFileIfExists() if err != nil { return err } @@ -65,7 +65,7 @@ func (p *Provider) Set(s *xorm.Session, img *background.Image, list *models.List return } - list.BackgroundInformation = &models.ListBackgroundType{Type: models.ListBackgroundUpload} + project.BackgroundInformation = &models.ProjectBackgroundType{Type: models.ProjectBackgroundUpload} - return models.SetListBackground(s, list.ID, file, list.BackgroundBlurHash) + return models.SetProjectBackground(s, project.ID, file, project.BackgroundBlurHash) } diff --git a/pkg/modules/migration/create_from_structure.go b/pkg/modules/migration/create_from_structure.go index 59bc51f72..d392a3c96 100644 --- a/pkg/modules/migration/create_from_structure.go +++ b/pkg/modules/migration/create_from_structure.go @@ -31,7 +31,7 @@ import ( // InsertFromStructure takes a fully nested Vikunja data structure and a user and then creates everything for this user // (Namespaces, tasks, etc. Even attachments and relations.) -func InsertFromStructure(str []*models.NamespaceWithListsAndTasks, user *user.User) (err error) { +func InsertFromStructure(str []*models.NamespaceWithProjectsAndTasks, user *user.User) (err error) { s := db.NewSession() defer s.Close() @@ -45,13 +45,13 @@ func InsertFromStructure(str []*models.NamespaceWithListsAndTasks, user *user.Us return s.Commit() } -func insertFromStructure(s *xorm.Session, str []*models.NamespaceWithListsAndTasks, user *user.User) (err error) { +func insertFromStructure(s *xorm.Session, str []*models.NamespaceWithProjectsAndTasks, user *user.User) (err error) { log.Debugf("[creating structure] Creating %d namespaces", len(str)) labels := make(map[string]*models.Label) - archivedLists := []int64{} + archivedProjects := []int64{} archivedNamespaces := []int64{} // Create all namespaces @@ -75,18 +75,18 @@ func insertFromStructure(s *xorm.Session, str []*models.NamespaceWithListsAndTas } log.Debugf("[creating structure] Created namespace %d", n.ID) - log.Debugf("[creating structure] Creating %d lists", len(n.Lists)) + log.Debugf("[creating structure] Creating %d projects", len(n.Projects)) - // Create all lists - for _, l := range n.Lists { - // The tasks and bucket slices are going to be reset during the creation of the list so we rescue it here - // to be able to still loop over them aftere the list was created. + // Create all projects + for _, l := range n.Projects { + // The tasks and bucket slices are going to be reset during the creation of the project so we rescue it here + // to be able to still loop over them aftere the project was created. tasks := l.Tasks originalBuckets := l.Buckets originalBackgroundInformation := l.BackgroundInformation needsDefaultBucket := false - // Saving the archived status to archive the list again after creating it + // Saving the archived status to archive the project again after creating it var wasArchived bool if l.IsArchived { wasArchived = true @@ -101,24 +101,24 @@ func insertFromStructure(s *xorm.Session, str []*models.NamespaceWithListsAndTas } if wasArchived { - archivedLists = append(archivedLists, l.ID) + archivedProjects = append(archivedProjects, l.ID) } - log.Debugf("[creating structure] Created list %d", l.ID) + log.Debugf("[creating structure] Created project %d", l.ID) bf, is := originalBackgroundInformation.(*bytes.Buffer) if is { backgroundFile := bytes.NewReader(bf.Bytes()) - log.Debugf("[creating structure] Creating a background file for list %d", l.ID) + log.Debugf("[creating structure] Creating a background file for project %d", l.ID) - err = handler.SaveBackgroundFile(s, user, &l.List, backgroundFile, "", uint64(backgroundFile.Len())) + err = handler.SaveBackgroundFile(s, user, &l.Project, backgroundFile, "", uint64(backgroundFile.Len())) if err != nil { return err } - log.Debugf("[creating structure] Created a background file for list %d", l.ID) + log.Debugf("[creating structure] Created a background file for project %d", l.ID) } // Create all buckets @@ -129,7 +129,7 @@ func insertFromStructure(s *xorm.Session, str []*models.NamespaceWithListsAndTas for _, bucket := range originalBuckets { oldID := bucket.ID bucket.ID = 0 // We want a new id - bucket.ListID = l.ID + bucket.ProjectID = l.ID err = bucket.Create(s, user) if err != nil { return @@ -157,7 +157,7 @@ func insertFromStructure(s *xorm.Session, str []*models.NamespaceWithListsAndTas for _, t := range tasks { setBucketOrDefault(&t.Task) - t.ListID = l.ID + t.ProjectID = l.ID err = t.Create(s, user) if err != nil { return @@ -179,7 +179,7 @@ func insertFromStructure(s *xorm.Session, str []*models.NamespaceWithListsAndTas // First create the related tasks if they do not exist if rt.ID == 0 { setBucketOrDefault(rt) - rt.ListID = t.ListID + rt.ProjectID = t.ProjectID err = rt.Create(s, user) if err != nil { return @@ -263,7 +263,7 @@ func insertFromStructure(s *xorm.Session, str []*models.NamespaceWithListsAndTas // All tasks brought their own bucket with them, therefore the newly created default bucket is just extra space if !needsDefaultBucket { - b := &models.Bucket{ListID: l.ID} + b := &models.Bucket{ProjectID: l.ID} bucketsIn, _, _, err := b.ReadAll(s, user, "", 1, 1) if err != nil { return err @@ -280,11 +280,11 @@ func insertFromStructure(s *xorm.Session, str []*models.NamespaceWithListsAndTas } } - if len(archivedLists) > 0 { + if len(archivedProjects) > 0 { _, err = s. Cols("is_archived"). - In("id", archivedLists). - Update(&models.List{IsArchived: true}) + In("id", archivedProjects). + Update(&models.Project{IsArchived: true}) if err != nil { return err } diff --git a/pkg/modules/migration/create_from_structure_test.go b/pkg/modules/migration/create_from_structure_test.go index 1b3eb5d40..ec3a37240 100644 --- a/pkg/modules/migration/create_from_structure_test.go +++ b/pkg/modules/migration/create_from_structure_test.go @@ -32,16 +32,16 @@ func TestInsertFromStructure(t *testing.T) { } t.Run("normal", func(t *testing.T) { db.LoadAndAssertFixtures(t) - testStructure := []*models.NamespaceWithListsAndTasks{ + testStructure := []*models.NamespaceWithProjectsAndTasks{ { Namespace: models.Namespace{ Title: "Test1", Description: "Lorem Ipsum", }, - Lists: []*models.ListWithTasksAndBuckets{ + Projects: []*models.ProjectWithTasksAndBuckets{ { - List: models.List{ - Title: "Testlist1", + Project: models.Project{ + Title: "Testproject1", Description: "Something", }, Buckets: []*models.Bucket{ @@ -133,19 +133,19 @@ func TestInsertFromStructure(t *testing.T) { "title": testStructure[0].Namespace.Title, "description": testStructure[0].Namespace.Description, }, false) - db.AssertExists(t, "lists", map[string]interface{}{ - "title": testStructure[0].Lists[0].Title, - "description": testStructure[0].Lists[0].Description, + db.AssertExists(t, "projects", map[string]interface{}{ + "title": testStructure[0].Projects[0].Title, + "description": testStructure[0].Projects[0].Description, }, false) db.AssertExists(t, "tasks", map[string]interface{}{ - "title": testStructure[0].Lists[0].Tasks[5].Title, - "bucket_id": testStructure[0].Lists[0].Buckets[0].ID, + "title": testStructure[0].Projects[0].Tasks[5].Title, + "bucket_id": testStructure[0].Projects[0].Buckets[0].ID, }, false) db.AssertMissing(t, "tasks", map[string]interface{}{ - "title": testStructure[0].Lists[0].Tasks[6].Title, + "title": testStructure[0].Projects[0].Tasks[6].Title, "bucket_id": 1111, // No task with that bucket should exist }) - assert.NotEqual(t, 0, testStructure[0].Lists[0].Tasks[0].BucketID) // Should get the default bucket - assert.NotEqual(t, 0, testStructure[0].Lists[0].Tasks[6].BucketID) // Should get the default bucket + assert.NotEqual(t, 0, testStructure[0].Projects[0].Tasks[0].BucketID) // Should get the default bucket + assert.NotEqual(t, 0, testStructure[0].Projects[0].Tasks[6].BucketID) // Should get the default bucket }) } diff --git a/pkg/modules/migration/microsoft-todo/microsoft_todo.go b/pkg/modules/migration/microsoft-todo/microsoft_todo.go index 0cf390f7f..165e1e612 100644 --- a/pkg/modules/migration/microsoft-todo/microsoft_todo.go +++ b/pkg/modules/migration/microsoft-todo/microsoft_todo.go @@ -98,19 +98,19 @@ type tasksResponse struct { Value []*task `json:"value"` } -type list struct { - ID string `json:"id"` - OdataEtag string `json:"@odata.etag"` - DisplayName string `json:"displayName"` - IsOwner bool `json:"isOwner"` - IsShared bool `json:"isShared"` - WellknownListName string `json:"wellknownListName"` - Tasks []*task `json:"-"` // This field does not exist in the api, we're just using it to return a structure with everything at once +type project struct { + ID string `json:"id"` + OdataEtag string `json:"@odata.etag"` + DisplayName string `json:"displayName"` + IsOwner bool `json:"isOwner"` + IsShared bool `json:"isShared"` + WellknownProjectName string `json:"wellknownProjectName"` + Tasks []*task `json:"-"` // This field does not exist in the api, we're just using it to return a structure with everything at once } -type listsResponse struct { - OdataContext string `json:"@odata.context"` - Value []*list `json:"value"` +type projectsResponse struct { + OdataContext string `json:"@odata.context"` + Value []*project `json:"value"` } func (dtt *dateTimeTimeZone) toTime() (t time.Time, err error) { @@ -213,22 +213,22 @@ func makeAuthenticatedGetRequest(token, urlPart string, v interface{}) error { return json.Unmarshal(buf.Bytes(), v) } -func getMicrosoftTodoData(token string) (microsoftTodoData []*list, err error) { +func getMicrosoftTodoData(token string) (microsoftTodoData []*project, err error) { - microsoftTodoData = []*list{} + microsoftTodoData = []*project{} - lists := &listsResponse{} - err = makeAuthenticatedGetRequest(token, "lists", lists) + projects := &projectsResponse{} + err = makeAuthenticatedGetRequest(token, "projects", projects) if err != nil { - log.Errorf("[Microsoft Todo Migration] Could not get lists: %s", err) + log.Errorf("[Microsoft Todo Migration] Could not get projects: %s", err) return } - log.Debugf("[Microsoft Todo Migration] Got %d lists", len(lists.Value)) + log.Debugf("[Microsoft Todo Migration] Got %d projects", len(projects.Value)) - for _, list := range lists.Value { - link := "lists/" + list.ID + "/tasks" - list.Tasks = []*task{} + for _, project := range projects.Value { + link := "projects/" + project.ID + "/tasks" + project.Tasks = []*task{} // Microsoft's Graph API has pagination, so we're going through all pages to get all tasks for { @@ -236,13 +236,13 @@ func getMicrosoftTodoData(token string) (microsoftTodoData []*list, err error) { err = makeAuthenticatedGetRequest(token, link, tr) if err != nil { - log.Errorf("[Microsoft Todo Migration] Could not get tasks for list %s: %s", list.ID, err) + log.Errorf("[Microsoft Todo Migration] Could not get tasks for project %s: %s", project.ID, err) return } - log.Debugf("[Microsoft Todo Migration] Got %d tasks for list %s", len(tr.Value), list.ID) + log.Debugf("[Microsoft Todo Migration] Got %d tasks for project %s", len(tr.Value), project.ID) - list.Tasks = append(list.Tasks, tr.Value...) + project.Tasks = append(project.Tasks, tr.Value...) if tr.Nextlink == "" { break @@ -251,35 +251,35 @@ func getMicrosoftTodoData(token string) (microsoftTodoData []*list, err error) { link = strings.ReplaceAll(tr.Nextlink, apiPrefix, "") } - microsoftTodoData = append(microsoftTodoData, list) + microsoftTodoData = append(microsoftTodoData, project) } - log.Debugf("[Microsoft Todo Migration] Got all tasks for %d lists", len(lists.Value)) + log.Debugf("[Microsoft Todo Migration] Got all tasks for %d projects", len(projects.Value)) return } -func convertMicrosoftTodoData(todoData []*list) (vikunjsStructure []*models.NamespaceWithListsAndTasks, err error) { +func convertMicrosoftTodoData(todoData []*project) (vikunjsStructure []*models.NamespaceWithProjectsAndTasks, err error) { - // One namespace with all lists - vikunjsStructure = []*models.NamespaceWithListsAndTasks{ + // One namespace with all projects + vikunjsStructure = []*models.NamespaceWithProjectsAndTasks{ { Namespace: models.Namespace{ Title: "Migrated from Microsoft Todo", }, - Lists: []*models.ListWithTasksAndBuckets{}, + Projects: []*models.ProjectWithTasksAndBuckets{}, }, } - log.Debugf("[Microsoft Todo Migration] Converting %d lists", len(todoData)) + log.Debugf("[Microsoft Todo Migration] Converting %d projects", len(todoData)) for _, l := range todoData { - log.Debugf("[Microsoft Todo Migration] Converting list %s", l.ID) + log.Debugf("[Microsoft Todo Migration] Converting project %s", l.ID) - // Lists only with title - list := &models.ListWithTasksAndBuckets{ - List: models.List{ + // Projects only with title + project := &models.ProjectWithTasksAndBuckets{ + Project: models.Project{ Title: l.DisplayName, }, } @@ -358,19 +358,19 @@ func convertMicrosoftTodoData(todoData []*list) (vikunjsStructure []*models.Name } } - list.Tasks = append(list.Tasks, &models.TaskWithComments{Task: *task}) + project.Tasks = append(project.Tasks, &models.TaskWithComments{Task: *task}) log.Debugf("[Microsoft Todo Migration] Done converted %d tasks", len(l.Tasks)) } - vikunjsStructure[0].Lists = append(vikunjsStructure[0].Lists, list) - log.Debugf("[Microsoft Todo Migration] Done converting list %s", l.ID) + vikunjsStructure[0].Projects = append(vikunjsStructure[0].Projects, project) + log.Debugf("[Microsoft Todo Migration] Done converting project %s", l.ID) } return } // Migrate gets all tasks from Microsoft Todo for a user and puts them into vikunja -// @Summary Migrate all lists, tasks etc. from Microsoft Todo +// @Summary Migrate all projects, tasks etc. from Microsoft Todo // @Description Migrates all tasklinsts, tasks, notes and reminders from Microsoft Todo to Vikunja. // @tags migration // @Accept json diff --git a/pkg/modules/migration/microsoft-todo/microsoft_todo_test.go b/pkg/modules/migration/microsoft-todo/microsoft_todo_test.go index a99511567..297d7db2f 100644 --- a/pkg/modules/migration/microsoft-todo/microsoft_todo_test.go +++ b/pkg/modules/migration/microsoft-todo/microsoft_todo_test.go @@ -35,9 +35,9 @@ func TestConverting(t *testing.T) { testtimeTime, err := time.Parse(time.RFC3339Nano, "2020-12-18T03:00:00.4770000Z") assert.NoError(t, err) - microsoftTodoData := []*list{ + microsoftTodoData := []*project{ { - DisplayName: "List 1", + DisplayName: "Project 1", Tasks: []*task{ { Title: "Task 1", @@ -88,7 +88,7 @@ func TestConverting(t *testing.T) { }, }, { - DisplayName: "List 2", + DisplayName: "Project 2", Tasks: []*task{ { Title: "Task 1", @@ -102,15 +102,15 @@ func TestConverting(t *testing.T) { }, } - expectedHierachie := []*models.NamespaceWithListsAndTasks{ + expectedHierachie := []*models.NamespaceWithProjectsAndTasks{ { Namespace: models.Namespace{ Title: "Migrated from Microsoft Todo", }, - Lists: []*models.ListWithTasksAndBuckets{ + Projects: []*models.ProjectWithTasksAndBuckets{ { - List: models.List{ - Title: "List 1", + Project: models.Project{ + Title: "Project 1", }, Tasks: []*models.TaskWithComments{ { @@ -162,8 +162,8 @@ func TestConverting(t *testing.T) { }, }, { - List: models.List{ - Title: "List 2", + Project: models.Project{ + Title: "Project 2", }, Tasks: []*models.TaskWithComments{ { diff --git a/pkg/modules/migration/migrator.go b/pkg/modules/migration/migrator.go index c7ca2d31d..ce5857766 100644 --- a/pkg/modules/migration/migrator.go +++ b/pkg/modules/migration/migrator.go @@ -43,7 +43,7 @@ type Migrator interface { // FileMigrator handles importing Vikunja data from a file. The implementation of it determines the format. type FileMigrator interface { MigratorName - // Migrate is the interface used to migrate a user's tasks, list and other things from a file to vikunja. + // Migrate is the interface used to migrate a user's tasks, project and other things from a file to vikunja. // The user object is the user who's tasks will be migrated. Migrate(user *user.User, file io.ReaderAt, size int64) error } diff --git a/pkg/modules/migration/ticktick/ticktick.go b/pkg/modules/migration/ticktick/ticktick.go index b553b567b..78b0be168 100644 --- a/pkg/modules/migration/ticktick/ticktick.go +++ b/pkg/modules/migration/ticktick/ticktick.go @@ -105,21 +105,21 @@ func parseDurationPart(value string, unit time.Duration) time.Duration { return 0 } -func convertTickTickToVikunja(tasks []*tickTickTask) (result []*models.NamespaceWithListsAndTasks) { - namespace := &models.NamespaceWithListsAndTasks{ +func convertTickTickToVikunja(tasks []*tickTickTask) (result []*models.NamespaceWithProjectsAndTasks) { + namespace := &models.NamespaceWithProjectsAndTasks{ Namespace: models.Namespace{ Title: "Migrated from TickTick", }, - Lists: []*models.ListWithTasksAndBuckets{}, + Projects: []*models.ProjectWithTasksAndBuckets{}, } - lists := make(map[string]*models.ListWithTasksAndBuckets) + projects := make(map[string]*models.ProjectWithTasksAndBuckets) for _, t := range tasks { - _, has := lists[t.ListName] + _, has := projects[t.ProjectName] if !has { - lists[t.ListName] = &models.ListWithTasksAndBuckets{ - List: models.List{ - Title: t.ListName, + projects[t.ProjectName] = &models.ProjectWithTasksAndBuckets{ + Project: models.Project{ + Title: t.ProjectName, }, } } @@ -158,18 +158,18 @@ func convertTickTickToVikunja(tasks []*tickTickTask) (result []*models.Namespace } } - lists[t.ListName].Tasks = append(lists[t.ListName].Tasks, task) + projects[t.ProjectName].Tasks = append(projects[t.ProjectName].Tasks, task) } - for _, l := range lists { - namespace.Lists = append(namespace.Lists, l) + for _, l := range projects { + namespace.Projects = append(namespace.Projects, l) } - sort.Slice(namespace.Lists, func(i, j int) bool { - return namespace.Lists[i].Title < namespace.Lists[j].Title + sort.Slice(namespace.Projects, func(i, j int) bool { + return namespace.Projects[i].Title < namespace.Projects[j].Title }) - return []*models.NamespaceWithListsAndTasks{namespace} + return []*models.NamespaceWithProjectsAndTasks{namespace} } // Name is used to get the name of the ticktick migration - we're using the docs here to annotate the status route. @@ -202,7 +202,7 @@ func newLineSkipDecoder(r io.Reader, linesToSkip int) gocsv.SimpleDecoder { } // Migrate takes a ticktick export, parses it and imports everything in it into Vikunja. -// @Summary Import all lists, tasks etc. from a TickTick backup export +// @Summary Import all projects, tasks etc. from a TickTick backup export // @Description Imports all projects, tasks, notes, reminders, subtasks and files from a TickTick backup export into Vikunja. // @tags migration // @Accept json diff --git a/pkg/modules/migration/ticktick/ticktick_test.go b/pkg/modules/migration/ticktick/ticktick_test.go index a6834442e..0eea6e20e 100644 --- a/pkg/modules/migration/ticktick/ticktick_test.go +++ b/pkg/modules/migration/ticktick/ticktick_test.go @@ -40,76 +40,76 @@ func TestConvertTicktickTasksToVikunja(t *testing.T) { tickTickTasks := []*tickTickTask{ { - TaskID: 1, - ParentID: 0, - ListName: "List 1", - Title: "Test task 1", - Tags: []string{"label1", "label2"}, - Content: "Lorem Ipsum Dolor sit amet", - StartDate: time1, - DueDate: time2, - Reminder: duration, - Repeat: "FREQ=WEEKLY;INTERVAL=1;UNTIL=20190117T210000Z", - Status: "0", - Order: -1099511627776, + TaskID: 1, + ParentID: 0, + ProjectName: "Project 1", + Title: "Test task 1", + Tags: []string{"label1", "label2"}, + Content: "Lorem Ipsum Dolor sit amet", + StartDate: time1, + DueDate: time2, + Reminder: duration, + Repeat: "FREQ=WEEKLY;INTERVAL=1;UNTIL=20190117T210000Z", + Status: "0", + Order: -1099511627776, }, { TaskID: 2, ParentID: 1, - ListName: "List 1", + ProjectName: "Project 1", Title: "Test task 2", Status: "1", CompletedTime: time3, Order: -1099511626, }, { - TaskID: 3, - ParentID: 0, - ListName: "List 1", - Title: "Test task 3", - Tags: []string{"label1", "label2", "other label"}, - StartDate: time1, - DueDate: time2, - Reminder: duration, - Status: "0", - Order: -109951627776, + TaskID: 3, + ParentID: 0, + ProjectName: "Project 1", + Title: "Test task 3", + Tags: []string{"label1", "label2", "other label"}, + StartDate: time1, + DueDate: time2, + Reminder: duration, + Status: "0", + Order: -109951627776, }, { - TaskID: 4, - ParentID: 0, - ListName: "List 2", - Title: "Test task 4", - Status: "0", - Order: -109951627777, + TaskID: 4, + ParentID: 0, + ProjectName: "Project 2", + Title: "Test task 4", + Status: "0", + Order: -109951627777, }, } vikunjaTasks := convertTickTickToVikunja(tickTickTasks) assert.Len(t, vikunjaTasks, 1) - assert.Len(t, vikunjaTasks[0].Lists, 2) + assert.Len(t, vikunjaTasks[0].Projects, 2) - assert.Len(t, vikunjaTasks[0].Lists[0].Tasks, 3) - assert.Equal(t, vikunjaTasks[0].Lists[0].Title, tickTickTasks[0].ListName) + assert.Len(t, vikunjaTasks[0].Projects[0].Tasks, 3) + assert.Equal(t, vikunjaTasks[0].Projects[0].Title, tickTickTasks[0].ProjectName) - assert.Equal(t, vikunjaTasks[0].Lists[0].Tasks[0].Title, tickTickTasks[0].Title) - assert.Equal(t, vikunjaTasks[0].Lists[0].Tasks[0].Description, tickTickTasks[0].Content) - assert.Equal(t, vikunjaTasks[0].Lists[0].Tasks[0].StartDate, tickTickTasks[0].StartDate.Time) - assert.Equal(t, vikunjaTasks[0].Lists[0].Tasks[0].EndDate, tickTickTasks[0].DueDate.Time) - assert.Equal(t, vikunjaTasks[0].Lists[0].Tasks[0].DueDate, tickTickTasks[0].DueDate.Time) - assert.Equal(t, vikunjaTasks[0].Lists[0].Tasks[0].Labels, []*models.Label{ + assert.Equal(t, vikunjaTasks[0].Projects[0].Tasks[0].Title, tickTickTasks[0].Title) + assert.Equal(t, vikunjaTasks[0].Projects[0].Tasks[0].Description, tickTickTasks[0].Content) + assert.Equal(t, vikunjaTasks[0].Projects[0].Tasks[0].StartDate, tickTickTasks[0].StartDate) + assert.Equal(t, vikunjaTasks[0].Projects[0].Tasks[0].EndDate, tickTickTasks[0].DueDate) + assert.Equal(t, vikunjaTasks[0].Projects[0].Tasks[0].DueDate, tickTickTasks[0].DueDate) + assert.Equal(t, vikunjaTasks[0].Projects[0].Tasks[0].Labels, []*models.Label{ {Title: "label1"}, {Title: "label2"}, }) - //assert.Equal(t, vikunjaTasks[0].Lists[0].Tasks[0].Reminders, tickTickTasks[0].) // TODO - assert.Equal(t, vikunjaTasks[0].Lists[0].Tasks[0].Position, tickTickTasks[0].Order) - assert.Equal(t, vikunjaTasks[0].Lists[0].Tasks[0].Done, false) + //assert.Equal(t, vikunjaTasks[0].Projects[0].Tasks[0].Reminders, tickTickTasks[0].) // TODO + assert.Equal(t, vikunjaTasks[0].Projects[0].Tasks[0].Position, tickTickTasks[0].Order) + assert.Equal(t, vikunjaTasks[0].Projects[0].Tasks[0].Done, false) - assert.Equal(t, vikunjaTasks[0].Lists[0].Tasks[1].Title, tickTickTasks[1].Title) - assert.Equal(t, vikunjaTasks[0].Lists[0].Tasks[1].Position, tickTickTasks[1].Order) - assert.Equal(t, vikunjaTasks[0].Lists[0].Tasks[1].Done, true) - assert.Equal(t, vikunjaTasks[0].Lists[0].Tasks[1].DoneAt, tickTickTasks[1].CompletedTime.Time) - assert.Equal(t, vikunjaTasks[0].Lists[0].Tasks[1].RelatedTasks, models.RelatedTaskMap{ + assert.Equal(t, vikunjaTasks[0].Projects[0].Tasks[1].Title, tickTickTasks[1].Title) + assert.Equal(t, vikunjaTasks[0].Projects[0].Tasks[1].Position, tickTickTasks[1].Order) + assert.Equal(t, vikunjaTasks[0].Projects[0].Tasks[1].Done, true) + assert.Equal(t, vikunjaTasks[0].Projects[0].Tasks[1].DoneAt, tickTickTasks[1].CompletedTime.Time) + assert.Equal(t, vikunjaTasks[0].Projects[0].Tasks[1].RelatedTasks, models.RelatedTaskMap{ models.RelationKindParenttask: []*models.Task{ { ID: tickTickTasks[1].ParentID, @@ -117,23 +117,23 @@ func TestConvertTicktickTasksToVikunja(t *testing.T) { }, }) - assert.Equal(t, vikunjaTasks[0].Lists[0].Tasks[2].Title, tickTickTasks[2].Title) - assert.Equal(t, vikunjaTasks[0].Lists[0].Tasks[2].Description, tickTickTasks[2].Content) - assert.Equal(t, vikunjaTasks[0].Lists[0].Tasks[2].StartDate, tickTickTasks[2].StartDate.Time) - assert.Equal(t, vikunjaTasks[0].Lists[0].Tasks[2].EndDate, tickTickTasks[2].DueDate.Time) - assert.Equal(t, vikunjaTasks[0].Lists[0].Tasks[2].DueDate, tickTickTasks[2].DueDate.Time) - assert.Equal(t, vikunjaTasks[0].Lists[0].Tasks[2].Labels, []*models.Label{ + assert.Equal(t, vikunjaTasks[0].Projects[0].Tasks[2].Title, tickTickTasks[2].Title) + assert.Equal(t, vikunjaTasks[0].Projects[0].Tasks[2].Description, tickTickTasks[2].Content) + assert.Equal(t, vikunjaTasks[0].Projects[0].Tasks[2].StartDate, tickTickTasks[2].StartDate.Time) + assert.Equal(t, vikunjaTasks[0].Projects[0].Tasks[2].EndDate, tickTickTasks[2].DueDate.Time) + assert.Equal(t, vikunjaTasks[0].Projects[0].Tasks[2].DueDate, tickTickTasks[2].DueDate.Time) + assert.Equal(t, vikunjaTasks[0].Projects[0].Tasks[2].Labels, []*models.Label{ {Title: "label1"}, {Title: "label2"}, {Title: "other label"}, }) - //assert.Equal(t, vikunjaTasks[0].Lists[0].Tasks[0].Reminders, tickTickTasks[0].) // TODO - assert.Equal(t, vikunjaTasks[0].Lists[0].Tasks[2].Position, tickTickTasks[2].Order) - assert.Equal(t, vikunjaTasks[0].Lists[0].Tasks[2].Done, false) + //assert.Equal(t, vikunjaTasks[0].Projects[0].Tasks[0].Reminders, tickTickTasks[0].) // TODO + assert.Equal(t, vikunjaTasks[0].Projects[0].Tasks[2].Position, tickTickTasks[2].Order) + assert.Equal(t, vikunjaTasks[0].Projects[0].Tasks[2].Done, false) - assert.Len(t, vikunjaTasks[0].Lists[1].Tasks, 1) - assert.Equal(t, vikunjaTasks[0].Lists[1].Title, tickTickTasks[3].ListName) + assert.Len(t, vikunjaTasks[0].Projects[1].Tasks, 1) + assert.Equal(t, vikunjaTasks[0].Projects[1].Title, tickTickTasks[3].ProjectName) - assert.Equal(t, vikunjaTasks[0].Lists[1].Tasks[0].Title, tickTickTasks[3].Title) - assert.Equal(t, vikunjaTasks[0].Lists[1].Tasks[0].Position, tickTickTasks[3].Order) + assert.Equal(t, vikunjaTasks[0].Projects[1].Tasks[0].Title, tickTickTasks[3].Title) + assert.Equal(t, vikunjaTasks[0].Projects[1].Tasks[0].Position, tickTickTasks[3].Order) } diff --git a/pkg/modules/migration/todoist/todoist_test.go b/pkg/modules/migration/todoist/todoist_test.go index d75a0a469..06593327c 100644 --- a/pkg/modules/migration/todoist/todoist_test.go +++ b/pkg/modules/migration/todoist/todoist_test.go @@ -363,14 +363,14 @@ func TestConvertTodoistToVikunja(t *testing.T) { }, } - expectedHierachie := []*models.NamespaceWithListsAndTasks{ + expectedHierachie := []*models.NamespaceWithProjectsAndTasks{ { Namespace: models.Namespace{ Title: "Migrated from todoist", }, - Lists: []*models.ListWithTasksAndBuckets{ + Projects: []*models.ProjectWithTasksAndBuckets{ { - List: models.List{ + Project: models.Project{ Title: "Project1", Description: "Lorem Ipsum dolor sit amet\nLorem Ipsum dolor sit amet 2\nLorem Ipsum dolor sit amet 3", HexColor: todoistColors["berry_red"], @@ -504,7 +504,7 @@ func TestConvertTodoistToVikunja(t *testing.T) { }, }, { - List: models.List{ + Project: models.Project{ Title: "Project2", Description: "Lorem Ipsum dolor sit amet 4\nLorem Ipsum dolor sit amet 5", HexColor: todoistColors["mint_green"], @@ -602,7 +602,7 @@ func TestConvertTodoistToVikunja(t *testing.T) { }, }, { - List: models.List{ + Project: models.Project{ Title: "Project3 - Archived", HexColor: todoistColors["mint_green"], IsArchived: true, diff --git a/pkg/modules/migration/trello/trello.go b/pkg/modules/migration/trello/trello.go index af0afad9c..85062a55d 100644 --- a/pkg/modules/migration/trello/trello.go +++ b/pkg/modules/migration/trello/trello.go @@ -99,14 +99,14 @@ func getTrelloData(token string) (trelloData []*trello.Board, err error) { log.Debugf("[Trello Migration] Got %d trello boards", len(trelloData)) for _, board := range trelloData { - log.Debugf("[Trello Migration] Getting lists for board %s", board.ID) + log.Debugf("[Trello Migration] Getting projects for board %s", board.ID) board.Lists, err = board.GetLists(trello.Defaults()) if err != nil { return } - log.Debugf("[Trello Migration] Got %d lists for board %s", len(board.Lists), board.ID) + log.Debugf("[Trello Migration] Got %d projects for board %s", len(board.Lists), board.ID) listMap := make(map[string]*trello.List, len(board.Lists)) for _, list := range board.Lists { @@ -161,27 +161,27 @@ func getTrelloData(token string) (trelloData []*trello.Board, err error) { } // Converts all previously obtained data from trello into the vikunja format. -// `trelloData` should contain all boards with their lists and cards respectively. -func convertTrelloDataToVikunja(trelloData []*trello.Board, token string) (fullVikunjaHierachie []*models.NamespaceWithListsAndTasks, err error) { +// `trelloData` should contain all boards with their projects and cards respectively. +func convertTrelloDataToVikunja(trelloData []*trello.Board, token string) (fullVikunjaHierachie []*models.NamespaceWithProjectsAndTasks, err error) { log.Debugf("[Trello Migration] ") - fullVikunjaHierachie = []*models.NamespaceWithListsAndTasks{ + fullVikunjaHierachie = []*models.NamespaceWithProjectsAndTasks{ { Namespace: models.Namespace{ Title: "Imported from Trello", }, - Lists: []*models.ListWithTasksAndBuckets{}, + Projects: []*models.ProjectWithTasksAndBuckets{}, }, } var bucketID int64 = 1 - log.Debugf("[Trello Migration] Converting %d boards to vikunja lists", len(trelloData)) + log.Debugf("[Trello Migration] Converting %d boards to vikunja projects", len(trelloData)) for _, board := range trelloData { - list := &models.ListWithTasksAndBuckets{ - List: models.List{ + project := &models.ProjectWithTasksAndBuckets{ + Project: models.Project{ Title: board.Name, Description: board.Desc, IsArchived: board.Closed, @@ -189,7 +189,7 @@ func convertTrelloDataToVikunja(trelloData []*trello.Board, token string) (fullV } // Background - // We're pretty much abusing the backgroundinformation field here - not sure if this is really better than adding a new property to the list + // We're pretty much abusing the backgroundinformation field here - not sure if this is really better than adding a new property to the project if board.Prefs.BackgroundImage != "" { log.Debugf("[Trello Migration] Downloading background %s for board %s", board.Prefs.BackgroundImage, board.ID) buf, err := migration.DownloadFile(board.Prefs.BackgroundImage) @@ -197,7 +197,7 @@ func convertTrelloDataToVikunja(trelloData []*trello.Board, token string) (fullV return nil, err } log.Debugf("[Trello Migration] Downloaded background %s for board %s", board.Prefs.BackgroundImage, board.ID) - list.BackgroundInformation = buf + project.BackgroundInformation = buf } else { log.Debugf("[Trello Migration] Board %s does not have a background image, not copying...", board.ID) } @@ -291,23 +291,23 @@ func convertTrelloDataToVikunja(trelloData []*trello.Board, token string) (fullV log.Debugf("[Trello Migration] Downloaded card attachment %s", attachment.ID) } - list.Tasks = append(list.Tasks, &models.TaskWithComments{Task: *task}) + project.Tasks = append(project.Tasks, &models.TaskWithComments{Task: *task}) } - list.Buckets = append(list.Buckets, bucket) + project.Buckets = append(project.Buckets, bucket) bucketID++ } log.Debugf("[Trello Migration] Converted all cards to tasks for board %s", board.ID) - fullVikunjaHierachie[0].Lists = append(fullVikunjaHierachie[0].Lists, list) + fullVikunjaHierachie[0].Projects = append(fullVikunjaHierachie[0].Projects, project) } return } // Migrate gets all tasks from trello for a user and puts them into vikunja -// @Summary Migrate all lists, tasks etc. from trello +// @Summary Migrate all projects, tasks etc. from trello // @Description Migrates all projects, tasks, notes, reminders, subtasks and files from trello to vikunja. // @tags migration // @Accept json diff --git a/pkg/modules/migration/trello/trello_test.go b/pkg/modules/migration/trello/trello_test.go index 1d0ff0062..9e8aedc4a 100644 --- a/pkg/modules/migration/trello/trello_test.go +++ b/pkg/modules/migration/trello/trello_test.go @@ -44,9 +44,9 @@ func TestConvertTrelloToVikunja(t *testing.T) { Name: "TestBoard", Desc: "This is a description", Closed: false, - Lists: []*trello.List{ + Projects: []*trello.Project{ { - Name: "Test List 1", + Name: "Test Project 1", Cards: []*trello.Card{ { Name: "Test Card 1", @@ -77,9 +77,9 @@ func TestConvertTrelloToVikunja(t *testing.T) { { Name: "Test Card 2", Pos: 124, - Checklists: []*trello.Checklist{ + Checkprojects: []*trello.Checkproject{ { - Name: "Checklist 1", + Name: "Checkproject 1", CheckItems: []trello.CheckItem{ { State: "pending", @@ -92,7 +92,7 @@ func TestConvertTrelloToVikunja(t *testing.T) { }, }, { - Name: "Checklist 2", + Name: "Checkproject 2", CheckItems: []trello.CheckItem{ { State: "pending", @@ -124,7 +124,7 @@ func TestConvertTrelloToVikunja(t *testing.T) { }, }, { - Name: "Test List 2", + Name: "Test Project 2", Cards: []*trello.Card{ { Name: "Test Card 5", @@ -157,9 +157,9 @@ func TestConvertTrelloToVikunja(t *testing.T) { { Name: "TestBoard 2", Closed: false, - Lists: []*trello.List{ + Projects: []*trello.Project{ { - Name: "Test List 4", + Name: "Test Project 4", Cards: []*trello.Card{ { Name: "Test Card 634", @@ -172,9 +172,9 @@ func TestConvertTrelloToVikunja(t *testing.T) { { Name: "TestBoard Archived", Closed: true, - Lists: []*trello.List{ + Projects: []*trello.Project{ { - Name: "Test List 5", + Name: "Test Project 5", Cards: []*trello.Card{ { Name: "Test Card 63423", @@ -187,14 +187,14 @@ func TestConvertTrelloToVikunja(t *testing.T) { } trelloData[0].Prefs.BackgroundImage = "https://vikunja.io/testimage.jpg" // Using an image which we are hosting, so it'll still be up - expectedHierachie := []*models.NamespaceWithListsAndTasks{ + expectedHierachie := []*models.NamespaceWithProjectsAndTasks{ { Namespace: models.Namespace{ Title: "Imported from Trello", }, - Lists: []*models.ListWithTasksAndBuckets{ + Projects: []*models.ProjectWithTasksAndBuckets{ { - List: models.List{ + Project: models.Project{ Title: "TestBoard", Description: "This is a description", BackgroundInformation: bytes.NewBuffer(exampleFile), @@ -202,11 +202,11 @@ func TestConvertTrelloToVikunja(t *testing.T) { Buckets: []*models.Bucket{ { ID: 1, - Title: "Test List 1", + Title: "Test Project 1", }, { ID: 2, - Title: "Test List 2", + Title: "Test Project 2", }, }, Tasks: []*models.TaskWithComments{ @@ -244,12 +244,12 @@ func TestConvertTrelloToVikunja(t *testing.T) { Title: "Test Card 2", Description: ` -## Checklist 1 +## Checkproject 1 * [ ] Pending Task * [x] Completed Task -## Checklist 2 +## Checkproject 2 * [ ] Pending Task * [ ] Another Pending Task`, @@ -315,13 +315,13 @@ func TestConvertTrelloToVikunja(t *testing.T) { }, }, { - List: models.List{ + Project: models.Project{ Title: "TestBoard 2", }, Buckets: []*models.Bucket{ { ID: 3, - Title: "Test List 4", + Title: "Test Project 4", }, }, Tasks: []*models.TaskWithComments{ @@ -335,14 +335,14 @@ func TestConvertTrelloToVikunja(t *testing.T) { }, }, { - List: models.List{ + Project: models.Project{ Title: "TestBoard Archived", IsArchived: true, }, Buckets: []*models.Bucket{ { ID: 4, - Title: "Test List 5", + Title: "Test Project 5", }, }, Tasks: []*models.TaskWithComments{ diff --git a/pkg/modules/migration/vikunja-file/vikunja.go b/pkg/modules/migration/vikunja-file/vikunja.go index 5fe953c35..3e4c6011d 100644 --- a/pkg/modules/migration/vikunja-file/vikunja.go +++ b/pkg/modules/migration/vikunja-file/vikunja.go @@ -51,7 +51,7 @@ func (v *FileMigrator) Name() string { } // Migrate takes a vikunja file export, parses it and imports everything in it into Vikunja. -// @Summary Import all lists, tasks etc. from a Vikunja data export +// @Summary Import all projects, tasks etc. from a Vikunja data export // @Description Imports all projects, tasks, notes, reminders, subtasks and files from a Vikunjda data export into Vikunja. // @tags migration // @Accept json @@ -113,21 +113,21 @@ func (v *FileMigrator) Migrate(user *user.User, file io.ReaderAt, size int64) er return fmt.Errorf("could not read data file: %w", err) } - namespaces := []*models.NamespaceWithListsAndTasks{} + namespaces := []*models.NamespaceWithProjectsAndTasks{} if err := json.Unmarshal(bufData.Bytes(), &namespaces); err != nil { return fmt.Errorf("could not read data: %w", err) } for _, n := range namespaces { - for _, l := range n.Lists { + for _, l := range n.Projects { if b, exists := storedFiles[l.BackgroundFileID]; exists { bf, err := b.Open() if err != nil { - return fmt.Errorf("could not open list background file %d for reading: %w", l.BackgroundFileID, err) + return fmt.Errorf("could not open project background file %d for reading: %w", l.BackgroundFileID, err) } var buf bytes.Buffer if _, err := buf.ReadFrom(bf); err != nil { - return fmt.Errorf("could not read list background file %d: %w", l.BackgroundFileID, err) + return fmt.Errorf("could not read project background file %d: %w", l.BackgroundFileID, err) } l.BackgroundInformation = &buf diff --git a/pkg/modules/migration/vikunja-file/vikunja_test.go b/pkg/modules/migration/vikunja-file/vikunja_test.go index 5d5361a4d..d63becb54 100644 --- a/pkg/modules/migration/vikunja-file/vikunja_test.go +++ b/pkg/modules/migration/vikunja-file/vikunja_test.go @@ -48,12 +48,12 @@ func TestVikunjaFileMigrator_Migrate(t *testing.T) { "title": "test", "owner_id": u.ID, }, false) - db.AssertExists(t, "lists", map[string]interface{}{ - "title": "Test list", + db.AssertExists(t, "projects", map[string]interface{}{ + "title": "Test project", "owner_id": u.ID, }, false) - db.AssertExists(t, "lists", map[string]interface{}{ - "title": "A list with a background", + db.AssertExists(t, "projects", map[string]interface{}{ + "title": "A project with a background", "owner_id": u.ID, }, false) db.AssertExists(t, "tasks", map[string]interface{}{ diff --git a/pkg/routes/api/v1/docs.go b/pkg/routes/api/v1/docs.go index 0eabc0feb..26c404557 100644 --- a/pkg/routes/api/v1/docs.go +++ b/pkg/routes/api/v1/docs.go @@ -89,7 +89,7 @@ const RedocUITemplate = ` * @author Feross Aboukhadijeh * @license MIT */ - var r=n(191),o=n(192),i=n(101);function a(){return l.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function s(e,t){if(a()=a())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a().toString(16)+" bytes");return 0|e}function h(e,t){if(l.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return B(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return z(e).length;default:if(r)return B(e).length;t=(""+t).toLowerCase(),r=!0}}function m(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function g(e,t,n,r,o){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=o?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(o)return-1;n=e.length-1}else if(n<0){if(!o)return-1;n=0}if("string"==typeof t&&(t=l.from(t,r)),l.isBuffer(t))return 0===t.length?-1:y(e,t,n,r,o);if("number"==typeof t)return t&=255,l.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,r,o);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,r,o){var i,a=1,s=e.length,l=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;a=2,s/=2,l/=2,n/=2}function c(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(o){var u=-1;for(i=n;is&&(n=s-l),i=n;i>=0;i--){for(var p=!0,f=0;fo&&(r=o):r=o;var i=t.length;if(i%2!=0)throw new TypeError("Invalid hex string");r>i/2&&(r=i/2);for(var a=0;a>8,o=n%256,i.push(o),i.push(r);return i}(t,e.length-n),e,n,r)}function S(e,t,n){return 0===t&&n===e.length?r.fromByteArray(e):r.fromByteArray(e.slice(t,n))}function _(e,t,n){n=Math.min(e.length,n);for(var r=[],o=t;o239?4:c>223?3:c>191?2:1;if(o+p<=n)switch(p){case 1:c<128&&(u=c);break;case 2:128==(192&(i=e[o+1]))&&(l=(31&c)<<6|63&i)>127&&(u=l);break;case 3:i=e[o+1],a=e[o+2],128==(192&i)&&128==(192&a)&&(l=(15&c)<<12|(63&i)<<6|63&a)>2047&&(l<55296||l>57343)&&(u=l);break;case 4:i=e[o+1],a=e[o+2],s=e[o+3],128==(192&i)&&128==(192&a)&&128==(192&s)&&(l=(15&c)<<18|(63&i)<<12|(63&a)<<6|63&s)>65535&&l<1114112&&(u=l)}null===u?(u=65533,p=1):u>65535&&(u-=65536,r.push(u>>>10&1023|55296),u=56320|1023&u),r.push(u),o+=p}return function(e){var t=e.length;if(t<=O)return String.fromCharCode.apply(String,e);var n="",r=0;for(;rthis.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return j(this,t,n);case"utf8":case"utf-8":return _(this,t,n);case"ascii":return C(this,t,n);case"latin1":case"binary":return T(this,t,n);case"base64":return S(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}.apply(this,arguments)},l.prototype.equals=function(e){if(!l.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===l.compare(this,e)},l.prototype.inspect=function(){var e="",n=t.INSPECT_MAX_BYTES;return this.length>0&&(e=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(e+=" ... ")),""},l.prototype.compare=function(e,t,n,r,o){if(!l.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===o&&(o=this.length),t<0||n>e.length||r<0||o>this.length)throw new RangeError("out of range index");if(r>=o&&t>=n)return 0;if(r>=o)return-1;if(t>=n)return 1;if(this===e)return 0;for(var i=(o>>>=0)-(r>>>=0),a=(n>>>=0)-(t>>>=0),s=Math.min(i,a),c=this.slice(r,o),u=e.slice(t,n),p=0;po)&&(n=o),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var i=!1;;)switch(r){case"hex":return v(this,e,t,n);case"utf8":case"utf-8":return b(this,e,t,n);case"ascii":return w(this,e,t,n);case"latin1":case"binary":return x(this,e,t,n);case"base64":return k(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,e,t,n);default:if(i)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),i=!0}},l.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var O=4096;function C(e,t,n){var r="";n=Math.min(e.length,n);for(var o=t;or)&&(n=r);for(var o="",i=t;in)throw new RangeError("Trying to access beyond buffer length")}function P(e,t,n,r,o,i){if(!l.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||te.length)throw new RangeError("Index out of range")}function R(e,t,n,r){t<0&&(t=65535+t+1);for(var o=0,i=Math.min(e.length-n,2);o>>8*(r?o:1-o)}function N(e,t,n,r){t<0&&(t=4294967295+t+1);for(var o=0,i=Math.min(e.length-n,4);o>>8*(r?o:3-o)&255}function L(e,t,n,r,o,i){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function M(e,t,n,r,i){return i||L(e,0,n,4),o.write(e,t,n,r,23,4),n+4}function D(e,t,n,r,i){return i||L(e,0,n,8),o.write(e,t,n,r,52,8),n+8}l.prototype.slice=function(e,t){var n,r=this.length;if((e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t0&&(o*=256);)r+=this[e+--t]*o;return r},l.prototype.readUInt8=function(e,t){return t||I(e,1,this.length),this[e]},l.prototype.readUInt16LE=function(e,t){return t||I(e,2,this.length),this[e]|this[e+1]<<8},l.prototype.readUInt16BE=function(e,t){return t||I(e,2,this.length),this[e]<<8|this[e+1]},l.prototype.readUInt32LE=function(e,t){return t||I(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},l.prototype.readUInt32BE=function(e,t){return t||I(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},l.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||I(e,t,this.length);for(var r=this[e],o=1,i=0;++i=(o*=128)&&(r-=Math.pow(2,8*t)),r},l.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||I(e,t,this.length);for(var r=t,o=1,i=this[e+--r];r>0&&(o*=256);)i+=this[e+--r]*o;return i>=(o*=128)&&(i-=Math.pow(2,8*t)),i},l.prototype.readInt8=function(e,t){return t||I(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},l.prototype.readInt16LE=function(e,t){t||I(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},l.prototype.readInt16BE=function(e,t){t||I(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},l.prototype.readInt32LE=function(e,t){return t||I(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},l.prototype.readInt32BE=function(e,t){return t||I(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},l.prototype.readFloatLE=function(e,t){return t||I(e,4,this.length),o.read(this,e,!0,23,4)},l.prototype.readFloatBE=function(e,t){return t||I(e,4,this.length),o.read(this,e,!1,23,4)},l.prototype.readDoubleLE=function(e,t){return t||I(e,8,this.length),o.read(this,e,!0,52,8)},l.prototype.readDoubleBE=function(e,t){return t||I(e,8,this.length),o.read(this,e,!1,52,8)},l.prototype.writeUIntLE=function(e,t,n,r){(e=+e,t|=0,n|=0,r)||P(this,e,t,n,Math.pow(2,8*n)-1,0);var o=1,i=0;for(this[t]=255&e;++i=0&&(i*=256);)this[t+o]=e/i&255;return t+n},l.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||P(this,e,t,1,255,0),l.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},l.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||P(this,e,t,2,65535,0),l.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):R(this,e,t,!0),t+2},l.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||P(this,e,t,2,65535,0),l.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):R(this,e,t,!1),t+2},l.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||P(this,e,t,4,4294967295,0),l.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):N(this,e,t,!0),t+4},l.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||P(this,e,t,4,4294967295,0),l.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):N(this,e,t,!1),t+4},l.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t|=0,!r){var o=Math.pow(2,8*n-1);P(this,e,t,n,o-1,-o)}var i=0,a=1,s=0;for(this[t]=255&e;++i>0)-s&255;return t+n},l.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t|=0,!r){var o=Math.pow(2,8*n-1);P(this,e,t,n,o-1,-o)}var i=n-1,a=1,s=0;for(this[t+i]=255&e;--i>=0&&(a*=256);)e<0&&0===s&&0!==this[t+i+1]&&(s=1),this[t+i]=(e/a>>0)-s&255;return t+n},l.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||P(this,e,t,1,127,-128),l.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},l.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||P(this,e,t,2,32767,-32768),l.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):R(this,e,t,!0),t+2},l.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||P(this,e,t,2,32767,-32768),l.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):R(this,e,t,!1),t+2},l.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||P(this,e,t,4,2147483647,-2147483648),l.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):N(this,e,t,!0),t+4},l.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||P(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),l.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):N(this,e,t,!1),t+4},l.prototype.writeFloatLE=function(e,t,n){return M(this,e,t,!0,n)},l.prototype.writeFloatBE=function(e,t,n){return M(this,e,t,!1,n)},l.prototype.writeDoubleLE=function(e,t,n){return D(this,e,t,!0,n)},l.prototype.writeDoubleBE=function(e,t,n){return D(this,e,t,!1,n)},l.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t=0;--o)e[o+t]=this[o+n];else if(i<1e3||!l.TYPED_ARRAY_SUPPORT)for(o=0;o>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(i=t;i55295&&n<57344){if(!o){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(a+1===r){(t-=3)>-1&&i.push(239,191,189);continue}o=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),o=n;continue}n=65536+(o-55296<<10|n-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function z(e){return r.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(F,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function $(e,t,n,r){for(var o=0;o=t.length||o>=e.length);++o)t[o+n]=e[o];return o}}).call(this,n(4))},function(e,t,n){"use strict";var r=n(184),o=n(186);function i(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}t.parse=b,t.resolve=function(e,t){return b(e,!1,!0).resolve(t)},t.resolveObject=function(e,t){return e?b(e,!1,!0).resolveObject(t):t},t.format=function(e){o.isString(e)&&(e=b(e));return e instanceof i?e.format():i.prototype.format.call(e)},t.URL=i;var a=/^([a-z0-9.+-]+:)/i,s=/:[0-9]*$/,l=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,c=["{","}","|","\\","^","` + "`" + `"].concat(["<",">",'"',"` + "`" + `"," ","\r","\n","\t"]),u=["'"].concat(c),p=["%","/","?",";","#"].concat(u),f=["/","?","#"],d=/^[+a-z0-9A-Z_-]{0,63}$/,h=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,m={javascript:!0,"javascript:":!0},g={javascript:!0,"javascript:":!0},y={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},v=n(187);function b(e,t,n){if(e&&o.isObject(e)&&e instanceof i)return e;var r=new i;return r.parse(e,t,n),r}i.prototype.parse=function(e,t,n){if(!o.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var i=e.indexOf("?"),s=-1!==i&&i127?R+="x":R+=P[N];if(!R.match(d)){var M=A.slice(0,C),D=A.slice(C+1),F=P.match(h);F&&(M.push(F[1]),D.unshift(F[2])),D.length&&(b="/"+D.join(".")+b),this.hostname=M.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),j||(this.hostname=r.toASCII(this.hostname));var U=this.port?":"+this.port:"",B=this.hostname||"";this.host=B+U,this.href+=this.host,j&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==b[0]&&(b="/"+b))}if(!m[k])for(C=0,I=u.length;C0)&&n.host.split("@"))&&(n.auth=j.shift(),n.host=n.hostname=j.shift());return n.search=e.search,n.query=e.query,o.isNull(n.pathname)&&o.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.href=n.format(),n}if(!E.length)return n.pathname=null,n.search?n.path="/"+n.search:n.path=null,n.href=n.format(),n;for(var _=E.slice(-1)[0],O=(n.host||e.host||E.length>1)&&("."===_||".."===_)||""===_,C=0,T=E.length;T>=0;T--)"."===(_=E[T])?E.splice(T,1):".."===_?(E.splice(T,1),C++):C&&(E.splice(T,1),C--);if(!x&&!k)for(;C--;C)E.unshift("..");!x||""===E[0]||E[0]&&"/"===E[0].charAt(0)||E.unshift(""),O&&"/"!==E.join("/").substr(-1)&&E.push("");var j,A=""===E[0]||E[0]&&"/"===E[0].charAt(0);S&&(n.hostname=n.host=A?"":E.length?E.shift():"",(j=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=j.shift(),n.host=n.hostname=j.shift()));return(x=x||n.host&&E.length)&&!A&&E.unshift(""),E.length?n.pathname=E.join("/"):(n.pathname=null,n.path=null),o.isNull(n.pathname)&&o.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.auth=e.auth||n.auth,n.slashes=n.slashes||e.slashes,n.href=n.format(),n},i.prototype.parseHost=function(){var e=this.host,t=s.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)}},function(e,t,n){e.exports=n(182)()},function(e,t,n){var r; + var r=n(191),o=n(192),i=n(101);function a(){return l.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function s(e,t){if(a()=a())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a().toString(16)+" bytes");return 0|e}function h(e,t){if(l.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return B(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return z(e).length;default:if(r)return B(e).length;t=(""+t).toLowerCase(),r=!0}}function m(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function g(e,t,n,r,o){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=o?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(o)return-1;n=e.length-1}else if(n<0){if(!o)return-1;n=0}if("string"==typeof t&&(t=l.from(t,r)),l.isBuffer(t))return 0===t.length?-1:y(e,t,n,r,o);if("number"==typeof t)return t&=255,l.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,r,o);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,r,o){var i,a=1,s=e.length,l=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;a=2,s/=2,l/=2,n/=2}function c(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(o){var u=-1;for(i=n;is&&(n=s-l),i=n;i>=0;i--){for(var p=!0,f=0;fo&&(r=o):r=o;var i=t.length;if(i%2!=0)throw new TypeError("Invalid hex string");r>i/2&&(r=i/2);for(var a=0;a>8,o=n%256,i.push(o),i.push(r);return i}(t,e.length-n),e,n,r)}function S(e,t,n){return 0===t&&n===e.length?r.fromByteArray(e):r.fromByteArray(e.slice(t,n))}function _(e,t,n){n=Math.min(e.length,n);for(var r=[],o=t;o239?4:c>223?3:c>191?2:1;if(o+p<=n)switch(p){case 1:c<128&&(u=c);break;case 2:128==(192&(i=e[o+1]))&&(l=(31&c)<<6|63&i)>127&&(u=l);break;case 3:i=e[o+1],a=e[o+2],128==(192&i)&&128==(192&a)&&(l=(15&c)<<12|(63&i)<<6|63&a)>2047&&(l<55296||l>57343)&&(u=l);break;case 4:i=e[o+1],a=e[o+2],s=e[o+3],128==(192&i)&&128==(192&a)&&128==(192&s)&&(l=(15&c)<<18|(63&i)<<12|(63&a)<<6|63&s)>65535&&l<1114112&&(u=l)}null===u?(u=65533,p=1):u>65535&&(u-=65536,r.push(u>>>10&1023|55296),u=56320|1023&u),r.push(u),o+=p}return function(e){var t=e.length;if(t<=O)return String.fromCharCode.apply(String,e);var n="",r=0;for(;rthis.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return j(this,t,n);case"utf8":case"utf-8":return _(this,t,n);case"ascii":return C(this,t,n);case"latin1":case"binary":return T(this,t,n);case"base64":return S(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}.apply(this,arguments)},l.prototype.equals=function(e){if(!l.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===l.compare(this,e)},l.prototype.inspect=function(){var e="",n=t.INSPECT_MAX_BYTES;return this.length>0&&(e=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(e+=" ... ")),""},l.prototype.compare=function(e,t,n,r,o){if(!l.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===o&&(o=this.length),t<0||n>e.length||r<0||o>this.length)throw new RangeError("out of range index");if(r>=o&&t>=n)return 0;if(r>=o)return-1;if(t>=n)return 1;if(this===e)return 0;for(var i=(o>>>=0)-(r>>>=0),a=(n>>>=0)-(t>>>=0),s=Math.min(i,a),c=this.slice(r,o),u=e.slice(t,n),p=0;po)&&(n=o),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var i=!1;;)switch(r){case"hex":return v(this,e,t,n);case"utf8":case"utf-8":return b(this,e,t,n);case"ascii":return w(this,e,t,n);case"latin1":case"binary":return x(this,e,t,n);case"base64":return k(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,e,t,n);default:if(i)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),i=!0}},l.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var O=4096;function C(e,t,n){var r="";n=Math.min(e.length,n);for(var o=t;or)&&(n=r);for(var o="",i=t;in)throw new RangeError("Trying to access beyond buffer length")}function P(e,t,n,r,o,i){if(!l.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||te.length)throw new RangeError("Index out of range")}function R(e,t,n,r){t<0&&(t=65535+t+1);for(var o=0,i=Math.min(e.length-n,2);o>>8*(r?o:1-o)}function N(e,t,n,r){t<0&&(t=4294967295+t+1);for(var o=0,i=Math.min(e.length-n,4);o>>8*(r?o:3-o)&255}function L(e,t,n,r,o,i){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function M(e,t,n,r,i){return i||L(e,0,n,4),o.write(e,t,n,r,23,4),n+4}function D(e,t,n,r,i){return i||L(e,0,n,8),o.write(e,t,n,r,52,8),n+8}l.prototype.slice=function(e,t){var n,r=this.length;if((e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t0&&(o*=256);)r+=this[e+--t]*o;return r},l.prototype.readUInt8=function(e,t){return t||I(e,1,this.length),this[e]},l.prototype.readUInt16LE=function(e,t){return t||I(e,2,this.length),this[e]|this[e+1]<<8},l.prototype.readUInt16BE=function(e,t){return t||I(e,2,this.length),this[e]<<8|this[e+1]},l.prototype.readUInt32LE=function(e,t){return t||I(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},l.prototype.readUInt32BE=function(e,t){return t||I(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},l.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||I(e,t,this.length);for(var r=this[e],o=1,i=0;++i=(o*=128)&&(r-=Math.pow(2,8*t)),r},l.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||I(e,t,this.length);for(var r=t,o=1,i=this[e+--r];r>0&&(o*=256);)i+=this[e+--r]*o;return i>=(o*=128)&&(i-=Math.pow(2,8*t)),i},l.prototype.readInt8=function(e,t){return t||I(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},l.prototype.readInt16LE=function(e,t){t||I(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},l.prototype.readInt16BE=function(e,t){t||I(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},l.prototype.readInt32LE=function(e,t){return t||I(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},l.prototype.readInt32BE=function(e,t){return t||I(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},l.prototype.readFloatLE=function(e,t){return t||I(e,4,this.length),o.read(this,e,!0,23,4)},l.prototype.readFloatBE=function(e,t){return t||I(e,4,this.length),o.read(this,e,!1,23,4)},l.prototype.readDoubleLE=function(e,t){return t||I(e,8,this.length),o.read(this,e,!0,52,8)},l.prototype.readDoubleBE=function(e,t){return t||I(e,8,this.length),o.read(this,e,!1,52,8)},l.prototype.writeUIntLE=function(e,t,n,r){(e=+e,t|=0,n|=0,r)||P(this,e,t,n,Math.pow(2,8*n)-1,0);var o=1,i=0;for(this[t]=255&e;++i=0&&(i*=256);)this[t+o]=e/i&255;return t+n},l.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||P(this,e,t,1,255,0),l.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},l.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||P(this,e,t,2,65535,0),l.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):R(this,e,t,!0),t+2},l.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||P(this,e,t,2,65535,0),l.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):R(this,e,t,!1),t+2},l.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||P(this,e,t,4,4294967295,0),l.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):N(this,e,t,!0),t+4},l.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||P(this,e,t,4,4294967295,0),l.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):N(this,e,t,!1),t+4},l.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t|=0,!r){var o=Math.pow(2,8*n-1);P(this,e,t,n,o-1,-o)}var i=0,a=1,s=0;for(this[t]=255&e;++i>0)-s&255;return t+n},l.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t|=0,!r){var o=Math.pow(2,8*n-1);P(this,e,t,n,o-1,-o)}var i=n-1,a=1,s=0;for(this[t+i]=255&e;--i>=0&&(a*=256);)e<0&&0===s&&0!==this[t+i+1]&&(s=1),this[t+i]=(e/a>>0)-s&255;return t+n},l.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||P(this,e,t,1,127,-128),l.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},l.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||P(this,e,t,2,32767,-32768),l.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):R(this,e,t,!0),t+2},l.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||P(this,e,t,2,32767,-32768),l.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):R(this,e,t,!1),t+2},l.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||P(this,e,t,4,2147483647,-2147483648),l.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):N(this,e,t,!0),t+4},l.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||P(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),l.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):N(this,e,t,!1),t+4},l.prototype.writeFloatLE=function(e,t,n){return M(this,e,t,!0,n)},l.prototype.writeFloatBE=function(e,t,n){return M(this,e,t,!1,n)},l.prototype.writeDoubleLE=function(e,t,n){return D(this,e,t,!0,n)},l.prototype.writeDoubleBE=function(e,t,n){return D(this,e,t,!1,n)},l.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t=0;--o)e[o+t]=this[o+n];else if(i<1e3||!l.TYPED_ARRAY_SUPPORT)for(o=0;o>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(i=t;i55295&&n<57344){if(!o){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(a+1===r){(t-=3)>-1&&i.push(239,191,189);continue}o=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),o=n;continue}n=65536+(o-55296<<10|n-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function z(e){return r.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(F,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function $(e,t,n,r){for(var o=0;o=t.length||o>=e.length);++o)t[o+n]=e[o];return o}}).call(this,n(4))},function(e,t,n){"use strict";var r=n(184),o=n(186);function i(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}t.parse=b,t.resolve=function(e,t){return b(e,!1,!0).resolve(t)},t.resolveObject=function(e,t){return e?b(e,!1,!0).resolveObject(t):t},t.format=function(e){o.isString(e)&&(e=b(e));return e instanceof i?e.format():i.prototype.format.call(e)},t.URL=i;var a=/^([a-z0-9.+-]+:)/i,s=/:[0-9]*$/,l=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,c=["{","}","|","\\","^","` + "`" + `"].concat(["<",">",'"',"` + "`" + `"," ","\r","\n","\t"]),u=["'"].concat(c),p=["%","/","?",";","#"].concat(u),f=["/","?","#"],d=/^[+a-z0-9A-Z_-]{0,63}$/,h=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,m={javascript:!0,"javascript:":!0},g={javascript:!0,"javascript:":!0},y={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},v=n(187);function b(e,t,n){if(e&&o.isObject(e)&&e instanceof i)return e;var r=new i;return r.parse(e,t,n),r}i.prototype.parse=function(e,t,n){if(!o.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var i=e.indexOf("?"),s=-1!==i&&i127?R+="x":R+=P[N];if(!R.match(d)){var M=A.slice(0,C),D=A.slice(C+1),F=P.match(h);F&&(M.push(F[1]),D.unshift(F[2])),D.length&&(b="/"+D.join(".")+b),this.hostname=M.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),j||(this.hostname=r.toASCII(this.hostname));var U=this.port?":"+this.port:"",B=this.hostname||"";this.host=B+U,this.href+=this.host,j&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==b[0]&&(b="/"+b))}if(!m[k])for(C=0,I=u.length;C0)&&n.host.split("@"))&&(n.auth=j.shift(),n.host=n.hostname=j.shift());return n.search=e.search,n.query=e.query,o.isNull(n.pathname)&&o.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.href=n.format(),n}if(!E.length)return n.pathname=null,n.search?n.path="/"+n.search:n.path=null,n.href=n.format(),n;for(var _=E.slice(-1)[0],O=(n.host||e.host||E.length>1)&&("."===_||".."===_)||""===_,C=0,T=E.length;T>=0;T--)"."===(_=E[T])?E.splice(T,1):".."===_?(E.splice(T,1),C++):C&&(E.splice(T,1),C--);if(!x&&!k)for(;C--;C)E.unshift("..");!x||""===E[0]||E[0]&&"/"===E[0].charAt(0)||E.unshift(""),O&&"/"!==E.join("/").substr(-1)&&E.push("");var j,A=""===E[0]||E[0]&&"/"===E[0].charAt(0);S&&(n.hostname=n.host=A?"":E.length?E.shift():"",(j=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=j.shift(),n.host=n.hostname=j.shift()));return(x=x||n.host&&E.length)&&!A&&E.unshift(""),E.length?n.pathname=E.join("/"):(n.pathname=null,n.path=null),o.isNull(n.pathname)&&o.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.auth=e.auth||n.auth,n.slashes=n.slashes||e.slashes,n.href=n.format(),n},i.prototype.parseHost=function(){var e=this.host,t=s.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)}},function(e,t,n){e.exports=n(182)()},function(e,t,n){var r; /*! Copyright (c) 2017 Jed Watson. Licensed under the MIT License (MIT), see @@ -100,19 +100,19 @@ const RedocUITemplate = ` Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ -!function(){"use strict";var n={}.hasOwnProperty;function o(){for(var e=[],t=0;t=0?e.substr(t).toLowerCase():""},t.getHash=function(e){var t=e.indexOf("#");return t>=0?e.substr(t):"#"},t.stripHash=function(e){var t=e.indexOf("#");return t>=0&&(e=e.substr(0,t)),e},t.isHttp=function(e){var t=s.getProtocol(e);return"http"===t||"https"===t||void 0===t&&r.browser},t.isFileSystemPath=function(e){if(r.browser)return!1;var t=s.getProtocol(e);return void 0===t||"file"===t},t.fromFileSystemPath=function(e){o&&(e=e.replace(/\\/g,"/")),e=encodeURI(e);for(var t=0;t0&&(h=e.exports.formatter.apply(null,s)),n&&n.message&&(h+=(h?" \n":"")+n.message);var m,g,y,v=new t(h);return function(e,t){var n,r;!function(e){if(!d)return!1;var t=Object.getOwnPropertyDescriptor(e,"stack");return!!t&&"function"==typeof t.get}(e)?e.stack=t?p(e.stack,t.stack):f(e.stack):t?function(e,t){var n=Object.getOwnPropertyDescriptor(e,"stack");Object.defineProperty(e,"stack",{get:function(){return p(n.get.apply(e),t.stack)},enumerable:!1,configurable:!0})}(e,t):(n=e,r=Object.getOwnPropertyDescriptor(n,"stack"),Object.defineProperty(n,"stack",{get:function(){return f(r.get.apply(n))},enumerable:!1,configurable:!0}))}(m=v,g=n),l(m,g),(y=v).toJSON=c,y.inspect=u,l(v,r),v}}function l(e,t){if(t&&"object"==typeof t)for(var n=Object.keys(t),r=0;r=0))try{e[o]=t[o]}catch(e){}}}function c(){var e={},t=Object.keys(this);t=t.concat(a);for(var n=0;n=0)return t.splice(n,1),t.join("\n")}return e}}e.exports=s(Error),e.exports.error=s(Error),e.exports.eval=s(EvalError),e.exports.range=s(RangeError),e.exports.reference=s(ReferenceError),e.exports.syntax=s(SyntaxError),e.exports.type=s(TypeError),e.exports.uri=s(URIError),e.exports.formatter=r;var d=!(!Object.getOwnPropertyDescriptor||!Object.defineProperty||"undefined"!=typeof navigator&&/Android/.test(navigator.userAgent))},function(e,t){var n={}.toString;e.exports=function(e){return n.call(e).slice(8,-1)}},function(e,t){e.exports=function(e){try{return!!e()}catch(e){return!0}}},function(e,t,n){var r=n(64),o=n(43);e.exports=function(e){return r(o(e))}},function(e,t,n){"use strict";var r=n(37),o=n(47),i=n(3);function a(e,t,n){var r=[];return e.include.forEach(function(e){n=a(e,t,n)}),e[t].forEach(function(e){n.forEach(function(t,n){t.tag===e.tag&&t.kind===e.kind&&r.push(n)}),n.push(e)}),n.filter(function(e,t){return-1===r.indexOf(t)})}function s(e){this.include=e.include||[],this.implicit=e.implicit||[],this.explicit=e.explicit||[],this.implicit.forEach(function(e){if(e.loadKind&&"scalar"!==e.loadKind)throw new o("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.")}),this.compiledImplicit=a(this,"implicit",[]),this.compiledExplicit=a(this,"explicit",[]),this.compiledTypeMap=function(){var e,t,n={scalar:{},sequence:{},mapping:{},fallback:{}};function r(e){n[e.kind][e.tag]=n.fallback[e.tag]=e}for(e=0,t=arguments.length;e0?o(r(e),9007199254740991):0}},function(e,t,n){var r=n(16).f,o=n(23),i=n(2)("toStringTag");e.exports=function(e,t,n){e&&!o(e=n?e:e.prototype,i)&&r(e,i,{configurable:!0,value:t})}},function(e,t,n){"use strict";function r(e){return null==e}e.exports.isNothing=r,e.exports.isObject=function(e){return"object"==typeof e&&null!==e},e.exports.toArray=function(e){return Array.isArray(e)?e:r(e)?[]:[e]},e.exports.repeat=function(e,t){var n,r="";for(n=0;n2?r:e).apply(void 0,o)}}e.memoize=o,e.debounce=i,e.bind=a,e.default={memoize:o,debounce:i,bind:a}})?r.apply(t,o):r)||(e.exports=i)},function(e,t,n){(function(t){!function(t){"use strict";var n={newline:/^\n+/,code:/^( {4}[^\n]+\n*)+/,fences:m,hr:/^ {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)/,heading:/^ *(#{1,6}) *([^\n]+?) *(?:#+ *)?(?:\n+|$)/,nptable:m,blockquote:/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,list:/^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,html:"^ {0,3}(?:<(script|pre|style)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?\\?>\\n*|\\n*|\\n*|)[\\s\\S]*?(?:\\n{2,}|$)|<(?!script|pre|style)([a-z][\\w-]*)(?:attribute)*? */?>(?=\\h*\\n)[\\s\\S]*?(?:\\n{2,}|$)|(?=\\h*\\n)[\\s\\S]*?(?:\\n{2,}|$))",def:/^ {0,3}\[(label)\]: *\n? *]+)>?(?:(?: +\n? *| *\n *)(title))? *(?:\n+|$)/,table:m,lheading:/^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,paragraph:/^([^\n]+(?:\n(?!hr|heading|lheading| {0,3}>|<\/?(?:tag)(?: +|\n|\/?>)|<(?:script|pre|style|!--))[^\n]+)*)/,text:/^[^\n]+/};function r(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||b.defaults,this.rules=n.normal,this.options.pedantic?this.rules=n.pedantic:this.options.gfm&&(this.options.tables?this.rules=n.tables:this.rules=n.gfm)}n._label=/(?!\s*\])(?:\\[\[\]]|[^\[\]])+/,n._title=/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/,n.def=p(n.def).replace("label",n._label).replace("title",n._title).getRegex(),n.bullet=/(?:[*+-]|\d+\.)/,n.item=/^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/,n.item=p(n.item,"gm").replace(/bull/g,n.bullet).getRegex(),n.list=p(n.list).replace(/bull/g,n.bullet).replace("hr","\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))").replace("def","\\n+(?="+n.def.source+")").getRegex(),n._tag="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",n._comment=//,n.html=p(n.html,"i").replace("comment",n._comment).replace("tag",n._tag).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>` + "`" + `]+)?/).getRegex(),n.paragraph=p(n.paragraph).replace("hr",n.hr).replace("heading",n.heading).replace("lheading",n.lheading).replace("tag",n._tag).getRegex(),n.blockquote=p(n.blockquote).replace("paragraph",n.paragraph).getRegex(),n.normal=g({},n),n.gfm=g({},n.normal,{fences:/^ *(` + "`" + `{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\n? *\1 *(?:\n+|$)/,paragraph:/^/,heading:/^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/}),n.gfm.paragraph=p(n.paragraph).replace("(?!","(?!"+n.gfm.fences.source.replace("\\1","\\2")+"|"+n.list.source.replace("\\1","\\3")+"|").getRegex(),n.tables=g({},n.gfm,{nptable:/^ *([^|\n ].*\|.*)\n *([-:]+ *\|[-| :]*)(?:\n((?:.*[^>\n ].*(?:\n|$))*)\n*|$)/,table:/^ *\|(.+)\n *\|?( *[-:]+[-| :]*)(?:\n((?: *[^>\n ].*(?:\n|$))*)\n*|$)/}),n.pedantic=g({},n.normal,{html:p("^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))").replace("comment",n._comment).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/}),r.rules=n,r.lex=function(e,t){return new r(t).lex(e)},r.prototype.lex=function(e){return e=e.replace(/\r\n|\r/g,"\n").replace(/\t/g," ").replace(/\u00a0/g," ").replace(/\u2424/g,"\n"),this.token(e,!0)},r.prototype.token=function(e,t){var r,o,i,a,s,l,c,u,p,f,d,h,m,g,b,w;for(e=e.replace(/^ +$/gm,"");e;)if((i=this.rules.newline.exec(e))&&(e=e.substring(i[0].length),i[0].length>1&&this.tokens.push({type:"space"})),i=this.rules.code.exec(e))e=e.substring(i[0].length),i=i[0].replace(/^ {4}/gm,""),this.tokens.push({type:"code",text:this.options.pedantic?i:v(i,"\n")});else if(i=this.rules.fences.exec(e))e=e.substring(i[0].length),this.tokens.push({type:"code",lang:i[2],text:i[3]||""});else if(i=this.rules.heading.exec(e))e=e.substring(i[0].length),this.tokens.push({type:"heading",depth:i[1].length,text:i[2]});else if(t&&(i=this.rules.nptable.exec(e))&&(l={type:"table",header:y(i[1].replace(/^ *| *\| *$/g,"")),align:i[2].replace(/^ *|\| *$/g,"").split(/ *\| */),cells:i[3]?i[3].replace(/\n$/,"").split("\n"):[]}).header.length===l.align.length){for(e=e.substring(i[0].length),d=0;d ?/gm,""),this.token(i,t),this.tokens.push({type:"blockquote_end"});else if(i=this.rules.list.exec(e)){for(e=e.substring(i[0].length),c={type:"list_start",ordered:g=(a=i[2]).length>1,start:g?+a:"",loose:!1},this.tokens.push(c),u=[],r=!1,m=(i=i[0].match(this.rules.item)).length,d=0;d1&&s.length>1||(e=i.slice(d+1).join("\n")+e,d=m-1)),o=r||/\n\n(?!\s*$)/.test(l),d!==m-1&&(r="\n"===l.charAt(l.length-1),o||(o=r)),o&&(c.loose=!0),w=void 0,(b=/^\[[ xX]\] /.test(l))&&(w=" "!==l[1],l=l.replace(/^\[[ xX]\] +/,"")),p={type:"list_item_start",task:b,checked:w,loose:o},u.push(p),this.tokens.push(p),this.token(l,!1),this.tokens.push({type:"list_item_end"});if(c.loose)for(m=u.length,d=0;d?@\[\]\\^_` + "`" + `{|}~])/,autolink:/^<(scheme:[^\s\x00-\x1f<>]*|email)>/,url:m,tag:"^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^",link:/^!?\[(label)\]\(href(?:\s+(title))?\s*\)/,reflink:/^!?\[(label)\]\[(?!\s*\])((?:\\[\[\]]?|[^\[\]\\])+)\]/,nolink:/^!?\[(?!\s*\])((?:\[[^\[\]]*\]|\\[\[\]]|[^\[\]])*)\](?:\[\])?/,strong:/^__([^\s])__(?!_)|^\*\*([^\s])\*\*(?!\*)|^__([^\s][\s\S]*?[^\s])__(?!_)|^\*\*([^\s][\s\S]*?[^\s])\*\*(?!\*)/,em:/^_([^\s_])_(?!_)|^\*([^\s*"<\[])\*(?!\*)|^_([^\s][\s\S]*?[^\s_])_(?!_|[^\s.])|^_([^\s_][\s\S]*?[^\s])_(?!_|[^\s.])|^\*([^\s"<\[][\s\S]*?[^\s*])\*(?!\*)|^\*([^\s*"<\[][\s\S]*?[^\s])\*(?!\*)/,code:/^(` + "`" + `+)([^` + "`" + `]|[^` + "`" + `][\s\S]*?[^` + "`" + `])\1(?!` + "`" + `)/,br:/^( {2,}|\\)\n(?!\s*$)/,del:m,text:/^(` + "`" + `+|[^` + "`" + `])[\s\S]*?(?=[\\?@\[\]\\^_` + "`" + `{|}~])/g,o._scheme=/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/,o._email=/[a-zA-Z0-9.!#$%&'*+\/=?^_` + "`" + `{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/,o.autolink=p(o.autolink).replace("scheme",o._scheme).replace("email",o._email).getRegex(),o._attribute=/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>` + "`" + `]+)?/,o.tag=p(o.tag).replace("comment",n._comment).replace("attribute",o._attribute).getRegex(),o._label=/(?:\[[^\[\]]*\]|\\[\[\]]?|` + "`" + `[^` + "`" + `]*` + "`" + `|[^\[\]\\])*?/,o._href=/\s*(<(?:\\[<>]?|[^\s<>\\])*>|(?:\\[()]?|\([^\s\x00-\x1f\\]*\)|[^\s\x00-\x1f()\\])*?)/,o._title=/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/,o.link=p(o.link).replace("label",o._label).replace("href",o._href).replace("title",o._title).getRegex(),o.reflink=p(o.reflink).replace("label",o._label).getRegex(),o.normal=g({},o),o.pedantic=g({},o.normal,{strong:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,em:/^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/,link:p(/^!?\[(label)\]\((.*?)\)/).replace("label",o._label).getRegex(),reflink:p(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",o._label).getRegex()}),o.gfm=g({},o.normal,{escape:p(o.escape).replace("])","~|])").getRegex(),_extended_email:/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,url:/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,_backpedal:/(?:[^?!.,:;*_~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_~)]+(?!$))+/,del:/^~+(?=\S)([\s\S]*?\S)~+/,text:p(o.text).replace("]|","~]|").replace("|$","|https?://|ftp://|www\\.|[a-zA-Z0-9.!#$%&'*+/=?^_` + "`" + `{\\|}~-]+@|$").getRegex()}),o.gfm.url=p(o.gfm.url).replace("email",o.gfm._extended_email).getRegex(),o.breaks=g({},o.gfm,{br:p(o.br).replace("{2,}","*").getRegex(),text:p(o.gfm.text).replace("{2,}","*").getRegex()}),i.rules=o,i.output=function(e,t,n){return new i(t,n).output(e)},i.prototype.output=function(e){for(var t,n,r,o,a,s,l="";e;)if(a=this.rules.escape.exec(e))e=e.substring(a[0].length),l+=a[1];else if(a=this.rules.autolink.exec(e))e=e.substring(a[0].length),r="@"===a[2]?"mailto:"+(n=c(this.mangle(a[1]))):n=c(a[1]),l+=this.renderer.link(r,null,n);else if(this.inLink||!(a=this.rules.url.exec(e))){if(a=this.rules.tag.exec(e))!this.inLink&&/^/i.test(a[0])&&(this.inLink=!1),!this.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(a[0])?this.inRawBlock=!0:this.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(a[0])&&(this.inRawBlock=!1),e=e.substring(a[0].length),l+=this.options.sanitize?this.options.sanitizer?this.options.sanitizer(a[0]):c(a[0]):a[0];else if(a=this.rules.link.exec(e))e=e.substring(a[0].length),this.inLink=!0,r=a[2],this.options.pedantic?(t=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(r))?(r=t[1],o=t[3]):o="":o=a[3]?a[3].slice(1,-1):"",r=r.trim().replace(/^<([\s\S]*)>$/,"$1"),l+=this.outputLink(a,{href:i.escapes(r),title:i.escapes(o)}),this.inLink=!1;else if((a=this.rules.reflink.exec(e))||(a=this.rules.nolink.exec(e))){if(e=e.substring(a[0].length),t=(a[2]||a[1]).replace(/\s+/g," "),!(t=this.links[t.toLowerCase()])||!t.href){l+=a[0].charAt(0),e=a[0].substring(1)+e;continue}this.inLink=!0,l+=this.outputLink(a,t),this.inLink=!1}else if(a=this.rules.strong.exec(e))e=e.substring(a[0].length),l+=this.renderer.strong(this.output(a[4]||a[3]||a[2]||a[1]));else if(a=this.rules.em.exec(e))e=e.substring(a[0].length),l+=this.renderer.em(this.output(a[6]||a[5]||a[4]||a[3]||a[2]||a[1]));else if(a=this.rules.code.exec(e))e=e.substring(a[0].length),l+=this.renderer.codespan(c(a[2].trim(),!0));else if(a=this.rules.br.exec(e))e=e.substring(a[0].length),l+=this.renderer.br();else if(a=this.rules.del.exec(e))e=e.substring(a[0].length),l+=this.renderer.del(this.output(a[1]));else if(a=this.rules.text.exec(e))e=e.substring(a[0].length),this.inRawBlock?l+=this.renderer.text(a[0]):l+=this.renderer.text(c(this.smartypants(a[0])));else if(e)throw new Error("Infinite loop on byte: "+e.charCodeAt(0))}else{if("@"===a[2])r="mailto:"+(n=c(a[0]));else{do{s=a[0],a[0]=this.rules._backpedal.exec(a[0])[0]}while(s!==a[0]);n=c(a[0]),r="www."===a[1]?"http://"+n:n}e=e.substring(a[0].length),l+=this.renderer.link(r,null,n)}return l},i.escapes=function(e){return e?e.replace(i.rules._escapes,"$1"):e},i.prototype.outputLink=function(e,t){var n=t.href,r=t.title?c(t.title):null;return"!"!==e[0].charAt(0)?this.renderer.link(n,r,this.output(e[1])):this.renderer.image(n,r,c(e[1]))},i.prototype.smartypants=function(e){return this.options.smartypants?e.replace(/---/g,"—").replace(/--/g,"–").replace(/(^|[-\u2014\/(\[{"\s])'/g,"$1‘").replace(/'/g,"’").replace(/(^|[-\u2014\/(\[{\u2018\s])"/g,"$1“").replace(/"/g,"”").replace(/\.{3}/g,"…"):e},i.prototype.mangle=function(e){if(!this.options.mangle)return e;for(var t,n="",r=e.length,o=0;o.5&&(t="x"+t.toString(16)),n+="&#"+t+";";return n},a.prototype.code=function(e,t,n){if(this.options.highlight){var r=this.options.highlight(e,t);null!=r&&r!==e&&(n=!0,e=r)}return t?'
'+(n?e:c(e,!0))+"
\n":"
"+(n?e:c(e,!0))+"
"},a.prototype.blockquote=function(e){return"
\n"+e+"
\n"},a.prototype.html=function(e){return e},a.prototype.heading=function(e,t,n){return this.options.headerIds?"'+e+"\n":""+e+"\n"},a.prototype.hr=function(){return this.options.xhtml?"
\n":"
\n"},a.prototype.list=function(e,t,n){var r=t?"ol":"ul";return"<"+r+(t&&1!==n?' start="'+n+'"':"")+">\n"+e+"\n"},a.prototype.listitem=function(e){return"
  • "+e+"
  • \n"},a.prototype.checkbox=function(e){return" "},a.prototype.paragraph=function(e){return"

    "+e+"

    \n"},a.prototype.table=function(e,t){return t&&(t=""+t+""),"\n\n"+e+"\n"+t+"
    \n"},a.prototype.tablerow=function(e){return"\n"+e+"\n"},a.prototype.tablecell=function(e,t){var n=t.header?"th":"td";return(t.align?"<"+n+' align="'+t.align+'">':"<"+n+">")+e+"\n"},a.prototype.strong=function(e){return""+e+""},a.prototype.em=function(e){return""+e+""},a.prototype.codespan=function(e){return""+e+""},a.prototype.br=function(){return this.options.xhtml?"
    ":"
    "},a.prototype.del=function(e){return""+e+""},a.prototype.link=function(e,t,n){if(this.options.sanitize){try{var r=decodeURIComponent(u(e)).replace(/[^\w:]/g,"").toLowerCase()}catch(e){return n}if(0===r.indexOf("javascript:")||0===r.indexOf("vbscript:")||0===r.indexOf("data:"))return n}this.options.baseUrl&&!h.test(e)&&(e=f(this.options.baseUrl,e));try{e=encodeURI(e).replace(/%25/g,"%")}catch(e){return n}var o='
    "},a.prototype.image=function(e,t,n){this.options.baseUrl&&!h.test(e)&&(e=f(this.options.baseUrl,e));var r=''+n+'":">"},a.prototype.text=function(e){return e},s.prototype.strong=s.prototype.em=s.prototype.codespan=s.prototype.del=s.prototype.text=function(e){return e},s.prototype.link=s.prototype.image=function(e,t,n){return""+n},s.prototype.br=function(){return""},l.parse=function(e,t){return new l(t).parse(e)},l.prototype.parse=function(e){this.inline=new i(e.links,this.options),this.inlineText=new i(e.links,g({},this.options,{renderer:new s})),this.tokens=e.reverse();for(var t="";this.next();)t+=this.tok();return t},l.prototype.next=function(){return this.token=this.tokens.pop()},l.prototype.peek=function(){return this.tokens[this.tokens.length-1]||0},l.prototype.parseText=function(){for(var e=this.token.text;"text"===this.peek().type;)e+="\n"+this.next().text;return this.inline.output(e)},l.prototype.tok=function(){switch(this.token.type){case"space":return"";case"hr":return this.renderer.hr();case"heading":return this.renderer.heading(this.inline.output(this.token.text),this.token.depth,u(this.inlineText.output(this.token.text)));case"code":return this.renderer.code(this.token.text,this.token.lang,this.token.escaped);case"table":var e,t,n,r,o="",i="";for(n="",e=0;e"']/,c.escapeReplace=/[&<>"']/g,c.replacements={"&":"&","<":"<",">":">",'"':""","'":"'"},c.escapeTestNoEncode=/[<>"']|&(?!#?\w+;)/,c.escapeReplaceNoEncode=/[<>"']|&(?!#?\w+;)/g;var d={},h=/^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;function m(){}function g(e){for(var t,n,r=1;r=0&&"\\"===n[o];)r=!r;return r?"|":" |"}).split(/ \|/),r=0;if(n.length>t)n.splice(t);else for(;n.lengthAn error occurred:

    "+c(e.message+"",!0)+"
    ";throw e}}m.exec=m,b.options=b.setOptions=function(e){return g(b.defaults,e),b},b.getDefaults=function(){return{baseUrl:null,breaks:!1,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:new a,sanitize:!1,sanitizer:null,silent:!1,smartLists:!1,smartypants:!1,tables:!0,xhtml:!1}},b.defaults=b.getDefaults(),b.Parser=l,b.parser=l.parse,b.Renderer=a,b.TextRenderer=s,b.Lexer=r,b.lexer=r.lex,b.InlineLexer=i,b.inlineLexer=i.output,b.parse=b,e.exports=b}(this||"undefined"!=typeof window&&window)}).call(this,n(4))},function(e,t){e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},function(e,t){e.exports=function(e){if(null==e)throw TypeError("Can't call method on "+e);return e}},function(e,t){e.exports=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e}},function(e,t){t.f={}.propertyIsEnumerable},function(e,t,n){"use strict";var r=n(195);e.exports=r},function(e,t,n){"use strict";function r(e,t){Error.call(this),this.name="YAMLException",this.reason=e,this.mark=t,this.message=(this.reason||"(unknown reason)")+(this.mark?" "+this.mark.toString():""),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack||""}r.prototype=Object.create(Error.prototype),r.prototype.constructor=r,r.prototype.toString=function(e){var t=this.name+": ";return t+=this.reason||"(unknown reason)",!e&&this.mark&&(t+=" "+this.mark.toString()),t},e.exports=r},function(e,t,n){"use strict";var r=n(29);e.exports=new r({include:[n(104)],implicit:[n(205),n(206)],explicit:[n(207),n(208),n(209),n(210)]})},function(e,t,n){"use strict";(function(t){!t.version||0===t.version.indexOf("v0.")||0===t.version.indexOf("v1.")&&0!==t.version.indexOf("v1.8.")?e.exports={nextTick:function(e,n,r,o){if("function"!=typeof e)throw new TypeError('"callback" argument must be a function');var i,a,s=arguments.length;switch(s){case 0:case 1:return t.nextTick(e);case 2:return t.nextTick(function(){e.call(null,n)});case 3:return t.nextTick(function(){e.call(null,n,r)});case 4:return t.nextTick(function(){e.call(null,n,r,o)});default:for(i=new Array(s-1),a=0;a0},o.isExternal$Ref=function(e){return o.is$Ref(e)&&"#"!==e.$ref[0]},o.isAllowed$Ref=function(e,t){if(o.is$Ref(e)){if("#/"===e.$ref.substr(0,2)||"#"===e.$ref)return!0;if("#"!==e.$ref[0]&&(!t||t.resolve.external))return!0}},o.isExtended$Ref=function(e){return o.is$Ref(e)&&Object.keys(e).length>1},o.dereference=function(e,t){if(t&&"object"==typeof t&&o.isExtended$Ref(e)){var n={};return Object.keys(e).forEach(function(t){"$ref"!==t&&(n[t]=e[t])}),Object.keys(t).forEach(function(e){e in n||(n[e]=t[e])}),n}return t}},function(e,t,n){(function(e){function n(e,t){for(var n=0,r=e.length-1;r>=0;r--){var o=e[r];"."===o?e.splice(r,1):".."===o?(e.splice(r,1),n++):n&&(e.splice(r,1),n--)}if(t)for(;n--;n)e.unshift("..");return e}var r=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/,o=function(e){return r.exec(e).slice(1)};function i(e,t){if(e.filter)return e.filter(t);for(var n=[],r=0;r=-1&&!r;o--){var a=o>=0?arguments[o]:e.cwd();if("string"!=typeof a)throw new TypeError("Arguments to path.resolve must be strings");a&&(t=a+"/"+t,r="/"===a.charAt(0))}return(r?"/":"")+(t=n(i(t.split("/"),function(e){return!!e}),!r).join("/"))||"."},t.normalize=function(e){var r=t.isAbsolute(e),o="/"===a(e,-1);return(e=n(i(e.split("/"),function(e){return!!e}),!r).join("/"))||r||(e="."),e&&o&&(e+="/"),(r?"/":"")+e},t.isAbsolute=function(e){return"/"===e.charAt(0)},t.join=function(){var e=Array.prototype.slice.call(arguments,0);return t.normalize(i(e,function(e,t){if("string"!=typeof e)throw new TypeError("Arguments to path.join must be strings");return e}).join("/"))},t.relative=function(e,n){function r(e){for(var t=0;t=0&&""===e[n];n--);return t>n?[]:e.slice(t,n-t+1)}e=t.resolve(e).substr(1),n=t.resolve(n).substr(1);for(var o=r(e.split("/")),i=r(n.split("/")),a=Math.min(o.length,i.length),s=a,l=0;le.length)return;if(!(x instanceof l)){if(m&&b!=t.length-1){if(f.lastIndex=w,!(C=f.exec(e)))break;for(var k=C.index+(h?C[1].length:0),E=C.index+C[0].length,S=b,_=w,O=t.length;S=(_+=t[S].length)&&(++b,w=_);if(t[b]instanceof l)continue;T=S-b,x=e.slice(w,_),C.index-=w}else{f.lastIndex=0;var C=f.exec(x),T=1}if(C){h&&(g=C[1]?C[1].length:0);E=(k=C.index+g)+(C=C[0].slice(g)).length;var j=x.slice(0,k),A=x.slice(E),I=[b,T];j&&(++b,w+=j.length,I.push(j));var P=new l(c,d?r.tokenize(C,d):C,y,C,m);if(I.push(P),A&&I.push(A),Array.prototype.splice.apply(t,I),1!=T&&r.matchGrammar(e,t,n,b,w,!0,c),a)break}else if(a)break}}}}},tokenize:function(e,t,n){var o=[e],i=t.rest;if(i){for(var a in i)t[a]=i[a];delete t.rest}return r.matchGrammar(e,o,t,0,0,!1),o},hooks:{all:{},add:function(e,t){var n=r.hooks.all;n[e]=n[e]||[],n[e].push(t)},run:function(e,t){var n=r.hooks.all[e];if(n&&n.length)for(var o,i=0;o=n[i++];)o(t)}}},o=r.Token=function(e,t,n,r,o){this.type=e,this.content=t,this.alias=n,this.length=0|(r||"").length,this.greedy=!!o};if(o.stringify=function(e,t,n){if("string"==typeof e)return e;if("Array"===r.util.type(e))return e.map(function(n){return o.stringify(n,t,e)}).join("");var i={type:e.type,content:o.stringify(e.content,t,n),tag:"span",classes:["token",e.type],attributes:{},language:t,parent:n};if(e.alias){var a="Array"===r.util.type(e.alias)?e.alias:[e.alias];Array.prototype.push.apply(i.classes,a)}r.hooks.run("wrap",i);var s=Object.keys(i.attributes).map(function(e){return e+'="'+(i.attributes[e]||"").replace(/"/g,""")+'"'}).join(" ");return"<"+i.tag+' class="'+i.classes.join(" ")+'"'+(s?" "+s:"")+">"+i.content+""},!n.document)return n.addEventListener?(r.disableWorkerMessageHandler||n.addEventListener("message",function(e){var t=JSON.parse(e.data),o=t.language,i=t.code,a=t.immediateClose;n.postMessage(r.highlight(i,r.languages[o],o)),a&&n.close()},!1),n.Prism):n.Prism;var i=document.currentScript||[].slice.call(document.getElementsByTagName("script")).pop();return i&&(r.filename=i.src,r.manual||i.hasAttribute("data-manual")||("loading"!==document.readyState?window.requestAnimationFrame?window.requestAnimationFrame(r.highlightAll):window.setTimeout(r.highlightAll,16):document.addEventListener("DOMContentLoaded",r.highlightAll))),n.Prism}();e.exports&&(e.exports=r),void 0!==t&&(t.Prism=r),r.languages.markup={comment://,prolog:/<\?[\s\S]+?\?>/,doctype://i,cdata://i,tag:{pattern:/<\/?(?!\d)[^\s>\/=$<%]+(?:\s+[^\s>\/=]+(?:=(?:("|')(?:\\[\s\S]|(?!\1)[^\\])*\1|[^\s'">=]+))?)*\s*\/?>/i,greedy:!0,inside:{tag:{pattern:/^<\/?[^\s>\/]+/i,inside:{punctuation:/^<\/?/,namespace:/^[^\s>\/:]+:/}},"attr-value":{pattern:/=(?:("|')(?:\\[\s\S]|(?!\1)[^\\])*\1|[^\s'">=]+)/i,inside:{punctuation:[/^=/,{pattern:/(^|[^\\])["']/,lookbehind:!0}]}},punctuation:/\/?>/,"attr-name":{pattern:/[^\s>\/]+/,inside:{namespace:/^[^\s>\/:]+:/}}}},entity:/&#?[\da-z]{1,8};/i},r.languages.markup.tag.inside["attr-value"].inside.entity=r.languages.markup.entity,r.hooks.add("wrap",function(e){"entity"===e.type&&(e.attributes.title=e.content.replace(/&/,"&"))}),r.languages.xml=r.languages.markup,r.languages.html=r.languages.markup,r.languages.mathml=r.languages.markup,r.languages.svg=r.languages.markup,r.languages.css={comment:/\/\*[\s\S]*?\*\//,atrule:{pattern:/@[\w-]+?.*?(?:;|(?=\s*\{))/i,inside:{rule:/@[\w-]+/}},url:/url\((?:(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1|.*?)\)/i,selector:/[^{}\s][^{};]*?(?=\s*\{)/,string:{pattern:/("|')(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,greedy:!0},property:/[-_a-z\xA0-\uFFFF][-\w\xA0-\uFFFF]*(?=\s*:)/i,important:/\B!important\b/i,function:/[-a-z0-9]+(?=\()/i,punctuation:/[(){};:]/},r.languages.css.atrule.inside.rest=r.languages.css,r.languages.markup&&(r.languages.insertBefore("markup","tag",{style:{pattern:/()[\s\S]*?(?=<\/style>)/i,lookbehind:!0,inside:r.languages.css,alias:"language-css",greedy:!0}}),r.languages.insertBefore("inside","attr-value",{"style-attr":{pattern:/\s*style=("|')(?:\\[\s\S]|(?!\1)[^\\])*\1/i,inside:{"attr-name":{pattern:/^\s*style/i,inside:r.languages.markup.tag.inside},punctuation:/^\s*=\s*['"]|['"]\s*$/,"attr-value":{pattern:/.+/i,inside:r.languages.css}},alias:"language-css"}},r.languages.markup.tag)),r.languages.clike={comment:[{pattern:/(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,lookbehind:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0,greedy:!0}],string:{pattern:/(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,greedy:!0},"class-name":{pattern:/((?:\b(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[\w.\\]+/i,lookbehind:!0,inside:{punctuation:/[.\\]/}},keyword:/\b(?:if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/,boolean:/\b(?:true|false)\b/,function:/[a-z0-9_]+(?=\()/i,number:/\b0x[\da-f]+\b|(?:\b\d+\.?\d*|\B\.\d+)(?:e[+-]?\d+)?/i,operator:/--?|\+\+?|!=?=?|<=?|>=?|==?=?|&&?|\|\|?|\?|\*|\/|~|\^|%/,punctuation:/[{}[\];(),.:]/},r.languages.javascript=r.languages.extend("clike",{keyword:/\b(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|var|void|while|with|yield)\b/,number:/\b(?:0[xX][\dA-Fa-f]+|0[bB][01]+|0[oO][0-7]+|NaN|Infinity)\b|(?:\b\d+\.?\d*|\B\.\d+)(?:[Ee][+-]?\d+)?/,function:/[_$a-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*\()/i,operator:/-[-=]?|\+[+=]?|!=?=?|<>?>?=?|=(?:==?|>)?|&[&=]?|\|[|=]?|\*\*?=?|\/=?|~|\^=?|%=?|\?|\.{3}/}),r.languages.insertBefore("javascript","keyword",{regex:{pattern:/((?:^|[^$\w\xA0-\uFFFF."'\])\s])\s*)\/(\[[^\]\r\n]+]|\\.|[^\/\\\[\r\n])+\/[gimyu]{0,5}(?=\s*($|[\r\n,.;})\]]))/,lookbehind:!0,greedy:!0},"function-variable":{pattern:/[_$a-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*=\s*(?:function\b|(?:\([^()]*\)|[_$a-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*)\s*=>))/i,alias:"function"},constant:/\b[A-Z][A-Z\d_]*\b/}),r.languages.insertBefore("javascript","string",{"template-string":{pattern:/` + "`" + `(?:\\[\s\S]|\${[^}]+}|[^\\` + "`" + `])*` + "`" + `/,greedy:!0,inside:{interpolation:{pattern:/\${[^}]+}/,inside:{"interpolation-punctuation":{pattern:/^\${|}$/,alias:"punctuation"},rest:null}},string:/[\s\S]+/}}}),r.languages.javascript["template-string"].inside.interpolation.inside.rest=r.languages.javascript,r.languages.markup&&r.languages.insertBefore("markup","tag",{script:{pattern:/()[\s\S]*?(?=<\/script>)/i,lookbehind:!0,inside:r.languages.javascript,alias:"language-javascript",greedy:!0}}),r.languages.js=r.languages.javascript,"undefined"!=typeof self&&self.Prism&&self.document&&document.querySelector&&(self.Prism.fileHighlight=function(){var e={js:"javascript",py:"python",rb:"ruby",ps1:"powershell",psm1:"powershell",sh:"bash",bat:"batch",h:"c",tex:"latex"};Array.prototype.slice.call(document.querySelectorAll("pre[data-src]")).forEach(function(t){for(var n,o=t.getAttribute("data-src"),i=t,a=/\blang(?:uage)?-([\w-]+)\b/i;i&&!a.test(i.className);)i=i.parentNode;if(i&&(n=(t.className.match(a)||[,""])[1]),!n){var s=(o.match(/\.(\w+)$/)||[,""])[1];n=e[s]||s}var l=document.createElement("code");l.className="language-"+n,t.textContent="",l.textContent="Loading…",t.appendChild(l);var c=new XMLHttpRequest;c.open("GET",o,!0),c.onreadystatechange=function(){4==c.readyState&&(c.status<400&&c.responseText?(l.textContent=c.responseText,r.highlightElement(l)):c.status>=400?l.textContent="✖ Error "+c.status+" while fetching file: "+c.statusText:l.textContent="✖ Error: File does not exist or is empty")},c.send(null)}),r.plugins.toolbar&&r.plugins.toolbar.registerButton("download-file",function(e){var t=e.element.parentNode;if(t&&/pre/i.test(t.nodeName)&&t.hasAttribute("data-src")&&t.hasAttribute("data-download-link")){var n=t.getAttribute("data-src"),r=document.createElement("a");return r.textContent=t.getAttribute("data-download-link-label")||"Download",r.setAttribute("download",""),r.href=n,r}})},document.addEventListener("DOMContentLoaded",self.Prism.fileHighlight))}).call(this,n(4))},function(e,t,n){"use strict";var r=n(57),o={};o[n(2)("toStringTag")]="z",o+""!="[object z]"&&n(21)(Object.prototype,"toString",function(){return"[object "+r(this)+"]"},!0)},function(e,t,n){var r=n(26),o=n(2)("toStringTag"),i="Arguments"==r(function(){return arguments}());e.exports=function(e){var t,n,a;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(n=function(e,t){try{return e[t]}catch(e){}}(t=Object(e),o))?n:i?r(t):"Object"==(a=r(t))&&"function"==typeof t.callee?"Arguments":a}},function(e,t,n){var r=n(7),o=n(5),i=o["__core-js_shared__"]||(o["__core-js_shared__"]={});(e.exports=function(e,t){return i[e]||(i[e]=void 0!==t?t:{})})("versions",[]).push({version:r.version,mode:n(31)?"pure":"global",copyright:"© 2018 Denis Pushkarev (zloirock.ru)"})},function(e,t,n){var r=n(8),o=n(5).document,i=r(o)&&r(o.createElement);e.exports=function(e){return i?o.createElement(e):{}}},function(e,t,n){var r=n(8);e.exports=function(e,t){if(!r(e))return e;var n,o;if(t&&"function"==typeof(n=e.toString)&&!r(o=n.call(e)))return o;if("function"==typeof(n=e.valueOf)&&!r(o=n.call(e)))return o;if(!t&&"function"==typeof(n=e.toString)&&!r(o=n.call(e)))return o;throw TypeError("Can't convert object to primitive value")}},function(e,t){var n=Math.ceil,r=Math.floor;e.exports=function(e){return isNaN(e=+e)?0:(e>0?r:n)(e)}},function(e,t,n){"use strict";var r=n(31),o=n(18),i=n(21),a=n(22),s=n(33),l=n(138),c=n(36),u=n(142),p=n(2)("iterator"),f=!([].keys&&"next"in[].keys()),d=function(){return this};e.exports=function(e,t,n,h,m,g,y){l(n,t,h);var v,b,w,x=function(e){if(!f&&e in _)return _[e];switch(e){case"keys":case"values":return function(){return new n(this,e)}}return function(){return new n(this,e)}},k=t+" Iterator",E="values"==m,S=!1,_=e.prototype,O=_[p]||_["@@iterator"]||m&&_[m],C=O||x(m),T=m?E?x("entries"):C:void 0,j="Array"==t&&_.entries||O;if(j&&(w=u(j.call(new e)))!==Object.prototype&&w.next&&(c(w,k,!0),r||"function"==typeof w[p]||a(w,p,d)),E&&O&&"values"!==O.name&&(S=!0,C=function(){return O.call(this)}),r&&!y||!f&&!S&&_[p]||a(_,p,C),s[t]=C,s[k]=d,m)if(v={values:E?C:x("values"),keys:g?C:x("keys"),entries:T},y)for(b in v)b in _||i(_,b,v[b]);else o(o.P+o.F*(f||S),t,v);return v}},function(e,t,n){var r=n(14),o=n(139),i=n(66),a=n(65)("IE_PROTO"),s=function(){},l=function(){var e,t=n(59)("iframe"),r=i.length;for(t.style.display="none",n(85).appendChild(t),t.src="javascript:",(e=t.contentWindow.document).open(),e.write(" ` diff --git a/pkg/routes/api/v1/link_sharing_auth.go b/pkg/routes/api/v1/link_sharing_auth.go index 2cc73629c..2dc574b6f 100644 --- a/pkg/routes/api/v1/link_sharing_auth.go +++ b/pkg/routes/api/v1/link_sharing_auth.go @@ -31,7 +31,7 @@ import ( type LinkShareToken struct { auth.Token *models.LinkSharing - ListID int64 `json:"list_id"` + ProjectID int64 `json:"project_id"` } // LinkShareAuth represents everything required to authenticate a link share @@ -42,7 +42,7 @@ type LinkShareAuth struct { // AuthenticateLinkShare gives a jwt auth token for valid share hashes // @Summary Get an auth token for a share -// @Description Get a jwt auth token for a shared list from a share hash. +// @Description Get a jwt auth token for a shared project from a share hash. // @tags sharing // @Accept json // @Produce json @@ -84,6 +84,6 @@ func AuthenticateLinkShare(c echo.Context) error { return c.JSON(http.StatusOK, LinkShareToken{ Token: auth.Token{Token: t}, LinkSharing: share, - ListID: share.ListID, + ProjectID: share.ProjectID, }) } diff --git a/pkg/routes/api/v1/list_by_namespace.go b/pkg/routes/api/v1/list_by_namespace.go index caebee692..2f6d421b9 100644 --- a/pkg/routes/api/v1/list_by_namespace.go +++ b/pkg/routes/api/v1/list_by_namespace.go @@ -29,21 +29,21 @@ import ( "github.com/labstack/echo/v4" ) -// GetListsByNamespaceID is the web handler to delete a namespace -// TODO: depricate this in favour of namespace.ReadOne() <-- should also return the lists -// @Summary Get all lists in a namespace -// @Description Returns all lists inside of a namespace. +// GetProjectsByNamespaceID is the web handler to delete a namespace +// TODO: depricate this in favour of namespace.ReadOne() <-- should also return the projects +// @Summary Get all projects in a namespace +// @Description Returns all projects inside of a namespace. // @tags namespace // @Accept json // @Produce json // @Param id path int true "Namespace ID" // @Security JWTKeyAuth -// @Success 200 {array} models.List "The lists." +// @Success 200 {array} models.Project "The projects." // @Failure 403 {object} models.Message "No access to that namespace." // @Failure 404 {object} models.Message "The namespace does not exist." // @Failure 500 {object} models.Message "Internal error" -// @Router /namespaces/{id}/lists [get] -func GetListsByNamespaceID(c echo.Context) error { +// @Router /namespaces/{id}/projects [get] +func GetProjectsByNamespaceID(c echo.Context) error { s := db.NewSession() defer s.Close() @@ -53,17 +53,17 @@ func GetListsByNamespaceID(c echo.Context) error { return handler.HandleHTTPError(err, c) } - // Get the lists + // Get the projects doer, err := user.GetCurrentUser(c) if err != nil { return handler.HandleHTTPError(err, c) } - lists, err := models.GetListsByNamespaceID(s, namespace.ID, doer) + projects, err := models.GetProjectsByNamespaceID(s, namespace.ID, doer) if err != nil { return handler.HandleHTTPError(err, c) } - return c.JSON(http.StatusOK, lists) + return c.JSON(http.StatusOK, projects) } func getNamespace(s *xorm.Session, c echo.Context) (namespace *models.Namespace, err error) { @@ -76,7 +76,7 @@ func getNamespace(s *xorm.Session, c echo.Context) (namespace *models.Namespace, } if namespaceID == -1 { - namespace = &models.SharedListsPseudoNamespace + namespace = &models.SharedProjectsPseudoNamespace return } diff --git a/pkg/routes/api/v1/user_caldav_token.go b/pkg/routes/api/v1/user_caldav_token.go index adf76a478..8010ed311 100644 --- a/pkg/routes/api/v1/user_caldav_token.go +++ b/pkg/routes/api/v1/user_caldav_token.go @@ -54,7 +54,7 @@ func GenerateCaldavToken(c echo.Context) (err error) { return c.JSON(http.StatusCreated, token) } -// GetCaldavTokens is the handler to return a list of all caldav tokens for the current user +// GetCaldavTokens is the handler to return a project of all caldav tokens for the current user // @Summary Returns the caldav tokens for the current user // @Description Return the IDs and created dates of all caldav tokens for the current user. // @tags user diff --git a/pkg/routes/api/v1/user_list.go b/pkg/routes/api/v1/user_list.go index 19f321ef0..73e2bda4e 100644 --- a/pkg/routes/api/v1/user_list.go +++ b/pkg/routes/api/v1/user_list.go @@ -29,7 +29,7 @@ import ( "github.com/labstack/echo/v4" ) -// UserList gets all information about a user +// UserProject gets all information about a user // @Summary Get users // @Description Search for a user by its username, name or full email. Name (not username) or email require that the user has enabled this in their settings. // @tags user @@ -41,13 +41,13 @@ import ( // @Failure 400 {object} web.HTTPError "Something's invalid." // @Failure 500 {object} models.Message "Internal server error." // @Router /users [get] -func UserList(c echo.Context) error { +func UserProject(c echo.Context) error { search := c.QueryParam("s") s := db.NewSession() defer s.Close() - users, err := user.ListUsers(s, search, nil) + users, err := user.ProjectUsers(s, search, nil) if err != nil { _ = s.Rollback() return handler.HandleHTTPError(err, c) @@ -66,27 +66,27 @@ func UserList(c echo.Context) error { return c.JSON(http.StatusOK, users) } -// ListUsersForList returns a list with all users who have access to a list, regardless of the method the list was shared with them. +// ProjectUsersForProject returns a project with all users who have access to a project, regardless of the method the project was shared with them. // @Summary Get users -// @Description Lists all users (without emailadresses). Also possible to search for a specific user. -// @tags list +// @Description Projects all users (without emailadresses). Also possible to search for a specific user. +// @tags project // @Accept json // @Produce json // @Param s query string false "Search for a user by its name." // @Security JWTKeyAuth -// @Param id path int true "List ID" +// @Param id path int true "Project ID" // @Success 200 {array} user.User "All (found) users." // @Failure 400 {object} web.HTTPError "Something's invalid." -// @Failure 401 {object} web.HTTPError "The user does not have the right to see the list." +// @Failure 401 {object} web.HTTPError "The user does not have the right to see the project." // @Failure 500 {object} models.Message "Internal server error." -// @Router /lists/{id}/listusers [get] -func ListUsersForList(c echo.Context) error { - listID, err := strconv.ParseInt(c.Param("list"), 10, 64) +// @Router /projects/{id}/projectusers [get] +func ProjectUsersForProject(c echo.Context) error { + projectID, err := strconv.ParseInt(c.Param("project"), 10, 64) if err != nil { return handler.HandleHTTPError(err, c) } - list := models.List{ID: listID} + project := models.Project{ID: projectID} auth, err := auth2.GetAuthFromClaims(c) if err != nil { return handler.HandleHTTPError(err, c) @@ -95,7 +95,7 @@ func ListUsersForList(c echo.Context) error { s := db.NewSession() defer s.Close() - canRead, _, err := list.CanRead(s, auth) + canRead, _, err := project.CanRead(s, auth) if err != nil { _ = s.Rollback() return handler.HandleHTTPError(err, c) @@ -105,7 +105,7 @@ func ListUsersForList(c echo.Context) error { } search := c.QueryParam("s") - users, err := models.ListUsersFromList(s, &list, search) + users, err := models.ProjectUsersFromProject(s, &project, search) if err != nil { _ = s.Rollback() return handler.HandleHTTPError(err, c) diff --git a/pkg/routes/api/v1/user_settings.go b/pkg/routes/api/v1/user_settings.go index 279ce260c..9e1053094 100644 --- a/pkg/routes/api/v1/user_settings.go +++ b/pkg/routes/api/v1/user_settings.go @@ -50,9 +50,9 @@ type UserSettings struct { OverdueTasksRemindersEnabled bool `json:"overdue_tasks_reminders_enabled"` // The time when the daily summary of overdue tasks will be sent via email. OverdueTasksRemindersTime string `json:"overdue_tasks_reminders_time" valid:"time,required"` - // If a task is created without a specified list this value should be used. Applies + // If a task is created without a specified project this value should be used. Applies // to tasks made directly in API and from clients. - DefaultListID int64 `json:"default_list_id"` + DefaultProjectID int64 `json:"default_project_id"` // The day when the week starts for this user. 0 = sunday, 1 = monday, etc. WeekStart int `json:"week_start" valid:"range(0|7)"` // The user's language @@ -193,7 +193,7 @@ func UpdateGeneralUserSettings(c echo.Context) error { user.DiscoverableByEmail = us.DiscoverableByEmail user.DiscoverableByName = us.DiscoverableByName user.OverdueTasksRemindersEnabled = us.OverdueTasksRemindersEnabled - user.DefaultListID = us.DefaultListID + user.DefaultProjectID = us.DefaultProjectID user.WeekStart = us.WeekStart user.Language = us.Language user.Timezone = us.Timezone @@ -215,7 +215,7 @@ func UpdateGeneralUserSettings(c echo.Context) error { // GetAvailableTimezones // @Summary Get all available time zones on this vikunja instance -// @Description Because available time zones depend on the system Vikunja is running on, this endpoint returns a list of all valid time zones this particular Vikunja instance can handle. The list of time zones is not sorted, you should sort it on the client. +// @Description Because available time zones depend on the system Vikunja is running on, this endpoint returns a project of all valid time zones this particular Vikunja instance can handle. The project of time zones is not sorted, you should sort it on the client. // @tags user // @Accept json // @Produce json diff --git a/pkg/routes/api/v1/user_show.go b/pkg/routes/api/v1/user_show.go index d1e6f1da7..1f9843f8d 100644 --- a/pkg/routes/api/v1/user_show.go +++ b/pkg/routes/api/v1/user_show.go @@ -71,7 +71,7 @@ func UserShow(c echo.Context) error { DiscoverableByName: u.DiscoverableByName, DiscoverableByEmail: u.DiscoverableByEmail, OverdueTasksRemindersEnabled: u.OverdueTasksRemindersEnabled, - DefaultListID: u.DefaultListID, + DefaultProjectID: u.DefaultProjectID, WeekStart: u.WeekStart, Language: u.Language, Timezone: u.Timezone, diff --git a/pkg/routes/caldav/handler.go b/pkg/routes/caldav/handler.go index a800343fc..429a33a99 100644 --- a/pkg/routes/caldav/handler.go +++ b/pkg/routes/caldav/handler.go @@ -42,9 +42,9 @@ func getBasicAuthUserFromContext(c echo.Context) (*user.User, error) { return u, nil } -// ListHandler returns all tasks from a list -func ListHandler(c echo.Context) error { - listID, err := getIntParam(c, "list") +// ProjectHandler returns all tasks from a project +func ProjectHandler(c echo.Context) error { + projectID, err := getIntParam(c, "project") if err != nil { return err } @@ -55,9 +55,9 @@ func ListHandler(c echo.Context) error { return echo.ErrInternalServerError } - storage := &VikunjaCaldavListStorage{ - list: &models.ListWithTasksAndBuckets{List: models.List{ID: listID}}, - user: u, + storage := &VikunjaCaldavProjectStorage{ + project: &models.ProjectWithTasksAndBuckets{Project: models.Project{ID: projectID}}, + user: u, } // Try to parse a task from the request payload @@ -78,7 +78,7 @@ func ListHandler(c echo.Context) error { log.Debugf("[CALDAV] Request Headers: %v\n", c.Request().Header) caldav.SetupStorage(storage) - caldav.SetupUser("dav/lists") + caldav.SetupUser("dav/projects") caldav.SetupSupportedComponents([]string{lib.VCALENDAR, lib.VTODO}) response := caldav.HandleRequest(c.Request()) response.Write(c.Response()) @@ -87,7 +87,7 @@ func ListHandler(c echo.Context) error { // TaskHandler is the handler which manages updating/deleting a single task func TaskHandler(c echo.Context) error { - listID, err := getIntParam(c, "list") + projectID, err := getIntParam(c, "project") if err != nil { return err } @@ -101,10 +101,10 @@ func TaskHandler(c echo.Context) error { // Get the task uid taskUID := strings.TrimSuffix(c.Param("task"), ".ics") - storage := &VikunjaCaldavListStorage{ - list: &models.ListWithTasksAndBuckets{List: models.List{ID: listID}}, - task: &models.Task{UID: taskUID}, - user: u, + storage := &VikunjaCaldavProjectStorage{ + project: &models.ProjectWithTasksAndBuckets{Project: models.Project{ID: projectID}}, + task: &models.Task{UID: taskUID}, + user: u, } caldav.SetupStorage(storage) @@ -121,7 +121,7 @@ func PrincipalHandler(c echo.Context) error { return echo.ErrInternalServerError } - storage := &VikunjaCaldavListStorage{ + storage := &VikunjaCaldavProjectStorage{ user: u, isPrincipal: true, } @@ -151,7 +151,7 @@ func EntryHandler(c echo.Context) error { return echo.ErrInternalServerError } - storage := &VikunjaCaldavListStorage{ + storage := &VikunjaCaldavProjectStorage{ user: u, isEntry: true, } diff --git a/pkg/routes/caldav/listStorageProvider.go b/pkg/routes/caldav/listStorageProvider.go index 079cae35d..88841670f 100644 --- a/pkg/routes/caldav/listStorageProvider.go +++ b/pkg/routes/caldav/listStorageProvider.go @@ -35,13 +35,13 @@ import ( // DavBasePath is the base url path const DavBasePath = `/dav/` -// ListBasePath is the base path for all lists resources -const ListBasePath = DavBasePath + `lists` +// ProjectBasePath is the base path for all projects resources +const ProjectBasePath = DavBasePath + `projects` -// VikunjaCaldavListStorage represents a list storage -type VikunjaCaldavListStorage struct { - // Used when handling a list - list *models.ListWithTasksAndBuckets +// VikunjaCaldavProjectStorage represents a project storage +type VikunjaCaldavProjectStorage struct { + // Used when handling a project + project *models.ProjectWithTasksAndBuckets // Used when handling a single task, like updating task *models.Task // The current user @@ -50,8 +50,8 @@ type VikunjaCaldavListStorage struct { isEntry bool // Entry level handling should only return a link to the principal url } -// GetResources returns either all lists, links to the principal, or only one list, depending on the request -func (vcls *VikunjaCaldavListStorage) GetResources(rpath string, withChildren bool) ([]data.Resource, error) { +// GetResources returns either all projects, links to the principal, or only one project, depending on the request +func (vcls *VikunjaCaldavProjectStorage) GetResources(rpath string, withChildren bool) ([]data.Resource, error) { // It looks like we need to have the same handler for returning both the calendar home set and the user principal // Since the client seems to ignore the whatever is being returned in the first request and just makes a second one @@ -61,12 +61,12 @@ func (vcls *VikunjaCaldavListStorage) GetResources(rpath string, withChildren bo // the home or principal url. Ough. // Ok, maybe the problem is more the client making a request to /dav/ and getting a response which says - // something like "hey, for /dav/lists, the calendar home is /dav/lists", but the client expects a - // response to go something like "hey, for /dav/, the calendar home is /dav/lists" since it requested /dav/ - // and not /dav/lists. I'm not sure if thats a bug in the client or in caldav-go. + // something like "hey, for /dav/projects, the calendar home is /dav/projects", but the client expects a + // response to go something like "hey, for /dav/, the calendar home is /dav/projects" since it requested /dav/ + // and not /dav/projects. I'm not sure if thats a bug in the client or in caldav-go. if vcls.isEntry { - r := data.NewResource(rpath, &VikunjaListResourceAdapter{ + r := data.NewResource(rpath, &VikunjaProjectResourceAdapter{ isPrincipal: true, isCollection: true, }) @@ -75,30 +75,30 @@ func (vcls *VikunjaCaldavListStorage) GetResources(rpath string, withChildren bo // If the request wants the principal url, we'll return that and nothing else if vcls.isPrincipal { - r := data.NewResource(DavBasePath+`/lists/`, &VikunjaListResourceAdapter{ + r := data.NewResource(DavBasePath+`/projects/`, &VikunjaProjectResourceAdapter{ isPrincipal: true, isCollection: true, }) return []data.Resource{r}, nil } - // If vcls.list.ID is != 0, this means the user is doing a PROPFIND request to /lists/:list - // Which means we need to get only one list - if vcls.list != nil && vcls.list.ID != 0 { - rr, err := vcls.getListRessource(true) + // If vcls.project.ID is != 0, this means the user is doing a PROPFIND request to /projects/:project + // Which means we need to get only one project + if vcls.project != nil && vcls.project.ID != 0 { + rr, err := vcls.getProjectRessource(true) if err != nil { return nil, err } r := data.NewResource(rpath, &rr) - r.Name = vcls.list.Title + r.Name = vcls.project.Title return []data.Resource{r}, nil } s := db.NewSession() defer s.Close() - // Otherwise get all lists - thelists, _, _, err := vcls.list.ReadAll(s, vcls.user, "", -1, 50) + // Otherwise get all projects + theprojects, _, _, err := vcls.project.ReadAll(s, vcls.user, "", -1, 50) if err != nil { _ = s.Rollback() return nil, err @@ -106,17 +106,17 @@ func (vcls *VikunjaCaldavListStorage) GetResources(rpath string, withChildren bo if err := s.Commit(); err != nil { return nil, err } - lists := thelists.([]*models.List) + projects := theprojects.([]*models.Project) var resources []data.Resource - for _, l := range lists { - rr := VikunjaListResourceAdapter{ - list: &models.ListWithTasksAndBuckets{ - List: *l, + for _, l := range projects { + rr := VikunjaProjectResourceAdapter{ + project: &models.ProjectWithTasksAndBuckets{ + Project: *l, }, isCollection: true, } - r := data.NewResource(ListBasePath+"/"+strconv.FormatInt(l.ID, 10), &rr) + r := data.NewResource(ProjectBasePath+"/"+strconv.FormatInt(l.ID, 10), &rr) r.Name = l.Title resources = append(resources, r) } @@ -124,11 +124,11 @@ func (vcls *VikunjaCaldavListStorage) GetResources(rpath string, withChildren bo return resources, nil } -// GetResourcesByList fetches a list of resources from a slice of paths -func (vcls *VikunjaCaldavListStorage) GetResourcesByList(rpaths []string) ([]data.Resource, error) { +// GetResourcesByList fetches a project of resources from a slice of paths +func (vcls *VikunjaCaldavProjectStorage) GetResourcesByList(rpaths []string) ([]data.Resource, error) { // Parse the set of resourcepaths into usable uids - // A path looks like this: /dav/lists/10/a6eb526d5748a5c499da202fe74f36ed1aea2aef.ics + // A path looks like this: /dav/projects/10/a6eb526d5748a5c499da202fe74f36ed1aea2aef.ics // So we split the url in parts, take the last one and strip the ".ics" at the end var uids []string for _, path := range rpaths { @@ -154,7 +154,7 @@ func (vcls *VikunjaCaldavListStorage) GetResourcesByList(rpaths []string) ([]dat var resources []data.Resource for _, t := range tasks { - rr := VikunjaListResourceAdapter{ + rr := VikunjaProjectResourceAdapter{ task: t, } r := data.NewResource(getTaskURL(t), &rr) @@ -165,17 +165,17 @@ func (vcls *VikunjaCaldavListStorage) GetResourcesByList(rpaths []string) ([]dat return resources, nil } -// GetResourcesByFilters fetches a list of resources with a filter -func (vcls *VikunjaCaldavListStorage) GetResourcesByFilters(rpath string, filters *data.ResourceFilter) ([]data.Resource, error) { +// GetResourcesByFilters fetches a project of resources with a filter +func (vcls *VikunjaCaldavProjectStorage) GetResourcesByFilters(rpath string, filters *data.ResourceFilter) ([]data.Resource, error) { - // If we already have a list saved, that means the user is making a REPORT request to find out if + // If we already have a project saved, that means the user is making a REPORT request to find out if // anything changed, in that case we need to return all tasks. - // That list is coming from a previous "getListRessource" in L177 - if vcls.list.Tasks != nil { + // That project is coming from a previous "getProjectRessource" in L177 + if vcls.project.Tasks != nil { var resources []data.Resource - for _, t := range vcls.list.Tasks { - rr := VikunjaListResourceAdapter{ - list: vcls.list, + for _, t := range vcls.project.Tasks { + rr := VikunjaProjectResourceAdapter{ + project: vcls.project, task: &t.Task, isCollection: false, } @@ -187,25 +187,25 @@ func (vcls *VikunjaCaldavListStorage) GetResourcesByFilters(rpath string, filter } // This is used to get all - rr, err := vcls.getListRessource(false) + rr, err := vcls.getProjectRessource(false) if err != nil { return nil, err } r := data.NewResource(rpath, &rr) - r.Name = vcls.list.Title + r.Name = vcls.project.Title return []data.Resource{r}, nil // For now, filtering is disabled. // return vcls.GetResources(rpath, false) } func getTaskURL(task *models.Task) string { - return ListBasePath + "/" + strconv.FormatInt(task.ListID, 10) + `/` + task.UID + `.ics` + return ProjectBasePath + "/" + strconv.FormatInt(task.ProjectID, 10) + `/` + task.UID + `.ics` } // GetResource fetches a single resource -func (vcls *VikunjaCaldavListStorage) GetResource(rpath string) (*data.Resource, bool, error) { +func (vcls *VikunjaCaldavProjectStorage) GetResource(rpath string) (*data.Resource, bool, error) { - // If the task is not nil, we need to get the task and not the list + // If the task is not nil, we need to get the task and not the project if vcls.task != nil { s := db.NewSession() defer s.Close() @@ -233,16 +233,16 @@ func (vcls *VikunjaCaldavListStorage) GetResource(rpath string) (*data.Resource, vcls.task.Updated = updated } - rr := VikunjaListResourceAdapter{ - list: vcls.list, - task: vcls.task, + rr := VikunjaProjectResourceAdapter{ + project: vcls.project, + task: vcls.task, } r := data.NewResource(rpath, &rr) return &r, true, nil } - // Otherwise get the list with all tasks - rr, err := vcls.getListRessource(true) + // Otherwise get the project with all tasks + rr, err := vcls.getProjectRessource(true) if err != nil { return nil, false, err } @@ -252,14 +252,14 @@ func (vcls *VikunjaCaldavListStorage) GetResource(rpath string) (*data.Resource, // GetShallowResource gets a ressource without childs // Since Vikunja has no children, this is the same as GetResource -func (vcls *VikunjaCaldavListStorage) GetShallowResource(rpath string) (*data.Resource, bool, error) { +func (vcls *VikunjaCaldavProjectStorage) GetShallowResource(rpath string) (*data.Resource, bool, error) { // Since Vikunja has no childs, this just returns the same as GetResource() - // FIXME: This should just get the list with no tasks whatsoever, nothing else + // FIXME: This should just get the project with no tasks whatsoever, nothing else return vcls.GetResource(rpath) } // CreateResource creates a new resource -func (vcls *VikunjaCaldavListStorage) CreateResource(rpath, content string) (*data.Resource, error) { +func (vcls *VikunjaCaldavProjectStorage) CreateResource(rpath, content string) (*data.Resource, error) { s := db.NewSession() defer s.Close() @@ -269,7 +269,7 @@ func (vcls *VikunjaCaldavListStorage) CreateResource(rpath, content string) (*da return nil, err } - vTask.ListID = vcls.list.ID + vTask.ProjectID = vcls.project.ID // Check the rights canCreate, err := vTask.CanCreate(s, vcls.user) @@ -299,16 +299,16 @@ func (vcls *VikunjaCaldavListStorage) CreateResource(rpath, content string) (*da } // Build up the proper response - rr := VikunjaListResourceAdapter{ - list: vcls.list, - task: vTask, + rr := VikunjaProjectResourceAdapter{ + project: vcls.project, + task: vTask, } r := data.NewResource(rpath, &rr) return &r, nil } // UpdateResource updates a resource -func (vcls *VikunjaCaldavListStorage) UpdateResource(rpath, content string) (*data.Resource, error) { +func (vcls *VikunjaCaldavProjectStorage) UpdateResource(rpath, content string) (*data.Resource, error) { vTask, err := caldav.ParseTaskFromVTODO(content) if err != nil { @@ -350,16 +350,16 @@ func (vcls *VikunjaCaldavListStorage) UpdateResource(rpath, content string) (*da } // Build up the proper response - rr := VikunjaListResourceAdapter{ - list: vcls.list, - task: vTask, + rr := VikunjaProjectResourceAdapter{ + project: vcls.project, + task: vTask, } r := data.NewResource(rpath, &rr) return &r, nil } // DeleteResource deletes a resource -func (vcls *VikunjaCaldavListStorage) DeleteResource(rpath string) error { +func (vcls *VikunjaCaldavProjectStorage) DeleteResource(rpath string) error { if vcls.task != nil { s := db.NewSession() defer s.Close() @@ -432,31 +432,31 @@ func persistLabels(s *xorm.Session, a web.Auth, task *models.Task, labels []*mod return task.UpdateTaskLabels(s, a, labels) } -// VikunjaListResourceAdapter holds the actual resource -type VikunjaListResourceAdapter struct { - list *models.ListWithTasksAndBuckets - listTasks []*models.TaskWithComments - task *models.Task +// VikunjaProjectResourceAdapter holds the actual resource +type VikunjaProjectResourceAdapter struct { + project *models.ProjectWithTasksAndBuckets + projectTasks []*models.TaskWithComments + task *models.Task isPrincipal bool isCollection bool } // IsCollection checks if the resoure in the adapter is a collection -func (vlra *VikunjaListResourceAdapter) IsCollection() bool { +func (vlra *VikunjaProjectResourceAdapter) IsCollection() bool { // If the discovery does not work, setting this to true makes it work again. return vlra.isCollection } // CalculateEtag returns the etag of a resource -func (vlra *VikunjaListResourceAdapter) CalculateEtag() string { +func (vlra *VikunjaProjectResourceAdapter) CalculateEtag() string { - // If we're updating a task, the client sends the etag of the list instead of the one from the task. + // If we're updating a task, the client sends the etag of the project instead of the one from the task. // And therefore, updating the task fails since these etags don't match. // To fix that, we use this extra field to determine if we're currently updating a task and return the - // etag of the list instead. - // if vlra.list != nil { - // return `"` + strconv.FormatInt(vlra.list.ID, 10) + `-` + strconv.FormatInt(vlra.list.Updated, 10) + `"` + // etag of the project instead. + // if vlra.project != nil { + // return `"` + strconv.FormatInt(vlra.project.ID, 10) + `-` + strconv.FormatInt(vlra.project.Updated, 10) + `"` // } // Return the etag of a task if we have one @@ -464,76 +464,76 @@ func (vlra *VikunjaListResourceAdapter) CalculateEtag() string { return `"` + strconv.FormatInt(vlra.task.ID, 10) + `-` + strconv.FormatInt(vlra.task.Updated.Unix(), 10) + `"` } - if vlra.list == nil { + if vlra.project == nil { return "" } - // This also returns the etag of the list, and not of the task, - // which becomes problematic because the client uses this etag (= the one from the list) to make + // This also returns the etag of the project, and not of the task, + // which becomes problematic because the client uses this etag (= the one from the project) to make // Requests to update a task. These do not match and thus updating a task fails. - return `"` + strconv.FormatInt(vlra.list.ID, 10) + `-` + strconv.FormatInt(vlra.list.Updated.Unix(), 10) + `"` + return `"` + strconv.FormatInt(vlra.project.ID, 10) + `-` + strconv.FormatInt(vlra.project.Updated.Unix(), 10) + `"` } // GetContent returns the content string of a resource (a task in our case) -func (vlra *VikunjaListResourceAdapter) GetContent() string { - if vlra.list != nil && vlra.list.Tasks != nil { - return caldav.GetCaldavTodosForTasks(vlra.list, vlra.listTasks) +func (vlra *VikunjaProjectResourceAdapter) GetContent() string { + if vlra.project != nil && vlra.project.Tasks != nil { + return caldav.GetCaldavTodosForTasks(vlra.project, vlra.projectTasks) } if vlra.task != nil { - list := models.ListWithTasksAndBuckets{Tasks: []*models.TaskWithComments{{Task: *vlra.task}}} - return caldav.GetCaldavTodosForTasks(&list, list.Tasks) + project := models.ProjectWithTasksAndBuckets{Tasks: []*models.TaskWithComments{{Task: *vlra.task}}} + return caldav.GetCaldavTodosForTasks(&project, project.Tasks) } return "" } // GetContentSize is the size of a caldav content -func (vlra *VikunjaListResourceAdapter) GetContentSize() int64 { +func (vlra *VikunjaProjectResourceAdapter) GetContentSize() int64 { return int64(len(vlra.GetContent())) } // GetModTime returns when the resource was last modified -func (vlra *VikunjaListResourceAdapter) GetModTime() time.Time { +func (vlra *VikunjaProjectResourceAdapter) GetModTime() time.Time { if vlra.task != nil { return vlra.task.Updated } - if vlra.list != nil { - return vlra.list.Updated + if vlra.project != nil { + return vlra.project.Updated } return time.Time{} } -func (vcls *VikunjaCaldavListStorage) getListRessource(isCollection bool) (rr VikunjaListResourceAdapter, err error) { +func (vcls *VikunjaCaldavProjectStorage) getProjectRessource(isCollection bool) (rr VikunjaProjectResourceAdapter, err error) { s := db.NewSession() defer s.Close() - if vcls.list == nil { + if vcls.project == nil { return } - can, _, err := vcls.list.CanRead(s, vcls.user) + can, _, err := vcls.project.CanRead(s, vcls.user) if err != nil { _ = s.Rollback() return } if !can { _ = s.Rollback() - log.Errorf("User %v tried to access a caldav resource (List %v) which they are not allowed to access", vcls.user.Username, vcls.list.ID) - return rr, models.ErrUserDoesNotHaveAccessToList{ListID: vcls.list.ID} + log.Errorf("User %v tried to access a caldav resource (Project %v) which they are not allowed to access", vcls.user.Username, vcls.project.ID) + return rr, models.ErrUserDoesNotHaveAccessToProject{ProjectID: vcls.project.ID} } - err = vcls.list.ReadOne(s, vcls.user) + err = vcls.project.ReadOne(s, vcls.user) if err != nil { _ = s.Rollback() return } - listTasks := vcls.list.Tasks - if listTasks == nil { + projectTasks := vcls.project.Tasks + if projectTasks == nil { tk := models.TaskCollection{ - ListID: vcls.list.ID, + ProjectID: vcls.project.ID, } iface, _, _, err := tk.ReadAll(s, vcls.user, "", 1, 1000) if err != nil { @@ -546,18 +546,18 @@ func (vcls *VikunjaCaldavListStorage) getListRessource(isCollection bool) (rr Vi } for _, t := range tasks { - listTasks = append(listTasks, &models.TaskWithComments{Task: *t}) + projectTasks = append(projectTasks, &models.TaskWithComments{Task: *t}) } - vcls.list.Tasks = listTasks + vcls.project.Tasks = projectTasks } if err := s.Commit(); err != nil { return rr, err } - rr = VikunjaListResourceAdapter{ - list: vcls.list, - listTasks: listTasks, + rr = VikunjaProjectResourceAdapter{ + project: vcls.project, + projectTasks: projectTasks, isCollection: isCollection, } diff --git a/pkg/routes/metrics.go b/pkg/routes/metrics.go index b9995bbee..ebe279436 100644 --- a/pkg/routes/metrics.go +++ b/pkg/routes/metrics.go @@ -44,8 +44,8 @@ func setupMetrics(a *echo.Group) { for _, c := range []countable{ { - metrics.ListCountKey, - models.List{}, + metrics.ProjectCountKey, + models.Project{}, }, { metrics.UserCountKey, diff --git a/pkg/routes/routes.go b/pkg/routes/routes.go index d2948e743..6f27c1802 100644 --- a/pkg/routes/routes.go +++ b/pkg/routes/routes.go @@ -15,14 +15,14 @@ // along with this program. If not, see . // @title Vikunja API -// @description This is the documentation for the [Vikunja](http://vikunja.io) API. Vikunja is a cross-plattform To-do-application with a lot of features, such as sharing lists with users or teams. +// @description This is the documentation for the [Vikunja](http://vikunja.io) API. Vikunja is a cross-plattform To-do-application with a lot of features, such as sharing projects with users or teams. // @description # Pagination // @description Every endpoint capable of pagination will return two headers: // @description * `x-pagination-total-pages`: The total number of available pages for this request // @description * `x-pagination-result-count`: The number of items returned for this request. // @description # Rights -// @description All endpoints which return a single item (list, task, namespace, etc.) - no array - will also return a `x-max-right` header with the max right the user has on this item as an int where `0` is `Read Only`, `1` is `Read & Write` and `2` is `Admin`. +// @description All endpoints which return a single item (project, task, namespace, etc.) - no array - will also return a `x-max-right` header with the max right the user has on this item as an int where `0` is `Read Only`, `1` is `Read & Write` and `2` is `Admin`. // @description This can be used to show or hide ui elements based on the rights the user has. // @description # Authorization // @description **JWT-Auth:** Main authorization method, used for most of the requests. Needs `Authorization: Bearer `-header to authenticate successfully. @@ -47,6 +47,7 @@ package routes import ( + "code.vikunja.io/api/pkg/modules/migration/wunderlist" "errors" "net/url" "strings" @@ -287,7 +288,7 @@ func registerAPIRoutes(a *echo.Group) { u.GET("", apiv1.UserShow) u.POST("/password", apiv1.UserChangePassword) - u.GET("s", apiv1.UserList) + u.GET("s", apiv1.UserProject) u.POST("/token", apiv1.RenewToken) u.POST("/settings/email", apiv1.UpdateUserEmail) u.GET("/settings/avatar", apiv1.GetUserAvatarProvider) @@ -316,28 +317,28 @@ func registerAPIRoutes(a *echo.Group) { u.POST("/deletion/cancel", apiv1.UserCancelDeletion) } - listHandler := &handler.WebHandler{ + projectHandler := &handler.WebHandler{ EmptyStruct: func() handler.CObject { - return &models.List{} + return &models.Project{} }, } - a.GET("/lists", listHandler.ReadAllWeb) - a.GET("/lists/:list", listHandler.ReadOneWeb) - a.POST("/lists/:list", listHandler.UpdateWeb) - a.DELETE("/lists/:list", listHandler.DeleteWeb) - a.PUT("/namespaces/:namespace/lists", listHandler.CreateWeb) - a.GET("/lists/:list/listusers", apiv1.ListUsersForList) + a.GET("/projects", projectHandler.ReadAllWeb) + a.GET("/projects/:project", projectHandler.ReadOneWeb) + a.POST("/projects/:project", projectHandler.UpdateWeb) + a.DELETE("/projects/:project", projectHandler.DeleteWeb) + a.PUT("/namespaces/:namespace/projects", projectHandler.CreateWeb) + a.GET("/projects/:project/projectusers", apiv1.ProjectUsersForProject) if config.ServiceEnableLinkSharing.GetBool() { - listSharingHandler := &handler.WebHandler{ + projectSharingHandler := &handler.WebHandler{ EmptyStruct: func() handler.CObject { return &models.LinkSharing{} }, } - a.PUT("/lists/:list/shares", listSharingHandler.CreateWeb) - a.GET("/lists/:list/shares", listSharingHandler.ReadAllWeb) - a.GET("/lists/:list/shares/:share", listSharingHandler.ReadOneWeb) - a.DELETE("/lists/:list/shares/:share", listSharingHandler.DeleteWeb) + a.PUT("/projects/:project/shares", projectSharingHandler.CreateWeb) + a.GET("/projects/:project/shares", projectSharingHandler.ReadAllWeb) + a.GET("/projects/:project/shares/:share", projectSharingHandler.ReadOneWeb) + a.DELETE("/projects/:project/shares/:share", projectSharingHandler.DeleteWeb) } taskCollectionHandler := &handler.WebHandler{ @@ -345,35 +346,35 @@ func registerAPIRoutes(a *echo.Group) { return &models.TaskCollection{} }, } - a.GET("/lists/:list/tasks", taskCollectionHandler.ReadAllWeb) + a.GET("/projects/:project/tasks", taskCollectionHandler.ReadAllWeb) kanbanBucketHandler := &handler.WebHandler{ EmptyStruct: func() handler.CObject { return &models.Bucket{} }, } - a.GET("/lists/:list/buckets", kanbanBucketHandler.ReadAllWeb) - a.PUT("/lists/:list/buckets", kanbanBucketHandler.CreateWeb) - a.POST("/lists/:list/buckets/:bucket", kanbanBucketHandler.UpdateWeb) - a.DELETE("/lists/:list/buckets/:bucket", kanbanBucketHandler.DeleteWeb) + a.GET("/projects/:project/buckets", kanbanBucketHandler.ReadAllWeb) + a.PUT("/projects/:project/buckets", kanbanBucketHandler.CreateWeb) + a.POST("/projects/:project/buckets/:bucket", kanbanBucketHandler.UpdateWeb) + a.DELETE("/projects/:project/buckets/:bucket", kanbanBucketHandler.DeleteWeb) - listDuplicateHandler := &handler.WebHandler{ + projectDuplicateHandler := &handler.WebHandler{ EmptyStruct: func() handler.CObject { - return &models.ListDuplicate{} + return &models.ProjectDuplicate{} }, } - a.PUT("/lists/:listid/duplicate", listDuplicateHandler.CreateWeb) + a.PUT("/projects/:projectid/duplicate", projectDuplicateHandler.CreateWeb) taskHandler := &handler.WebHandler{ EmptyStruct: func() handler.CObject { return &models.Task{} }, } - a.PUT("/lists/:list", taskHandler.CreateWeb) - a.GET("/tasks/:listtask", taskHandler.ReadOneWeb) + a.PUT("/projects/:project", taskHandler.CreateWeb) + a.GET("/tasks/:projecttask", taskHandler.ReadOneWeb) a.GET("/tasks/all", taskCollectionHandler.ReadAllWeb) - a.DELETE("/tasks/:listtask", taskHandler.DeleteWeb) - a.POST("/tasks/:listtask", taskHandler.UpdateWeb) + a.DELETE("/tasks/:projecttask", taskHandler.DeleteWeb) + a.POST("/tasks/:projecttask", taskHandler.UpdateWeb) bulkTaskHandler := &handler.WebHandler{ EmptyStruct: func() handler.CObject { @@ -387,32 +388,32 @@ func registerAPIRoutes(a *echo.Group) { return &models.TaskAssginee{} }, } - a.PUT("/tasks/:listtask/assignees", assigneeTaskHandler.CreateWeb) - a.DELETE("/tasks/:listtask/assignees/:user", assigneeTaskHandler.DeleteWeb) - a.GET("/tasks/:listtask/assignees", assigneeTaskHandler.ReadAllWeb) + a.PUT("/tasks/:projecttask/assignees", assigneeTaskHandler.CreateWeb) + a.DELETE("/tasks/:projecttask/assignees/:user", assigneeTaskHandler.DeleteWeb) + a.GET("/tasks/:projecttask/assignees", assigneeTaskHandler.ReadAllWeb) bulkAssigneeHandler := &handler.WebHandler{ EmptyStruct: func() handler.CObject { return &models.BulkAssignees{} }, } - a.POST("/tasks/:listtask/assignees/bulk", bulkAssigneeHandler.CreateWeb) + a.POST("/tasks/:projecttask/assignees/bulk", bulkAssigneeHandler.CreateWeb) labelTaskHandler := &handler.WebHandler{ EmptyStruct: func() handler.CObject { return &models.LabelTask{} }, } - a.PUT("/tasks/:listtask/labels", labelTaskHandler.CreateWeb) - a.DELETE("/tasks/:listtask/labels/:label", labelTaskHandler.DeleteWeb) - a.GET("/tasks/:listtask/labels", labelTaskHandler.ReadAllWeb) + a.PUT("/tasks/:projecttask/labels", labelTaskHandler.CreateWeb) + a.DELETE("/tasks/:projecttask/labels/:label", labelTaskHandler.DeleteWeb) + a.GET("/tasks/:projecttask/labels", labelTaskHandler.ReadAllWeb) bulkLabelTaskHandler := &handler.WebHandler{ EmptyStruct: func() handler.CObject { return &models.LabelTaskBulk{} }, } - a.POST("/tasks/:listtask/labels/bulk", bulkLabelTaskHandler.CreateWeb) + a.POST("/tasks/:projecttask/labels/bulk", bulkLabelTaskHandler.CreateWeb) taskRelationHandler := &handler.WebHandler{ EmptyStruct: func() handler.CObject { @@ -458,25 +459,25 @@ func registerAPIRoutes(a *echo.Group) { a.DELETE("/labels/:label", labelHandler.DeleteWeb) a.POST("/labels/:label", labelHandler.UpdateWeb) - listTeamHandler := &handler.WebHandler{ + projectTeamHandler := &handler.WebHandler{ EmptyStruct: func() handler.CObject { - return &models.TeamList{} + return &models.TeamProject{} }, } - a.GET("/lists/:list/teams", listTeamHandler.ReadAllWeb) - a.PUT("/lists/:list/teams", listTeamHandler.CreateWeb) - a.DELETE("/lists/:list/teams/:team", listTeamHandler.DeleteWeb) - a.POST("/lists/:list/teams/:team", listTeamHandler.UpdateWeb) + a.GET("/projects/:project/teams", projectTeamHandler.ReadAllWeb) + a.PUT("/projects/:project/teams", projectTeamHandler.CreateWeb) + a.DELETE("/projects/:project/teams/:team", projectTeamHandler.DeleteWeb) + a.POST("/projects/:project/teams/:team", projectTeamHandler.UpdateWeb) - listUserHandler := &handler.WebHandler{ + projectUserHandler := &handler.WebHandler{ EmptyStruct: func() handler.CObject { - return &models.ListUser{} + return &models.ProjectUser{} }, } - a.GET("/lists/:list/users", listUserHandler.ReadAllWeb) - a.PUT("/lists/:list/users", listUserHandler.CreateWeb) - a.DELETE("/lists/:list/users/:user", listUserHandler.DeleteWeb) - a.POST("/lists/:list/users/:user", listUserHandler.UpdateWeb) + a.GET("/projects/:project/users", projectUserHandler.ReadAllWeb) + a.PUT("/projects/:project/users", projectUserHandler.CreateWeb) + a.DELETE("/projects/:project/users/:user", projectUserHandler.DeleteWeb) + a.POST("/projects/:project/users/:user", projectUserHandler.UpdateWeb) savedFiltersHandler := &handler.WebHandler{ EmptyStruct: func() handler.CObject { @@ -498,7 +499,7 @@ func registerAPIRoutes(a *echo.Group) { a.GET("/namespaces/:namespace", namespaceHandler.ReadOneWeb) a.POST("/namespaces/:namespace", namespaceHandler.UpdateWeb) a.DELETE("/namespaces/:namespace", namespaceHandler.DeleteWeb) - a.GET("/namespaces/:namespace/lists", apiv1.GetListsByNamespaceID) + a.GET("/namespaces/:namespace/projects", apiv1.GetProjectsByNamespaceID) namespaceTeamHandler := &handler.WebHandler{ EmptyStruct: func() handler.CObject { @@ -562,17 +563,17 @@ func registerAPIRoutes(a *echo.Group) { m := a.Group("/migration") registerMigrations(m) - // List Backgrounds + // Project Backgrounds if config.BackgroundsEnabled.GetBool() { - a.GET("/lists/:list/background", backgroundHandler.GetListBackground) - a.DELETE("/lists/:list/background", backgroundHandler.RemoveListBackground) + a.GET("/projects/:project/background", backgroundHandler.GetProjectBackground) + a.DELETE("/projects/:project/background", backgroundHandler.RemoveProjectBackground) if config.BackgroundsUploadEnabled.GetBool() { uploadBackgroundProvider := &backgroundHandler.BackgroundProvider{ Provider: func() background.Provider { return &upload.Provider{} }, } - a.PUT("/lists/:list/backgrounds/upload", uploadBackgroundProvider.UploadBackground) + a.PUT("/projects/:project/backgrounds/upload", uploadBackgroundProvider.UploadBackground) } if config.BackgroundsUnsplashEnabled.GetBool() { unsplashBackgroundProvider := &backgroundHandler.BackgroundProvider{ @@ -581,7 +582,7 @@ func registerAPIRoutes(a *echo.Group) { }, } a.GET("/backgrounds/unsplash/search", unsplashBackgroundProvider.SearchBackgrounds) - a.POST("/lists/:list/backgrounds/unsplash", unsplashBackgroundProvider.SetBackground) + a.POST("/projects/:project/backgrounds/unsplash", unsplashBackgroundProvider.SetBackground) a.GET("/backgrounds/unsplash/images/:image/thumb", unsplash.ProxyUnsplashThumb) a.GET("/backgrounds/unsplash/images/:image", unsplash.ProxyUnsplashImage) } @@ -641,13 +642,13 @@ func registerCalDavRoutes(c *echo.Group) { // Basic auth middleware c.Use(middleware.BasicAuth(caldav.BasicAuth)) - // THIS is the entry point for caldav clients, otherwise lists will show up double + // THIS is the entry point for caldav clients, otherwise projects will show up double c.Any("", caldav.EntryHandler) c.Any("/", caldav.EntryHandler) c.Any("/principals/*/", caldav.PrincipalHandler) - c.Any("/lists", caldav.ListHandler) - c.Any("/lists/", caldav.ListHandler) - c.Any("/lists/:list", caldav.ListHandler) - c.Any("/lists/:list/", caldav.ListHandler) - c.Any("/lists/:list/:task", caldav.TaskHandler) // Mostly used for editing + c.Any("/projects", caldav.ProjectHandler) + c.Any("/projects/", caldav.ProjectHandler) + c.Any("/projects/:project", caldav.ProjectHandler) + c.Any("/projects/:project/", caldav.ProjectHandler) + c.Any("/projects/:project/:task", caldav.TaskHandler) // Mostly used for editing } diff --git a/pkg/user/notifications.go b/pkg/user/notifications.go index e008ad2e6..768ac9e24 100644 --- a/pkg/user/notifications.go +++ b/pkg/user/notifications.go @@ -204,7 +204,7 @@ func (n *AccountDeletionConfirmNotification) ToMail() *notifications.Mail { Action("Confirm the deletion of my account", config.ServiceFrontendurl.GetString()+"?accountDeletionConfirm="+n.ConfirmToken). Line("This link will be valid for 24 hours."). Line("Once you confirm the deletion we will schedule the deletion of your account in three days and send you another email until then."). - Line("If you proceed with the deletion of your account, we will remove all of your namespaces, lists and tasks you created. Everything you shared with another user or team will transfer ownership to them."). + Line("If you proceed with the deletion of your account, we will remove all of your namespaces, projects and tasks you created. Everything you shared with another user or team will transfer ownership to them."). Line("If you did not requested the deletion or changed your mind, you can simply ignore this email."). Line("Have a nice day!") } diff --git a/pkg/user/user.go b/pkg/user/user.go index 9bad49113..667fb2173 100644 --- a/pkg/user/user.go +++ b/pkg/user/user.go @@ -95,7 +95,7 @@ type User struct { DiscoverableByEmail bool `xorm:"bool default false index" json:"-"` OverdueTasksRemindersEnabled bool `xorm:"bool default true index" json:"-"` OverdueTasksRemindersTime string `xorm:"varchar(5) not null default '09:00'" json:"-"` - DefaultListID int64 `xorm:"bigint null index" json:"-"` + DefaultProjectID int64 `xorm:"bigint null index" json:"-"` WeekStart int `xorm:"null" json:"-"` Language string `xorm:"varchar(50) null" json:"-"` Timezone string `xorm:"varchar(255) null" json:"-"` @@ -498,7 +498,7 @@ func UpdateUser(s *xorm.Session, user *User, forceOverride bool) (updatedUser *U "discoverable_by_name", "discoverable_by_email", "overdue_tasks_reminders_enabled", - "default_list_id", + "default_project_id", "week_start", "language", "timezone", diff --git a/pkg/user/user_create.go b/pkg/user/user_create.go index cb01fc048..b51e94bb3 100644 --- a/pkg/user/user_create.go +++ b/pkg/user/user_create.go @@ -63,7 +63,7 @@ func CreateUser(s *xorm.Session, user *User) (newUser *User, err error) { user.DiscoverableByEmail = config.DefaultSettingsDiscoverableByEmail.GetBool() user.OverdueTasksRemindersEnabled = config.DefaultSettingsOverdueTaskRemindersEnabled.GetBool() user.OverdueTasksRemindersTime = config.DefaultSettingsOverdueTaskRemindersTime.GetString() - user.DefaultListID = config.DefaultSettingsDefaultListID.GetInt64() + user.DefaultProjectID = config.DefaultSettingsDefaultProjectID.GetInt64() user.WeekStart = config.DefaultSettingsWeekStart.GetInt() user.Language = config.DefaultSettingsLanguage.GetString() user.Timezone = config.DefaultSettingsTimezone.GetString() diff --git a/pkg/user/user_test.go b/pkg/user/user_test.go index b339f2101..244ed467d 100644 --- a/pkg/user/user_test.go +++ b/pkg/user/user_test.go @@ -371,13 +371,13 @@ func TestUpdateUserPassword(t *testing.T) { }) } -func TestListUsers(t *testing.T) { +func TestProjectUsers(t *testing.T) { t.Run("normal", func(t *testing.T) { db.LoadAndAssertFixtures(t) s := db.NewSession() defer s.Close() - all, err := ListUsers(s, "user1", nil) + all, err := ProjectUsers(s, "user1", nil) assert.NoError(t, err) assert.True(t, len(all) > 0) assert.Equal(t, all[0].Username, "user1") @@ -387,7 +387,7 @@ func TestListUsers(t *testing.T) { s := db.NewSession() defer s.Close() - all, err := ListUsers(s, "uSEr1", nil) + all, err := ProjectUsers(s, "uSEr1", nil) assert.NoError(t, err) assert.True(t, len(all) > 0) assert.Equal(t, all[0].Username, "user1") @@ -397,7 +397,7 @@ func TestListUsers(t *testing.T) { s := db.NewSession() defer s.Close() - all, err := ListAllUsers(s) + all, err := ProjectAllUsers(s) assert.NoError(t, err) assert.Len(t, all, 15) }) @@ -406,7 +406,7 @@ func TestListUsers(t *testing.T) { s := db.NewSession() defer s.Close() - all, err := ListUsers(s, "", nil) + all, err := ProjectUsers(s, "", nil) assert.NoError(t, err) assert.Len(t, all, 0) }) @@ -415,7 +415,7 @@ func TestListUsers(t *testing.T) { s := db.NewSession() defer s.Close() - all, err := ListUsers(s, "user1@example.com", nil) + all, err := ProjectUsers(s, "user1@example.com", nil) assert.NoError(t, err) assert.Len(t, all, 0) db.AssertExists(t, "users", map[string]interface{}{ @@ -428,7 +428,7 @@ func TestListUsers(t *testing.T) { s := db.NewSession() defer s.Close() - all, err := ListUsers(s, "one else", nil) + all, err := ProjectUsers(s, "one else", nil) assert.NoError(t, err) assert.Len(t, all, 0) db.AssertExists(t, "users", map[string]interface{}{ @@ -441,7 +441,7 @@ func TestListUsers(t *testing.T) { s := db.NewSession() defer s.Close() - all, err := ListUsers(s, "user7@example.com", nil) + all, err := ProjectUsers(s, "user7@example.com", nil) assert.NoError(t, err) assert.Len(t, all, 1) assert.Equal(t, int64(7), all[0].ID) @@ -455,7 +455,7 @@ func TestListUsers(t *testing.T) { s := db.NewSession() defer s.Close() - all, err := ListUsers(s, "with space", nil) + all, err := ProjectUsers(s, "with space", nil) assert.NoError(t, err) assert.Len(t, all, 1) assert.Equal(t, int64(12), all[0].ID) @@ -469,7 +469,7 @@ func TestListUsers(t *testing.T) { s := db.NewSession() defer s.Close() - all, err := ListUsers(s, "user7@example.com", &ListUserOpts{AdditionalCond: builder.In("id", 7)}) + all, err := ProjectUsers(s, "user7@example.com", &ProjectUserOpts{AdditionalCond: builder.In("id", 7)}) assert.NoError(t, err) assert.Len(t, all, 1) assert.Equal(t, int64(7), all[0].ID) @@ -483,7 +483,7 @@ func TestListUsers(t *testing.T) { s := db.NewSession() defer s.Close() - all, err := ListUsers(s, "user7", nil) + all, err := ProjectUsers(s, "user7", nil) assert.NoError(t, err) assert.Len(t, all, 1) assert.Equal(t, int64(7), all[0].ID) @@ -496,7 +496,7 @@ func TestListUsers(t *testing.T) { s := db.NewSession() defer s.Close() - all, err := ListUsers(s, "user", nil) + all, err := ProjectUsers(s, "user", nil) assert.NoError(t, err) assert.Len(t, all, 0) db.AssertExists(t, "users", map[string]interface{}{ diff --git a/pkg/user/users_list.go b/pkg/user/users_list.go index 296e49024..9a60b54de 100644 --- a/pkg/user/users_list.go +++ b/pkg/user/users_list.go @@ -26,15 +26,15 @@ import ( "xorm.io/xorm/schemas" ) -type ListUserOpts struct { +type ProjectUserOpts struct { AdditionalCond builder.Cond ReturnAllIfNoSearchProvided bool } -// ListUsers returns a list with all users, filtered by an optional search string -func ListUsers(s *xorm.Session, search string, opts *ListUserOpts) (users []*User, err error) { +// ProjectUsers returns a project with all users, filtered by an optional search string +func ProjectUsers(s *xorm.Session, search string, opts *ProjectUserOpts) (users []*User, err error) { if opts == nil { - opts = &ListUserOpts{} + opts = &ProjectUserOpts{} } // Prevent searching for placeholders @@ -89,8 +89,8 @@ func ListUsers(s *xorm.Session, search string, opts *ListUserOpts) (users []*Use return } -// ListAllUsers returns all users -func ListAllUsers(s *xorm.Session) (users []*User, err error) { +// ProjectAllUsers returns all users +func ProjectAllUsers(s *xorm.Session) (users []*User, err error) { err = s.Find(&users) return } diff --git a/pkg/utils/umask_windows.go b/pkg/utils/umask_windows.go index a2689a0e3..a5f04998f 100644 --- a/pkg/utils/umask_windows.go +++ b/pkg/utils/umask_windows.go @@ -14,6 +14,7 @@ // You should have received a copy of the GNU Affero General Public Licensee // along with this program. If not, see . +//go:build windows // +build windows package utils diff --git a/tools.go b/tools.go index 77775b149..a7086dd8e 100644 --- a/tools.go +++ b/tools.go @@ -14,6 +14,7 @@ // You should have received a copy of the GNU Affero General Public Licensee // along with this program. If not, see . +//go:build tools // +build tools package tools