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

pulibrary / pdc_describe / e2b7cc8f-6e85-4359-a4fd-10005487ea11

pending completion
e2b7cc8f-6e85-4359-a4fd-10005487ea11

Pull #1060

circleci

Carolyn Cole
Removing UploadSnapshotController
Pull Request #1060: Integrating Support for Upload Snapshots

89 of 89 new or added lines in 6 files covered. (100.0%)

1955 of 2196 relevant lines covered (89.03%)

164.96 hits per line

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

96.53
/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
201✔
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
359✔
62
    valid_states = self.class.aasm.states.map(&:name)
359✔
63
    raise(StandardError, "Invalid state '#{new_state}'") unless valid_states.include?(new_state_sym)
359✔
64
    aasm_write_state_without_persistence(new_state_sym)
358✔
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)
205✔
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?
129✔
82

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

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

91
  def administered_by?(user)
1✔
92
    user.has_role?(:collection_admin, collection)
64✔
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?
44✔
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)
763✔
123
    work.save_pre_curation_uploads
763✔
124
  end
125

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

132
  validate do |work|
1✔
133
    if none?
795✔
134
      work.validate_doi
123✔
135
    elsif draft?
672✔
136
      work.valid_to_draft
452✔
137
    else
138
      work.valid_to_submit
220✔
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
183✔
155
    # Force `resource` to be reloaded
156
    @resource = nil
183✔
157
    self
183✔
158
  end
159

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

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

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

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

192
  def title
1✔
193
    resource.main_title
341✔
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
61✔
198
    uploads.map do |upload|
57✔
199
      {
200
        id: upload.id,
20✔
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
61✔
212
    }
213
  end
214

215
  def draft_doi
1✔
216
    return if resource.doi.present?
42✔
217
    resource.doi = if self.class.publish_test_doi?
21✔
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)
20✔
222
                     if result.success?
20✔
223
                       result.success.doi
19✔
224
                     else
225
                       raise("Error generating DOI. #{result.failure.status} / #{result.failure.reason_phrase}")
1✔
226
                     end
227
                   end
228
    save!
20✔
229
  end
230

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

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

243
  def resource
1✔
244
    @resource ||= PDCMetadata::Resource.new_from_jsonb(metadata)
14,847✔
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"
67✔
259
  end
260

261
  def files_location_other?
1✔
262
    files_location == "file_other"
67✔
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?
4✔
299
                  user
3✔
300
                else
301
                  curator
1✔
302
                end
303
    persisted.uid
4✔
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
17✔
321
    WorkActivity.add_work_activity(id, changes.to_json, current_user_id, activity_type: WorkActivity::FILE_CHANGES)
17✔
322
  end
323

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

328
  def new_notification_count_for_user(user_id)
1✔
329
    WorkActivityNotification.joins(:work_activity)
98✔
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|
86✔
340
      unread_notifications = WorkActivityNotification.where(user_id: user_id, work_activity_id: activity.id, read_at: nil)
130✔
341
      unread_notifications.each do |notification|
130✔
342
        notification.read_at = Time.now.utc
31✔
343
        notification.save
31✔
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?
637✔
354

355
    pre_curation_uploads_fast
571✔
356
  end
357

358
  # Fetches the data from S3 directly bypassing ActiveStorage
359
  def pre_curation_uploads_fast
1✔
360
    s3_query_service.client_s3_files.sort_by(&:filename)
1,065✔
361
  end
362

363
  # This ensures that new ActiveStorage::Attachment objects can be modified before they are persisted
364
  def save_pre_curation_uploads
1✔
365
    return if pre_curation_uploads.empty?
763✔
366

367
    new_attachments = pre_curation_uploads.reject(&:persisted?)
46✔
368
    return if new_attachments.empty?
46✔
369

370
    save_new_attachments(new_attachments: new_attachments)
33✔
371
  end
372

373
  # Accesses post-curation S3 Bucket Objects
374
  def post_curation_s3_resources
1✔
375
    return [] unless approved?
163✔
376

377
    s3_resources
100✔
378
  end
379
  alias post_curation_uploads post_curation_s3_resources
1✔
380

381
  def s3_files
1✔
382
    pre_curation_uploads_fast
356✔
383
  end
384

385
  def s3_client
1✔
386
    s3_query_service.client
17✔
387
  end
388

389
  delegate :bucket_name, to: :s3_query_service
1✔
390

391
  # Generates the S3 Object key
392
  # @return [String]
393
  def s3_object_key
1✔
394
    "#{doi}/#{id}"
