• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

pulibrary / pdc_describe / aa4d17ae-5b88-4b80-9b41-f98c7bc03ef4

pending completion
aa4d17ae-5b88-4b80-9b41-f98c7bc03ef4

Pull #1060

circleci

jrgriffiniii
wip
Pull Request #1060: [wip] Integrating Support for Upload Snapshots

152 of 152 new or added lines in 7 files covered. (100.0%)

2016 of 2058 relevant lines covered (97.96%)

171.45 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

97.14
/app/models/work.rb
1
# frozen_string_literal: true
2

3
# rubocop:disable Metrics/ClassLength
4
class Work < ApplicationRecord
1✔
5
  # Errors for cases where there is no valid Collection
6
  class InvalidCollectionError < ::ArgumentError; end
1✔
7

8
  has_many :work_activity, -> { order(updated_at: :desc) }, dependent: :destroy
186✔
9
  has_many :user_work, -> { order(updated_at: :desc) }, dependent: :destroy
9✔
10
  has_many :upload_snapshots, -> { order(updated_at: :desc) }, dependent: :destroy
6✔
11
  has_many_attached :pre_curation_uploads, service: :amazon_pre_curation
1✔
12

13
  belongs_to :collection
1✔
14
  belongs_to :curator, class_name: "User", foreign_key: "curator_user_id", optional: true
1✔
15

16
  attribute :work_type, :string, default: "DATASET"
1✔
17
  attribute :profile, :string, default: "DATACITE"
1✔
18

19
  attr_accessor :user_entered_doi
1✔
20

21
  alias state_history user_work
1✔
22

23
  include AASM
1✔
24

25
  aasm column: :state do
1✔
26
    state :none, inital: true
1✔
27
    state :draft, :awaiting_approval, :approved, :withdrawn, :tombstone
1✔
28

29
    event :draft, after: :draft_doi do
1✔
30
      transitions from: :none, to: :draft, guard: :valid_to_draft
1✔
31
    end
32

33
    event :complete_submission do
1✔
34
      transitions from: :draft, to: :awaiting_approval, guard: :valid_to_submit
1✔
35
    end
36

37
    event :request_changes do
1✔
38
      transitions from: :awaiting_approval, to: :awaiting_approval, guard: :valid_to_submit
1✔
39
    end
40

41
    event :approve do
1✔
42
      transitions from: :awaiting_approval, to: :approved, guard: :valid_to_approve, after: :publish
1✔
43
    end
44

45
    event :withdraw do
1✔
46
      transitions from: [:draft, :awaiting_approval, :approved], to: :withdrawn
1✔
47
    end
48

49
    event :resubmit do
1✔
50
      transitions from: :withdrawn, to: :draft
1✔
51
    end
52

53
    event :remove do
1✔
54
      transitions from: :withdrawn, to: :tombstone
1✔
55
    end
56

57
    after_all_events :track_state_change
1✔
58
  end
59

60
  def state=(new_state)
1✔
61
    new_state_sym = new_state.to_sym
346✔
62
    valid_states = self.class.aasm.states.map(&:name)
346✔
63
    raise(StandardError, "Invalid state '#{new_state}'") unless valid_states.include?(new_state_sym)
346✔
64
    aasm_write_state_without_persistence(new_state_sym)
345✔
65
  end
66

67
  ##
68
  # Is this work editable by a given user?
69
  # A work is editable when:
70
  # * it is being edited by the person who made it
71
  # * it is being edited by a collection admin of the collection where is resides
72
  # * it is being edited by a super admin
73
  # @param [User]
74
  # @return [Boolean]
75
  def editable_by?(user)
1✔
76
    submitted_by?(user) || administered_by?(user)
264✔
77
  end
78

79
  def editable_in_current_state?(user)
1✔
80
    # anyone with edit privleges can edit a work while it is in draft or awaiting approval
81
    return editable_by?(user) if draft? || awaiting_approval?
202✔
82

83
    # Only admisitrators can edit a work in other states
84
    administered_by?(user)
35✔
85
  end
86

87
  def submitted_by?(user)
1✔
88
    created_by_user_id == user.id
264✔
89
  end
90

91
  def administered_by?(user)
1✔
92
    user.has_role?(:collection_admin, collection)
88✔
93
  end
94

95
  class << self
