entities.rb 40.2 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 25
      expose :avatar_path, if: ->(user, options) { options.fetch(:only_path, false) && user.avatar_path }

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

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

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

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

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

      # EE-only
      expose :shared_runners_minutes_limit
60 61
    end

62
    class UserWithAdmin < UserPublic
63
      expose :admin?, as: :is_admin
64 65
    end

66 67 68 69
    class Email < Grape::Entity
      expose :id, :email
    end

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

75
    class ProjectHook < Hook
76
      expose :project_id, :issues_events, :merge_requests_events
77
      expose :note_events, :pipeline_events, :wiki_page_events
78
      expose :job_events
79
    end
Valery Sizov's avatar
Valery Sizov committed
80

81
    class ProjectPushRule < Grape::Entity
Valery Sizov's avatar
Valery Sizov committed
82
      expose :id, :project_id, :created_at
83
      expose :commit_message_regex, :branch_name_regex, :deny_delete_tag
84 85
      expose :member_check, :prevent_secrets, :author_email_regex
      expose :file_name_regex, :max_file_size
Valery Sizov's avatar
Valery Sizov committed
86
    end
87

88 89 90 91 92 93 94 95
    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

96 97
    class ProjectIdentity < Grape::Entity
      expose :id, :description
98 99
      expose :name, :name_with_namespace
      expose :path, :path_with_namespace
100 101 102 103
      expose :created_at
    end

    class BasicProjectDetails < ProjectIdentity
104 105 106 107 108 109 110 111 112 113 114
      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
115
      expose :ssh_url_to_repo, :http_url_to_repo, :web_url
116 117 118
      expose :avatar_url do |project, options|
        project.avatar_url(only_path: false)
      end
119
      expose :star_count, :forks_count
120
      expose :last_activity_at
121 122 123 124 125 126

      def self.preload_relation(projects_relation, options =  {})
        projects_relation.preload(:project_feature, :route)
                         .preload(namespace: [:route, :owner],
                                  tags: :taggings)
      end
127 128
    end

129
    class Project < BasicProjectDetails
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
      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

162
      expose :archived?, as: :archived
163
      expose :visibility
164
      expose :owner, using: Entities::UserBasic, unless: ->(project, options) { project.group }
165
      expose :resolve_outdated_diff_discussions
166 167 168
      expose :container_registry_enabled

      # Expose old field names with the new permissions methods to keep API compatible
169 170 171
      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]) }
172
      expose(:jobs_enabled) { |project, options| project.feature_available?(:builds, options[:current_user]) }
173
      expose(:snippets_enabled) { |project, options| project.feature_available?(:snippets, options[:current_user]) }
174

175 176
      expose :shared_runners_enabled
      expose :lfs_enabled?, as: :lfs_enabled
177
      expose :creator_id
178
      expose :namespace, using: 'API::Entities::NamespaceBasic'
179
      expose :forked_from_project, using: Entities::BasicProjectDetails, if: lambda { |project, options| project.forked? }
180 181
      expose :import_status
      expose :import_error, if: lambda { |_project, options| options[:user_can_admin_project] }
182

183
      expose :open_issues_count, if: lambda { |project, options| project.feature_available?(:issues, options[:current_user]) }
184
      expose :runners_token, if: lambda { |_project, options| options[:user_can_admin_project] }
185
      expose :public_builds, as: :public_jobs
186
      expose :ci_config_path
187
      expose :shared_with_groups do |project, options|
188
        SharedGroup.represent(project.project_group_links, options)
189
      end
190
      expose :only_allow_merge_if_pipeline_succeeds
191
      expose :repository_storage, if: lambda { |_project, options| options[:current_user].try(:admin?) }
192
      expose :request_access_enabled
193
      expose :only_allow_merge_if_all_discussions_are_resolved
194
      expose :printing_merge_request_link_enabled
195 196

      # EE only
197
      expose :approvals_before_merge, if: ->(project, _) { project.feature_available?(:merge_request_approvers) }
198

199
      expose :statistics, using: 'API::Entities::ProjectStatistics', if: :statistics