41✔
395
  end
396

397
  # Transmit a HEAD request for the S3 Bucket directory for this Work
398
  # @param bucket_name location to be checked to be found
399
  # @return [Aws::S3::Types::HeadObjectOutput]
400
  def find_post_curation_s3_dir(bucket_name:)
1✔
401
    # TODO: Directories really do not exists in S3
402
    #      if we really need this check then we need to do something else to check the bucket
403
    s3_client.head_object({
17✔
404
                            bucket: bucket_name,
405
                            key: s3_object_key
406
                          })
407
    true
×
408
  rescue Aws::S3::Errors::NotFound
409
    nil
17✔
410
  end
411

412
  def as_json(*)
1✔
413
    # Pre-curation files are not accessible externally,
414
    # so we are not interested in listing them in JSON.
415
    # (The items in pre_curation_uploads also have different properties.)
416
    files = post_curation_uploads.map do |upload|
85✔
417
      {
418
        "filename": upload.filename,
42✔
419
        "size": upload.size,
420
        "url": upload.globus_url
421
      }
422
    end
423

424
    # to_json returns a string of serialized JSON.
425
    # as_json returns the corresponding hash.
426
    {
427
      "resource" => resource.as_json,
85✔
428
      "files" => files,
429
      "collection" => collection.as_json.except("id")
430
    }
431
  end
432

433
  def pre_curation_uploads_count
1✔
434
    s3_query_service.file_count
2✔
435
  end
436

437
  delegate :ark, :doi, :resource_type, :resource_type=, :resource_type_general, :resource_type_general=,
1✔
438
           :to_xml, to: :resource
439

440
  # S3QueryService object associated with this Work
441
  # @return [S3QueryService]
442
  def s3_query_service
1✔
443
    @s3_query_service ||= S3QueryService.new(self, !approved?)
1,297✔
444
  end
445

446
  def reload_snapshots
1✔
447
    results = s3_files.map do |s3_file|
89✔
448
      UploadSnapshot.find_or_initialize_by(url: s3_file.url, filename: s3_file.filename, work: self)
45✔
449
    end
450

451
    s3_resource_urls = s3_files.map(&:url)
89✔
452
    s3_resource_filenames = s3_files.map(&:filename)
89✔
453

454
    # remove the snapshots for s3 file resources which have been deleted
455
    persisted = results.reject do |snapshot|
89✔
456
      removed = !s3_resource_urls.include?(snapshot.url) && !s3_resource_filenames.include?(snapshot.filename)
45✔
457

458
      if removed
45✔
459
        snapshot.destroy
×
460
        changes = {
×
461
          action: "removed"
462
        }
463
        WorkActivity.add_work_activity(id, changes.to_json, nil, activity_type: WorkActivity::FILE_CHANGES)
×
464
      end
465

466
      removed
45✔
467
    end
468

469
    changes = []
89✔
470
    s3_files.map do |s3_file|
89✔
471
      s3_match = s3_file.filename.match(/_\d+_/)
45✔
472
      s3_filename = if s3_match
45✔
473
                      s3_file.filename.gsub(/_\d+\.([0-9a-zA-Z]+)$/, ".\\1")
×
474
                    else
475
                      s3_file.filename
45✔
476
                    end
477

478
      selected = persisted.select do |s|
45✔
479
        # checking for version substrings
480
        snapshot_match = s.filename.match(/_\d+_/)
99✔
481
        s_filename = if snapshot_match
99✔
482
                       s.filename.gsub(/_\d+\.([0-9a-zA-Z]+)$/, ".\\1")
×
483
                     else
484
                       s.filename
99✔
485
                     end
486

487
        s_filename == s3_filename
99✔
488
      end
489
      snapshot = selected.last
45✔
490

491
      if snapshot.checksum != s3_file.checksum
45✔
492

493
        # cases where the s3 resources are replaced
494
        snapshot.checksum = s3_file.checksum
45✔
495
        changes << if !snapshot.persisted?
45✔
496
                     {
44✔
497
                       action: "added"
498
                     }
499
                   else
500
                     {
1✔
501
                       action: "replaced"
502
                     }
503
                   end
504
        snapshot.save
45✔
505
      end
506

507
      snapshot.reload
45✔
508
    end
509
    unless changes.empty?
89✔
510
      WorkActivity.add_work_activity(id, changes.to_json, nil, activity_type: WorkActivity::FILE_CHANGES)
24✔
511
    end
512
  end
513

514
  protected
1✔
515

