summaryrefslogtreecommitdiffhomepage
path: root/dragon/ios_wizard.rb
blob: e38faf1a0435dd86677a5df2b0e032f6d533b854 (plain)
1
2
3
4
5
6
7
8
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
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
107
108
109
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
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
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
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
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
414
415
416
417
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
443
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
499
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
# Copyright 2019 DragonRuby LLC
# MIT License
# ios_wizard.rb has been released under MIT (*only this file*).

class WizardException < Exception
  attr_accessor :console_primitives

  def initialize *console_primitives
    @console_primitives = console_primitives
  end
end

class IOSWizard
  def initialize
    @doctor_executed_at = 0
  end

  def relative_path
    (File.dirname $gtk.binary_path)
  end

  def steps
    [
      :check_for_xcode,
      :check_for_brew,
      :check_for_certs,
      :check_for_device,
      :check_for_dev_profile,
      :determine_app_name,
      :determine_app_id,
      :blow_away_temp,
      :stage_app,
      :write_info_plist,
      :write_entitlements_plist,
      :code_sign,
      :create_ipa,
      :deploy,
    ]
  end

  def get_reserved_sprite png
    sprite_path = ".dragonruby/sprites/wizards/ios/#{png}"

    if !$gtk.ivar :rcb_release_mode
      sprite_path = "deploy_template/#{sprite_path}"
      $gtk.reset_sprite sprite_path
    end

    if !$gtk.read_file sprite_path
      log_error "png #{png} not found."
    end

    sprite_path
  end

  def start
    @certificate_name = nil
    init_wizard_status
    log_info "Starting iOS Wizard so we can deploy to your device."
    @start_at = Kernel.global_tick_count
    steps.each do |m|
      begin
        result = (send m) || :success if @wizard_status[m][:result] != :success
        @wizard_status[m][:result] = result
      rescue Exception => e
        if e.is_a? WizardException
          $console.log.clear
          $console.archived_log.clear
          log "=" * $console.console_text_width
          e.console_primitives.each do |p|
            $console.add_primitive p
          end
          log "=" * $console.console_text_width
        else
          log_error "Step #{m} failed."
          log_error e.to_s
        end

        $console.set_command "$wizards.ios.start"

        break
      end
    end

    return nil
  end

  def always_fail
    return false if $gtk.ivar :rcb_release_mode
    return true
  end

  def check_for_xcode
    if !cli_app_exist?(xcodebuild_cli_app)
      raise WizardException.new(
        "* You need Xcode to use $wizards.ios.start.",
        { w: 75, h: 75, path: get_reserved_sprite("xcode.png") },
        "** 1. Go to http://developer.apple.com and register.",
        "** 2. Download Xcode 11.3+ from http://developer.apple.com/downloads.",
        "   NOTE: DO NOT install Xcode from the App Store. Use the link above.",
        { w: 700, h: 359, path: get_reserved_sprite("xcode-downloads.png") },
        "** 3. After installing. Open up Xcode to accept the EULA."
      )
    end
  end

  def check_for_brew
    if !cli_app_exist?('brew')
      raise WizardException.new(
        "* You need to install Brew.",
        { w: 700, h: 388, path: get_reserved_sprite("brew.png") },
        "** 1. Go to http://brew.sh.",
        "** 2. Copy the command that starts with `/bin/bash -c` on the site.",
        "** 3. Open Terminal and run the command you copied from the website.",
        { w: 700, h: 99, path: get_reserved_sprite("terminal.png") },
      )
    end
  end

  def init_wizard_status
    @wizard_status = {}
    steps.each do |m|
      @wizard_status[m] = { result: :not_started }
    end

    previous_step = nil
    next_step = nil
    steps.each_cons(2) do |current_step, next_step|
      @wizard_status[current_step][:next_step] = next_step
    end

    steps.reverse.each_cons(2) do |current_step, previous_step|
      @wizard_status[current_step][:previous_step] = previous_step
    end
  end

  def restart
    init_wizard_status
    start
  end

  def check_for_dev_profile
    if !($gtk.read_file 'profiles/development.mobileprovision')
      $gtk.system "mkdir -p #{relative_path}/profiles"
      $gtk.system "open #{relative_path}/profiles"
      $gtk.system "echo Download the mobile provisioning profile and place it here with the name development.mobileprovision > #{relative_path}/profiles/README.txt"
      raise WizardException.new(
        "* I didn't find a mobile provision.",
        "** 1. Go to http://developer.apple.com and click \"Certificates, IDs & Profiles\".",
        "** 2. Add an App Identifier.",
        "** 3. Select the App IDs option from the list.",
        { w: 700, h: 75, path: get_reserved_sprite("identifiers.png") },
        "** 4. Add your Device next. You can use idevice_id -l to get the UUID of your device.",
        { w: 365, h: 69, path: get_reserved_sprite("device-link.png") },
        "** 5. Create a Profile. Associate your certs, id, and device.",
        { w: 300, h: 122, path: get_reserved_sprite("profiles.png") },
        "** 6. Download the mobile provision and save it to 'profiles/development.mobileprovision'.",
        { w: 200, h: 124, path: get_reserved_sprite("profiles-folder.png") },
      )
    end
  end

  def determine_app_name
    @app_name = dev_profile_xml[:children].first[:children].first[:children][1][:children].first[:data]
    log_info "App name is: #{@app_name}."
  end

  def dev_profile_xml
    xml = $gtk.read_file 'profiles/development.mobileprovision'
    scrubbed = xml.each_line.map do |l|
      if l.strip.start_with? "<"
        if l.start_with? '</plist>'
          '</plist>'
        elsif l.include? "Apple Inc."
          nil
        elsif l.include? '<data>'
          nil
        else
          l
        end
      else
        nil
      end
    end.reject { |l| !l }.join
    $gtk.parse_xml scrubbed
  end

  def determine_app_id
    # lol
    @app_id = dev_profile_xml[:children].first[:children].first[:children][13][:children][1][:children].first[:data]
    log_info "App Identifier is set to : #{@app_id}"
  end

  def set_app_name name
    @app_name = name
    start
  end

  def set_dev_profile path
    if !$gtk.read_file path
      log_error "I couldn't find a development profile at #{path}."
      ask_for_dev_profile
    else
      @dev_profile_path = path
      start
    end
  end

  def blow_away_temp
    sh "rm -rf #{tmp_directory}"
  end

  def stage_app
    log_info "Staging."
    sh "mkdir -p #{tmp_directory}"
    sh "cp -R #{relative_path}/dragonruby-ios.app \"#{tmp_directory}/#{@app_name}.app\""
  end

  def set_app_id id
    log_info = "App Id set to: #{id}"
    @app_id = id
    start
  end

  def check_for_device
    log_info "Looking for device."

    if !cli_app_exist?(idevice_id_cli_app)
      raise WizardException.new(
         "* It doesn't look like you have the libimobiledevice iOS protocol library installed.",
         "** 1. Open Terminal.",
         { w: 700, h: 99, path: get_reserved_sprite("terminal.png") },
         "** 2. Run: `brew install libimobiledevice`.",
         { w: 500, h: 93, path: get_reserved_sprite("brew-install-libimobiledevice.png") },
      )
    end

    if connected_devices.length == 0
      raise WizardException.new("* I couldn't find any connected devices. Connect your iOS device to your Mac and try again.")
    end

    @device_id = connected_devices.first
    log_info "I will be using device with UUID #{@device_id}"
  end

  def check_for_certs
    log_info "Attempting to find certificates on your computer."

    if !cli_app_exist?(security_cli_app)
      raise WizardException.new(
              "* It doesn't look like you have #{security_cli_app}.",
              "** 1. Open Disk Utility and run First Aid.",
              { w: 700, h: 148, path: get_reserved_sprite("disk-utility.png") },
            )
    end

    if valid_certs.length == 0
      raise WizardException.new(
              "* It doesn't look like you have any valid certs installed.",
              "** 1. Open Xcode.",
              "** 2. Log into your developer account. Xcode -> Preferences -> Accounts.",
              { w: 700, h: 98, path: get_reserved_sprite("login-xcode.png") },
              "** 3. After loggin in, select Manage Certificates...",
              { w: 700, h: 115, path: get_reserved_sprite("manage-certificates.png") },
              "** 4. Add a certificate for Apple Development.",
              { w: 700, h: 217, path: get_reserved_sprite("add-cert.png") },
      )
      raise "You do not have any Apple development certs on this computer."
    end

    @certificate_name = valid_certs.first[:name]
    log_info "I will be using '#{@certificate_name}' to deploy to your device."
  end

  def idevice_id_cli_app
    "idevice_id"
  end

  def security_cli_app
    "/usr/bin/security"
  end

  def xcodebuild_cli_app
    "xcodebuild"
  end

  def valid_certs
    certs = sh("#{security_cli_app} -q find-identity -p codesigning -v").each_line.map do |l|
      if l.include?(")") && !l.include?("Developer ID") && l.include?("Development")
        l.strip
      else
        nil
      end
    end.reject_nil.map do |l|
      number, id, name = l.split(' ', 3)
      name = name.gsub("\"", "") if name
      {
        number: 1,
        id: id,
        name: name
      }
    end
  end

  def connected_devices
    sh("idevice_id -l").strip.each_line.map do |l|
      l.strip
    end.reject { |l| l.length == 0 }
  end

  def cli_app_exist? app
    `which #{app}`.strip.length != 0
  end

  def write_entitlements_plist
    entitlement_plist_string = <<-XML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
	<dict>
		<key>application-identifier</key>
		<string>:app_id</string>
		<key>get-task-allow</key>
		<true/>
	</dict>