200 201 202 203 204 205 206 207 208 209 210 211

      def self.preload_relation(projects_relation, options =  {})
        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])
      end

      def self.forks_counting_projects(projects_relation)
        projects_relation + projects_relation.map(&:forked_from_project).compact
      end
212 213 214 215 216 217 218
    end

    class ProjectStatistics < Grape::Entity
      expose :commit_count
      expose :storage_size
      expose :repository_size
      expose :lfs_objects_size
219
      expose :build_artifacts_size, as: :job_artifacts_size
Nihad Abbasov's avatar
Nihad Abbasov committed
220 221
    end

222
    class Member < UserBasic
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
223
      expose :access_level do |user, options|
224
        member = options[:member] || options[:source].members.find_by(user_id: user.id)
225 226
        member.access_level
      end
227
      expose :expires_at do |user, options|
228
        member = options[:member] || options[:source].members.find_by(user_id: user.id)
229 230
        member.expires_at
      end
231 232 233 234
    end

    class AccessRequester < UserBasic
      expose :requested_at do |user, options|
235
        access_requester = options[:access_requester] || options[:source].requesters.find_by(user_id: user.id)
236
        access_requester.requested_at
237
      end
miks's avatar
miks committed
238 239
    end

240 241 242 243
    class LdapGroupLink < Grape::Entity
      expose :cn, :group_access, :provider
    end

244
    class Group < Grape::Entity
245
      expose :id, :name, :path, :description, :visibility
Douwe Maan's avatar
Douwe Maan committed
246

247
      ## EE-only
248 249 250 251
      expose :ldap_cn, :ldap_access
      expose :ldap_group_links,
        using: Entities::LdapGroupLink,
        if: lambda { |group, options| group.ldap_group_links.any? }
252
      ## EE-only
Douwe Maan's avatar
Douwe Maan committed
253

254
      expose :lfs_enabled?, as: :lfs_enabled
255 256
      expose :avatar_url do |group, options|
        group.avatar_url(only_path: false)
257
      end
258
      expose :web_url
259
      expose :request_access_enabled
260
      expose :full_name, :full_path
261 262 263 264

      if ::Group.supports_nested_groups?
        expose :parent_id
      end
265 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 294

      # EE-only
      expose :shared_runners_minutes_limit
295 296
    end

297
    class Commit < Grape::Entity
298 299 300 301 302 303 304
      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

305
    class CommitStats < Grape::Entity
306 307 308
      expose :additions, :deletions, :total
    end

309 310
    class CommitDetail < Commit
      expose :stats, using: Entities::CommitStats
311
      expose :status
312
      expose :last_pipeline, using: 'API::Entities::PipelineBasic'
313 314
    end

315
    class Branch < Grape::Entity
316 317
      expose :name

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

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

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

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

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

343
    class TreeObject < Grape::Entity
344
      expose :id, :name, :type, :path
345 346

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

Nihad Abbasov's avatar
Nihad Abbasov committed
353
    class ProjectSnippet < Grape::Entity
354
      expose :id, :title, :file_name, :description
355
      expose :author, using: Entities::UserBasic
356
      expose :updated_at, :created_at
357

358 359 360
      expose :web_url do |snippet, options|
        Gitlab::UrlBuilder.build(snippet)
      end
Nihad Abbasov's avatar
Nihad Abbasov committed
361
    end
Nihad Abbasov's avatar
Nihad Abbasov committed
362

363
    class PersonalSnippet < Grape::Entity
364
      expose :id, :title, :file_name, :description
365 366 367 368 369 370 371 372 373 374 375
      expose :author, using: Entities::UserBasic
      expose :updated_at, :created_at

      expose :web_url do |snippet|
        Gitlab::UrlBuilder.build(snippet)
      end
      expose :raw_url do |snippet|
        Gitlab::UrlBuilder.build(snippet) + "/raw"
      end
    end

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

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

391 392
    class ProtectedRefAccess < Grape::Entity
      expose :access_level
393 394 395 396 397 398

      ## EE-only
      expose :user_id
      expose :group_id
      ## EE-only

399 400 401 402 403 404 405 406 407 408 409
      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
410 411
    class Milestone < Grape::Entity
      expose :id, :iid
412 413
      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
414 415
      expose :title, :description
      expose :state, :created_at, :updated_at
416
      expose :due_date