516
    # This must be protected, NOT private for ActiveRecord to work properly with this attribute.
517
    #   Protected will still keep others from setting the metatdata, but allows ActiveRecord the access it needs
518
    def metadata=(metadata)
1✔
519
      super
1,285✔
520
      @resource = PDCMetadata::Resource.new_from_jsonb(metadata)
1,285✔
521
    end
522

523
  private
1✔
524

525
    def publish(user)
1✔
526
      publish_doi(user)
25✔
527
      update_ark_information
25✔
528
      publish_precurated_files
25✔
529
      save!
25✔
530
    end
531

532
    # Update EZID (our provider of ARKs) with the new information for this work.
533
    def update_ark_information
1✔
534
      # We only want to update the ark url under certain conditions.
535
      # Set this value in config/update_ark_url.yml
536
      if Rails.configuration.update_ark_url
25✔
537
        if ark.present?
20✔
538
          Ark.update(ark, url)
3✔
539
        end
540
      end
541
    end
542

543
    # Generates the key for ActiveStorage::Attachment and Attachment::Blob objects
544
    # @param attachment [ActiveStorage::Attachment]
545
    # @return [String]
546
    def generate_attachment_key(attachment)
1✔
547
      attachment_filename = attachment.filename.to_s
29✔
548
      attachment_key = attachment.key
29✔
549

550
      # Files actually coming from S3 include the DOI and bucket as part of the file name
551
      #  Files being attached in another manner may not have it, so we should include it.
552
      #  This is really for testing only.
553
      key_base = "#{doi}/#{id}"
29✔
554
      attachment_key = [key_base, attachment_filename].join("/") unless attachment_key.include?(key_base)
29✔
555

556
      attachment_ext = File.extname(attachment_filename)
29✔
557
      attachment_query = attachment_key.gsub(attachment_ext, "")
29✔
558
      results = ActiveStorage::Blob.where("key LIKE :query", query: "%#{attachment_query}%")
29✔
559
      blobs = results.to_a
29✔
560

561
      if blobs.present?
29✔
562
        index = blobs.length + 1
2✔
563
        attachment_key = attachment_key.gsub(/\.([a-zA-Z0-9\.]+)$/, "_#{index}.\\1")
2✔
564
      end
565

566
      attachment_key
29✔
567
    end
568

569
    def track_state_change(user, state = aasm.to_state)
1✔
570
      uw = UserWork.new(user_id: user.id, work_id: id, state: state)
146✔
571
      uw.save!
146✔
572
      WorkActivity.add_work_activity(id, "marked as #{state.to_s.titleize}", user.id, activity_type: WorkActivity::SYSTEM)
146✔
573
      WorkStateTransitionNotification.new(self, user.id).send
146✔
574
    end
575

576
    def data_cite_connection
1✔
577
      @data_cite_connection ||= Datacite::Client.new(username: Rails.configuration.datacite.user,
39✔
578
                                                     password: Rails.configuration.datacite.password,
579
                                                     host: Rails.configuration.datacite.host)
580
    end
581

582
    def validate_ark
1✔
583
      return if ark.blank?
792✔
584
      first_save = id.blank?
166✔
585
      changed_value = metadata["ark"] != ark
166✔
586
      if first_save || changed_value
166✔
587
        errors.add(:base, "Invalid ARK provided for the Work: #{ark}") unless Ark.valid?(ark)
61✔
588
      end
589
    end
590

591
    # rubocop:disable Metrics/AbcSize
592
    def validate_metadata
1✔
593
      return if metadata.blank?
299✔
594
      errors.add(:base, "Must provide a title") if resource.main_title.blank?
299✔
595
      errors.add(:base, "Must provide a description") if resource.description.blank?
299✔
596
      errors.add(:base, "Must indicate the Publisher") if resource.publisher.blank?
299✔
597
      errors.add(:base, "Must indicate the Publication Year") if resource.publication_year.blank?
299✔
598
      errors.add(:base, "Must indicate a Rights statement") if resource.rights.nil?
299✔
599
      errors.add(:base, "Must provide a Version number") if resource.version_number.blank?
299✔
600
      validate_creators
299✔
601
      validate_related_objects
299✔
602
    end
603
    # rubocop:enable Metrics/AbcSize
604

605
    def validate_creators
1✔
606
      if resource.creators.count == 0
1,091✔
607
        errors.add(:base, "Must provide at least one Creator")
1✔
608
      else
609
        resource.creators.each do |creator|
