Class: Fastlane::Helper::HuaweiAppgalleryConnectHelper

Inherits:
Object
  • Object
show all
Defined in:
lib/fastlane/plugin/huawei_appgallery_connect/helper/huawei_appgallery_connect_helper.rb

Class Method Summary collapse

Class Method Details

.get_app_id(token, client_id, package_id) ⇒ Object



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
# File 'lib/fastlane/plugin/huawei_appgallery_connect/helper/huawei_appgallery_connect_helper.rb', line 26

def self.get_app_id(token, client_id, package_id)
  UI.message("Fetching App ID")

  uri = URI.parse("https://connect-api.cloud.huawei.com/api/publish/v2/appid-list?packageName=#{package_id}")

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  request = Net::HTTP::Get.new(uri.request_uri)
  request["client_id"] = client_id
  request["Authorization"] = "Bearer #{token}"
  response = http.request(request)
  if !response.kind_of? Net::HTTPSuccess
    UI.user_error!("Cannot obtain app id, please check API Token / Permissions (status code: #{response.code})")
    return false
  end
  result_json = JSON.parse(response.body)

  if result_json['ret']['code'] == 0
    UI.success("Successfully getting app id")
    return result_json['appids'][0]['value']
  else
    UI.user_error!(result_json)
    UI.user_error!("Failed to get app id")
  end

end

.get_app_info(token, client_id, app_id) ⇒ Object



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
# File 'lib/fastlane/plugin/huawei_appgallery_connect/helper/huawei_appgallery_connect_helper.rb', line 53

def self.get_app_info(token, client_id, app_id)
  UI.message("Fetching App Info")

  uri = URI.parse("https://connect-api.cloud.huawei.com/api/publish/v2/app-info?appId=#{app_id}")

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  request = Net::HTTP::Get.new(uri.request_uri)
  request["client_id"] = client_id
  request["Authorization"] = "Bearer #{token}"
  response = http.request(request)
  if !response.kind_of? Net::HTTPSuccess
    UI.user_error!("Cannot obtain app info, please check API Token / Permissions (status code: #{response.code})")
    return false
  end
  result_json = JSON.parse(response.body)

  if result_json['ret']['code'] == 0
    UI.success("Successfully getting app info")
    return result_json['appInfo']
  else
    UI.user_error!(result_json)
    UI.user_error!("Failed to get app info")
  end

end

.get_token(client_id, client_secret) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/fastlane/plugin/huawei_appgallery_connect/helper/huawei_appgallery_connect_helper.rb', line 11

def self.get_token(client_id, client_secret)
  UI.important("Fetching app access token")

  uri = URI('https://connect-api.cloud.huawei.com/api/oauth2/v1/token')
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  req = Net::HTTP::Post.new(uri.path, 'Content-Type' => 'application/json')
  req.body = {client_id: client_id, grant_type: 'client_credentials', client_secret: client_secret }.to_json
  res = http.request(req)

  result_json = JSON.parse(res.body)

  return result_json['access_token']
end

.prepare_test_config(params) ⇒ Object



418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
# File 'lib/fastlane/plugin/huawei_appgallery_connect/helper/huawei_appgallery_connect_helper.rb', line 418

def self.prepare_test_config(params)
  # Calculate test start time (1 hour from now if not provided)
  start_time = if params[:test_start_time]
                Time.parse(params[:test_start_time])
              else
                Time.now + (60 * 60) # 1 hour from now
              end

  # Calculate test end time (80 days from start if not provided)
  end_time = if params[:test_end_time]
              Time.parse(params[:test_end_time])
            else
              start_time + (80 * 24 * 60 * 60) # 80 days from start
            end

  {
    testStartTime: start_time.strftime('%Y-%m-%dT%H:%M:%S+0000'),
    testEndTime: end_time.strftime('%Y-%m-%dT%H:%M:%S+0000'),
    skipManualReview: params[:skip_manual_review] != false,
    feedbackEmail: params[:feedback_email],
    releaseType: 1, # Force open testing release type
    testPhase: true, # Explicitly set test phase
    testMode: 1 # Set test mode to open testing
  }
end

.query_aab_compilation_status(token, params, pkgVersion) ⇒ Object