1✔
96
    def find_by_doi(doi)
1✔
97
      prefix = "10.34770/"
3✔
98
      doi = "#{prefix}#{doi}" unless doi.start_with?(prefix)
3✔
99
      Work.find_by!("metadata @> ?", JSON.dump(doi: doi))
3✔
100
    end
101

102
    def find_by_ark(ark)
1✔
103
      prefix = "ark:/"
3✔
104
      ark = "#{prefix}#{ark}" unless ark.start_with?(prefix)
3✔
105
      Work.find_by!("metadata @> ?", JSON.dump(ark: ark))
3✔
106
    end
107

108
    delegate :resource_type_general_values, to: PDCMetadata::Resource
1✔
109

110
    # Determines whether or not a test DOI should be referenced
111
    # (this avoids requests to the DOI API endpoint for non-production deployments)
112
    # @return [Boolean]
113
    def publish_test_doi?
1✔
114
      (Rails.env.development? || Rails.env.test?) && Rails.configuration.datacite.user.blank?
48✔
115
    end
116
  end
117

118
  include Rails.application.routes.url_helpers
1✔
119

120
  before_save do |work|
1✔
121
    # Ensure that the metadata JSONB postgres field is persisted properly
122
    work.metadata = JSON.parse(work.resource.to_json)
738✔
123
    work.save_pre_curation_uploads
738✔
124
  end
125

126
  after_save do |work|
1✔
127
    if work.approved?
737✔
128
      work.reload
93✔
129
    end
130
  end
131

132
  validate do |work|
1✔
133
    if none?
764✔
134
      work.validate_doi
105✔
135
    elsif draft?
659✔
136
      work.valid_to_draft
424✔
137
    else
138
      work.valid_to_submit
235✔
139
    end
140
  end
141

142
  # Overload ActiveRecord.reload method
143
  # https://apidock.com/rails/ActiveRecord/Base/reload
144
  #
145
  # NOTE: Usually `after_save` is a better place to put this kind of code:
146
  #
147
  #   after_save do |work|
148
  #     work.resource = nil
149
  #   end
150
  #
151
  # but that does not work in this case because the block points to a different
152
  # memory object for `work` than the we want we want to reload.
153
  def reload(options = nil)
1✔
154
    super
188✔
155
    # Force `resource` to be reloaded
156
    @resource = nil
188✔
157
    self
188✔
158
  end
159

160
  def validate_doi
1✔
161
    return true unless user_entered_doi
105✔
162
    if /^10.\d{4,9}\/[-._;()\/:a-z0-9\-]+$/.match?(doi.downcase)
15✔
163
      response = Faraday.get("#{Rails.configuration.datacite.doi_url}#{doi}")
14✔
164
      errors.add(:base, "Invalid DOI: can not verify it's authenticity") unless response.success? || response.status == 302
14✔
165
    else
166
      errors.add(:base, "Invalid DOI: does not match format")
1✔
167
    end
168
    errors.count == 0
15✔
169
  end
170

171
  def valid_to_draft
1✔
172
    errors.add(:base, "Must provide a title") if resource.main_title.blank?
773✔
173
    validate_ark
773✔
174
    validate_creators
773✔
175
    errors.count == 0
773✔
176
  end
177

178
  def valid_to_submit
1✔
179
    valid_to_draft
314✔
180
    validate_metadata
314✔
181
    errors.count == 0
314✔
182
  end
183

184
  def valid_to_approve(user)
1✔
185
    valid_to_submit
35✔
186
    unless user.has_role? :collection_admin, collection
35✔
187
      errors.add :base, "Unauthorized to Approve"
4✔
188
    end
189
    errors.count == 0
35✔
190
  end
191

192
  def title
1✔
193
    resource.main_title
319✔
194
  end
195

196
  def uploads_attributes
1✔
197
    return [] if approved? # once approved we no longer allow the updating of uploads via the application
56✔
198
    uploads.map do |upload|
52✔
199
      {
200
        id: upload.id,
19✔
201
        key: upload.key,
202
        filename: upload.filename.to_s,
203
        created_at: upload.created_at,
204
        url: upload.url
205
      }
206
    end
207
  end
208

209
  def form_attributes
1✔
210
    {
211
      uploads: uploads_attributes
56✔
212
    }
213
  end
214

215
  def draft_doi