1,090✔
610
          if creator.orcid.present? && Orcid.invalid?(creator.orcid)
2,099✔
611
            errors.add(:base, "ORCID for creator #{creator.value} is not in format 0000-0000-0000-0000")
1✔
612
          end
613
        end
614
      end
615
    end
616

617
    def validate_related_objects
1✔
618
      return if resource.related_objects.empty?
299✔
619
      invalid = resource.related_objects.reject(&:valid?)
16✔
620
      errors.add(:base, "Related Objects are invalid: #{invalid.map(&:errors).join(', ')}") if invalid.count.positive?
16✔
621
    end
622

623
    def publish_doi(user)
1✔
624
      return Rails.logger.info("Publishing hard-coded test DOI during development.") if self.class.publish_test_doi?
23✔
625

626
      if doi&.starts_with?(Rails.configuration.datacite.prefix)
23✔
627
        result = data_cite_connection.update(id: doi, attributes: doi_attributes)
19✔
628
        if result.failure?
19✔
629
          resolved_user = curator_or_current_uid(user)
3✔
630
          message = "@#{resolved_user} Error publishing DOI. #{result.failure.status} / #{result.failure.reason_phrase}"
3✔
631
          WorkActivity.add_work_activity(id, message, user.id, activity_type: WorkActivity::DATACITE_ERROR)
3✔
632
        end
633
      elsif ark.blank? # we can not update the url anywhere
4✔
634
        Honeybadger.notify("Publishing for a DOI we do not own and no ARK is present: #{doi}")
3✔
635
      end
636
    end
637

638
    def doi_attribute_url
1✔
639
      "https://datacommons.princeton.edu/discovery/doi/#{doi}"
19✔
640
    end
641

642
    def doi_attribute_resource
1✔
643
      PDCMetadata::Resource.new_from_jsonb(metadata)
19✔
644
    end
645

646
    def doi_attribute_xml
1✔
647
      unencoded = doi_attribute_resource.to_xml
19✔
648
      Base64.encode64(unencoded)
19✔
649
    end
650

651
    def doi_attributes
1✔
652
      {
653
        "event" => "publish",
19✔
654
        "xml" => doi_attribute_xml,
655
        "url" => doi_attribute_url
656
      }
657
    end
658

659
    # This needs to be called #before_save
660
    # This ensures that new ActiveStorage::Attachment objects are persisted with custom keys (which are generated from the file name and DOI)
661
    # @param new_attachments [Array<ActiveStorage::Attachment>]
662
    def save_new_attachments(new_attachments:)
1✔
663
      new_attachments.each do |attachment|
33✔
664
        # There are cases (race conditions?) where the ActiveStorage::Blob objects are not persisted
665
        next if attachment.frozen?
33✔
666

667
        # This ensures that the custom key for the ActiveStorage::Attachment and ActiveStorage::Blob objects are generated
668
        generated_key = generate_attachment_key(attachment)
29✔
669
        attachment.blob.key = generated_key
29✔
670
        attachment.blob.save
29✔
671

672
        attachment.save
29✔
673
      end
674
    end
675

676
    # Request S3 Bucket Objects associated with this Work
677
    # @return [Array<S3File>]
678
    def s3_resources
1✔
679
      data_profile = s3_query_service.data_profile
100✔
680
      data_profile.fetch(:objects, [])
100✔
681
    end
682
    alias pre_curation_s3_resources s3_resources
1✔
683

684
    def s3_object_persisted?(s3_file)
1✔
685
      uploads_keys = uploads.map(&:key)
×
686
      uploads_keys.include?(s3_file.key)
×
687
    end
688

689
    def add_pre_curation_s3_object(s3_file)
1✔
690
      return if s3_object_persisted?(s3_file)
×
691

692
      persisted = s3_file.to_blob
×
693
      pre_curation_uploads.attach(persisted)
×
694
    end
695

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

700
      # We need to explicitly access to post-curation services here.
701
      # Lets explicitly create it so the state of the work does not have any impact.
702
      s3_post_curation_query_service = S3QueryService.new(self, false)
17✔
703

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

707
      # Copy the pre-curation S3 Objects to the post-curation S3 Bucket...
708
      transferred_file_errors = s3_query_service.publish_files
17✔
709

710
      # ...check that the files are indeed now in the post-curation bucket...
711
      if transferred_file_errors.count > 0
17✔
712
        raise(StandardError, "Failed to validate the uploaded S3 Object #{transferred_file_errors.map(&:key).join(', ')}")
×
713
      end
714
    end
715
end
716
# 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