273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
# File 'lib/fastlane/plugin/huawei_appgallery_connect/helper/huawei_appgallery_connect_helper.rb', line 273

def self.query_aab_compilation_status(token,params, pkgVersion)
  UI.important("Checking aab compilation status")
  uri = URI.parse("https://connect-api.cloud.huawei.com/api/publish/v2/aab/complile/status?appId=#{params[:app_id]}&pkgIds=#{pkgVersion}")

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  request = Net::HTTP::Get.new(uri.request_uri)
  request["client_id"] = params[:client_id]
  request["Authorization"] = "Bearer #{token}"

  response = http.request(request)

  if !response.kind_of? Net::HTTPSuccess
    UI.user_error!("Cannot query compilation status (status code: #{response.code}, body: #{response.body})")
    return false
  end

  result_json = JSON.parse(response.body)

  if result_json['ret']['code'] == 0
    return result_json['pkgStateList'][0]['aabCompileStatus']
  else
    UI.user_error!(result_json)
    return -999
  end
end

.set_gms_dependency(token, client_id, app_id, gms_dependency) ⇒ Object



500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
# File 'lib/fastlane/plugin/huawei_appgallery_connect/helper/huawei_appgallery_connect_helper.rb', line 500

def self.set_gms_dependency(token, client_id, app_id, gms_dependency)
  UI.message("Setting GMS Dependency")

  uri = URI.parse("https://connect-api.cloud.huawei.com/api/publish/v2/properties/gms?appId=#{app_id}")

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  request = Net::HTTP::Put.new(uri.request_uri)
  request["client_id"] = client_id
  request["Authorization"] = "Bearer #{token}"
  request["Content-Type"] = "application/json"

  request.body = {needGms: gms_dependency}.to_json

  response = http.request(request)
  if !response.kind_of? Net::HTTPSuccess
    UI.user_error!("Cannot update gms dependency, please check API Token / Permissions (status code: #{response.code})")
    return false
  end
  result_json = JSON.parse(response.body)

  if result_json['ret']['code'] == 0
    UI.success("Successfully updated GMS Dependency")
  else
    UI.user_error!(result_json)
    UI.user_error!("Failed to update GMS Dependency")
  end
end

.submit_app_for_review(token, params) ⇒ Object



300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
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
# File 'lib/fastlane/plugin/huawei_appgallery_connect/helper/huawei_appgallery_connect_helper.rb', line 300

def self.submit_app_for_review(token, params)
  UI.important("Submitting app for review")

  release_type = ''
  release_time = ''
  test_config = {}

  # Handle open testing configuration
  if params[:use_testing_version]
    UI.important("Configuring open testing")
    test_config = prepare_test_config(params)
    release_type = '&releaseType=1' # Open testing release type
  elsif (params[:phase_wise_release] != nil && params[:phase_wise_release]) && (
        params[:phase_release_start_time] == nil ||
        params[:phase_release_end_time] == nil ||
        params[:phase_release_percent] == nil ||
        params[:phase_release_description] == nil
  )
    UI.user_error!("Submit for review failed. Phase wise release requires Start time, End time Release Percent & Description")
    return
  elsif params[:phase_wise_release] != nil && params[:phase_wise_release]
    release_type = '&releaseType=3'
  end

  if params[:release_time] != nil
    params[:release_time] = CGI.escape(params[:release_time])
    release_time = "&releaseTime=#{params[:release_time]}"
  end

  changelog = ''

  if params[:changelog_path] != nil
    changelog_data = File.read(params[:changelog_path])

    if changelog_data.length < 10 || changelog_data.length > 300
      UI.user_error!("Failed to submit app for review. Changelog must be between 10 and 300 characters (got #{changelog_data.length})")
      return
    else
      changelog = "&remark=" + CGI.escape(changelog_data)
    end
  end

  uri = URI.parse("https://connect-api.cloud.huawei.com/api/publish/v2/app-submit?appId=#{params[:app_id]}" + changelog + release_type + release_time)

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  request = Net::HTTP::Post.new(uri.request_uri)
  request["client_id"] = params[:client_id]
  request["Authorization"] = "Bearer #{token}"
  request["Content-Type"] = "application/json"

  if params[:phase_wise_release] != nil && params[:phase_wise_release]
    request.body = {
        phasedReleaseStartTime: params[:phase_release_start_time],
        phasedReleaseEndTime: params[:phase_release_end_time],
        phasedReleasePercent: params[:phase_release_percent],
        phasedReleaseDescription: params[:phase_release_description]
    }.to_json
  elsif params[:use_testing_version]
    test_config[:releaseType] = 1  # Explicitly set release type for open testing
    request.body = test_config.to_json
  end

  UI.important("Request URL: #{uri.to_s}")
  UI.important("Request Body: #{request.body}")

  response = http.request(request)

  if !response.kind_of? Net::HTTPSuccess
    UI.user_error!("Cannot submit app for review (status code: #{response.code}, body: #{response.body})")
    return false
  end

  result_json = JSON.parse(response.body)

  if result_json['ret']['code'] == 0
    UI.success("Successfully submitted app for review")
  elsif result_json['ret']['code'] == 204144660 && result_json['ret']['msg'].include?("It may take 2-5 minutes")
    UI.important(result_json)
    UI.important("Build is currently processing, waiting for 2 minutes before submitting again...")
    sleep(120)
    self.submit_app_for_review(token, params)
  else
    UI.user_error!(result_json)
    UI.user_error!("Failed to submit app for review.")
  end