</plist>
XML

    log_info "Creating Entitlements.plist"

    $gtk.write_file_root "tmp/ios/Entitlements.plist", entitlement_plist_string.gsub(":app_id", @app_id).strip

    sh "/usr/bin/plutil -convert binary1 \"#{tmp_directory}/Entitlements.plist\""
    sh "/usr/bin/plutil -convert xml1 \"#{tmp_directory}/Entitlements.plist\""

    @entitlement_plist_written = true
  end

  def code_sign
    sh "cp #{@dev_profile_path} \"#{app_path}/embedded.mobileprovision\""

    log_info "Signing app with #{@certificate_name}."

    sh "/usr/bin/plutil -convert binary1 \"#{app_path}/Info.plist\""

    sh "CODESIGN_ALLOCATE=\"/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate\" /usr/bin/codesign -f -s \"#{@certificate_name}\" --entitlements #{tmp_directory}/Entitlements.plist \"#{tmp_directory}/#{@app_name}.app\""

    @code_sign_completed = true
  end

  def write_info_plist
    log_info "Adding Info.plist."

    info_plist_string = <<-XML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
        <key>NSAppTransportSecurity</key>
        <dict>
                <key>NSAllowsArbitraryLoads</key>
                <true/>
                <key>NSExceptionDomains</key>
                <dict>
                        <key>google.com</key>
                        <dict>
                                <key>NSExceptionAllowsInsecureHTTPLoads</key>
                                <true/>
                                <key>NSIncludesSubdomains</key>
                                <true/>
                        </dict>
                </dict>
        </dict>
	<key>BuildMachineOSBuild</key>
	<string>19C57</string>
	<key>CFBundleDevelopmentRegion</key>
	<string>en</string>
	<key>CFBundleDisplayName</key>
	<string>:app_name</string>
	<key>CFBundleExecutable</key>
	<string>Runtime</string>
	<key>CFBundleIconFiles</key>
	<array>
		<string>AppIcon60x60</string>
	</array>
	<key>CFBundleIcons</key>
	<dict>
		<key>CFBundlePrimaryIcon</key>
		<dict>
			<key>CFBundleIconFiles</key>
			<array>
				<string>AppIcon60x60</string>
			</array>
			<key>CFBundleIconName</key>
			<string>AppIcon</string>
		</dict>
	</dict>
	<key>CFBundleIcons~ipad</key>
	<dict>
		<key>CFBundlePrimaryIcon</key>
		<dict>
			<key>CFBundleIconFiles</key>
			<array>
				<string>AppIcon60x60</string>
				<string>AppIcon76x76</string>
			</array>
			<key>CFBundleIconName</key>
			<string>AppIcon</string>
		</dict>
	</dict>
	<key>CFBundleIdentifier</key>
	<string>com.carlile.swisscheese</string>
	<key>CFBundleInfoDictionaryVersion</key>
	<string>6.0</string>
	<key>CFBundleName</key>
	<string>:app_name</string>
	<key>CFBundlePackageType</key>
	<string>APPL</string>
	<key>CFBundleShortVersionString</key>
	<string>1.0</string>
	<key>CFBundleSignature</key>
	<string>????</string>
	<key>CFBundleSupportedPlatforms</key>
	<array>
		<string>iPhoneOS</string>
	</array>
	<key>CFBundleVersion</key>
	<string>1.0</string>
	<key>DTCompiler</key>
	<string>com.apple.compilers.llvm.clang.1_0</string>
	<key>DTPlatformBuild</key>
	<string>17B102</string>
	<key>DTPlatformName</key>
	<string>iphoneos</string>
	<key>DTPlatformVersion</key>
	<string>13.2</string>
	<key>DTSDKBuild</key>
	<string>17B102</string>
	<key>DTSDKName</key>
	<string>iphoneos13.2</string>
	<key>DTXcode</key>
	<string>01131</string>
	<key>DTXcodeBuild</key>
	<string>11C505</string>
	<key>ITSAppUsesNonExemptEncryption</key>
	<false/>
	<key>MinimumOSVersion</key>
	<string>11.0</string>
	<key>UIAppFonts</key>
	<array/>
	<key>UIBackgroundModes</key>
	<array/>
	<key>UIDeviceFamily</key>
	<array>
		<integer>1</integer>
		<integer>2</integer>
	</array>
	<key>UILaunchImages</key>
	<array>
		<dict>
			<key>UILaunchImageMinimumOSVersion</key>
			<string>11.0</string>
			<key>UILaunchImageName</key>
			<string>LaunchImage-1100-Portrait-2436h</string>
			<key>UILaunchImageOrientation</key>
			<string>Portrait</string>
			<key>UILaunchImageSize</key>
			<string>{375, 812}</string>
		</dict>
		<dict>
			<key>UILaunchImageMinimumOSVersion</key>
			<string>8.0</string>
			<key>UILaunchImageName</key>
			<string>LaunchImage-800-Portrait-736h</string>
			<key>UILaunchImageOrientation</key>
			<string>Portrait</string>
			<key>UILaunchImageSize</key>
			<string>{414, 736}</string>
		</dict>
		<dict>
			<key>UILaunchImageMinimumOSVersion</key>
			<string>8.0</string>
			<key>UILaunchImageName</key>
			<string>LaunchImage-800-667h</string>
			<key>UILaunchImageOrientation</key>
			<string>Portrait</string>
			<key>UILaunchImageSize</key>
			<string>{375, 667}</string>
		</dict>
		<dict>
			<key>UILaunchImageMinimumOSVersion</key>
			<string>7.0</string>
			<key>UILaunchImageName</key>
			<string>LaunchImage-700</string>
			<key>UILaunchImageOrientation</key>
			<string>Portrait</string>
			<key>UILaunchImageSize</key>
			<string>{320, 480}</string>
		</dict>
		<dict>
			<key>UILaunchImageMinimumOSVersion</key>
			<string>7.0</string>
			<key>UILaunchImageName</key>
			<string>LaunchImage-700-568h</string>
			<key>UILaunchImageOrientation</key>
			<string>Portrait</string>
			<key>UILaunchImageSize</key>
			<string>{320, 568}</string>
		</dict>
		<dict>
			<key>UILaunchImageMinimumOSVersion</key>
			<string>7.0</string>
			<key>UILaunchImageName</key>
			<string>LaunchImage-700-Portrait</string>
			<key>UILaunchImageOrientation</key>
			<string>Portrait</string>
			<key>UILaunchImageSize</key>
			<string>{768, 1024}</string>
		</dict>
	</array>
	<key>UIRequiredDeviceCapabilities</key>
	<array>
		<string>arm64</string>
	</array>
	<key>UIRequiresFullScreen</key>
	<true/>
	<key>UIStatusBarStyle</key>
	<string>UIStatusBarStyleDefault</string>
	<key>UISupportedInterfaceOrientations</key>
	<array>
		<string>#{device_orientation_xml}</string>
	</array>