1✔
216
    return if resource.doi.present?
36✔
217
    resource.doi = if self.class.publish_test_doi?
20✔
218
                     Rails.logger.info "Using hard-coded test DOI during development."
1✔
219
                     "10.34770/tbd"
1✔
220
                   else
221
                     result = data_cite_connection.autogenerate_doi(prefix: Rails.configuration.datacite.prefix)
19✔
222
                     if result.success?
19✔
223
                       result.success.doi
18✔
224
                     else
225
                       raise("Error generating DOI. #{result.failure.status} / #{result.failure.reason_phrase}")
1✔
226
                     end
227
                   end
228
    save!
19✔
229
  end
230

231
  def created_by_user
1✔
232
    User.find(created_by_user_id)
350✔
233
  rescue ActiveRecord::RecordNotFound
234
    nil
1✔
235
  end
236

237
  def resource=(resource)
1✔
238
    @resource = resource
492✔
239
    # Ensure that the metadata JSONB postgres field is persisted properly
240
    self.metadata = JSON.parse(resource.to_json)
492✔
241
  end
242

243
  def resource
1✔
244
    @resource ||= PDCMetadata::Resource.new_from_jsonb(metadata)
14,266✔
245
  end
246

247
  def url
1✔
248
    return unless persisted?
3✔
249

250
    @url ||= url_for(self)
3✔
251
  end
252

253
  def files_location_upload?
1✔
254
    files_location.blank? || files_location == "file_upload"
6✔
255
  end
256

257
  def files_location_cluster?
1✔
258
    files_location == "file_cluster"
63✔
259
  end
260

261
  def files_location_other?
1✔
262
    files_location == "file_other"
63✔
263
  end
264

265
  def change_curator(curator_user_id, current_user)
1✔
266
    if curator_user_id == "no-one"
5✔
267
      clear_curator(current_user)
1✔
268
    else
269
      update_curator(curator_user_id, current_user)
4✔
270
    end
271
  end
272

273
  def clear_curator(current_user)
1✔
274
    # Update the curator on the Work
275
    self.curator_user_id = nil
2✔
276
    save!
2✔
277

278
    # ...and log the activity
279
    WorkActivity.add_work_activity(id, "Unassigned existing curator", current_user.id, activity_type: WorkActivity::SYSTEM)
2✔
280
  end
281

282
  def update_curator(curator_user_id, current_user)
1✔
283
    # Update the curator on the Work
284
    self.curator_user_id = curator_user_id
5✔
285
    save!
5✔
286

287
    # ...and log the activity
288
    new_curator = User.find(curator_user_id)
4✔
289
    message = if curator_user_id == current_user.id
4✔
290
                "Self-assigned as curator"
1✔
291
              else
292
                "Set curator to @#{new_curator.uid}"
3✔
293
              end
294
    WorkActivity.add_work_activity(id, message, current_user.id, activity_type: WorkActivity::SYSTEM)
4✔
295
  end
296

297
  def curator_or_current_uid(user)
1✔
298
    persisted = if curator.nil?
12✔
299
                  user
11✔
300
                else
301
                  curator
1✔
302
                end
303
    persisted.uid
12✔
304
  end
305

306
  def add_message(message, current_user_id)
1✔
307
    WorkActivity.add_work_activity(id, message, current_user_id, activity_type: WorkActivity::MESSAGE)
11✔
308
  end
309

310
  def add_provenance_note(date, note, current_user_id)
1✔
311
    WorkActivity.add_work_activity(id, note, current_user_id, activity_type: WorkActivity::PROVENANCE_NOTES, created_at: date)
1✔
312
  end
313

314
  def log_changes(resource_compare, current_user_id)
1✔
315
    return if resource_compare.identical?
42✔
316
    WorkActivity.add_work_activity(id, resource_compare.differences.to_json, current_user_id, activity_type: WorkActivity::CHANGES)
40✔
317
  end
318

319
  def log_file_changes(changes, current_user_id)
1✔
320
    return if changes.count == 0
13✔
321
    WorkActivity.add_work_activity(id, changes.to_json, current_user_id, activity_type: WorkActivity::FILE_CHANGES)
13✔
322
  end
323

324
  def activities
1✔
325
    WorkActivity.activities_for_work(id, WorkActivity::MESSAGE_ACTIVITY_TYPES + WorkActivity::CHANGE_LOG_ACTIVITY_TYPES)
