entities.rb 39.9 KB
Newer Older
1
module API
Nihad Abbasov's avatar
Nihad Abbasov committed
2
  module Entities
3 4 5 6 7 8 9 10 11 12
    class WikiPageBasic < Grape::Entity
      expose :format
      expose :slug
      expose :title
    end

    class WikiPage < WikiPageBasic
      expose :content
    end

13
    class UserSafe < Grape::Entity
14
      expose :id, :name, :username
15
    end
16

17
    class UserBasic < UserSafe
18
      expose :state
19

20 21 22
      expose :avatar_url do |user, options|
        user.avatar_url(only_path: false)
      end
Douwe Maan's avatar
Douwe Maan committed
23

24
      expose :avatar_path, if: ->(user, options) { options.fetch(:only_path, false) && user.avatar_path }
25
      expose :custom_attributes, using: 'API::Entities::CustomAttribute', if: :with_custom_attributes
26

Douwe Maan's avatar
Douwe Maan committed
27
      expose :web_url do |user, options|
28
        Gitlab::Routing.url_helpers.user_url(user)
Douwe Maan's avatar
Douwe Maan committed
29
      end
Nihad Abbasov's avatar
Nihad Abbasov committed
30
    end
Nihad Abbasov's avatar
Nihad Abbasov committed
31

32 33
    class User < UserBasic
      expose :created_at
34
      expose :bio, :location, :skype, :linkedin, :twitter, :website_url, :organization
35 36
    end

37 38
    class UserActivity < Grape::Entity
      expose :username
39 40
      expose :last_activity_on
      expose :last_activity_on, as: :last_activity_at # Back-compat
41 42
    end

43 44 45 46
    class Identity < Grape::Entity
      expose :provider, :extern_uid
    end

47
    class UserPublic < User
48 49
      expose :last_sign_in_at
      expose :confirmed_at
50
      expose :last_activity_on
51
      expose :email
52
      expose :theme_id, :color_scheme_id, :projects_limit, :current_sign_in_at
53
      expose :identities, using: Entities::Identity
54 55
      expose :can_create_group?, as: :can_create_group
      expose :can_create_project?, as: :can_create_project
56
      expose :two_factor_enabled?, as: :two_factor_enabled
57
      expose :external
58 59
    end

60
    class UserWithAdmin < UserPublic
61
      expose :admin?, as: :is_admin
62 63
    end

64 65 66 67
    class Email < Grape::Entity
      expose :id, :email
    end

miks's avatar
miks committed
68
    class Hook < Grape::Entity
69
      expose :id, :url, :created_at, :push_events, :tag_push_events, :merge_requests_events, :repository_update_events
70
      expose :enable_ssl_verification
miks's avatar
miks committed
71 72
    end

73
    class ProjectHook < Hook
74
      expose :project_id, :issues_events, :confidential_issues_events
75
      expose :note_events, :confidential_note_events, :pipeline_events, :wiki_page_events
76
      expose :job_events
77 78
    end

79 80 81 82 83 84 85 86
    class SharedGroup < Grape::Entity
      expose :group_id
      expose :group_name do |group_link, options|
        group_link.group.name
      end
      expose :group_access, as: :group_access_level
    end

87 88
    class ProjectIdentity < Grape::Entity
      expose :id, :description
89 90
      expose :name, :name_with_namespace
      expose :path, :path_with_namespace
91 92 93
      expose :created_at
    end

94 95 96 97
    class ProjectExportStatus < ProjectIdentity
      include ::API::Helpers::RelatedResourcesHelpers

      expose :export_status
98
      expose :_links, if: lambda { |project, _options| project.export_status == :finished } do
99 100 101 102 103 104 105 106 107 108
        expose :api_url do |project|
          expose_url(api_v4_projects_export_download_path(id: project.id))
        end

        expose :web_url do |project|
          Gitlab::Routing.url_helpers.download_export_project_url(project)
        end
      end
    end

James Lopez's avatar
James Lopez committed
109 110
    class ProjectImportStatus < ProjectIdentity
      expose :import_status
James Lopez's avatar
James Lopez committed
111 112 113

      # TODO: Use `expose_nil` once we upgrade the grape-entity gem
      expose :import_error, if: lambda { |status, _ops| status.import_error }
James Lopez's avatar
James Lopez committed
114 115
    end

116
    class BasicProjectDetails < ProjectIdentity
Francisco Lopez's avatar
Francisco Lopez committed
117 118 119 120 121 122 123 124 125 126 127
      include ::API::ProjectsRelationBuilder

      expose :default_branch
      # Avoids an N+1 query: https://github.com/mbleigh/acts-as-taggable-on/issues/91#issuecomment-168273770
      expose :tag_list do |project|
        # project.tags.order(:name).pluck(:name) is the most suitable option
        # to avoid loading all the ActiveRecord objects but, if we use it here
        # it override the preloaded associations and makes a query
        # (fixed in https://github.com/rails/rails/pull/25976).
        project.tags.map(&:name).sort
      end
128
      expose :ssh_url_to_repo, :http_url_to_repo, :web_url
129 130 131
      expose :avatar_url do |project, options|
        project.avatar_url(only_path: false)
      end
132
      expose :star_count, :forks_count
Francisco Lopez's avatar
Francisco Lopez committed
133
      expose :last_activity_at
134

135 136
      expose :custom_attributes, using: 'API::Entities::CustomAttribute', if: :with_custom_attributes

137
      def self.preload_relation(projects_relation, options =  {})
138 139 140 141
        projects_relation.preload(:project_feature, :route)
                         .preload(namespace: [:route, :owner],
                                  tags: :taggings)
      end
142 143
    end

144
    class Project < BasicProjectDetails
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
      include ::API::Helpers::RelatedResourcesHelpers

      expose :_links do
        expose :self do |project|
          expose_url(api_v4_projects_path(id: project.id))
        end

        expose :issues, if: -> (*args) { issues_available?(*args) } do |project|
          expose_url(api_v4_projects_issues_path(id: project.id))
        end

        expose :merge_requests, if: -> (*args) { mrs_available?(*args) } do |project|
          expose_url(api_v4_projects_merge_requests_path(id: project.id))
        end

        expose :repo_branches do |project|
          expose_url(api_v4_projects_repository_branches_path(id: project.id))
        end

        expose :labels do |project|
          expose_url(api_v4_projects_labels_path(id: project.id))
        end

        expose :events do |project|
          expose_url(api_v4_projects_events_path(id: project.id))
        end

        expose :members do |project|
          expose_url(api_v4_projects_members_path(id: project.id))
        end
      end

