Class: Deliver::UploadScreenshots

Inherits:
Object
  • Object
show all
Defined in:
deliver/lib/deliver/upload_screenshots.rb

Overview

upload screenshots to App Store Connect

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.available_languagesObject

helper method so Spaceship::Tunes.client.available_languages is easier to test



264
265
266
267
268
269
270
# File 'deliver/lib/deliver/upload_screenshots.rb', line 264

def self.available_languages
  if Helper.test?
    FastlaneCore::Languages::ALL_LANGUAGES
  else
    Spaceship::Tunes.client.available_languages
  end
end

Instance Method Details

#collect_screenshots(options) ⇒ Object



195
196
197
198
# File 'deliver/lib/deliver/upload_screenshots.rb', line 195

def collect_screenshots(options)
  return [] if options[:skip_screenshots]
  return collect_screenshots_for_languages(options[:screenshots_path], options[:ignore_language_directory_validation])
end

#collect_screenshots_for_languages(path, ignore_validation) ⇒ Object



200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'deliver/lib/deliver/upload_screenshots.rb', line 200

def collect_screenshots_for_languages(path, ignore_validation)
  screenshots = []
  extensions = '{png,jpg,jpeg}'

  available_languages = UploadScreenshots.available_languages.each_with_object({}) do |lang, lang_hash|
    lang_hash[lang.downcase] = lang
  end

  Loader.language_folders(path, ignore_validation).each do |lng_folder|
    language = File.basename(lng_folder)

    # Check to see if we need to traverse multiple platforms or just a single platform
    if language == Loader::APPLE_TV_DIR_NAME || language == Loader::IMESSAGE_DIR_NAME
      screenshots.concat(collect_screenshots_for_languages(File.join(path, language), ignore_validation))
      next
    end

    files = Dir.glob(File.join(lng_folder, "*.#{extensions}"), File::FNM_CASEFOLD).sort
    next if files.count == 0

    framed_screenshots_found = Dir.glob(File.join(lng_folder, "*_framed.#{extensions}"), File::FNM_CASEFOLD).count > 0

    UI.important("Framed screenshots are detected! 🖼 Non-framed screenshot files may be skipped. 🏃") if framed_screenshots_found

    language_dir_name = File.basename(lng_folder)

    if available_languages[language_dir_name.downcase].nil?
      UI.user_error!("#{language_dir_name} is not an available language. Please verify that your language codes are available in iTunesConnect. See https://developer.apple.com/library/content/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/Chapters/AppStoreTerritories.html for more information.")
    end

    language = available_languages[language_dir_name.downcase]

    files.each do |file_path|
      is_framed = file_path.downcase.include?("_framed.")
      is_watch = file_path.downcase.include?("watch")

      if framed_screenshots_found && !is_framed && !is_watch
        UI.important("🏃 Skipping screenshot file: #{file_path}")
        next
      end

      screenshots << AppScreenshot.new(file_path, language)
    end
  end

  # Checking if the device type exists in spaceship
  # Ex: iPhone 6.1 inch isn't supported in App Store Connect but need
  # to have it in there for frameit support
  unaccepted_device_shown = false
  screenshots.select! do |screenshot|
    exists = !screenshot.device_type.nil?
    unless exists
      UI.important("Unaccepted device screenshots are detected! 🚫 Screenshot file will be skipped. 🏃") unless unaccepted_device_shown
      unaccepted_device_shown = true

      UI.important("🏃 Skipping screenshot file: #{screenshot.path} - Not an accepted App Store Connect device...")
    end
    exists
  end

  return screenshots
end

#upload(options, screenshots) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'deliver/lib/deliver/upload_screenshots.rb', line 11

def upload(options, screenshots)
  return if options[:skip_screenshots]
  return if options[:edit_live]

  legacy_app = options[:app]
  app_id = legacy_app.apple_id
  app = Spaceship::ConnectAPI::App.get(app_id: app_id)

  platform = Spaceship::ConnectAPI::Platform.map(options[:platform])
  version = app.get_edit_app_store_version(platform: platform)
  UI.user_error!("Could not find a version to edit for app '#{app.name}' for '#{platform}'") unless version

  UI.important("Will begin uploading snapshots for '#{version.version_string}' on App Store Connect")

  UI.message("Starting with the upload of screenshots...")
  screenshots_per_language = screenshots.group_by(&:language)

  localizations = version.get_app_store_version_localizations

  if options[:overwrite_screenshots]
    # Get localizations on version
    localizations.each do |localization|
      # Only delete screenshots if trying to upload
      next unless screenshots_per_language.keys.include?(localization.locale)

      # Iterate over all screenshots for each set and delete
      screenshot_sets = localization.get_app_screenshot_sets

      # Multi threading delete on single localization
      threads = []
      errors = []

      screenshot_sets.each do |screenshot_set|
        UI.message("Removing all previously uploaded screenshots for '#{localization.locale}' '#{screenshot_set.screenshot_display_type}'...")
        screenshot_set.app_screenshots.each do |screenshot|
          UI.verbose("Deleting screenshot - #{localization.locale} #{screenshot_set.screenshot_display_type} #{screenshot.id}")
          threads << Thread.new do
            begin
              screenshot.delete!
              UI.verbose("Deleted screenshot - #{localization.locale} #{screenshot_set.screenshot_display_type} #{screenshot.id}")
            rescue => error
              UI.verbose("Failed to delete screenshot - #{localization.locale} #{screenshot_set.screenshot_display_type} #{screenshot.id}")
              errors << error
            end
          end
        end
      end

      sleep(1) # Feels bad but sleeping a bit to let the threads catchup

      unless threads.empty?
        Helper.show_loading_indicator("Waiting for screenshots to be deleted for '#{localization.locale}'... (might be slow)") unless FastlaneCore::Globals.verbose?
        threads.each(&:join)
        Helper.hide_loading_indicator unless FastlaneCore::Globals.verbose?
      end

      # Crash if any errors happen while deleting
      errors.each do |error|
        UI.error(error.message)
      end
    end
  end

  # Finding languages to enable
  languages = screenshots_per_language.keys
  locales_to_enable = languages - localizations.map(&:locale)

  if locales_to_enable.count > 0
    lng_text = "language"
    lng_text += "s" if locales_to_enable.count != 1
    Helper.show_loading_indicator("Activating #{lng_text} #{locales_to_enable.join(', ')}...")

    locales_to_enable.each do |locale|
      version.create_app_store_version_localization(attributes: {
        locale: locale
      })
    end

    Helper.hide_loading_indicator

    # Refresh version localizations
    localizations = version.get_app_store_version_localizations
  end

  upload_screenshots(screenshots_per_language, localizations, options)
