Class: Fastlane::Actions::UploadBuildToAppsCdnAction

Inherits:
Action
  • Object
show all
Defined in:
lib/fastlane/plugin/wpmreleasetoolkit/actions/common/upload_build_to_apps_cdn.rb

Constant Summary collapse

RESOURCE_TYPE =
'Build'
VALID_POST_STATUS =
%w[publish draft].freeze
VALID_BUILD_TYPES =
%w[Alpha Beta Nightly Production Prototype].freeze
VALID_PLATFORMS =
['Android', 'iOS', 'Mac - Silicon', 'Mac - Intel', 'Mac - Any', 'Windows'].freeze

Class Method Summary collapse

Class Method Details

.authorsObject



143
144
145
# File 'lib/fastlane/plugin/wpmreleasetoolkit/actions/common/upload_build_to_apps_cdn.rb', line 143

def self.authors
  ['Automattic']
end

.available_optionsObject



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
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# File 'lib/fastlane/plugin/wpmreleasetoolkit/actions/common/upload_build_to_apps_cdn.rb', line 158

def self.available_options
  [
    FastlaneCore::ConfigItem.new(
      key: :site_id,
      env_name: 'APPS_CDN_SITE_ID',
      description: 'The WordPress.com CDN site ID to upload the media to',
      optional: false,
      type: String,
      verify_block: proc do |value|
        UI.user_error!('Site ID cannot be empty') if value.to_s.empty?
      end
    ),
    FastlaneCore::ConfigItem.new(
      key: :product,
      env_name: 'APPS_CDN_PRODUCT',
      # Valid values can be found at https://github.a8c.com/Automattic/wpcom/blob/trunk/wp-content/lib/a8c/cdn/src/enums/enum-product.php
      description: 'The product the build belongs to (e.g. \'WordPress.com Studio\')',
      optional: false,
      type: String,
      verify_block: proc do |value|
        UI.user_error!('Product cannot be empty') if value.to_s.empty?
      end
    ),
    FastlaneCore::ConfigItem.new(
      key: :platform,
      env_name: 'APPS_CDN_PLATFORM',
      # Valid values can be found at https://github.a8c.com/Automattic/wpcom/blob/trunk/wp-content/lib/a8c/cdn/src/enums/enum-platform.php
      description: "The platform the build runs on. One of: #{VALID_PLATFORMS.join(', ')}",
      optional: false,
      type: String,
      verify_block: proc do |value|
        UI.user_error!('Platform cannot be empty') if value.to_s.empty?
        UI.user_error!("Platform must be one of: #{VALID_PLATFORMS.join(', ')}") unless VALID_PLATFORMS.include?(value)
      end
    ),
    FastlaneCore::ConfigItem.new(
      key: :file_path,
      description: 'The path to the build file to upload',
      optional: false,
      type: String,
      verify_block: proc do |value|
        UI.user_error!("File not found at path '#{value}'") unless File.exist?(value)
      end
    ),
    FastlaneCore::ConfigItem.new(
      key: :build_type,
      # Valid values can be found at https://github.a8c.com/Automattic/wpcom/blob/trunk/wp-content/lib/a8c/cdn/src/enums/enum-build-type.php
      description: "The type of the build. One of: #{VALID_BUILD_TYPES.join(', ')}",
      optional: false,
      type: String,
      verify_block: proc do |value|
        UI.user_error!('Build type cannot be empty') if value.to_s.empty?
        UI.user_error!("Build type must be one of: #{VALID_BUILD_TYPES.join(', ')}") unless VALID_BUILD_TYPES.include?(value)
      end
    ),
    FastlaneCore::ConfigItem.new(
      key: :visibility,
      description: 'The visibility of the build (:internal or :external)',
      optional: false,
      type: Symbol,
      verify_block: proc do |value|
        UI.user_error!('Visibility must be either :internal or :external') unless %i[internal external].include?(value)
      end
    ),
    FastlaneCore::ConfigItem.new(
      key: :post_status,
      description: 'The post status (defaults to \'publish\')',
      optional: true,
      default_value: 'publish',
      type: String,
      verify_block: proc do |value|
        UI.user_error!("Post status must be one of: #{VALID_POST_STATUS.join(', ')}") unless VALID_POST_STATUS.include?(value)
      end
    ),
    FastlaneCore::ConfigItem.new(
      key: :version,
      description: 'The version string for the build (e.g. \'20.0\', \'17.8.1\')',
      optional: false,
      type: String,
      verify_block: proc do |value|
        UI.user_error!('Version cannot be empty') if value.to_s.empty?
      end
    ),
    FastlaneCore::ConfigItem.new(
      key: :build_number,
      description: 'The build number for the build (e.g. \'42\')',
      optional: true,
      type: String
    ),
    FastlaneCore::ConfigItem.new(
      key: :minimum_system_version,
      description: 'The minimum version for the provided platform (e.g. \'13.0\' for macOS Ventura)',
      optional: true,
      type: String
    ),
    FastlaneCore::ConfigItem.new(
      key: :release_notes,
      description: 'The release notes to show with the build on the blog frontend',
      optional: true,
      type: String
    ),
    FastlaneCore::ConfigItem.new(
      key: :error_on_duplicate,
      description: 'If true, the action will error if a build matching the same metadata already exists. If false, any potential existing build matching the same metadata will be updated to replace the build with the new file',
      default_value: false,
      type: Boolean
    ),
    FastlaneCore::ConfigItem.new(
      key: :api_token,
      env_name: 'WPCOM_API_TOKEN',
      description: 'The WordPress.com API token for authentication',
      optional: false,
      type: String,
      verify_block: proc do |value|
        UI.user_error!('API token cannot be empty') if value.to_s.empty?
      end
    ),
  ]