177
      expose :archived?, as: :archived
178
      expose :visibility
179
      expose :owner, using: Entities::UserBasic, unless: ->(project, options) { project.group }
180
      expose :resolve_outdated_diff_discussions
181 182 183
      expose :container_registry_enabled

      # Expose old field names with the new permissions methods to keep API compatible
184 185 186
      expose(:issues_enabled) { |project, options| project.feature_available?(:issues, options[:current_user]) }
      expose(:merge_requests_enabled) { |project, options| project.feature_available?(:merge_requests, options[:current_user]) }
      expose(:wiki_enabled) { |project, options| project.feature_available?(:wiki, options[:current_user]) }
187
      expose(:jobs_enabled) { |project, options| project.feature_available?(:builds, options[:current_user]) }
188
      expose(:snippets_enabled) { |project, options| project.feature_available?(:snippets, options[:current_user]) }
189

190 191
      expose :shared_runners_enabled
      expose :lfs_enabled?, as: :lfs_enabled
192
      expose :creator_id
193
      expose :namespace, using: 'API::Entities::NamespaceBasic'
194
      expose :forked_from_project, using: Entities::BasicProjectDetails, if: lambda { |project, options| project.forked? }
195 196
      expose :import_status
      expose :import_error, if: lambda { |_project, options| options[:user_can_admin_project] }
197

198
      expose :open_issues_count, if: lambda { |project, options| project.feature_available?(:issues, options[:current_user]) }
199
      expose :runners_token, if: lambda { |_project, options| options[:user_can_admin_project] }
200
      expose :public_builds, as: :public_jobs
201
      expose :ci_config_path
202
      expose :shared_with_groups do |project, options|
203
        SharedGroup.represent(project.project_group_links, options)
204
      end
205
      expose :only_allow_merge_if_pipeline_succeeds
206
      expose :request_access_enabled
207
      expose :only_allow_merge_if_all_discussions_are_resolved
208
      expose :printing_merge_request_link_enabled
209
      expose :merge_method
210 211

      expose :statistics, using: 'API::Entities::ProjectStatistics', if: :statistics
212 213

      def self.preload_relation(projects_relation, options =  {})
214 215 216 217 218
        super(projects_relation).preload(:group)
                                .preload(project_group_links: :group,
                                         fork_network: :root_project,
                                         forked_project_link: :forked_from_project,
                                         forked_from_project: [:route, :forks, namespace: :route, tags: :taggings])
219 220 221
      end

      def self.forks_counting_projects(projects_relation)
222
        projects_relation + projects_relation.map(&:forked_from_project).compact
223
      end
224 225 226 227 228 229 230
    end

    class ProjectStatistics < Grape::Entity
      expose :commit_count
      expose :storage_size
      expose :repository_size
      expose :lfs_objects_size
231
      expose :build_artifacts_size, as: :job_artifacts_size
Nihad Abbasov's avatar
Nihad Abbasov committed
232 233
    end

234 235 236 237
    class Member < Grape::Entity
      expose :user, merge: true, using: UserBasic
      expose :access_level
      expose :expires_at
238 239
    end

240 241 242
    class AccessRequester < Grape::Entity
      expose :user, merge: true, using: UserBasic
      expose :requested_at
miks's avatar
miks committed
243 244
    end

245 246 247 248 249 250 251 252
    class BasicGroupDetails < Grape::Entity
      expose :id
      expose :web_url
      expose :name
    end

    class Group < BasicGroupDetails
      expose :path, :description, :visibility
253
      expose :lfs_enabled?, as: :lfs_enabled
254 255
      expose :avatar_url do |group, options|
        group.avatar_url(only_path: false)
256
      end
257
      expose :request_access_enabled
258
      expose :full_name, :full_path
259 260 261 262

      if ::Group.supports_nested_groups?
        expose :parent_id
      end
263

264 265
      expose :custom_attributes, using: 'API::Entities::CustomAttribute', if: :with_custom_attributes

266 267 268 269 270
      expose :statistics, if: :statistics do
        with_options format_with: -> (value) { value.to_i } do
          expose :storage_size
          expose :repository_size
          expose :lfs_objects_size
271
          expose :build_artifacts_size, as: :job_artifacts_size
272 273
        end
      end
274
    end
Andrew8xx8's avatar
Andrew8xx8 committed
275

276
    class GroupDetail < Group
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
      expose :projects, using: Entities::Project do |group, options|
        GroupProjectsFinder.new(
          group: group,
          current_user: options[:current_user],
          options: { only_owned: true }
        ).execute
      end

      expose :shared_projects, using: Entities::Project do |group, options|
        GroupProjectsFinder.new(
          group: group,
          current_user: options[:current_user],
          options: { only_shared: true }
        ).execute
      end
292 293
    end

294
    class Commit < Grape::Entity
295 296 297 298 299 300 301
      expose :id, :short_id, :title, :created_at
      expose :parent_ids
      expose :safe_message, as: :message
      expose :author_name, :author_email, :authored_date
      expose :committer_name, :committer_email, :committed_date
    end

302
    class CommitStats < Grape::Entity
303 304 305
      expose :additions, :deletions, :total
    end

306
    class CommitDetail < Commit
307
      expose :stats, using: Entities::CommitStats, if: :stats
308
      expose :status
309
      expose :last_pipeline, using: 'API::Entities::PipelineBasic'
310
      expose :project_id
311 312
    end

313
    class BasicRef < Grape::Entity
314
      expose :type, :name
315 316
    end

Robert Schilling's avatar
Robert Schilling committed
317
    class Branch < Grape::Entity
318 319
      expose :name

320
      expose :commit, using: Entities::Commit do |repo_branch, options|