417
      expose :start_date
Nihad Abbasov's avatar
Nihad Abbasov committed
418 419
    end

420
    class IssueBasic < ProjectEntity
421
      expose :closed_at
422 423 424 425
      expose :labels do |issue, options|
        # Avoids an N+1 query since labels are preloaded
        issue.labels.map(&:title).sort
      end
426
      expose :milestone, using: Entities::Milestone
427
      expose :assignees, :author, using: Entities::UserBasic
428

429 430 431 432
      expose :assignee, using: ::API::Entities::UserBasic do |issue, options|
        issue.assignees.first
      end

433
      expose :user_notes_count
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
      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
450
      expose :due_date
451
      expose :confidential
452
      expose :weight, if: ->(issue, _) { issue.supports_weight? }
453
      expose :discussion_locked
454 455 456 457

      expose :web_url do |issue, options|
        Gitlab::UrlBuilder.build(issue)
      end
458 459 460 461

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

464
    class Issue < IssueBasic
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
      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

485 486 487 488 489
      expose :subscribed do |issue, options|
        issue.subscribed?(options[:current_user], options[:project] || issue.project)
      end
    end

490 491 492 493
    class RelatedIssue < Issue
      expose :issue_link_id
    end

494 495 496 497 498 499 500 501 502 503 504 505
    class Epic < Grape::Entity
      expose :id
      expose :iid
      expose :title
      expose :description
      expose :author, using: Entities::UserBasic
      expose :start_date
      expose :end_date
    end

    class EpicIssue < Issue
      expose :epic_issue_id
506
      expose :relative_position
507 508 509 510
    end

    class EpicIssueLink < Grape::Entity
      expose :id
511
      expose :relative_position
512 513 514 515
      expose :epic, using: Entities::Epic
      expose :issue, using: Entities::IssueBasic
    end

516
    class IssueLink < Grape::Entity
517 518
      expose :source, as: :source_issue, using: Entities::IssueBasic
      expose :target, as: :target_issue, using: Entities::IssueBasic
519 520
    end

521
    class IssuableTimeStats < Grape::Entity
522 523 524 525
      format_with(:time_tracking_formatter) do |time_spent|
        Gitlab::TimeTrackingFormatter.output(time_spent)
      end

526 527 528
      expose :time_estimate
      expose :total_time_spent
      expose :human_time_estimate
529 530 531 532 533 534 535 536 537

      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
538 539
    end

540 541 542 543 544
    class ExternalIssue < Grape::Entity
      expose :title
      expose :id
    end

545 546 547 548 549 550 551
    class MergeRequestSimple < ProjectEntity
      expose :title
      expose :web_url do |merge_request, options|
        Gitlab::UrlBuilder.build(merge_request)
      end
    end

552
    class MergeRequestBasic < ProjectEntity
553
      expose :target_branch, :source_branch
554 555 556 557 558 559 560 561 562 563 564 565 566 567
      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
568 569
      expose :author, :assignee, using: Entities::UserBasic
      expose :source_project_id, :target_project_id
570 571 572 573
      expose :labels do |merge_request, options|
        # Avoids an N+1 query since labels are preloaded
        merge_request.labels.map(&:title).sort
      end
574
      expose :work_in_progress?, as: :work_in_progress
575
      expose :milestone, using: Entities::Milestone
576
      expose :merge_when_pipeline_succeeds
577
      expose :merge_status
578 579
      expose :diff_head_sha, as: :sha
      expose :merge_commit_sha
580
      expose :user_notes_count
581
      expose :approvals_before_merge
582
      expose :discussion_locked
583 584
      expose :should_remove_source_branch?, as: :should_remove_source_branch
      expose :force_remove_source_branch?, as: :force_remove_source_branch
585 586

      expose :squash, if: -> (mr, _) { mr.project.feature_available?(:merge_request_squash) }
587 588 589 590

      expose :web_url do |merge_request, options|
        Gitlab::UrlBuilder.build(merge_request)
      end
591 592 593 594

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

597 598 599 600
    class MergeRequest < MergeRequestBasic
      expose :subscribed do |merge_request, options|
        merge_request.subscribed?(options[:current_user], options[:project])
      end