end

.update_app_localization_info(token, params) ⇒ Object



444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
# File 'lib/fastlane/plugin/huawei_appgallery_connect/helper/huawei_appgallery_connect_helper.rb', line 444

def self.update_app_localization_info(token, params)
   = if !params[:metadata_path].nil?
                    params[:metadata_path]
                  else
                    'fastlane/metadata/huawei'
                  end

  UI.important("Uploading app localization information from path: #{}")

  # gather info from metadata folders
  Dir.glob("#{}/*") do |folder|
    uri = URI.parse("https://connect-api.cloud.huawei.com/api/publish/v2/app-language-info?appId=#{params[:app_id]}")
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true
    request = Net::HTTP::Put.new(uri.request_uri)
    request['client_id'] = params[:client_id]
    request['Authorization'] = "Bearer #{token}"
    request['Content-Type'] = 'application/json'
    lang = File.basename(folder)
    body = { "lang": lang }

    Dir.glob("#{folder}/*") do |file|
      case file
      when /app_name/
        body[:appName] = File.read(file)
      when /app_description/
        body[:appDesc] = File.read(file)
      when /introduction/
        body[:briefInfo] = File.read(file)
      when /release_notes/
        body[:newFeatures] = File.read(file)
      end
    end

    body.length.zero? && next
    UI.important(body.to_json)
    request.body = body.to_json
    response = http.request(request)

    UI.important(response)

    unless response.is_a? Net::HTTPSuccess
      UI.user_error!("Cannot upload localization info (status code: #{response.code}, body: #{response.body})")
      return false
    end

    result_json = JSON.parse(response.body)

    if result_json['ret']['code'].zero?
      UI.success("Successfully uploaded app localization info for #{File.basename(folder)}")
    else
      UI.user_error!(result_json)
    end
  end
end

.update_appinfo(client_id, token, app_id, privacy_policy_url) ⇒ Object



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
107
# File 'lib/fastlane/plugin/huawei_appgallery_connect/helper/huawei_appgallery_connect_helper.rb', line 80

def self.update_appinfo(client_id, token, app_id, privacy_policy_url)
  UI.important("Updating app info")

  uri = URI.parse("https://connect-api.cloud.huawei.com/api/publish/v2/app-info?appId=#{app_id}")

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  request = Net::HTTP::Put.new(uri.request_uri)
  request["client_id"] = client_id
  request["Authorization"] = "Bearer #{token}"
  request["Content-Type"] = "application/json"

  request.body = {privacyPolicy: privacy_policy_url}.to_json

  response = http.request(request)
  if !response.kind_of? Net::HTTPSuccess
    UI.user_error!("Cannot update app info, please check API Token / Permissions (status code: #{response.code})")
    return false
  end
  result_json = JSON.parse(response.body)

  if result_json['ret']['code'] == 0
    UI.success("Successfully updated app info")
  else
    UI.user_error!(result_json)
    UI.user_error!("Failed to update app info")
  end
end

.upload_app(token, client_id, app_id, apk_path, is_aab) ⇒ Object



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
194
195
196
197
198
199
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
# File 'lib/fastlane/plugin/huawei_appgallery_connect/helper/huawei_appgallery_connect_helper.rb', line 110

def self.upload_app(token, client_id, app_id, apk_path, is_aab)
  UI.message("Fetching upload URL")

  responseData = JSON.parse("{}")
  responseData["success"] = false
  responseData["code"] = 0

  file_size_in_bytes = File.size(apk_path.to_s)
  sha256 = Digest::SHA256.file(apk_path).hexdigest

  if(is_aab)
    uri = URI.parse("https://connect-api.cloud.huawei.com/api/publish/v2/upload-url/for-obs?appId=#{app_id}&fileName=release.aab&contentLength=#{file_size_in_bytes}&suffix=aab")
    upload_filename = "release.aab"
  else
    uri = URI.parse("https://connect-api.cloud.huawei.com/api/publish/v2/upload-url/for-obs?appId=#{app_id}&fileName=release.apk&contentLength=#{file_size_in_bytes}&suffix=apk")
    upload_filename = "release.apk"
  end

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  request = Net::HTTP::Get.new(uri.request_uri)
  request["client_id"] = client_id
  request["Authorization"] = "Bearer #{token}"
  request["Content-Type"] = "application/json"

  response = http.request(request)

  if !response.kind_of? Net::HTTPSuccess
    UI.user_error!("Cannot obtain upload url, please check API Token / Permissions (status code: #{response.code})")
    responseData["success"] = false
    return responseData
  end

  result_json = JSON.parse(response.body)

  if result_json.nil? || result_json['urlInfo'].nil? || result_json['urlInfo']['url'].nil?
    UI.message('Cannot obtain upload url')
    UI.user_error!(response.body)

    responseData["success"] = false
    return responseData
  else
    UI.important('Uploading app')
    # Upload App
    boundary = "755754302457647"
    uri = URI(result_json['urlInfo']['url'])
    # uri = URI("http://localhost/dashboard/test")
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true
    request = Net::HTTP::Put.new(uri)
    request["Authorization"] = result_json['urlInfo']['headers']['Authorization']
    request["Content-Type"] = result_json['urlInfo']['headers']['Content-Type']
    request["user-agent"] = result_json['urlInfo']['headers']['user-agent']
    request["Host"] = result_json['urlInfo']['headers']['Host']
    request["x-amz-date"] = result_json['urlInfo']['headers']['x-amz-date']
    request["x-amz-content-sha256"] = result_json['urlInfo']['headers']['x-amz-content-sha256']

    request.body = File.read(apk_path.to_s)
    request.content_type = 'application/octet-stream'

    result = http.request(request)
    if !result.kind_of? Net::HTTPSuccess
      UI.user_error!(result.body)
      UI.user_error!("Cannot upload app, please check API Token / Permissions (status code: #{result.code})")
      responseData["success"] = false
      return responseData
    end

    if result.code.to_i == 200
      UI.success('Upload app to AppGallery Connect successful')
      UI.important("Saving app information")

      uri = URI.parse("https://connect-api.cloud.huawei.com/api/publish/v2/app-file-info?appId=#{app_id}")

      http = Net::HTTP.new(uri.host, uri.port)
      http.use_ssl = true
      request = Net::HTTP::Put.new(uri.request_uri)
      request["client_id"] = client_id
      request["Authorization"] = "Bearer #{token}"
      request["Content-Type"] = "application/json"

      data = {fileType: 5, files: [{

          fileName: upload_filename,
          fileDestUrl: result_json['urlInfo']['objectId']
          # size: result_json['result']['UploadFileRsp']['fileInfoList'][0]['size'].to_s

      }] }.to_json

      request.body = data
      response = http.request(request)
      if !response.kind_of? Net::HTTPSuccess
        UI.user_error!("Cannot save app info, please check API Token / Permissions (status code: #{response.code})")
        responseData["success"] = false
        return responseData
      end
      result_json = JSON.parse(response.body)

      if result_json['ret']['code'] == 0
        UI.success("App information saved.")
        responseData["success"] = true
        responseData["pkgVersion"] = result_json["pkgVersion"][0]
        return responseData
      else
        UI.user_error!(result_json)
        UI.user_error!("Failed to save app information")
        responseData["success"] = false
        return responseData
      end
    else
      responseData["success"] = false
      return responseData
    end
  end