</dict>
</plist>
XML

    # <string>UIInterfaceOrientationPortrait</string>
    # <string>UIInterfaceOrientationLandscapeRight</string>

    $gtk.write_file_root "tmp/ios/#{@app_name}.app/Info.plist", info_plist_string.gsub(":app_name", @app_name).strip

    @info_plist_written = true
  end

  def device_orientation_xml
    return "UIInterfaceOrientationLandscapeRight" if $gtk.logical_width > $gtk.logical_height
    return "UIInterfaceOrientationPortrait"
  end

  def tmp_directory
    "#{relative_path}/tmp/ios"
  end

  def app_path
    "#{tmp_directory}/#{@app_name}.app"
  end

  def root_folder
    "#{relative_path}/#{$gtk.cli_arguments[:dragonruby]}"
  end

  def write_ip_address
    $gtk.write_file "app/server_ip_address.txt", $gtk.ffi_misc.get_local_ip_address.strip
  end

  def create_ipa
    write_ip_address
    sh "rm \"#{@app_name}\".ipa"
    sh "rm -rf \"#{app_path}/app\""
    sh "rm -rf \"#{app_path}/sounds\""
    sh "rm -rf \"#{app_path}/sprites\""
    sh "rm -rf \"#{app_path}/data\""
    sh "rm -rf \"#{app_path}/fonts\""
    sh "cp -r \"#{root_folder}/app/\" \"#{app_path}/app/\""
    sh "cp -r \"#{root_folder}/sounds/\" \"#{app_path}/sounds/\""
    sh "cp -r \"#{root_folder}/sprites/\" \"#{app_path}/sprites/\""
    sh "cp -r \"#{root_folder}/data/\" \"#{app_path}/data/\""
    sh "cp -r \"#{root_folder}/fonts/\" \"#{app_path}/fonts/\""
    sh "mkdir -p #{tmp_directory}/ipa_root/Payload"
    sh "cp -r \"#{app_path}\" \"#{tmp_directory}/ipa_root/Payload\""
    sh "chmod -R 755 \"#{tmp_directory}/ipa_root/Payload\""
    do_zip
    sh "cp \"#{tmp_directory}/ipa_root/archive.zip\" \"#{tmp_directory}/#{@app_name}.ipa\""
    sh "XCODE_DIR=\"/Applications/Xcode.app/Contents/Developer\" \"#{relative_path}/dragonruby-deploy-ios\" -d \"#{@device_id}\" \"#{tmp_directory}/#{@app_name}.ipa\""
    cmd_result = `ps -e | grep civetweb`
    is_civet_running = (`ps -e | grep civetweb`).strip.each_line.to_a.length > 2
    if !is_civet_running
      $gtk.system "cp \"#{relative_path}/civetweb\" \"#{tmp_directory}/../src_backup/civetweb\""
      $gtk.system "open \"#{tmp_directory}/../src_backup/civetweb\" -g"
    else
      log "* INFO: civetweb is running already running. No need to start another instance."
    end
    log_info "Check your device!!"
  end

  def do_zip
    $gtk.write_file_root "tmp/ios/do_zip.sh", <<-SCRIPT
pushd #{tmp_directory}/ipa_root/
zip -q -r archive.zip Payload
popd
SCRIPT

    sh "sh #{tmp_directory}/do_zip.sh"
  end

  def sh cmd
    log_info cmd.strip
    result = `#{cmd}`
    if result.strip.length > 0
      log_info result.strip.each_line.map(&:strip).join("\n")
    end
    result
  end

  def deploy
  end
end