601 602 603 604

      expose :changes_count do |merge_request, _options|
        merge_request.merge_request_diff.real_size
      end
605 606
    end

607
    class MergeRequestChanges < MergeRequest
608
      expose :diffs, as: :changes, using: Entities::Diff do |compare, _|
Douwe Maan's avatar
Douwe Maan committed
609
        compare.raw_diffs(limits: false).to_a
610 611 612
      end
    end

Patricio Cano's avatar
Patricio Cano committed
613
    class Approvals < Grape::Entity
Patricio Cano's avatar
Patricio Cano committed
614
      expose :user, using: Entities::UserBasic
Patricio Cano's avatar
Patricio Cano committed
615 616 617 618
    end

    class MergeRequestApprovals < ProjectEntity
      expose :merge_status
619 620
      expose :approvals_required
      expose :approvals_left
Patricio Cano's avatar
Patricio Cano committed
621
      expose :approvals, as: :approved_by, using: Entities::Approvals
622
      expose :approvers_left, as: :suggested_approvers, using: Entities::UserBasic
623 624 625 626 627 628 629 630

      expose :user_has_approved do |merge_request, options|
        merge_request.has_approved?(options[:current_user])
      end

      expose :user_can_approve do |merge_request, options|
        merge_request.can_approve?(options[:current_user])
      end
Patricio Cano's avatar
Patricio Cano committed
631 632
    end

633 634 635
    class MergeRequestDiff < Grape::Entity
      expose :id, :head_commit_sha, :base_commit_sha, :start_commit_sha,
        :created_at, :merge_request_id, :state, :real_size
636
    end
637

638
    class MergeRequestDiffFull < MergeRequestDiff
639
      expose :commits, using: Entities::Commit
640

641
      expose :diffs, using: Entities::Diff do |compare, _|
Douwe Maan's avatar
Douwe Maan committed
642
        compare.raw_diffs(limits: false).to_a
643 644 645
      end
    end

646
    class SSHKey < Grape::Entity
647
      expose :id, :title, :key, :created_at, :can_push
648
    end
649

650
    class SSHKeyWithUser < SSHKey
651
      expose :user, using: Entities::UserPublic
652 653
    end

654 655 656 657
    class GPGKey < Grape::Entity
      expose :id, :key, :created_at
    end

658
    class Note < Grape::Entity
sue445's avatar
sue445 committed
659 660 661
      # Only Issue and MergeRequest have iid
      NOTEABLE_TYPES_WITH_IID = %w(Issue MergeRequest).freeze

662 663
      expose :id
      expose :note, as: :body
664
      expose :attachment_identifier, as: :attachment
665
      expose :author, using: Entities::UserBasic
666
      expose :created_at, :updated_at
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
667
      expose :system?, as: :system
668
      expose :noteable_id, :noteable_type
sue445's avatar
sue445 committed
669 670 671

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

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

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

687 688
    class CommitNote < Grape::Entity
      expose :note
689 690 691
      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? }
692
      expose :author, using: Entities::UserBasic
693
      expose :created_at
694 695
    end

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

702 703 704 705 706
    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
707
    class Event < Grape::Entity
708
      expose :project_id, :action_name
sue445's avatar
sue445 committed
709
      expose :target_id, :target_iid, :target_type, :author_id
710
      expose :target_title
711
      expose :created_at
712 713
      expose :note, using: Entities::Note, if: ->(event, options) { event.note? }
      expose :author, using: Entities::UserBasic, if: ->(event, options) { event.author }
714

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

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

    class LdapGroup < Grape::Entity
      expose :cn
    end
728 729

    class ProjectGroupLink < Grape::Entity
730
      expose :id, :project_id, :group_id, :group_access, :expires_at
731
    end
732

Douglas Barbosa Alexandre's avatar
Douglas Barbosa Alexandre committed
733 734 735 736
    class Todo < Grape::Entity
      expose :id
      expose :project, using: Entities::BasicProjectDetails
      expose :author, using: Entities::UserBasic
Robert Schilling's avatar
Robert Schilling committed
737
      expose :action_name
Douglas Barbosa Alexandre's avatar
Douglas Barbosa Alexandre committed
738
      expose :target_type
