Class: Fastlane::Actions::FirebaseAppDistributionAction

Inherits:
Action
  • Object
show all
Extended by:
Fastlane::Auth::FirebaseAppDistributionAuthClient, Helper::FirebaseAppDistributionHelper
Defined in:
lib/fastlane/plugin/firebase_app_distribution/actions/firebase_app_distribution_action.rb

Overview

rubocop:disable Metrics/ClassLength

Constant Summary collapse

DEFAULT_UPLOAD_TIMEOUT_SECONDS =
300
MAX_POLLING_RETRIES =
60
POLLING_INTERVAL_SECONDS =
5

Constants included from Fastlane::Auth::FirebaseAppDistributionAuthClient

Fastlane::Auth::FirebaseAppDistributionAuthClient::CLIENT_ID, Fastlane::Auth::FirebaseAppDistributionAuthClient::CLIENT_SECRET, Fastlane::Auth::FirebaseAppDistributionAuthClient::REDACTION_CHARACTER, Fastlane::Auth::FirebaseAppDistributionAuthClient::REDACTION_EXPOSED_LENGTH, Fastlane::Auth::FirebaseAppDistributionAuthClient::SCOPE, Fastlane::Auth::FirebaseAppDistributionAuthClient::TOKEN_CREDENTIAL_URI

Class Method Summary collapse

Methods included from Fastlane::Auth::FirebaseAppDistributionAuthClient

get_authorization

Methods included from Helper::FirebaseAppDistributionHelper

app_name_from_app_id, binary_type_from_path, blank?, deep_symbolize_keys, get_ios_app_id_from_archive_plist, get_value_from_value_or_file, group_name, init_client, init_v1_client, init_v1alpha_client, parse_plist, present?, project_name, project_number_from_app_id, string_to_array

Class Method Details

.aab_certs_included?(test_certificate) ⇒ Boolean

Returns:

  • (Boolean)


201
202
203
204
# File 'lib/fastlane/plugin/firebase_app_distribution/actions/firebase_app_distribution_action.rb', line 201

def self.aab_certs_included?(test_certificate)
  present?(test_certificate.hash_md5) && present?(test_certificate.hash_sha1) &&
    present?(test_certificate.hash_sha256)
end

.aab_info_name(app_name) ⇒ Object



206
207
208
# File 'lib/fastlane/plugin/firebase_app_distribution/actions/firebase_app_distribution_action.rb', line 206

def self.aab_info_name(app_name)
  "#{app_name}/aabInfo"
end

.app_id_from_params(params) ⇒ Object



121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/fastlane/plugin/firebase_app_distribution/actions/firebase_app_distribution_action.rb', line 121

def self.app_id_from_params(params)
  if params[:app]
    app_id = params[:app]
  elsif xcode_archive_path
    plist_path = params[:googleservice_info_plist_path]
    app_id = get_ios_app_id_from_archive_plist(xcode_archive_path, plist_path)
  end
  if app_id.nil?
    UI.crash!(ErrorMessage::MISSING_APP_ID)
  end
  app_id
end

.authorsObject



112
113
114
# File 'lib/fastlane/plugin/firebase_app_distribution/actions/firebase_app_distribution_action.rb', line 112

def self.authors
  ["Stefan Natchev", "Manny Jimenez Github: mannyjimenez0810, Alonso Salas Infante Github: alonsosalasinfante"]
end

.available_optionsObject



322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
# File 'lib/fastlane/plugin/firebase_app_distribution/actions/firebase_app_distribution_action.rb', line 322