81✔
326
  end
327

328
  def new_notification_count_for_user(user_id)
1✔
329
    WorkActivityNotification.joins(:work_activity)
82✔
330
                            .where(user_id: user_id, read_at: nil)
331
                            .where(work_activity: { work_id: id })
332
                            .count
333
  end
334

335
  # Marks as read the notifications for the given user_id in this work.
336
  # In practice, the user_id is the id of the current user and therefore this method marks the current's user
337
  # notifications as read.
338
  def mark_new_notifications_as_read(user_id)
1✔
339
    activities.each do |activity|
81✔
340
      unread_notifications = WorkActivityNotification.where(user_id: user_id, work_activity_id: activity.id, read_at: nil)
114✔
341
      unread_notifications.each do |notification|
114✔
342
        notification.read_at = Time.now.utc
26✔
343
        notification.save
26✔
344
      end
345
    end
346
  end
347

348
  def current_transition
1✔
349
    aasm.current_event.to_s.humanize.delete("!")
16✔
350
  end
351

352
  def uploads
1✔
353
    return post_curation_uploads if approved?
595✔
354

355
    pre_curation_uploads_fast
526✔
356
  end
357

358
  def pre_curation_s3_files
1✔
359
    loaded = pre_curation_uploads.sort_by(&:filename)
280✔
360

361
    loaded.map do |attachment|
280✔
362
      S3File.new(
28✔
363
        work: self,
364
        filename: attachment.key,
365
        last_modified: attachment.created_at,
366
        size: attachment.byte_size,
367
        checksum: attachment.checksum
368
      )
369
    end
370
  end
371

372
  # Fetches the data from S3 directly bypassing ActiveStorage
373
  def pre_curation_uploads_fast
1✔
374
    return local_pre_curation_s3_files if Rails.env.development?
651✔
375

376
    s3_query_service.client_s3_files.sort_by(&:filename)
651✔
377
  end
378

379
  # This ensures that new ActiveStorage::Attachment objects can be modified before they are persisted
380
  def save_pre_curation_uploads
1✔
381
    return if pre_curation_uploads.empty?
738✔
382

383
    new_attachments = pre_curation_uploads.reject(&:persisted?)
42✔
384
    return if new_attachments.empty?
42✔
385

386
    save_new_attachments(new_attachments: new_attachments)
30✔
387
  end
388

389
  # Accesses post-curation S3 Bucket Objects
390
  def post_curation_s3_resources
1✔
391
    return [] unless approved?
160✔
392

393
    s3_resources
103✔
394
  end
395
  alias post_curation_uploads post_curation_s3_resources
1✔
396

397
  def s3_files
1✔
398
    return s3_resources if approved?
328✔
399

400
    pre_curation_s3_files
280✔
401
  end
402

403
  def s3_client
1✔
404
    s3_query_service.client
22✔
405
  end
406

407
  delegate :bucket_name, to: :s3_query_service
1✔
408

409
  # Generates the S3 Object key
410
  # @return [String]
411
  def s3_object_key
1✔
412
    "#{doi}/#{id}"
51✔
413
  end
414

415
  # Transmit a HEAD request for the S3 Bucket directory for this Work
416
  # @param bucket_name location to be checked to be found
417
  # @return [Aws::S3::Types::HeadObjectOutput]
418
  def find_post_curation_s3_dir(bucket_name:)
1✔
419
    # TODO: Directories really do not exists in S3
420
    #      if we really need this check then we need to do something else to check the bucket
421
    s3_client.head_object({
22✔
422
                            bucket: bucket_name,
423
                            key: s3_object_key
424
                          })
425
    true
×
426
  rescue Aws::S3::Errors::NotFound
427
    nil
22✔
428
  end
429

430
  def as_json(*)
1✔
431
    # Pre-curation files are not accessible externally,
432
    # so we are not interested in listing them in JSON.
433
    # (The items in pre_curation_uploads also have different properties.)
434
    files = post_curation_uploads.map do |upload|
79✔
435
      {
436
        "filename": upload.filename,
42✔
437
        "size": upload.size,
438
        "url": upload.globus_url
439
      }
440
    end
441

442
    # to_json returns a string of serialized JSON.