739 740

      expose :target do |todo, options|
741
        Entities.const_get(todo.target_type).represent(todo.target, options)
Douglas Barbosa Alexandre's avatar
Douglas Barbosa Alexandre committed
742 743 744 745 746
      end

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

749 750 751
        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
752 753 754 755 756 757 758
      end

      expose :body
      expose :state
      expose :created_at
    end

759
    class NamespaceBasic < Grape::Entity
760
      expose :id, :name, :path, :kind, :full_path, :parent_id
761
    end
762

763
    class Namespace < NamespaceBasic
764 765 766 767 768 769
      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)
770 771
      end

772
      # EE-only
773
      expose :shared_runners_minutes_limit, if: lambda { |_, options| options[:current_user]&.admin? }
774 775 776
      expose :plan, if: -> (namespace, opts) { Ability.allowed?(opts[:current_user], :admin_namespace, namespace) } do |namespace, _|
        namespace.plan&.name
      end
777
    end
778

779
    class MemberAccess < Grape::Entity
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
780
      expose :access_level
781 782
      expose :notification_level do |member, options|
        if member.notification_setting
783
          ::NotificationSetting.levels[member.notification_setting.level]
784 785
        end
      end
786 787
    end

788
    class ProjectAccess < MemberAccess
789 790
    end

791
    class GroupAccess < MemberAccess
792 793
    end

794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
    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

809 810
    class ProjectService < Grape::Entity
      expose :id, :title, :created_at, :updated_at, :active
811 812 813
      expose :push_events, :issues_events, :confidential_issues_events
      expose :merge_requests_events, :tag_push_events, :note_events
      expose :pipeline_events, :wiki_page_events
814
      expose :job_events
815 816
      # Expose serialized properties
      expose :properties do |service, options|
817 818 819
        field_names = service.fields
          .select { |field| options[:include_passwords] || field[:type] != 'password' }
          .map { |field| field[:name] }
820 821 822 823
        service.properties.slice(*field_names)
      end
    end

824 825 826
    class ProjectWithAccess < Project
      expose :permissions do
        expose :project_access, using: Entities::ProjectAccess do |project, options|
827 828 829
          if options.key?(:project_members)
            (options[:project_members] || []).find { |member| member.source_id == project.id }
          else
830
            project.project_member(options[:current_user])
831
          end
832 833 834
        end

        expose :group_access, using: Entities::GroupAccess do |project, options|
835
          if project.group
836 837 838
            if options.key?(:group_members)
              (options[:group_members] || []).find { |member| member.source_id == project.namespace_id }
            else
839
              project.group.group_member(options[:current_user])
840
            end
841
          end
842 843
        end
      end
844 845 846 847 848 849 850 851 852 853 854 855 856 857

      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
858
    end
859

860
    class LabelBasic < Grape::Entity
Rares Sfirlogea's avatar
Rares Sfirlogea committed
861
      expose :id, :name, :color, :description
862 863 864
    end

    class Label < LabelBasic
865
      expose :open_issues_count do |label, options|
Francesco Coda Zabetta's avatar
Francesco Coda Zabetta committed
866 867
        label.open_issues_count(options[:current_user])
      end
868

Francesco Coda Zabetta's avatar
Francesco Coda Zabetta committed
869 870 871
      expose :closed_issues_count do |label, options|
        label.closed_issues_count(options[:current_user])
      end
872

Francesco Coda Zabetta's avatar
Francesco Coda Zabetta committed
873 874
      expose :open_merge_requests_count do |label, options|
        label.open_merge_requests_count(options[:current_user])
875 876
      end

877 878 879
      expose :priority do |label, options|
        label.priority(options[:project])
      end
880 881

      expose :subscribed do |label, options|
882
        label.subscribed?(options[:current_user], options[:project])
883
      end
884
    end
885

886 887 888 889 890 891 892 893
    class List < Grape::Entity
      expose :id
      expose :label, using: Entities::LabelBasic
      expose :position
    end

    class Board < Grape::Entity
      expose :id
894
      expose :project, using: Entities::BasicProjectDetails
895 896 897

      # EE-specific
      # Default filtering configuration
898 899
      expose :name
      expose :group