end

.build_multipart_request(parameters:, file_path:) ⇒ Array

Builds a multipart request body for the WordPress.com Media API

Parameters:

  • parameters (Hash)

    The parameters to include in the request as top-level form fields

  • file_path (String)

    The path to the file to upload

Returns:

  • (Array)

    An array containing the request body and the content-type header



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/fastlane/plugin/wpmreleasetoolkit/actions/common/upload_build_to_apps_cdn.rb', line 87

def self.build_multipart_request(parameters:, file_path:)
  boundary = "----WebKitFormBoundary#{SecureRandom.hex(10)}"
  content_type = "multipart/form-data; boundary=#{boundary}"
  post_body = []

  # Add the file first
  post_body << "--#{boundary}"
  post_body << "Content-Disposition: form-data; name=\"media[]\"; filename=\"#{File.basename(file_path)}\""
  post_body << 'Content-Type: application/octet-stream'
  post_body << ''
  post_body << File.binread(file_path)

  # Add each parameter as a separate form field
  parameters.each do |key, value|
    post_body << "--#{boundary}"
    post_body << "Content-Disposition: form-data; name=\"#{key}\""
    post_body << ''
    post_body << value.to_s
  end

  # Add the closing boundary
  post_body << "--#{boundary}--"

  [post_body.join("\r\n"), content_type]
end

.descriptionObject



139
140
141
# File 'lib/fastlane/plugin/wpmreleasetoolkit/actions/common/upload_build_to_apps_cdn.rb', line 139

def self.description
  'Uploads a build binary to the Apps CDN'
end

.detailsObject



151
152
153
154
155
156
# File 'lib/fastlane/plugin/wpmreleasetoolkit/actions/common/upload_build_to_apps_cdn.rb', line 151

def self.details
  <<~DETAILS
    Uploads a build binary file to a WordPress blog that has the Apps CDN plugin enabled.
    See PCYsg-15tP-p2 internal a8c documentation for details about the Apps CDN plugin.
  DETAILS
end

.example_codeObject



291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
# File 'lib/fastlane/plugin/wpmreleasetoolkit/actions/common/upload_build_to_apps_cdn.rb', line 291

def self.example_code
  [
    'upload_build_to_apps_cdn(
      site_id: "12345678",
      api_token: ENV["WPCOM_API_TOKEN"],
      product: "WordPress.com Studio",
      build_type: "Beta",
      visibility: :internal,
      platform: "Mac - Any",
      version: "20.0",
      build_number: "42",
      file_path: "path/to/app.zip"
    )',
    'upload_build_to_apps_cdn(
      site_id: "12345678",
      api_token: ENV["WPCOM_API_TOKEN"],
      product: "WordPress.com Studio",
      build_type: "Beta",
      visibility: :external,
      platform: "Android",
      version: "20.0",
      build_number: "42",
      file_path: "path/to/app.apk",
      error_on_duplicate: true
    )',
  ]
end

.is_supported?(platform) ⇒ Boolean

Returns:

  • (Boolean)


278
279
280
# File 'lib/fastlane/plugin/wpmreleasetoolkit/actions/common/upload_build_to_apps_cdn.rb', line 278