end

#upload_screenshots(screenshots_per_language, localizations, options) ⇒ Object



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'deliver/lib/deliver/upload_screenshots.rb', line 98

def upload_screenshots(screenshots_per_language, localizations, options)
  # Check if should wait for processing
  # Default to waiting if submitting for review (since needed for submission)
  # Otherwise use enviroment variable
  if ENV["DELIVER_SKIP_WAIT_FOR_SCREENSHOT_PROCESSING"].nil?
    wait_for_processing = options[:submit_for_review]
    UI.verbose("Setting wait_for_processing from ':submit_for_review' option")
  else
    UI.verbose("Setting wait_for_processing from 'DELIVER_SKIP_WAIT_FOR_SCREENSHOT_PROCESSING' environment variable")
    wait_for_processing = !FastlaneCore::Env.truthy?("DELIVER_SKIP_WAIT_FOR_SCREENSHOT_PROCESSING")
  end

  if wait_for_processing
    UI.important("Will wait for screenshot image processing")
    UI.important("Set env DELIVER_SKIP_WAIT_FOR_SCREENSHOT_PROCESSING=true to skip waiting for screenshots to process")
  else
    UI.important("Skipping the wait for screenshot image processing (which may affect submission)")
    UI.important("Set env DELIVER_SKIP_WAIT_FOR_SCREENSHOT_PROCESSING=false to skip waiting for screenshots to process")
  end

  # Upload screenshots
  indized = {} # per language and device type

  screenshots_per_language.each do |language, screenshots_for_language|
    # Find localization to upload screenshots to
    localization = localizations.find do |l|
      l.locale == language
    end

    unless localization
      UI.error("Couldn't find localization on version for #{language}")
      next
    end

    indized[localization.locale] ||= {}

    # Create map to find screenshot set to add screenshot to
    app_screenshot_sets_map = {}
    app_screenshot_sets = localization.get_app_screenshot_sets
    app_screenshot_sets.each do |app_screenshot_set|
      app_screenshot_sets_map[app_screenshot_set.screenshot_display_type] = app_screenshot_set

      # Set initial screnshot count
      indized[localization.locale][app_screenshot_set.screenshot_display_type] ||= {
        count: app_screenshot_set.app_screenshots.size,
        checksums: []
      }

      checksums = app_screenshot_set.app_screenshots.map(&:source_file_checksum).uniq
      indized[localization.locale][app_screenshot_set.screenshot_display_type][:checksums] = checksums
    end

    UI.message("Uploading #{screenshots_for_language.length} screenshots for language #{language}")
    screenshots_for_language.each do |screenshot|
      display_type = screenshot.device_type
      set = app_screenshot_sets_map[display_type]

      if display_type.nil?
        UI.error("Error... Screenshot size #{screenshot.screen_size} not valid for App Store Connect")
        next
      end

      unless set
        set = localization.create_app_screenshot_set(attributes: {
          screenshotDisplayType: display_type
        })
        app_screenshot_sets_map[display_type] = set

        indized[localization.locale][set.screenshot_display_type] = {
          count: 0,
          checksums: []
        }
      end

      index = indized[localization.locale][set.screenshot_display_type][:count]

      if index >= 10
        UI.error("Too many screenshots found for device '#{screenshot.device_type}' in '#{screenshot.language}', skipping this one (#{screenshot.path})")
        next
      end

      bytes = File.binread(screenshot.path)
      checksum = Digest::MD5.hexdigest(bytes)
      duplicate = indized[localization.locale][set.screenshot_display_type][:checksums].include?(checksum)

      if duplicate
        UI.message("Previous uploaded. Skipping '#{screenshot.path}'...")
      else
        indized[localization.locale][set.screenshot_display_type][:count] += 1
        UI.message("Uploading '#{screenshot.path}'...")
        set.upload_screenshot(path: screenshot.path, wait_for_processing: wait_for_processing)
      end
    end
  end
  UI.success("Successfully uploaded screenshots to App Store Connect")
end