900 901 902 903
      expose :milestone, using: Entities::Milestone, if: -> (board, _) { scoped_issue_available?(board) }
      expose :assignee, using: Entities::UserBasic, if: -> (board, _) { scoped_issue_available?(board) }
      expose :labels, using: Entities::LabelBasic, if: -> (board, _) { scoped_issue_available?(board) }
      expose :weight, if: -> (board, _) { scoped_issue_available?(board) }
904

905 906 907
      expose :lists, using: Entities::List do |board|
        board.lists.destroyable
      end
908 909 910 911

      def scoped_issue_available?(board)
        board.parent.feature_available?(:scoped_issue_board)
      end
912 913
    end

914
    class Compare < Grape::Entity
915 916
      expose :commit, using: Entities::Commit do |compare, options|
        ::Commit.decorate(compare.commits, nil).last
917
      end
918

919 920
      expose :commits, using: Entities::Commit do |compare, options|
        ::Commit.decorate(compare.commits, nil)
921
      end
922

923
      expose :diffs, using: Entities::Diff do |compare, options|
Douwe Maan's avatar
Douwe Maan committed
924
        compare.diffs(limits: false).to_a
925
      end
926 927

      expose :compare_timeout do |compare, options|
928
        compare.diffs.overflow?
929 930 931
      end

      expose :same, as: :compare_same_ref
932
    end
933 934 935 936

    class Contributor < Grape::Entity
      expose :name, :email, :commits, :additions, :deletions
    end
937 938 939 940

    class BroadcastMessage < Grape::Entity
      expose :message, :starts_at, :ends_at, :color, :font
    end
941 942 943

    class ApplicationSetting < Grape::Entity
      expose :id
Lin Jen-Shin's avatar
Lin Jen-Shin committed
944
      expose(*::ApplicationSettingsHelper.visible_attributes)
945 946 947
      expose(*EE::ApplicationSettingsHelper.repository_mirror_attributes, if: lambda do |_instance, _options|
        ::License.feature_available?(:repository_mirrors)
      end)
948 949 950 951 952 953
      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) }
954 955 956 957

      # 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
958
    end
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
959 960

    class Release < Grape::Entity
961 962
      expose :tag, as: :tag_name
      expose :description
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
963
    end
964

965
    class Tag < Grape::Entity
966
      expose :name, :message
967

968
      expose :commit, using: Entities::Commit do |repo_tag, options|
969
        options[:project].repository.commit(repo_tag.dereferenced_target)
970 971
      end

972 973
      expose :release, using: Entities::Release do |repo_tag, options|
        options[:project].releases.find_by(tag: repo_tag.name)
974 975
      end
    end
976

977
    class GitlabLicense < Grape::Entity
978
      expose :starts_at, :expires_at, :licensee, :add_ons
979 980 981 982 983 984 985 986 987

      expose :user_limit do |license, options|
        license.restricted?(:active_user_count) ? license.restrictions[:active_user_count] : 0
      end

      expose :active_users do |license, options|
        ::User.active.count
      end
    end
988

Kamil Trzcinski's avatar
Kamil Trzcinski committed
989 990 991
    class TriggerRequest < Grape::Entity
      expose :id, :variables
    end
992 993 994 995 996 997 998 999 1000

    class Runner < Grape::Entity
      expose :id
      expose :description
      expose :active
      expose :is_shared
      expose :name
    end

1001 1002
    class RunnerDetails < Runner
      expose :tag_list
1003
      expose :run_untagged
1004
      expose :locked
1005
      expose :access_level
1006
      expose :version, :revision, :platform, :architecture
1007
      expose :contacted_at
1008
      expose :token, if: lambda { |runner, options| options[:current_user].admin? || !runner.is_shared? }
1009
      expose :projects, with: Entities::BasicProjectDetails do |runner, options|
1010
        if options[:current_user].admin?
1011 1012
          runner.projects
        else
1013
          options[:current_user].authorized_projects.where(id: runner.projects)
1014 1015
        end
      end
1016 1017
    end

1018 1019 1020 1021
    class RunnerRegistrationDetails < Grape::Entity
      expose :id, :token
    end

1022
    class JobArtifactFile < Grape::Entity
1023 1024 1025
      expose :filename, :size
    end