443
    # as_json returns the corresponding hash.
444
    {
445
      "resource" => resource.as_json,
79✔
446
      "files" => files,
447
      "collection" => collection.as_json.except("id")
448
    }
449
  end
450

451
  def pre_curation_uploads_count
1✔
452
    s3_query_service.file_count
2✔
453
  end
454

455
  delegate :ark, :doi, :resource_type, :resource_type=, :resource_type_general, :resource_type_general=,
1✔
456
           :to_xml, to: :resource
457

458
  # S3QueryService object associated with this Work
459
  # @return [S3QueryService]
460
  def s3_query_service
1✔
461
    @s3_query_service ||= S3QueryService.new(self, !approved?)
914✔
462
  end
463

464
  def reload_snapshots
1✔
465
    results = s3_files.map do |s3_file|
82✔
466
      UploadSnapshot.find_or_initialize_by(url: s3_file.url, filename: s3_file.filename, work: self)
21✔
467
    end
468

469
    s3_resource_urls = s3_files.map(&:url)
82✔
470
    s3_resource_filenames = s3_files.map(&:filename)
82✔
471

472
    # remove the snapshots for s3 file resources which have been deleted
473
    persisted = results.reject do |snapshot|
82✔
474
      removed = !s3_resource_urls.include?(snapshot.url) && !s3_resource_filenames.include?(snapshot.filename)
21✔
475

476
      if removed
21✔
477
        snapshot.destroy
×
478
        changes = {
×
479
          action: "removed"
480
        }
481
        WorkActivity.add_work_activity(id, changes.to_json, nil, activity_type: WorkActivity::FILE_CHANGES)
×
482
      end
483

484
      removed
21✔
485
    end
486

487
    s3_files.map do |s3_file|
82✔
488
      s3_match = s3_file.filename.match(/_\d+_/)
21✔
489
      s3_filename = if s3_match
21✔
490
                      s3_file.filename.gsub(/_\d+\.([0-9a-zA-Z]+)$/, ".\\1")
1✔
491
                    else
492
                      s3_file.filename
20✔
493
                    end
494

495
      selected = persisted.select do |s|
21✔
496
        # checking for version substrings
497
        snapshot_match = s.filename.match(/_\d+_/)
37✔
498
        s_filename = if snapshot_match
37✔
499
                       s.filename.gsub(/_\d+\.([0-9a-zA-Z]+)$/, ".\\1")
2✔
500
                     else
501
                       s.filename
35✔
502
                     end
503

504
        s_filename == s3_filename
37✔
505
      end
506
      snapshot = selected.last
21✔
507

508
      if snapshot.checksum != s3_file.checksum
21✔
509

510
        # cases where the s3 resources are replaced
511
        snapshot.checksum = s3_file.checksum
21✔
512
        changes = if !snapshot.persisted?
21✔
513
                    {
20✔
514
                      action: "added"
515
                    }
516
                  else
517
                    {
1✔
518
                      action: "replaced"
519
                    }
520
                  end
521
        snapshot.save
21✔
522

523
        WorkActivity.add_work_activity(id, changes.to_json, nil, activity_type: WorkActivity::FILE_CHANGES)
21✔
524
      end
525

526
      snapshot.reload
21✔
527
    end
528
  end
529

530
  protected
1✔
531

532
    # This must be protected, NOT private for ActiveRecord to work properly with this attribute.
533
    #   Protected will still keep others from setting the metatdata, but allows ActiveRecord the access it needs
534
    def metadata=(metadata)
1✔
535
      super
1,230✔
536
      @resource = PDCMetadata::Resource.new_from_jsonb(metadata)
1,230✔
537
    end
538

539
  private
1✔
540

541
    def publish(user)
1✔
542
      publish_doi(user)
30✔
543
      update_ark_information
30✔
544
      publish_precurated_files
30✔
545
      save!
30✔
546
    end
547

548
    # Update EZID (our provider of ARKs) with the new information for this work.
549
    def update_ark_information
1✔
550
      # We only want to update the ark url under certain conditions.
551
      # Set this value in config/update_ark_url.yml
552
      if Rails.configuration.update_ark_url
30✔
553
        if ark.present?
12✔
554
          Ark.update(ark, url)
3✔
555
        end
556
      end
557
    end
558