321
        options[:project].repository.commit(repo_branch.dereferenced_target)
322 323
      end

324
      expose :merged do |repo_branch, options|
325 326 327 328 329
        if options[:merged_branch_names]
          options[:merged_branch_names].include?(repo_branch.name)
        else
          options[:project].repository.merged_to_root_ref?(repo_branch)
        end
330 331
      end

332
      expose :protected do |repo_branch, options|
333
        ::ProtectedBranch.protected?(options[:project], repo_branch.name)
334 335
      end

336
      expose :developers_can_push do |repo_branch, options|
337
        options[:project].protected_branches.developers_can?(:push, repo_branch.name)
338
      end
339

340
      expose :developers_can_merge do |repo_branch, options|
341
        options[:project].protected_branches.developers_can?(:merge, repo_branch.name)
342
      end
Nihad Abbasov's avatar
Nihad Abbasov committed
343
    end
Nihad Abbasov's avatar
Nihad Abbasov committed
344

345
    class TreeObject < Grape::Entity
346
      expose :id, :name, :type, :path
347 348

      expose :mode do |obj, options|
349
        filemode = obj.mode
350 351 352 353 354
        filemode = "0" + filemode if filemode.length < 6
        filemode
      end
    end

Jarka Kadlecová's avatar
Jarka Kadlecová committed
355
    class Snippet < Grape::Entity
356
      expose :id, :title, :file_name, :description
357
      expose :author, using: Entities::UserBasic
358
      expose :updated_at, :created_at
Jarka Kadlecová's avatar
Jarka Kadlecová committed
359 360
      expose :project_id
      expose :web_url do |snippet|
361 362
        Gitlab::UrlBuilder.build(snippet)
      end
Nihad Abbasov's avatar
Nihad Abbasov committed
363
    end
Nihad Abbasov's avatar
Nihad Abbasov committed
364

Jarka Kadlecová's avatar
Jarka Kadlecová committed
365 366
    class ProjectSnippet < Snippet
    end
367

Jarka Kadlecová's avatar
Jarka Kadlecová committed
368
    class PersonalSnippet < Snippet
369 370 371 372 373
      expose :raw_url do |snippet|
        Gitlab::UrlBuilder.build(snippet) + "/raw"
      end
    end

374 375
    class ProjectEntity < Grape::Entity
      expose :id, :iid
Felipe Artur's avatar
Felipe Artur committed
376
      expose(:project_id) { |entity| entity&.project.try(:id) }
377 378
      expose :title, :description
      expose :state, :created_at, :updated_at
379 380
    end

381
    class Diff < Grape::Entity
382
      expose :old_path, :new_path, :a_mode, :b_mode
383 384 385
      expose :new_file?, as: :new_file
      expose :renamed_file?, as: :renamed_file
      expose :deleted_file?, as: :deleted_file
386
      expose :json_safe_diff, as: :diff
387 388
    end

389 390 391 392 393 394 395 396 397 398 399 400 401
    class ProtectedRefAccess < Grape::Entity
      expose :access_level
      expose :access_level_description do |protected_ref_access|
        protected_ref_access.humanize
      end
    end

    class ProtectedBranch < Grape::Entity
      expose :name
      expose :push_access_levels, using: Entities::ProtectedRefAccess
      expose :merge_access_levels, using: Entities::ProtectedRefAccess
    end

Felipe Artur's avatar
Felipe Artur committed
402 403
    class Milestone < Grape::Entity
      expose :id, :iid
404 405
      expose :project_id, if: -> (entity, options) { entity&.project_id }
      expose :group_id, if: -> (entity, options) { entity&.group_id }
Felipe Artur's avatar
Felipe Artur committed
406 407
      expose :title, :description
      expose :state, :created_at, :updated_at
408
      expose :due_date
409
      expose :start_date
Nihad Abbasov's avatar
Nihad Abbasov committed
410 411
    end

412
    class IssueBasic < ProjectEntity
413
      expose :closed_at
haseeb's avatar
haseeb committed
414
      expose :closed_by, using: Entities::UserBasic
415 416 417 418
      expose :labels do |issue, options|
        # Avoids an N+1 query since labels are preloaded
        issue.labels.map(&:title).sort
      end
419
      expose :milestone, using: Entities::Milestone
420 421 422 423 424
      expose :assignees, :author, using: Entities::UserBasic

      expose :assignee, using: ::API::Entities::UserBasic do |issue, options|
        issue.assignees.first
      end
425

Z.J. van de Weg's avatar
Z.J. van de Weg committed
426
      expose :user_notes_count
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
      expose :upvotes do |issue, options|
        if options[:issuable_metadata]
          # Avoids an N+1 query when metadata is included
          options[:issuable_metadata][issue.id].upvotes
        else
          issue.upvotes
        end
      end
      expose :downvotes do |issue, options|
        if options[:issuable_metadata]
          # Avoids an N+1 query when metadata is included
          options[:issuable_metadata][issue.id].downvotes
        else
          issue.downvotes
        end
      end
443
      expose :due_date
444
      expose :confidential
445
      expose :discussion_locked
446 447 448 449

      expose :web_url do |issue, options|
        Gitlab::UrlBuilder.build(issue)
      end
450 451 452 453

      expose :time_stats, using: 'API::Entities::IssuableTimeStats' do |issue|
        issue
      end
Nihad Abbasov's avatar
Nihad Abbasov committed
454
    end
Alex Denisov's avatar
Alex Denisov committed
455

456
    class Issue < IssueBasic
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
      include ::API::Helpers::RelatedResourcesHelpers

      expose :_links do
        expose :self do |issue|
          expose_url(api_v4_project_issue_path(id: issue.project_id, issue_iid: issue.iid))
        end

        expose :notes do |issue|
          expose_url(api_v4_projects_issues_notes_path(id: issue.project_id, noteable_id: issue.iid))
        end

        expose :award_emoji do |issue|
          expose_url(api_v4_projects_issues_award_emoji_path(id: issue.project_id, issue_iid: issue.iid))
        end

        expose :project do |issue|
          expose_url(api_v4_projects_path(id: issue.project_id))
        end
      end

