Module: EnterpriseAppStoreUploadService

Defined in:
lib/fastlane/plugin/appcircle_enterprise_app_store/helper/upload_service.rb

Constant Summary collapse

UI =
FastlaneCore::UI
BASE_URL =
"https://api.appcircle.io"

Class Method Summary collapse

Class Method Details

.getAppVersions(auth_token:, entProfileId:, api_endpoint: BASE_URL) ⇒ Object



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/fastlane/plugin/appcircle_enterprise_app_store/helper/upload_service.rb', line 98

def self.getAppVersions(auth_token:, entProfileId:, api_endpoint: BASE_URL)
  url = "#{api_endpoint}/store/v2/profiles/#{entProfileId}/app-versions"

  # Set up the headers with authentication
  headers = {
    Authorization: "Bearer #{auth_token}",
    accept: 'application/json'
  }

  begin
    response = RestClient.get(url, headers)
    JSON.parse(response.body)
  rescue RestClient::ExceptionWithResponse => e
    raise e
  rescue StandardError => e
    raise e
  end
end

.getEntProfiles(authToken:, api_endpoint: BASE_URL) ⇒ Object



149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/fastlane/plugin/appcircle_enterprise_app_store/helper/upload_service.rb', line 149

def self.getEntProfiles(authToken:, api_endpoint: BASE_URL)
  url = "#{api_endpoint}/store/v2/profiles"
  headers = {
    Authorization: "Bearer #{authToken}",
    accept: 'application/json'
  }

  begin
    response = RestClient.get(url, headers)
    JSON.parse(response.body)
  rescue RestClient::ExceptionWithResponse => e
    raise e
  rescue StandardError => e
    raise e
  end
end

.getProfileId(authToken:, api_endpoint: BASE_URL) ⇒ Object



166
167
168
169
170
171
172
173
174
175
176
# File 'lib/fastlane/plugin/appcircle_enterprise_app_store/helper/upload_service.rb', line 166

def self.getProfileId(authToken:, api_endpoint: BASE_URL)
  profiles = self.getEntProfiles(authToken: authToken, api_endpoint: api_endpoint)
  return nil unless profiles.is_a?(Array) && !profiles.empty?

  sortedProfiles = profiles.sort_by do |profile|
    date = profile["lastBinaryReceivedDate"]
    date ? DateTime.parse(date) : DateTime.new(0)
  end.reverse

  sortedProfiles[0] && sortedProfiles[0]['id']
end

.getVersionId(versionList:) ⇒ Object



117
118
119
120
121
122
123
124
125
126
# File 'lib/fastlane/plugin/appcircle_enterprise_app_store/helper/upload_service.rb', line 117

def self.getVersionId(versionList:)
  if versionList.kind_of?(Array) && !versionList.empty?
    return versionList[0]["id"]
  else
    return nil
  end
rescue StandardError => e
  puts("An error occurred while getting app versions: #{e.message}")
  raise e
end

.publishVersion(options) ⇒ Object



128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/fastlane/plugin/appcircle_enterprise_app_store/helper/upload_service.rb', line 128

def self.publishVersion(options)
  endpoint = "store/v2/profiles/#{options[:ent_profile_id]}/app-versions/#{options[:ent_version_id]}?action=publish"
  url = "#{options[:api_endpoint] || BASE_URL}/#{endpoint}"

  payload = {
    summary: options[:summary],
    releaseNotes: options[:release_notes],
    publishType: options[:publish_type]
  }

  headers = {
    'Content-Type': 'application/json',
    Authorization: "Bearer #{options[:auth_token]}"
  }

  response = RestClient.patch(url, payload.to_json, headers)
  JSON.parse(response.body)
rescue RestClient::ExceptionWithResponse => e
  raise e
end

.put_with_retry(url, body, headers, max_retries: 5) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/fastlane/plugin/appcircle_enterprise_app_store/helper/upload_service.rb', line 10

def self.put_with_retry(url, body, headers, max_retries: 5)
  attempt = 0
  delay = 1.0

  begin
    RestClient.put(url, body, headers)
  rescue => e
    status = e.respond_to?(:http_code) ? e.http_code : nil
    retryable = status == 503 ||
                e.is_a?(RestClient::ServerBrokeConnection) ||
                e.is_a?(Errno::ECONNRESET) ||
                (defined?(RestClient::Exceptions::OpenTimeout) && e.is_a?(RestClient::Exceptions::OpenTimeout)) ||
                (defined?(RestClient::Exceptions::ReadTimeout) && e.is_a?(RestClient::Exceptions::ReadTimeout))

    raise e if !retryable || attempt >= max_retries

    attempt += 1
    sleep(delay + rand(0.3)) # backoff + jitter (0-300ms)
    delay *= 2
    retry
  end
end

.upload_artifact(token:, app:, api_endpoint: BASE_URL) ⇒ Object



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 'lib/fastlane/plugin/appcircle_enterprise_app_store/helper/upload_service.rb', line 34

def self.upload_artifact(token:, app:, api_endpoint: BASE_URL)
  file_path = app
  file_name = File.basename(file_path)
  file_size = File.size(file_path)
  auth_header = { Authorization: "Bearer #{token}", accept: 'application/json' }

  begin
    info_uri = URI("#{api_endpoint}/store/v1/profiles/app-versions")
    info_uri.query = URI.encode_www_form({ action: 'uploadInformation', fileName: file_name, fileSize: file_size })

    UI.message("Getting file upload information...")
    info_response = RestClient.get(info_uri.to_s, auth_header)
    if info_response.code.between?(200, 299)
      UI.success("File upload information retrieved successfully with status code: #{info_response.code}")
    else
      UI.error("Failed to retrieve file upload information with status code: #{info_response.code}")
      raise "Failed to retrieve file upload information."
    end
    upload_info = JSON.parse(info_response.body)
    file_id = upload_info['fileId']
    upload_url = upload_info['uploadUrl']
    configuration = upload_info['configuration']
    http_method = (configuration && configuration['httpMethod']) ? configuration['httpMethod'].to_s.upcase : 'PUT'

    UI.message("Uploading file to Appcircle...")
    if http_method == 'POST'
      sign_parameters = configuration['signParameters'] || {}
      payload = {}
      sign_parameters.each { |key, value| payload[key] = value }
      payload['file'] = File.new(file_path, 'rb') # the 'file' field MUST be last
      upload_response = RestClient.post(upload_url, payload)
    else
      upload_response = put_with_retry(upload_url, File.binread(file_path), { content_type: 'application/octet-stream' })
    end

    if upload_response.code.between?(200, 299)
      UI.success("File upload finished successfully with status code: #{upload_response.code}")
    else
      UI.error("File upload failed with status code: #{upload_response.code}")
      raise "File upload failed."
    end

    commit_uri = URI("#{api_endpoint}/store/v1/profiles/app-versions")
    commit_uri.query = URI.encode_www_form({ action: 'commitFileUpload', createNewProfile: true })

    commit_payload = { fileId: file_id, fileName: file_name }.to_json
    commit_headers = { Authorization: "Bearer #{token}", content_type: :json, accept: 'application/json' }

    UI.message("Committing file upload...")
    commit_response = RestClient.post(commit_uri.to_s, commit_payload, commit_headers)
    if commit_response.code.between?(200, 299)
      UI.success("Commit successful with status code: #{commit_response.code}")
    else
      UI.error("Commit failed with status code: #{commit_response.code}")
      raise "Commit failed with status code: #{commit_response.code}"
    end
    JSON.parse(commit_response.body)
  rescue RestClient::ExceptionWithResponse => e
    raise e
  rescue StandardError => e
    raise e
  end
end