def self.available_options
  [
    # iOS Specific
    FastlaneCore::ConfigItem.new(key: :ipa_path,
                                 env_name: "FIREBASEAPPDISTRO_IPA_PATH",
                                 description: "Path to your IPA file. Optional if you use the _gym_ or _xcodebuild_ action",
                                 optional: true),
    FastlaneCore::ConfigItem.new(key: :googleservice_info_plist_path,
                                 env_name: "GOOGLESERVICE_INFO_PLIST_PATH",
                                 description: "Path to your GoogleService-Info.plist file, relative to the archived product path",
                                 default_value: "GoogleService-Info.plist",
                                 optional: true,
                                 type: String),
    # Android Specific
    FastlaneCore::ConfigItem.new(key: :apk_path,
                                 env_name: "FIREBASEAPPDISTRO_APK_PATH",
                                 description: "Path to your APK file",
                                 optional: true),
    FastlaneCore::ConfigItem.new(key: :android_artifact_path,
                                 env_name: "FIREBASEAPPDISTRO_ANDROID_ARTIFACT_PATH",
                                 description: "Path to your APK or AAB file",
                                 optional: true),
    FastlaneCore::ConfigItem.new(key: :android_artifact_type,
                                 env_name: "FIREBASEAPPDISTRO_ANDROID_ARTIFACT_TYPE",
                                 description: "Android artifact type. Set to 'APK' or 'AAB'. Defaults to 'APK' if not set",
                                 default_value: "APK",
                                 default_value_dynamic: true,
                                 optional: true,
                                 verify_block: proc do |value|
                                   UI.user_error!("firebase_app_distribution: '#{value}' is not a valid value for android_artifact_type. Should be 'APK' or 'AAB'") unless ['APK', 'AAB'].include?(value)
                                 end),
    # Generic
    FastlaneCore::ConfigItem.new(key: :app,
                                 env_name: "FIREBASEAPPDISTRO_APP",
                                 description: "Your app's Firebase App ID. You can find the App ID in the Firebase console, on the General Settings page",
                                 optional: true,
                                 type: String),
    FastlaneCore::ConfigItem.new(key: :firebase_cli_path,
                                 deprecated: "This plugin no longer uses the Firebase CLI",
                                 env_name: "FIREBASEAPPDISTRO_FIREBASE_CLI_PATH",
                                 description: "The absolute path of the firebase cli command",
                                 type: String),
    FastlaneCore::ConfigItem.new(key: :groups,
                                 env_name: "FIREBASEAPPDISTRO_GROUPS",
                                 description: "The group aliases used for distribution, separated by commas",
                                 optional: true,
                                 type: String),
    FastlaneCore::ConfigItem.new(key: :groups_file,
                                 env_name: "FIREBASEAPPDISTRO_GROUPS_FILE",
                                 description: "The group aliases used for distribution, separated by commas",
                                 optional: true,
                                 type: String),
    FastlaneCore::ConfigItem.new(key: :testers,
                                 env_name: "FIREBASEAPPDISTRO_TESTERS",
                                 description: "Pass email addresses of testers, separated by commas",
                                 optional: true,
                                 type: String),
    FastlaneCore::ConfigItem.new(key: :testers_file,
                                 env_name: "FIREBASEAPPDISTRO_TESTERS_FILE",
                                 description: "Pass email addresses of testers, separated by commas",
                                 optional: true,
                                 type: String),
    FastlaneCore::ConfigItem.new(key: :release_notes,
                                 env_name: "FIREBASEAPPDISTRO_RELEASE_NOTES",
                                 description: "Release notes for this build",
                                 optional: true,
                                 type: String),
    FastlaneCore::ConfigItem.new(key: :release_notes_file,
                                 env_name: "FIREBASEAPPDISTRO_RELEASE_NOTES_FILE",
                                 description: "Release notes file for this build",
                                 optional: true,
                                 type: String),
    FastlaneCore::ConfigItem.new(key: :firebase_cli_token,
                                 description: "Auth token generated using the Firebase CLI's login:ci command",
                                 optional: true,
                                 type: String),
    FastlaneCore::ConfigItem.new(key: :debug,
                                 description: "Print verbose debug output",
                                 optional: true,
                                 default_value: false,
                                 is_string: false),
    FastlaneCore::ConfigItem.new(key: :service_credentials_file,
                                 description: "Path to Google service account json",
                                 optional: true,
                                 type: String),
    FastlaneCore::ConfigItem.new(key: :upload_timeout,
                                 description: "The amount of seconds before the upload will timeout, if not completed",
                                 optional: true,
                                 default_value: DEFAULT_UPLOAD_TIMEOUT_SECONDS,
                                 type: Integer)
  ]