1026 1027 1028 1029
    class PipelineBasic < Grape::Entity
      expose :id, :sha, :ref, :status
    end

Tomasz Maczukin's avatar
Tomasz Maczukin committed
1030
    class JobBasic < Grape::Entity
1031 1032
      expose :id, :status, :stage, :name, :ref, :tag, :coverage
      expose :created_at, :started_at, :finished_at
1033
      expose :duration
1034
      expose :user, with: User
1035
      expose :commit, with: Commit
1036
      expose :pipeline, with: PipelineBasic
1037 1038
    end

Tomasz Maczukin's avatar
Tomasz Maczukin committed
1039 1040 1041 1042 1043 1044
    class Job < JobBasic
      expose :artifacts_file, using: JobArtifactFile, if: -> (job, opts) { job.artifacts? }
      expose :runner, with: Runner
    end

    class JobBasicWithProject < JobBasic
1045 1046 1047
      expose :project, with: ProjectIdentity
    end

1048
    class Trigger < Grape::Entity
1049
      expose :id
1050 1051 1052
      expose :token, :description
      expose :created_at, :updated_at, :deleted_at, :last_used
      expose :owner, using: Entities::UserBasic
1053 1054 1055 1056
    end

    class Variable < Grape::Entity
      expose :key, :value
1057
      expose :protected?, as: :protected, if: -> (entity, _) { entity.respond_to?(:protected?) }
1058 1059

      # EE
1060
      expose :environment_scope, if: ->(variable, options) {
1061 1062 1063
        if variable.respond_to?(:environment_scope)
          variable.project.feature_available?(:variable_environment_scope)
        end
1064
      }
1065
    end
1066

1067 1068
    class Pipeline < PipelineBasic
      expose :before_sha, :tag, :yaml_errors
1069 1070 1071 1072

      expose :user, with: Entities::UserBasic
      expose :created_at, :updated_at, :started_at, :finished_at, :committed_at
      expose :duration
1073
      expose :coverage
1074 1075
    end

1076 1077 1078
    class PipelineSchedule < Grape::Entity
      expose :id
      expose :description, :ref, :cron, :cron_timezone, :next_run_at, :active
1079
      expose :created_at, :updated_at
1080 1081 1082
      expose :owner, using: Entities::UserBasic
    end

Shinya Maeda's avatar
Shinya Maeda committed
1083 1084
    class PipelineScheduleDetails < PipelineSchedule
      expose :last_pipeline, using: Entities::PipelineBasic
1085
      expose :variables, using: Entities::Variable
Shinya Maeda's avatar
Shinya Maeda committed
1086 1087
    end

1088
    class EnvironmentBasic < Grape::Entity
Nick Thomas's avatar
Nick Thomas committed
1089
      expose :id, :name, :slug, :external_url
1090 1091
    end

1092
    class Environment < EnvironmentBasic
1093
      expose :project, using: Entities::BasicProjectDetails
1094 1095 1096 1097 1098 1099
    end

    class Deployment < Grape::Entity
      expose :id, :iid, :ref, :sha, :created_at
      expose :user,        using: Entities::UserBasic
      expose :environment, using: Entities::EnvironmentBasic
1100
      expose :deployable,  using: Entities::Job
1101 1102
    end

1103
    class License < Grape::Entity
1104 1105
      expose :key, :name, :nickname
      expose :featured, as: :popular
1106 1107 1108
      expose :url, as: :html_url
      expose(:source_url) { |license| license.meta['source'] }
      expose(:description) { |license| license.meta['description'] }
1109 1110 1111
      expose(:conditions) { |license| license.meta['conditions'] }
      expose(:permissions) { |license| license.meta['permissions'] }
      expose(:limitations) { |license| license.meta['limitations'] }
1112 1113
      expose :content
    end
1114

1115
    class TemplatesList < Grape::Entity
1116 1117 1118
      expose :name
    end

1119
    class Template < Grape::Entity
1120 1121
      expose :name, :content
    end
1122 1123 1124 1125 1126

    class BroadcastMessage < Grape::Entity
      expose :id, :message, :starts_at, :ends_at, :color, :font
      expose :active?, as: :active
    end
1127