559
    # Generates the key for ActiveStorage::Attachment and Attachment::Blob objects
560
    # @param attachment [ActiveStorage::Attachment]
561
    # @return [String]
562
    def generate_attachment_key(attachment)
1✔
563
      attachment_filename = attachment.filename.to_s
26✔
564
      attachment_key = attachment.key
26✔
565

566
      # Files actually coming from S3 include the DOI and bucket as part of the file name
567
      #  Files being attached in another manner may not have it, so we should include it.
568
      #  This is really for testing only.
569
      key_base = "#{doi}/#{id}"
26✔
570
      attachment_key = [key_base, attachment_filename].join("/") unless attachment_key.include?(key_base)
26✔
571

572
      attachment_ext = File.extname(attachment_filename)
26✔
573
      attachment_query = attachment_key.gsub(attachment_ext, "")
26✔
574
      results = ActiveStorage::Blob.where("key LIKE :query", query: "%#{attachment_query}%")
26✔
575
      blobs = results.to_a
26✔
576

577
      if blobs.present?
26✔
578
        index = blobs.length + 1
3✔
579
        attachment_key = attachment_key.gsub(/\.([a-zA-Z0-9\.]+)$/, "_#{index}.\\1")
3✔
580
      end
581

582
      attachment_key
26✔
583
    end
584

585
    def track_state_change(user, state = aasm.to_state)
1✔
586
      uw = UserWork.new(user_id: user.id, work_id: id, state: state)
140✔
587
      uw.save!
140✔
588
      WorkActivity.add_work_activity(id, "marked as #{state.to_s.titleize}", user.id, activity_type: WorkActivity::SYSTEM)
140✔
589
      WorkStateTransitionNotification.new(self, user.id).send
140✔
590
    end
591

592
    def data_cite_connection
1✔
593
      @data_cite_connection ||= Datacite::Client.new(username: Rails.configuration.datacite.user,
45✔
594
                                                     password: Rails.configuration.datacite.password,
595
                                                     host: Rails.configuration.datacite.host)
596
    end
597

598
    def validate_ark
1✔
599
      return if ark.blank?
773✔
600
      first_save = id.blank?
144✔
601
      changed_value = metadata["ark"] != ark
144✔
602
      if first_save || changed_value
144✔
603
        errors.add(:base, "Invalid ARK provided for the Work: #{ark}") unless Ark.valid?(ark)
51✔
604
      end
605
    end
606

607
    # rubocop:disable Metrics/AbcSize
608
    def validate_metadata
1✔
609
      return if metadata.blank?
314✔
610
      errors.add(:base, "Must provide a title") if resource.main_title.blank?
314✔
611
      errors.add(:base, "Must provide a description") if resource.description.blank?
314✔
612
      errors.add(:base, "Must indicate the Publisher") if resource.publisher.blank?
314✔
613
      errors.add(:base, "Must indicate the Publication Year") if resource.publication_year.blank?
314✔
614
      errors.add(:base, "Must indicate a Rights statement") if resource.rights.nil?
314✔
615
      errors.add(:base, "Must provide a Version number") if resource.version_number.blank?
314✔
616
      validate_creators
314✔
617
      validate_related_objects
314✔
618
    end
619
    # rubocop:enable Metrics/AbcSize
620

621
    def validate_creators
1✔
622
      if resource.creators.count == 0
1,087✔
623
        errors.add(:base, "Must provide at least one Creator")
1✔
624
      else
625
        resource.creators.each do |creator|
1,086✔
626
          if creator.orcid.present? && Orcid.invalid?(creator.orcid)
1,839✔
627
            errors.add(:base, "ORCID for creator #{creator.value} is not in format 0000-0000-0000-0000")
1✔
628
          end
629
        end
630
      end
631
    end
632

633
    def validate_related_objects
1✔
634
      return if resource.related_objects.empty?
314✔
635
      invalid = resource.related_objects.reject(&:valid?)
6✔
636
      errors.add(:base, "Related Objects are invalid: #{invalid.map(&:errors).join(', ')}") if invalid.count.positive?
6✔
637
    end
638

639
    def publish_doi(user)
1✔
640
      return Rails.logger.info("Publishing hard-coded test DOI during development.") if self.class.publish_test_doi?
28✔
641

642
      if doi.starts_with?(Rails.configuration.datacite.prefix)