end

.descriptionObject



108
109
110
# File 'lib/fastlane/plugin/firebase_app_distribution/actions/firebase_app_distribution_action.rb', line 108

def self.description
  "Release your beta builds with Firebase App Distribution"
end

.detailsObject

supports markdown.



117
118
119
# File 'lib/fastlane/plugin/firebase_app_distribution/actions/firebase_app_distribution_action.rb', line 117

def self.details
  "Release your beta builds with Firebase App Distribution"
end

.distribute_release(client, release, request) ⇒ Object



311
312
313
314
315
316
317
318
319
320
# File 'lib/fastlane/plugin/firebase_app_distribution/actions/firebase_app_distribution_action.rb', line 311

def self.distribute_release(client, release, request)
  client.distribute_project_app_release(release.name, request)
rescue Google::Apis::Error => err
  case err.status_code.to_i
  when 400
    UI.user_error!("#{ErrorMessage::INVALID_TESTERS}\nEmails: #{request.tester_emails} \nGroup Aliases: #{request.group_aliases}")
  else
    UI.crash!(err)
  end
end

.example_codeObject



423
424
425
426
427
428
429
430
431
432
# File 'lib/fastlane/plugin/firebase_app_distribution/actions/firebase_app_distribution_action.rb', line 423

def self.example_code
  [
    "      firebase_app_distribution(\n        app: \"<your Firebase app ID>\",\n        testers: \"[email protected], [email protected]\"\n      )\n    CODE\n  ]\nend\n"

.extract_release(operation) ⇒ Object



275
276
277
# File 'lib/fastlane/plugin/firebase_app_distribution/actions/firebase_app_distribution_action.rb', line 275

def self.extract_release(operation)
  Google::Apis::FirebaseappdistributionV1::GoogleFirebaseAppdistroV1Release.from_json(operation.response['release'].to_json)
end

.get_aab_info(client, app_name) ⇒ Object



289
290
291
292
293
294
295
296
297
298
# File 'lib/fastlane/plugin/firebase_app_distribution/actions/firebase_app_distribution_action.rb', line 289

def self.get_aab_info(client, app_name)
  client.get_project_app_aab_info(aab_info_name(app_name))
rescue Google::Apis::Error => err
  case err.status_code.to_i
  when 404
    UI.user_error!(ErrorMessage::INVALID_APP_ID)
  else
    UI.crash!(err)
  end
end

.get_binary_path(platform, params) ⇒ Object



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/fastlane/plugin/firebase_app_distribution/actions/firebase_app_distribution_action.rb', line 154

def self.get_binary_path(platform, params)
  if platform == :ios
    return params[:ipa_path] ||
           Actions.lane_context[SharedValues::IPA_OUTPUT_PATH] ||
           Dir["*.ipa"].sort_by { |x| File.mtime(x) }.last
  end

  if platform == :android
    return params[:apk_path] || params[:android_artifact_path] if params[:apk_path] || params[:android_artifact_path]

    if params[:android_artifact_type] == 'AAB'
      return Actions.lane_context[SharedValues::GRADLE_AAB_OUTPUT_PATH] ||
             Dir["*.aab"].last ||
             Dir[File.join("app", "build", "outputs", "bundle", "release", "app-release.aab")].last
    end

    return Actions.lane_context[SharedValues::GRADLE_APK_OUTPUT_PATH] ||
           Dir["*.apk"].last ||
           Dir[File.join("app", "build", "outputs", "apk", "release", "app-release.apk")].last
  end
end

.get_upload_timeout(params) ⇒ Object



176
177
178
179
180
181
182
# File 'lib/fastlane/plugin/firebase_app_distribution/actions/firebase_app_distribution_action.rb', line 176

def self.get_upload_timeout(params)
  if params[:upload_timeout]
    return params[:upload_timeout]
  else
    return DEFAULT_UPLOAD_TIMEOUT_SECONDS
  end
end

.is_supported?(platform) ⇒ Boolean

Returns:

  • (Boolean)


415
416
417
418
419
420
421
# File 'lib/fastlane/plugin/firebase_app_distribution/actions/firebase_app_distribution_action.rb', line 415

def self.is_supported?(platform)
  # Adjust this if your plugin only works for a particular platform (iOS vs. Android, for example)
  # See: https://docs.fastlane.tools/advanced/#control-configuration-by-lane-and-by-platform
  #
  # [:ios, :mac, :android].include?(platform)
  true
end

.lane_platformObject



142
143
144
# File 'lib/fastlane/plugin/firebase_app_distribution/actions/firebase_app_distribution_action.rb', line 142

def self.lane_platform
  Actions.lane_context[Actions::SharedValues::PLATFORM_NAME]
end

.outputObject



434
435
436
437
438
# File 'lib/fastlane/plugin/firebase_app_distribution/actions/firebase_app_distribution_action.rb', line 434

def self.output
  [
    ['FIREBASE_APP_DISTRO_RELEASE', 'A hash representing the uploaded release created in Firebase App Distribution']
  ]
end

.platform_from_app_id(app_id) ⇒ Object



146
147
148
149
150
151
152
# File 'lib/fastlane/plugin/firebase_app_distribution/actions/firebase_app_distribution_action.rb', line 146

def self.platform_from_app_id(app_id)
  if app_id.include?(':ios:')
    :ios
  elsif app_id.include?(':android:')
    :android
  end
end

.poll_upload_release_operation(client, operation, binary_type) ⇒ Object



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
# File 'lib/fastlane/plugin/firebase_app_distribution/actions/firebase_app_distribution_action.rb', line 216

def self.poll_upload_release_operation(client, operation, binary_type)
  operation = client.get_project_app_release_operation(operation.name)
  MAX_POLLING_RETRIES.times do
    if operation.done && operation.response && operation.response['release']
      release = extract_release(operation)
      result = operation.response['result']
      if result == 'RELEASE_UPDATED'
        UI.success("✅ Uploaded #{binary_type} successfully; updated provisioning profile of existing release #{release_version(release)}.")
        break
      elsif result == 'RELEASE_UNMODIFIED'
        UI.success("✅ The same #{binary_type} was found in release #{release_version(release)} with no changes, skipping.")
        break
      else
        UI.success("✅ Uploaded #{binary_type} successfully and created release #{release_version(release)}.")
      end
      break
    elsif !operation.done
      sleep(POLLING_INTERVAL_SECONDS)
      operation = client.get_project_app_release_operation(operation.name)
    else
      if operation.error && operation.error.message
        UI.user_error!("#{ErrorMessage.upload_binary_error(binary_type)}: #{operation.error.message}")
      else
        UI.user_error!(ErrorMessage.upload_binary_error(binary_type))
      end
    end
  end

  unless operation.done && operation.response && operation.response['release']
    UI.crash!("It took longer than expected to process your #{binary_type}, please try again.")
  end

  extract_release(operation)
end

.release_notes(params) ⇒ Object



210
211
212
213
214
# File 'lib/fastlane/plugin/firebase_app_distribution/actions/firebase_app_distribution_action.rb', line 210

def self.release_notes(params)
  release_notes_param =
    get_value_from_value_or_file(params[:release_notes], params[:release_notes_file])
  release_notes_param || Actions.lane_context[SharedValues::FL_CHANGELOG]
end

.release_version(release) ⇒ Object



279
280
281
282
283
284
285
286
287
# File 'lib/fastlane/plugin/firebase_app_distribution/actions/firebase_app_distribution_action.rb', line 279

def self.release_version(release)
  if release.display_version && release.build_version
    "#{release.display_version} (#{release.build_version})"
  elsif release.display_version
    release.display_version
  else
    release.build_version
  end
end

.run(params) ⇒ Object



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
97
98
99
100
101
102
103
104
105
106
# File 'lib/fastlane/plugin/firebase_app_distribution/actions/firebase_app_distribution_action.rb', line 25

def self.run(params)
  params.values # to validate all inputs before looking for the ipa/apk/aab

  app_id = app_id_from_params(params)
  app_name = app_name_from_app_id(app_id)
  platform = lane_platform || platform_from_app_id(app_id)
  timeout = get_upload_timeout(params)

  binary_path = get_binary_path(platform, params)
  UI.user_error!("Couldn't find binary") if binary_path.nil?
  UI.user_error!("Couldn't find binary at path #{binary_path}") unless File.exist?(binary_path)
  binary_type = binary_type_from_path(binary_path)

  # TODO(lkellogg): This sets the send timeout for all POST requests made by the client, but
  # ideally the timeout should only apply to the binary upload
  client = init_v1_client(params[:service_credentials_file],
                          params[:firebase_cli_token],
                          params[:debug],
                          timeout)

  # If binary is an AAB, get the AAB info for this app, which includes the integration state
  # and certificate data
  if binary_type == :AAB
    aab_info = get_aab_info(client, app_name)
    validate_aab_setup!(aab_info)
  end

  binary_type = binary_type_from_path(binary_path)
  UI.message("⌛ Uploading the #{binary_type}.")
  operation = upload_binary(app_name, binary_path, client, timeout)
  UI.message("🕵️ Validating upload.")
  release = poll_upload_release_operation(client, operation, binary_type)

  if binary_type == :AAB && aab_info && !aab_certs_included?(aab_info.test_certificate)
    updated_aab_info = get_aab_info(client, app_name)
    if aab_certs_included?(updated_aab_info.test_certificate)
      UI.message("After you upload an AAB for the first time, App Distribution " \
        "generates a new test certificate. All AAB uploads are re-signed with this test " \
        "certificate. Use the certificate fingerprints below to register your app " \
        "signing key with API providers, such as Google Sign-In and Google Maps.\n" \
        "MD-1 certificate fingerprint: #{updated_aab_info.test_certificate.hash_md5}\n" \
        "SHA-1 certificate fingerprint: #{updated_aab_info.test_certificate.hash_sha1}\n" \
        "SHA-256 certificate fingerprint: #{updated_aab_info.test_certificate.hash_sha256}")
    end
  end

  release_notes = release_notes(params)
  if release_notes.nil? || release_notes.empty?
    UI.message("⏩ No release notes passed in. Skipping this step.")
  else
    release.release_notes = Google::Apis::FirebaseappdistributionV1::GoogleFirebaseAppdistroV1ReleaseNotes.new(
      text: release_notes
    )
    UI.message("📜 Setting release notes.")
    release = update_release(client, release)
  end

  testers = get_value_from_value_or_file(params[:testers], params[:testers_file])
  groups = get_value_from_value_or_file(params[:groups], params[:groups_file])
  emails = string_to_array(testers)
  group_aliases = string_to_array(groups)
  if present?(emails) || present?(group_aliases)
    request = Google::Apis::FirebaseappdistributionV1::GoogleFirebaseAppdistroV1DistributeReleaseRequest.new(
      tester_emails: emails,
      group_aliases: group_aliases
    )
    UI.message("📦 Distributing release.")
    distribute_release(client, release, request)
  else
    UI.message("⏩ No testers or groups passed in. Skipping this step.")
  end

  UI.success("🎉 App Distribution upload finished successfully. Setting Actions.lane_context[SharedValues::FIREBASE_APP_DISTRO_RELEASE] to the uploaded release.")

  UI.message("🔗 View this release in the Firebase console: #{release.firebase_console_uri}") if release.firebase_console_uri
  UI.message("🔗 Share this release with testers who have access: #{release.testing_uri}") if release.testing_uri
  UI.message("🔗 Download the release binary (link expires in 1 hour): #{release.binary_download_uri}") if release.binary_download_uri

  release_hash = deep_symbolize_keys(JSON.parse(release.to_json))
  Actions.lane_context[SharedValues::FIREBASE_APP_DISTRO_RELEASE] = release_hash
  release_hash
end

.update_release(client, release) ⇒ Object



300
301
302
303
304
305
306
307
308
309
# File 'lib/fastlane/plugin/firebase_app_distribution/actions/firebase_app_distribution_action.rb', line 300

def self.update_release(client, release)
  client.patch_project_app_release(release.name, release)
rescue Google::Apis::Error => err
  case err.status_code.to_i
  when 400
    UI.user_error!("#{ErrorMessage::INVALID_RELEASE_NOTES}: #{err.body}")
  else
    UI.crash!(err)
  end
end

.upload_binary(app_name, binary_path, client, timeout) ⇒ Object



251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/fastlane/plugin/firebase_app_distribution/actions/firebase_app_distribution_action.rb', line 251

def self.upload_binary(app_name, binary_path, client, timeout)
  options = Google::Apis::RequestOptions.new
  options.max_elapsed_time = timeout # includes retries (default = no retries)
  options.header = {
    'Content-Type' => 'application/octet-stream',
    'X-Goog-Upload-File-Name' => CGI.escape(File.basename(binary_path)),
    'X-Goog-Upload-Protocol' => 'raw'
  }

  # For some reason calling the client.upload_medium returns nil when
  # it should return a long running operation object, so we make a
  # standard http call instead and convert it to a long running object
  # https://github.com/googleapis/google-api-ruby-client/blob/main/generated/google-apis-firebaseappdistribution_v1/lib/google/apis/firebaseappdistribution_v1/service.rb#L79
  # TODO(kbolay) Prefer client.upload_medium
  response = client.http(
    :post,
    "https://firebaseappdistribution.googleapis.com/upload/v1/#{app_name}/releases:upload",
    body: File.open(binary_path, 'rb'),
    options: options
  )

  Google::Apis::FirebaseappdistributionV1::GoogleLongrunningOperation.from_json(response)
end

.validate_aab_setup!(aab_info) ⇒ Object



184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/fastlane/plugin/firebase_app_distribution/actions/firebase_app_distribution_action.rb', line 184

def self.validate_aab_setup!(aab_info)
  if aab_info && aab_info.integration_state != 'INTEGRATED' && aab_info.integration_state != 'AAB_STATE_UNAVAILABLE'
    case aab_info.integration_state
    when 'PLAY_ACCOUNT_NOT_LINKED'
      UI.user_error!(ErrorMessage::)
    when 'APP_NOT_PUBLISHED'
      UI.user_error!(ErrorMessage::APP_NOT_PUBLISHED)
    when 'NO_APP_WITH_GIVEN_BUNDLE_ID_IN_PLAY_ACCOUNT'
      UI.user_error!(ErrorMessage::)
    when 'PLAY_IAS_TERMS_NOT_ACCEPTED'
      UI.user_error!(ErrorMessage::PLAY_IAS_TERMS_NOT_ACCEPTED)
    else
      UI.user_error!(ErrorMessage.aab_upload_error(aab_info.integration_state))
    end
  end
end

.xcode_archive_pathObject



134
135
136
137
138
139
140
# File 'lib/fastlane/plugin/firebase_app_distribution/actions/firebase_app_distribution_action.rb', line 134

def self.xcode_archive_path
  # prevents issues on cross-platform build environments where an XCode build happens within
  # the same lane
  return nil if lane_platform == :android

  Actions.lane_context[SharedValues::XCODEBUILD_ARCHIVE]
end