477 478 479 480 481
      expose :subscribed do |issue, options|
        issue.subscribed?(options[:current_user], options[:project] || issue.project)
      end
    end

482
    class IssuableTimeStats < Grape::Entity
483 484 485 486
      format_with(:time_tracking_formatter) do |time_spent|
        Gitlab::TimeTrackingFormatter.output(time_spent)
      end

487 488 489
      expose :time_estimate
      expose :total_time_spent
      expose :human_time_estimate
490 491 492 493 494 495 496 497 498

      with_options(format_with: :time_tracking_formatter) do
        expose :total_time_spent, as: :human_total_time_spent
      end

      def total_time_spent
        # Avoids an N+1 query since timelogs are preloaded
        object.timelogs.map(&:time_spent).sum
      end
499 500
    end

501 502 503 504 505
    class ExternalIssue < Grape::Entity
      expose :title
      expose :id
    end

506 507 508 509
    class PipelineBasic < Grape::Entity
      expose :id, :sha, :ref, :status
    end

510 511 512 513 514 515 516
    class MergeRequestSimple < ProjectEntity
      expose :title
      expose :web_url do |merge_request, options|
        Gitlab::UrlBuilder.build(merge_request)
      end
    end

517
    class MergeRequestBasic < ProjectEntity
Valery Sizov's avatar
Valery Sizov committed
518
      expose :target_branch, :source_branch
519 520 521 522 523 524 525 526 527 528 529 530 531 532
      expose :upvotes do |merge_request, options|
        if options[:issuable_metadata]
          options[:issuable_metadata][merge_request.id].upvotes
        else
          merge_request.upvotes
        end
      end
      expose :downvotes do |merge_request, options|
        if options[:issuable_metadata]
          options[:issuable_metadata][merge_request.id].downvotes
        else
          merge_request.downvotes
        end
      end
533 534
      expose :author, :assignee, using: Entities::UserBasic
      expose :source_project_id, :target_project_id
535 536 537 538
      expose :labels do |merge_request, options|
        # Avoids an N+1 query since labels are preloaded
        merge_request.labels.map(&:title).sort
      end
539
      expose :work_in_progress?, as: :work_in_progress
540
      expose :milestone, using: Entities::Milestone
541
      expose :merge_when_pipeline_succeeds
542 543 544 545 546 547

      # Ideally we should deprecate `MergeRequest#merge_status` exposure and
      # use `MergeRequest#mergeable?` instead (boolean).
      # See https://gitlab.com/gitlab-org/gitlab-ce/issues/42344 for more
      # information.
      expose :merge_status do |merge_request|
548 549
        merge_request.check_if_can_be_merged
        merge_request.merge_status
550
      end
551 552
      expose :diff_head_sha, as: :sha
      expose :merge_commit_sha
Z.J. van de Weg's avatar
Z.J. van de Weg committed
553
      expose :user_notes_count
554
      expose :discussion_locked
555 556
      expose :should_remove_source_branch?, as: :should_remove_source_branch
      expose :force_remove_source_branch?, as: :force_remove_source_branch
557
      expose :allow_maintainer_to_push, if: -> (merge_request, _) { merge_request.for_fork? }
558 559 560 561

      expose :web_url do |merge_request, options|
        Gitlab::UrlBuilder.build(merge_request)
      end
562 563 564 565

      expose :time_stats, using: 'API::Entities::IssuableTimeStats' do |merge_request|
        merge_request
      end
Alex Denisov's avatar
Alex Denisov committed
566
    end
567

568 569 570 571
    class MergeRequest < MergeRequestBasic
      expose :subscribed do |merge_request, options|
        merge_request.subscribed?(options[:current_user], options[:project])
      end
572 573 574 575

      expose :changes_count do |merge_request, _options|
        merge_request.merge_request_diff.real_size
      end
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611

      expose :merged_by, using: Entities::UserBasic do |merge_request, _options|
        merge_request.metrics&.merged_by
      end

      expose :merged_at do |merge_request, _options|
        merge_request.metrics&.merged_at
      end

      expose :closed_by, using: Entities::UserBasic do |merge_request, _options|
        merge_request.metrics&.latest_closed_by
      end

      expose :closed_at do |merge_request, _options|
        merge_request.metrics&.latest_closed_at
      end

      expose :latest_build_started_at, if: -> (_, options) { build_available?(options) } do |merge_request, _options|
        merge_request.metrics&.latest_build_started_at
      end

      expose :latest_build_finished_at, if: -> (_, options) { build_available?(options) } do |merge_request, _options|
        merge_request.metrics&.latest_build_finished_at
      end

      expose :first_deployed_to_production_at, if: -> (_, options) { build_available?(options) } do |merge_request, _options|
        merge_request.metrics&.first_deployed_to_production_at
      end

      expose :pipeline, using: Entities::PipelineBasic, if: -> (_, options) { build_available?(options) } do |merge_request, _options|
        merge_request.metrics&.pipeline
      end

      def build_available?(options)
        options[:project]&.feature_available?(:builds, options[:current_user])
      end
612 613
    end

614
    class MergeRequestChanges < MergeRequest
615
      expose :diffs, as: :changes, using: Entities::Diff do |compare, _|
Douwe Maan's avatar
Douwe Maan committed
616
        compare.raw_diffs(limits: false).to_a
617 618 619
      end
    end

620 621 622
    class MergeRequestDiff < Grape::Entity
      expose :id, :head_commit_sha, :base_commit_sha, :start_commit_sha,
        :created_at, :merge_request_id, :state, :real_size
623
    end
624

625
    class MergeRequestDiffFull < MergeRequestDiff
626
      expose :commits, using: Entities::Commit
627

628
      expose :diffs, using: Entities::Diff do |compare, _|
Douwe Maan's avatar
Douwe Maan committed
629
        compare.raw_diffs(limits: false).to_a
630 631 632
      end
    end

633
    class SSHKey < Grape::Entity
634
      expose :id, :title, :key, :created_at
635
    end
636

637
    class SSHKeyWithUser < SSHKey
638
      expose :user, using: Entities::UserPublic
639 640
    end