28✔
643
        result = data_cite_connection.update(id: doi, attributes: doi_attributes)
26✔
644
        if result.failure?
26✔
645
          resolved_user = curator_or_current_uid(user)
11✔
646
          message = "@#{resolved_user} Error publishing DOI. #{result.failure.status} / #{result.failure.reason_phrase}"
11✔
647
          WorkActivity.add_work_activity(id, message, user.id, activity_type: WorkActivity::DATACITE_ERROR)
11✔
648
        end
649
      elsif ark.blank? # we can not update the url anywhere
2✔
650
        Honeybadger.notify("Publishing for a DOI we do not own and no ARK is present: #{doi}")
1✔
651
      end
652
    end
653

654
    def doi_attribute_url
1✔
655
      "https://datacommons.princeton.edu/discovery/doi/#{doi}"
26✔
656
    end
657

658
    def doi_attribute_resource
1✔
659
      PDCMetadata::Resource.new_from_jsonb(metadata)
26✔
660
    end
661

662
    def doi_attribute_xml
1✔
663
      unencoded = doi_attribute_resource.to_xml
26✔
664
      Base64.encode64(unencoded)
26✔
665
    end
666

667
    def doi_attributes
1✔
668
      {
669
        "event" => "publish",
26✔
670
        "xml" => doi_attribute_xml,
671
        "url" => doi_attribute_url
672
      }
673
    end
674

675
    # This needs to be called #before_save
676
    # This ensures that new ActiveStorage::Attachment objects are persisted with custom keys (which are generated from the file name and DOI)
677
    # @param new_attachments [Array<ActiveStorage::Attachment>]
678
    def save_new_attachments(new_attachments:)
1✔
679
      new_attachments.each do |attachment|
30✔
680
        # There are cases (race conditions?) where the ActiveStorage::Blob objects are not persisted
681
        next if attachment.frozen?
30✔
682

683
        # This ensures that the custom key for the ActiveStorage::Attachment and ActiveStorage::Blob objects are generated
684
        generated_key = generate_attachment_key(attachment)
26✔
685
        attachment.blob.key = generated_key
26✔
686
        attachment.blob.save
26✔
687

688
        attachment.save
26✔
689
      end
690
    end
691

692
    # Request S3 Bucket Objects associated with this Work
693
    # @return [Array<S3File>]
694
    def s3_resources
1✔
695
      data_profile = s3_query_service.data_profile
151✔
696
      data_profile.fetch(:objects, [])
151✔
697
    end
698
    alias pre_curation_s3_resources s3_resources
1✔
699

700
    def s3_object_persisted?(s3_file)
1✔
701
      uploads_keys = uploads.map(&:key)
×
702
      uploads_keys.include?(s3_file.key)
×
703
    end
704

705
    def add_pre_curation_s3_object(s3_file)
1✔
706
      return if s3_object_persisted?(s3_file)
×
707

708
      persisted = s3_file.to_blob
×
709
      pre_curation_uploads.attach(persisted)
×
710
    end
711

712
    def publish_precurated_files
1✔
713
      # An error is raised if there are no files to be moved
714
      raise(StandardError, "Attempting to publish a Work without attached uploads for #{s3_object_key}") if pre_curation_uploads_fast.empty? && post_curation_uploads.empty?
22✔
715

716
      # We need to explicitly access to post-curation services here.
717
      # Lets explicitly create it so the state of the work does not have any impact.
718
      s3_post_curation_query_service = S3QueryService.new(self, false)
22✔
719

720
      s3_dir = find_post_curation_s3_dir(bucket_name: s3_post_curation_query_service.bucket_name)
22✔
721
      raise(StandardError, "Attempting to publish a Work with an existing S3 Bucket directory for: #{s3_object_key}") unless s3_dir.nil?
22✔
722

723
      # Copy the pre-curation S3 Objects to the post-curation S3 Bucket...
724
      transferred_file_errors = s3_query_service.publish_files
22✔
725

726
      # ...check that the files are indeed now in the post-curation bucket...
727
      if transferred_file_errors.count > 0
22✔
728
        raise(StandardError, "Failed to validate the uploaded S3 Object #{transferred_file_errors.map(&:key).join(', ')}")
×
729
      end
730
    end
731
end
732
# rubocop:enable Metrics/ClassLength
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc