Method: Codes::ItunesConnect#download

Defined in:
lib/codes/itunes_connect.rb

#download(args) ⇒ Object

rubocop:disable Metrics/AbcSize



9
10
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
# File 'lib/codes/itunes_connect.rb', line 9

def download(args)
  number_of_codes = args[:number_of_codes]

  code_or_codes = number_of_codes == 1 ? 'code' : 'codes'
  Helper.log.info "Downloading #{number_of_codes} promo #{code_or_codes}..."

  fetch_app_data args

  # Use Pathname because it correctly handles the distinction between relative paths vs. absolute paths
  output_file_path = Pathname.new(args[:output_file_path]) if args[:output_file_path]
  output_file_path ||= Pathname.new(File.join(Dir.getwd, "#{@app_identifier || @app_id}_codes.txt"))
  fail 'Insufficient permissions to write to output file'.red if File.exist?(output_file_path) && !File.writable?(output_file_path)
  visit PROMO_URL.gsub('[[app_id]]', @app_id.to_s).gsub('[[platform]]', @platform)

  begin
    text_fields = wait_for_elements('input[type=text]')
  rescue
    raise "Could not open details page for app #{@app_identifier}. Are you sure you are using the correct apple account and have access to this app?".red
  end
  fail 'There should only be a single text input field to specify the number of codes'.red unless text_fields.count == 1

  text_fields.first.set(number_of_codes.to_s)
  click_next

  # are there any errors ?
  errors = []
  begin
    errors = wait_for_elements('div[id=LCPurpleSoftwarePageWrapperErrorMessage]')
  rescue
  end
  fail errors.first.text.red unless errors.count == 0

  Helper.log.debug 'Accepting the App Store Volume Custom Code Agreement'
  wait_for_elements('input[type=checkbox]').first.click
  click_next

  # the find(:xpath, "..") gets the parent element of the previous expression
  download_url = wait_for_elements("div[class='large-blue-rect-button']").first.find(:xpath, '..')['href']

  codes, request_date = download_codes(download_url)

  format = args[:format]
  codes = download_format(codes, format, request_date, app) if format

  bytes_written = File.write(output_file_path.to_s, codes, mode: 'a+')
  Helper.log.warn 'Could not write your codes to the codes.txt file, but you can still access them from iTunes Connect later' if bytes_written == 0
  Helper.log.info "Added generated codes to '#{output_file_path}'".green unless  bytes_written == 0

  Helper.log.info "Your codes (requested #{request_date}) were successfully downloaded:".green
  puts codes
end