641 642 643 644 645
    class DeployKeysProject < Grape::Entity
      expose :deploy_key, merge: true, using: Entities::SSHKey
      expose :can_push
    end

646 647 648 649
    class GPGKey < Grape::Entity
      expose :id, :key, :created_at
    end

650
    class Note < Grape::Entity
sue445's avatar
sue445 committed
651 652 653
      # Only Issue and MergeRequest have iid
      NOTEABLE_TYPES_WITH_IID = %w(Issue MergeRequest).freeze

654
      expose :id
Jan Provaznik's avatar
Jan Provaznik committed
655
      expose :type
656
      expose :note, as: :body
657
      expose :attachment_identifier, as: :attachment
658
      expose :author, using: Entities::UserBasic
659
      expose :created_at, :updated_at
660
      expose :system?, as: :system
661
      expose :noteable_id, :noteable_type
sue445's avatar
sue445 committed
662 663 664

      # Avoid N+1 queries as much as possible
      expose(:noteable_iid) { |note| note.noteable.iid if NOTEABLE_TYPES_WITH_IID.include?(note.noteable_type) }
665
    end
666

Jan Provaznik's avatar
Jan Provaznik committed
667 668 669 670 671 672
    class Discussion < Grape::Entity
      expose :id
      expose :individual_note?, as: :individual_note
      expose :notes, using: Entities::Note
    end

673 674 675 676 677 678 679 680
    class AwardEmoji < Grape::Entity
      expose :id
      expose :name
      expose :user, using: Entities::UserBasic
      expose :created_at, :updated_at
      expose :awardable_id, :awardable_type
    end

681 682 683 684
    class MRNote < Grape::Entity
      expose :note
      expose :author, using: Entities::UserBasic
    end
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
685

686 687
    class CommitNote < Grape::Entity
      expose :note
688 689 690
      expose(:path) { |note| note.diff_file.try(:file_path) if note.diff_note? }
      expose(:line) { |note| note.diff_line.try(:new_line) if note.diff_note? }
      expose(:line_type) { |note| note.diff_line.try(:type) if note.diff_note? }
691
      expose :author, using: Entities::UserBasic
692
      expose :created_at
693 694
    end

695 696
    class CommitStatus < Grape::Entity
      expose :id, :sha, :ref, :status, :name, :target_url, :description,
697
             :created_at, :started_at, :finished_at, :allow_failure, :coverage
Kamil Trzcinski's avatar
Kamil Trzcinski committed
698
      expose :author, using: Entities::UserBasic
699 700
    end

701 702 703 704 705
    class PushEventPayload < Grape::Entity
      expose :commit_count, :action, :ref_type, :commit_from, :commit_to
      expose :ref, :commit_title
    end

Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
706
    class Event < Grape::Entity
707
      expose :project_id, :action_name
sue445's avatar
sue445 committed
708
      expose :target_id, :target_iid, :target_type, :author_id
709
      expose :target_title
710
      expose :created_at
711 712
      expose :note, using: Entities::Note, if: ->(event, options) { event.note? }
      expose :author, using: Entities::UserBasic, if: ->(event, options) { event.author }
713

714 715 716 717 718
      expose :push_event_payload,
        as: :push_data,
        using: PushEventPayload,
        if: -> (event, _) { event.push? }

719
      expose :author_username do |event, options|
720
        event.author&.username
721
      end
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
722
    end
723

724
    class ProjectGroupLink < Grape::Entity
725
      expose :id, :project_id, :group_id, :group_access, :expires_at
726 727
    end

Douglas Barbosa Alexandre's avatar
Douglas Barbosa Alexandre committed
728 729 730 731
    class Todo < Grape::Entity
      expose :id
      expose :project, using: Entities::BasicProjectDetails
      expose :author, using: Entities::UserBasic
Robert Schilling's avatar
Robert Schilling committed
732
      expose :action_name
Douglas Barbosa Alexandre's avatar
Douglas Barbosa Alexandre committed
733
      expose :target_type
734 735

      expose :target do |todo, options|
736
        Entities.const_get(todo.target_type).represent(todo.target, options)
Douglas Barbosa Alexandre's avatar
Douglas Barbosa Alexandre committed
737 738 739 740 741
      end

      expose :target_url do |todo, options|
        target_type   = todo.target_type.underscore
        target_url    = "namespace_project_#{target_type}_url"
742
        target_anchor = "note_#{todo.note_id}" if todo.note_id?
Douglas Barbosa Alexandre's avatar
Douglas Barbosa Alexandre committed
743

744 745 746
        Gitlab::Routing
          .url_helpers
          .public_send(target_url, todo.project.namespace, todo.project, todo.target, anchor: target_anchor) # rubocop:disable GitlabSecurity/PublicSend
Douglas Barbosa Alexandre's avatar
Douglas Barbosa Alexandre committed
747 748 749 750 751 752 753
      end

      expose :body
      expose :state
      expose :created_at
    end

754
    class NamespaceBasic < Grape::Entity
755
      expose :id, :name, :path, :kind, :full_path, :parent_id
756
    end
757

758
    class Namespace < NamespaceBasic
759 760 761 762 763 764
      expose :members_count_with_descendants, if: -> (namespace, opts) { expose_members_count_with_descendants?(namespace, opts) } do |namespace, _|
        namespace.users_with_descendants.count
      end

      def expose_members_count_with_descendants?(namespace, opts)
        namespace.kind == 'group' && Ability.allowed?(opts[:current_user], :admin_group, namespace)
765
      end
766
    end
767

768
    class MemberAccess < Grape::Entity
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
769
      expose :access_level
770
      expose :notification_level do |member, options|
771 772 773
        if member.notification_setting
          ::NotificationSetting.levels[member.notification_setting.level]
        end
774
      end
775 776
    end

777
    class ProjectAccess < MemberAccess
778 779
    end

780
    class GroupAccess < MemberAccess
781 782
    end

783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
    class NotificationSetting < Grape::Entity
      expose :level
      expose :events, if: ->(notification_setting, _) { notification_setting.custom? } do
        ::NotificationSetting::EMAIL_EVENTS.each do |event|
          expose event
        end
      end
    end

    class GlobalNotificationSetting < NotificationSetting
      expose :notification_email do |notification_setting, options|
        notification_setting.user.notification_email
      end
    end

798 799
    class ProjectService < Grape::Entity
      expose :id, :title, :created_at, :updated_at, :active
800 801
      expose :push_events, :issues_events, :confidential_issues_events
      expose :merge_requests_events, :tag_push_events, :note_events
802
      expose :confidential_note_events, :pipeline_events, :wiki_page_events
803
      expose :job_events
804 805
      # Expose serialized properties
      expose :properties do |service, options|
Stan Hu's avatar
Stan Hu committed
806
        service.properties.slice(*service.api_field_names)
807 808 809
      end
    end

810 811 812
    class ProjectWithAccess < Project
      expose :permissions do
        expose :project_access, using: Entities::ProjectAccess do |project, options|
813
          if options.key?(:project_members)
814 815 816
            (options[:project_members] || []).find { |member| member.source_id == project.id }
          else
            project.project_member(options[:current_user])
817
          end
818 819 820
        end

        expose :group_access, using: Entities::GroupAccess do |project, options|
821
          if project.group
822
            if options.key?(:group_members)
823 824 825
              (options[:group_members] || []).find { |member| member.source_id == project.namespace_id }
            else
              project.group.group_member(options[:current_user])
826
            end
827
          end
828 829
        end
      end
830 831 832 833 834 835 836 837 838 839 840 841 842 843

      def self.preload_relation(projects_relation, options = {})
        relation = super(projects_relation, options)

        unless options.key?(:group_members)
          relation = relation.preload(group: [group_members: [:source, user: [notification_settings: :source]]])
        end

        unless options.key?(:project_members)
          relation = relation.preload(project_members: [:source, user: [notification_settings: :source]])
        end

        relation
      end
844
    end
845

846
    class LabelBasic < Grape::Entity
Rares Sfirlogea's avatar
Rares Sfirlogea committed
847
      expose :id, :name, :color, :description
848 849 850
    end

    class Label < LabelBasic
851
      expose :open_issues_count do |label, options|
Francesco Coda Zabetta's avatar
Francesco Coda Zabetta committed
852 853
        label.open_issues_count(options[:current_user])
      end
854

Francesco Coda Zabetta's avatar
Francesco Coda Zabetta committed
855 856 857
      expose :closed_issues_count do |label, options|
        label.closed_issues_count(options[:current_user])
      end
858

Francesco Coda Zabetta's avatar
Francesco Coda Zabetta committed
859 860
      expose :open_merge_requests_count do |label, options|
        label.open_merge_requests_count(options[:current_user])
861 862
      end

863 864 865
      expose :priority do |label, options|
        label.priority(options[:project])
      end
866 867

      expose :subscribed do |label, options|
868
        label.subscribed?(options[:current_user], options[:project])
869
      end
870
    end
871

872 873 874 875 876 877 878 879
    class List < Grape::Entity
      expose :id
      expose :label, using: Entities::LabelBasic
      expose :position
    end

    class Board < Grape::Entity
      expose :id
Felipe Artur's avatar
Felipe Artur committed
880 881
      expose :project, using: Entities::BasicProjectDetails

882 883 884 885 886
      expose :lists, using: Entities::List do |board|
        board.lists.destroyable
      end
    end

887
    class Compare < Grape::Entity
888 889
      expose :commit, using: Entities::Commit do |compare, options|
        ::Commit.decorate(compare.commits, nil).last
890
      end
891

892 893
      expose :commits, using: Entities::Commit do |compare, options|
        ::Commit.decorate(compare.commits, nil)
894
      end
895

896
      expose :diffs, using: Entities::Diff do |compare, options|
Douwe Maan's avatar
Douwe Maan committed
897
        compare.diffs(limits: false).to_a
898
      end
899 900

      expose :compare_timeout do |compare, options|
901
        compare.diffs.overflow?
902 903 904
      end

      expose :same, as: :compare_same_ref
905
    end
906 907 908 909

    class Contributor < Grape::Entity
      expose :name, :email, :commits, :additions, :deletions
    end
910 911 912 913

    class BroadcastMessage < Grape::Entity
      expose :message, :starts_at, :ends_at, :color, :font
    end
914 915 916

    class ApplicationSetting < Grape::Entity
      expose :id
917
      expose(*::ApplicationSettingsHelper.visible_attributes)
918 919 920 921 922 923
      expose(:restricted_visibility_levels) do |setting, _options|
        setting.restricted_visibility_levels.map { |level| Gitlab::VisibilityLevel.string_level(level) }
      end
      expose(:default_project_visibility) { |setting, _options| Gitlab::VisibilityLevel.string_level(setting.default_project_visibility) }
      expose(:default_snippet_visibility) { |setting, _options| Gitlab::VisibilityLevel.string_level(setting.default_snippet_visibility) }
      expose(:default_group_visibility) { |setting, _options| Gitlab::VisibilityLevel.string_level(setting.default_group_visibility) }
924 925 926 927

      # support legacy names, can be removed in v5
      expose :password_authentication_enabled_for_web, as: :password_authentication_enabled
      expose :password_authentication_enabled_for_web, as: :signin_enabled
928
    end
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
929 930

    class Release < Grape::Entity
931 932
      expose :tag, as: :tag_name
      expose :description
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
933
    end
934

Robert Schilling's avatar
Robert Schilling committed
935
    class Tag < Grape::Entity
936
      expose :name, :message, :target
937

938
      expose :commit, using: Entities::Commit do |repo_tag, options|
939
        options[:project].repository.commit(repo_tag.dereferenced_target)
940 941
      end

942 943
      expose :release, using: Entities::Release do |repo_tag, options|
        options[:project].releases.find_by(tag: repo_tag.name)
944 945
      end
    end
Kamil Trzcinski's avatar
Kamil Trzcinski committed
946

947
    class Runner < Grape::Entity
948 949 950 951 952
      expose :id
      expose :description
      expose :active
      expose :is_shared
      expose :name
953
      expose :online?, as: :online
954
      expose :status