end

.upload_asset(token, client_id, app_id, asset_path, file_type: 5, lang: nil) ⇒ Object

Uploads a visual asset (icon, screenshot, video, or PDF) to AGC. Huawei uses the same OBS upload flow for all supported file formats; callers provide the fileType used by their Publishing API account.



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
262
263
264
265
266
267
268
269
270
271
# File 'lib/fastlane/plugin/huawei_appgallery_connect/helper/huawei_appgallery_connect_helper.rb', line 229

def self.upload_asset(token, client_id, app_id, asset_path, file_type: 5, lang: nil)
  UI.message("Uploading AppGallery asset #{File.basename(asset_path)}")
  UI.user_error!("Asset does not exist: #{asset_path}") unless File.file?(asset_path)

  filename = File.basename(asset_path)
  suffix = File.extname(filename).delete('.').downcase
  size = File.size(asset_path)
  query = URI.encode_www_form(appId: app_id, fileName: filename,
                              contentLength: size, suffix: suffix)
  uri = URI.parse("https://connect-api.cloud.huawei.com/api/publish/v2/upload-url/for-obs?#{query}")
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  request = Net::HTTP::Get.new(uri.request_uri)
  request['client_id'] = client_id
  request['Authorization'] = "Bearer #{token}"
  response = http.request(request)
  UI.user_error!("Cannot obtain asset upload URL (status code: #{response.code})") unless response.is_a?(Net::HTTPSuccess)

  upload_info = JSON.parse(response.body).fetch('urlInfo')
  upload_uri = URI.parse(upload_info.fetch('url'))
  upload_http = Net::HTTP.new(upload_uri.host, upload_uri.port)
  upload_http.use_ssl = true
  upload_request = Net::HTTP::Put.new(upload_uri)
  upload_info.fetch('headers').each { |key, value| upload_request[key] = value }
  upload_request.body = File.binread(asset_path)
  upload_response = upload_http.request(upload_request)
  UI.user_error!("Cannot upload asset (status code: #{upload_response.code})") unless upload_response.is_a?(Net::HTTPSuccess)

  info_uri = URI.parse("https://connect-api.cloud.huawei.com/api/publish/v2/app-file-info?appId=#{CGI.escape(app_id.to_s)}")
  info_http = Net::HTTP.new(info_uri.host, info_uri.port)
  info_http.use_ssl = true
  info_request = Net::HTTP::Put.new(info_uri.request_uri)
  info_request['client_id'] = client_id
  info_request['Authorization'] = "Bearer #{token}"
  info_request['Content-Type'] = 'application/json'
  file = { fileName: filename, fileDestUrl: upload_info.fetch('objectId'), size: size }
  payload = { fileType: file_type, files: [file] }
  payload[:lang] = lang if lang
  info_request.body = payload.to_json
  info_response = info_http.request(info_request)
  UI.user_error!("Cannot save asset information (status code: #{info_response.code})") unless info_response.is_a?(Net::HTTPSuccess)
  JSON.parse(info_response.body)
end

.withdraw_app_review(token, client_id, app_id) ⇒ Object



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
414
415
416
# File 'lib/fastlane/plugin/huawei_appgallery_connect/helper/huawei_appgallery_connect_helper.rb', line 388

def self.withdraw_app_review(token, client_id, app_id)
  UI.important("Withdrawing app review")

  uri = URI.parse("https://connect-api.cloud.huawei.com/api/publish/v1/app-info/withdraw?appId=#{CGI.escape(app_id)}")

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  request = Net::HTTP::Post.new(uri.request_uri)
  request["client_id"] = client_id
  request["Authorization"] = "Bearer #{token}"
  request["Content-Type"] = "application/json"

  response = http.request(request)

  unless response.kind_of? Net::HTTPSuccess
    UI.user_error!("Cannot withdraw app review (status code: #{response.code}, body: #{response.body})")
    return false
  end

  result_json = JSON.parse(response.body)

  if result_json['ret']['code'] == 0
    UI.success("Successfully withdrew app review")
    true
  else
    UI.user_error!(result_json)
    false
  end
end