1128
    class GeoNode < Grape::Entity
1129
      expose :id
1130 1131 1132
      expose :url
      expose :primary?, as: :primary
      expose :enabled
1133
      expose :current?, as: :current
1134 1135
      expose :files_max_capacity
      expose :repos_max_capacity
1136 1137 1138 1139 1140

      # Retained for backwards compatibility. Remove in API v5
      expose :clone_protocol do |_record, _options|
        'http'
      end
Nick Thomas's avatar
Nick Thomas committed
1141 1142
    end

1143
    class PersonalAccessToken < Grape::Entity
1144 1145 1146 1147 1148 1149 1150
      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

1151
    class PersonalAccessTokenWithToken < PersonalAccessToken
1152 1153
      expose :token
    end
1154 1155 1156 1157

    class ImpersonationToken < PersonalAccessTokenWithToken
      expose :impersonation
    end
1158

1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
    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

1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
    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
1197

1198 1199 1200
      class RunnerInfo < Grape::Entity
        expose :timeout
      end
Tomasz Maczukin's avatar
Tomasz Maczukin committed
1201

1202
      class Step < Grape::Entity
Tomasz Maczukin's avatar
Tomasz Maczukin committed
1203
        expose :name, :script, :timeout, :when, :allow_failure
1204
      end
Tomasz Maczukin's avatar
Tomasz Maczukin committed
1205

1206
      class Image < Grape::Entity
1207 1208 1209
        expose :name, :entrypoint
      end

1210
      class Service < Image
1211
        expose :alias, :command
1212
      end
Tomasz Maczukin's avatar
Tomasz Maczukin committed
1213

1214 1215
      class Artifacts < Grape::Entity
        expose :name, :untracked, :paths, :when, :expire_in
Tomasz Maczukin's avatar
Tomasz Maczukin committed
1216 1217
      end

1218
      class Cache < Grape::Entity
1219
        expose :key, :untracked, :paths, :policy
Tomasz Maczukin's avatar
Tomasz Maczukin committed
1220 1221
      end

1222 1223 1224
      class Credentials < Grape::Entity
        expose :type, :url, :username, :password
      end
Tomasz Maczukin's avatar
Tomasz Maczukin committed
1225

1226
      class Dependency < Grape::Entity
1227
        expose :id, :name, :token
1228
        expose :artifacts_file, using: JobArtifactFile, if: ->(job, _) { job.artifacts? }
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
      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
1251
        expose :services, using: Service
1252 1253 1254
        expose :artifacts, using: Artifacts
        expose :cache, using: Cache
        expose :credentials, using: Credentials
1255
        expose :dependencies, using: Dependency
1256
        expose :features
1257
      end
1258
    end
1259 1260 1261 1262

    class UserAgentDetail < Grape::Entity
      expose :user_agent
      expose :ip_address
1263
      expose :submitted, as: :akismet_submitted
1264
    end
1265 1266 1267 1268 1269 1270

    class RepositoryStorageHealth < Grape::Entity
      expose :storage_name
      expose :failing_on_hosts
      expose :total_failures
    end
1271 1272 1273 1274 1275

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

1277 1278 1279 1280 1281
    class PagesDomainCertificateExpiration < Grape::Entity
      expose :expired?, as: :expired
      expose :expiration
    end

1282 1283 1284 1285 1286 1287 1288
    class PagesDomainCertificate < Grape::Entity
      expose :subject
      expose :expired?, as: :expired
      expose :certificate
      expose :certificate_text
    end

1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
    class PagesDomainBasic < Grape::Entity
      expose :domain
      expose :url
      expose :certificate,
        as: :certificate_expiration,
        if: ->(pages_domain, _) { pages_domain.certificate? },
        using: PagesDomainCertificateExpiration do |pages_domain|
        pages_domain
      end
    end

1300 1301 1302 1303
    class PagesDomain < Grape::Entity
      expose :domain
      expose :url
      expose :certificate,
1304 1305
        if: ->(pages_domain, _) { pages_domain.certificate? },
        using: PagesDomainCertificate do |pages_domain|
1306 1307 1308
        pages_domain
      end
    end
Nihad Abbasov's avatar
Nihad Abbasov committed
1309 1310
  end
end