955 956
    end

957 958
    class RunnerDetails < Runner
      expose :tag_list
959
      expose :run_untagged
960
      expose :locked
961
      expose :maximum_timeout
Shinya Maeda's avatar
Shinya Maeda committed
962
      expose :access_level
963
      expose :version, :revision, :platform, :architecture
964
      expose :contacted_at
965
      expose :token, if: lambda { |runner, options| options[:current_user].admin? || !runner.is_shared? }
966
      expose :projects, with: Entities::BasicProjectDetails do |runner, options|
967
        if options[:current_user].admin?
968 969
          runner.projects
        else
970
          options[:current_user].authorized_projects.where(id: runner.projects)
971 972
        end
      end
973 974 975 976 977 978 979
      expose :groups, with: Entities::BasicGroupDetails do |runner, options|
        if options[:current_user].admin?
          runner.groups
        else
          options[:current_user].authorized_groups.where(id: runner.groups)
        end
      end
980 981
    end

982 983 984 985
    class RunnerRegistrationDetails < Grape::Entity
      expose :id, :token
    end

986
    class JobArtifactFile < Grape::Entity
987 988 989
      expose :filename, :size
    end

Tomasz Maczukin's avatar
Tomasz Maczukin committed
990
    class JobBasic < Grape::Entity
991
      expose :id, :status, :stage, :name, :ref, :tag, :coverage
992
      expose :created_at, :started_at, :finished_at
993
      expose :duration
Tomasz Maczukin's avatar
Tomasz Maczukin committed
994
      expose :user, with: User
995
      expose :commit, with: Commit
996
      expose :pipeline, with: PipelineBasic
997
    end
998

Tomasz Maczukin's avatar
Tomasz Maczukin committed
999 1000 1001 1002 1003 1004
    class Job < JobBasic
      expose :artifacts_file, using: JobArtifactFile, if: -> (job, opts) { job.artifacts? }
      expose :runner, with: Runner
    end

    class JobBasicWithProject < JobBasic
1005 1006 1007
      expose :project, with: ProjectIdentity
    end

1008
    class Trigger < Grape::Entity
1009
      expose :id
1010
      expose :token, :description
1011
      expose :created_at, :updated_at, :last_used
1012
      expose :owner, using: Entities::UserBasic
1013
    end
1014

1015
    class Variable < Grape::Entity
Tomasz Maczukin's avatar
Tomasz Maczukin committed
1016
      expose :key, :value
Shinya Maeda's avatar
Shinya Maeda committed
1017
      expose :protected?, as: :protected, if: -> (entity, _) { entity.respond_to?(:protected?) }
1018
    end
1019

1020 1021
    class Pipeline < PipelineBasic
      expose :before_sha, :tag, :yaml_errors
1022 1023 1024 1025

      expose :user, with: Entities::UserBasic
      expose :created_at, :updated_at, :started_at, :finished_at, :committed_at
      expose :duration
1026
      expose :coverage
1027 1028
    end

1029 1030 1031
    class PipelineSchedule < Grape::Entity
      expose :id
      expose :description, :ref, :cron, :cron_timezone, :next_run_at, :active
1032
      expose :created_at, :updated_at
1033 1034 1035
      expose :owner, using: Entities::UserBasic
    end

Shinya Maeda's avatar
Shinya Maeda committed
1036 1037
    class PipelineScheduleDetails < PipelineSchedule
      expose :last_pipeline, using: Entities::PipelineBasic
1038
      expose :variables, using: Entities::Variable
Shinya Maeda's avatar
Shinya Maeda committed
1039 1040
    end

1041
    class EnvironmentBasic < Grape::Entity
Nick Thomas's avatar
Nick Thomas committed
1042
      expose :id, :name, :slug, :external_url
1043 1044
    end

1045
    class Environment < EnvironmentBasic
1046
      expose :project, using: Entities::BasicProjectDetails
Z.J. van de Weg's avatar
Z.J. van de Weg committed
1047 1048 1049 1050
    end

    class Deployment < Grape::Entity
      expose :id, :iid, :ref, :sha, :created_at
1051 1052
      expose :user,        using: Entities::UserBasic
      expose :environment, using: Entities::EnvironmentBasic
1053
      expose :deployable,  using: Entities::Job
1054 1055
    end

1056
    class License < Grape::Entity
1057 1058
      expose :key, :name, :nickname
      expose :featured, as: :popular
1059 1060 1061
      expose :url, as: :html_url
      expose(:source_url) { |license| license.meta['source'] }
      expose(:description) { |license| license.meta['description'] }
1062 1063 1064
      expose(:conditions) { |license| license.meta['conditions'] }
      expose(:permissions) { |license| license.meta['permissions'] }
      expose(:limitations) { |license| license.meta['limitations'] }
1065 1066
      expose :content
    end
1067

1068
    class TemplatesList < Grape::Entity
1069 1070 1071
      expose :name
    end

1072
    class Template < Grape::Entity
1073 1074
      expose :name, :content
    end
1075 1076 1077 1078 1079

    class BroadcastMessage < Grape::Entity
      expose :id, :message, :starts_at, :ends_at, :color, :font
      expose :active?, as: :active
    end
Tomasz Maczukin's avatar
Tomasz Maczukin committed
1080

1081
    class PersonalAccessToken < Grape::Entity
1082 1083 1084 1085 1086 1087 1088
      expose :id, :name, :revoked, :created_at, :scopes
      expose :active?, as: :active
      expose :expires_at do |personal_access_token|
        personal_access_token.expires_at ? personal_access_token.expires_at.strftime("%Y-%m-%d") : nil
      end
    end

1089
    class PersonalAccessTokenWithToken < PersonalAccessToken
1090 1091
      expose :token
    end
1092 1093 1094 1095

    class ImpersonationToken < PersonalAccessTokenWithToken
      expose :impersonation
    end
1096

1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
    class FeatureGate < Grape::Entity
      expose :key
      expose :value
    end

    class Feature < Grape::Entity
      expose :name
      expose :state
      expose :gates, using: FeatureGate do |model|
        model.gates.map do |gate|
          value = model.gate_values[gate.key]

          # By default all gate values are populated. Only show relevant ones.
          if (value.is_a?(Integer) && value.zero?) || (value.is_a?(Set) && value.empty?)
            next
          end

          { key: gate.key, value: value }
        end.compact
      end
    end