def self.is_supported?(platform)
  true
end

.outputObject



282
283
284
285
286
287
288
289
# File 'lib/fastlane/plugin/wpmreleasetoolkit/actions/common/upload_build_to_apps_cdn.rb', line 282

def self.output
  [
    ['APPS_CDN_UPLOADED_FILE_URL', 'The URL of the uploaded file'],
    ['APPS_CDN_UPLOADED_FILE_ID', 'The ID of the uploaded file'],
    ['APPS_CDN_UPLOADED_POST_ID', 'The ID of the post / page created for the uploaded build'],
    ['APPS_CDN_UPLOADED_POST_URL', 'The URL of the post / page created for the uploaded build'],
  ]
end

.parse_successful_response(response_body) ⇒ Hash

Parse the successful response and return a hash with the upload details

Parameters:

  • response_body (String)

    The raw response body from the API

Returns:

  • (Hash)

    A hash containing the upload details



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/fastlane/plugin/wpmreleasetoolkit/actions/common/upload_build_to_apps_cdn.rb', line 117

def self.parse_successful_response(response_body)
  json_response = JSON.parse(response_body)
  media = json_response['media'].first
  media_id = media['ID']
  media_url = media['URL']
  post_id = media['post_ID']

  # Compute the post URL using the same base URL as media_url
  post_url = URI.parse(media_url)
  post_url.path = '/'
  post_url.query = "p=#{post_id}"
  post_url = post_url.to_s

  {
    post_id: post_id,
    post_url: post_url,
    media_id: media_id,
    media_url: media_url,
    mime_type: media['mime_type']
  }
end

.return_valueObject



147
148
149
# File 'lib/fastlane/plugin/wpmreleasetoolkit/actions/common/upload_build_to_apps_cdn.rb', line 147

def self.return_value
  'Returns a Hash containing the upload result: { post_id:, post_url:, media_id:, media_url:, mime_type: }. On error, raises a FastlaneError.'
end

.run(params) ⇒ Object



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
# File 'lib/fastlane/plugin/wpmreleasetoolkit/actions/common/upload_build_to_apps_cdn.rb', line 23

def self.run(params)
  UI.message('Uploading build to Apps CDN...')

  file_path = params[:file_path]
  UI.user_error!("File not found at path '#{file_path}'") unless File.exist?(file_path)

  api_endpoint = "https://public-api.wordpress.com/rest/v1.1/sites/#{params[:site_id]}/media/new"
  uri = URI.parse(api_endpoint)

  # Create the request body and headers
  parameters = {
    product: params[:product],
    build_type: params[:build_type],
    visibility: params[:visibility].to_s.capitalize,
    platform: params[:platform],
    resource_type: RESOURCE_TYPE,
    version: params[:version],
    build_number: params[:build_number], # Optional: may be nil
    minimum_system_version: params[:minimum_system_version], # Optional: may be nil
    post_status: params[:post_status], # Optional: may be nil
    release_notes: params[:release_notes], # Optional: may be nil
    error_on_duplicate: params[:error_on_duplicate] # defaults to false
  }.compact
  request_body, content_type = build_multipart_request(parameters: parameters, file_path: file_path)

  # Create and send the HTTP request
  request = Net::HTTP::Post.new(uri.request_uri)
  request.body = request_body
  request['Content-Type'] = content_type
  request['Accept'] = 'application/json'
  request['Authorization'] = "Bearer #{params[:api_token]}"

  response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http|
    http.request(request)
  end

  # Handle the response
  case response
  when Net::HTTPSuccess
    result = parse_successful_response(response.body)

    Actions.lane_context[SharedValues::APPS_CDN_UPLOADED_POST_ID] = result[:post_id]
    Actions.lane_context[SharedValues::APPS_CDN_UPLOADED_POST_URL] = result[:post_url]
    Actions.lane_context[SharedValues::APPS_CDN_UPLOADED_FILE_ID] = result[:media_id]
    Actions.lane_context[SharedValues::APPS_CDN_UPLOADED_FILE_URL] = result[:media_url]

    UI.success('Build successfully uploaded to Apps CDN')
    UI.message("Post ID: #{result[:post_id]}")
    UI.message("Post URL: #{result[:post_url]}")

    result
  else
    UI.error("Failed to upload build to Apps CDN: #{response.code} #{response.message}")
    UI.error(response.body)
    UI.user_error!('Upload to Apps CDN failed')
  end
end