1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
    module JobRequest
      class JobInfo < Grape::Entity
        expose :name, :stage
        expose :project_id, :project_name
      end

      class GitInfo < Grape::Entity
        expose :repo_url, :ref, :sha, :before_sha
        expose :ref_type do |model|
          if model.tag
            'tag'
          else
            'branch'
          end
        end
      end
Tomasz Maczukin's avatar
Tomasz Maczukin committed
1135

1136
      class RunnerInfo < Grape::Entity
Tomasz Maczukin's avatar
Tomasz Maczukin committed
1137
        expose :metadata_timeout, as: :timeout
1138
      end
Tomasz Maczukin's avatar
Tomasz Maczukin committed
1139

1140
      class Step < Grape::Entity
Tomasz Maczukin's avatar
Tomasz Maczukin committed
1141
        expose :name, :script, :timeout, :when, :allow_failure
1142
      end
Tomasz Maczukin's avatar
Tomasz Maczukin committed
1143

1144
      class Image < Grape::Entity
1145 1146 1147
        expose :name, :entrypoint
      end

1148
      class Service < Image
1149
        expose :alias, :command
1150
      end
Tomasz Maczukin's avatar
Tomasz Maczukin committed
1151

1152 1153
      class Artifacts < Grape::Entity
        expose :name, :untracked, :paths, :when, :expire_in
Tomasz Maczukin's avatar
Tomasz Maczukin committed
1154 1155
      end

1156
      class Cache < Grape::Entity
1157
        expose :key, :untracked, :paths, :policy
Tomasz Maczukin's avatar
Tomasz Maczukin committed
1158 1159
      end

1160 1161 1162
      class Credentials < Grape::Entity
        expose :type, :url, :username, :password
      end
Tomasz Maczukin's avatar
Tomasz Maczukin committed
1163

1164
      class Dependency < Grape::Entity
1165
        expose :id, :name, :token
1166
        expose :artifacts_file, using: JobArtifactFile, if: ->(job, _) { job.artifacts? }
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
      end

      class Response < Grape::Entity
        expose :id
        expose :token
        expose :allow_git_fetch

        expose :job_info, using: JobInfo do |model|
          model
        end

        expose :git_info, using: GitInfo do |model|
          model
        end

        expose :runner_info, using: RunnerInfo do |model|
          model
        end

        expose :variables
        expose :steps, using: Step
        expose :image, using: Image
1189
        expose :services, using: Service
1190 1191 1192
        expose :artifacts, using: Artifacts
        expose :cache, using: Cache
        expose :credentials, using: Credentials
1193
        expose :dependencies, using: Dependency
1194
        expose :features
1195
      end
Tomasz Maczukin's avatar
Tomasz Maczukin committed
1196
    end
1197 1198 1199 1200

    class UserAgentDetail < Grape::Entity
      expose :user_agent
      expose :ip_address
1201
      expose :submitted, as: :akismet_submitted
1202
    end
1203 1204 1205 1206 1207 1208

    class RepositoryStorageHealth < Grape::Entity
      expose :storage_name
      expose :failing_on_hosts
      expose :total_failures
    end
1209 1210 1211 1212 1213

    class CustomAttribute < Grape::Entity
      expose :key
      expose :value
    end
1214

1215 1216 1217 1218 1219
    class PagesDomainCertificateExpiration < Grape::Entity
      expose :expired?, as: :expired
      expose :expiration
    end

1220 1221 1222 1223 1224 1225 1226
    class PagesDomainCertificate < Grape::Entity
      expose :subject
      expose :expired?, as: :expired
      expose :certificate
      expose :certificate_text
    end

1227 1228 1229
    class PagesDomainBasic < Grape::Entity
      expose :domain
      expose :url
1230
      expose :project_id
1231 1232 1233 1234
      expose :verified?, as: :verified
      expose :verification_code, as: :verification_code
      expose :enabled_until

1235 1236 1237 1238 1239 1240 1241 1242
      expose :certificate,
        as: :certificate_expiration,
        if: ->(pages_domain, _) { pages_domain.certificate? },
        using: PagesDomainCertificateExpiration do |pages_domain|
        pages_domain
      end
    end

1243 1244 1245
    class PagesDomain < Grape::Entity
      expose :domain
      expose :url
1246 1247 1248 1249
      expose :verified?, as: :verified
      expose :verification_code, as: :verification_code
      expose :enabled_until

1250
      expose :certificate,
1251 1252
        if: ->(pages_domain, _) { pages_domain.certificate? },
        using: PagesDomainCertificate do |pages_domain|
1253 1254 1255
        pages_domain
      end
    end
1256 1257 1258 1259 1260

    class Application < Grape::Entity
      expose :uid, as: :application_id
      expose :redirect_uri, as: :callback_url
    end
1261 1262 1263 1264 1265

    # Use with care, this exposes the secret
    class ApplicationWithSecret < Application
      expose :secret
    end
Jarka Kadlecová's avatar
Jarka Kadlecová committed
1266 1267 1268 1269 1270 1271 1272 1273

    class Blob < Grape::Entity
      expose :basename
      expose :data
      expose :filename
      expose :id
      expose :ref
      expose :startline
1274
      expose :project_id
Jarka Kadlecová's avatar
Jarka Kadlecová committed
1275
    end
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293

    class BasicBadgeDetails < Grape::Entity
      expose :link_url
      expose :image_url
      expose :rendered_link_url do |badge, options|
        badge.rendered_link_url(options.fetch(:project, nil))
      end
      expose :rendered_image_url do |badge, options|
        badge.rendered_image_url(options.fetch(:project, nil))
      end
    end

    class Badge < BasicBadgeDetails
      expose :id
      expose :kind do |badge|
        badge.type == 'ProjectBadge' ? 'project' : 'group'
      end
    end
Nihad Abbasov's avatar
Nihad Abbasov committed
1294 1295
  end
end