open-merou

Open Mérou, a free iOS app for the Oceanic+ underwater iPhone housing
git clone https://git.schurger.org/open-merou.git
Log | Files | Refs | README | LICENSE

Fastfile (13402B)


      1 require "tmpdir"
      2 
      3 default_platform(:ios)
      4 
      5 # Developer account (team CM5RQKJH56); the App Store Connect key comes from the environment (~/.zshrc_build on the build Mac).
      6 APP_ID = "org.schurger.openmerou"
      7 
      8 def api_key
      9   app_store_connect_api_key(
     10     key_id: ENV["PERSO_ASC_KEY_ID"],
     11     issuer_id: ENV["PERSO_ASC_ISSUER_ID"],
     12     key_filepath: ENV["PERSO_ASC_KEY_PATH"],
     13   )
     14 end
     15 
     16 def xcode_auth
     17   [
     18     "-allowProvisioningUpdates",
     19     "-authenticationKeyPath", ENV["PERSO_ASC_KEY_PATH"],
     20     "-authenticationKeyID", ENV["PERSO_ASC_KEY_ID"],
     21     "-authenticationKeyIssuerID", ENV["PERSO_ASC_ISSUER_ID"],
     22   ]
     23 end
     24 
     25 platform :ios do
     26   def asc(method, path, body = nil)
     27     require "net/http"
     28     uri = URI(path.start_with?("http") ? path : "https://api.appstoreconnect.apple.com#{path}")
     29     klass = { get: Net::HTTP::Get, post: Net::HTTP::Post, patch: Net::HTTP::Patch }[method]
     30     req = klass.new(uri, "Content-Type" => "application/json", "Authorization" => "Bearer #{Spaceship::ConnectAPI.token.text}")
     31     req.body = body.to_json if body
     32     res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |h| h.request(req) }
     33     [res.code.to_i, (JSON.parse(res.body) rescue {})]
     34   end
     35 
     36   desc "Registers the app identifier (the App Store record is created by hand)"
     37   lane :register do
     38     api_key
     39     if Spaceship::ConnectAPI::BundleId.find(APP_ID)
     40       UI.message("#{APP_ID} already registered")
     41     else
     42       Spaceship::ConnectAPI::BundleId.create(name: "Open Merou", identifier: APP_ID, platform: "IOS")
     43       UI.success("#{APP_ID} registered")
     44     end
     45   end
     46 
     47   desc "Does the App Store Connect record exist?"
     48   lane :app_exists do
     49     api_key
     50     app = Spaceship::ConnectAPI::App.find(APP_ID)
     51     UI.message(app ? "APP RECORD #{app.id} #{app.name}" : "NO APP RECORD")
     52   end
     53 
     54   desc "Signed archive (no upload); BUILD=n sets the build number"
     55   lane :archive do
     56     key = api_key
     57     get_certificates(api_key: key, output_path: Dir.tmpdir)
     58     sigh(app_identifier: APP_ID, api_key: key, output_path: Dir.tmpdir, force: ENV["SIGH_FORCE"] == "1")
     59     profile = lane_context[SharedValues::SIGH_NAME]
     60 
     61     build_number = ENV["BUILD"] || Time.now.strftime("%Y%m%d%H%M")
     62     archive_path = File.expand_path("~/Library/Developer/Xcode/Archives/OpenMerou-#{build_number}.xcarchive")
     63     output_dir = File.expand_path("../build_output")
     64     FileUtils.rm_rf(output_dir)
     65     export_plist = File.join(Dir.tmpdir, "OpenMerou-ExportOptions.plist")
     66     File.write(export_plist, <<~PLIST)
     67       <?xml version="1.0" encoding="UTF-8"?>
     68       <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
     69       <plist version="1.0">
     70       <dict>
     71         <key>method</key><string>app-store-connect</string>
     72         <key>signingStyle</key><string>manual</string>
     73         <key>signingCertificate</key><string>Apple Distribution</string>
     74         <key>provisioningProfiles</key>
     75         <dict><key>#{APP_ID}</key><string>#{profile}</string></dict>
     76         <key>teamID</key><string>CM5RQKJH56</string>
     77         <key>uploadSymbols</key><true/>
     78       </dict>
     79       </plist>
     80     PLIST
     81 
     82     # Homebrew's rsync ahead of /usr/bin breaks -exportArchive ("Copy failed").
     83     ENV["PATH"] = "/usr/bin:/bin:#{ENV["PATH"]}"
     84     sh("xcodebuild", "-project", "../OpenMerou.xcodeproj", "-scheme", "OpenMerou", "-configuration", "Release",
     85        "-destination", "generic/platform=iOS", "-archivePath", archive_path,
     86        "CURRENT_PROJECT_VERSION=#{build_number}", *xcode_auth, "archive")
     87     sh("xcodebuild", "-exportArchive", "-archivePath", archive_path, "-exportOptionsPlist", export_plist,
     88        "-exportPath", output_dir, *xcode_auth)
     89     lane_context[:OM_IPA] = File.join(output_dir, "OpenMerou.ipa")
     90     lane_context[:OM_BUILD] = build_number
     91   end
     92 
     93   desc "Archive then upload to TestFlight (the App Store Connect record must exist)"
     94   lane :testflight do
     95     archive
     96     upload_to_testflight(api_key: api_key, ipa: lane_context[:OM_IPA], skip_waiting_for_build_processing: true)
     97     UI.success("Build #{lane_context[:OM_BUILD]} uploaded to TestFlight")
     98   end
     99 
    100   desc "Uploads an already built IPA (build_output/OpenMerou.ipa) to TestFlight, after a stuck upload"
    101   lane :upload do
    102     upload_to_testflight(api_key: api_key, ipa: File.expand_path("../build_output/OpenMerou.ipa"), skip_waiting_for_build_processing: true)
    103   end
    104 
    105   # Adds a build to the "Externes" group and submits it to beta review (no effect when already done).
    106   # "Externes" and "Interne" are the names of the tester groups in App Store Connect.
    107   def share_external(app, build)
    108     _, groups = asc(:get, "/v1/apps/#{app.id}/betaGroups")
    109     group = groups["data"].find { |g| g["attributes"]["name"] == "Externes" }
    110     return UI.message("EXTERNAL: no group") unless group
    111     c, r = asc(:post, "/v1/betaGroups/#{group["id"]}/relationships/builds", { data: [{ type: "builds", id: build["id"] }] })
    112     UI.message("EXTERNAL build #{build["attributes"]["version"]} -> #{c} #{(r["errors"] || []).map { |e| e["detail"] }.join(" ; ")}")
    113     _, sub = asc(:get, "/v1/builds/#{build["id"]}/betaAppReviewSubmission")
    114     if sub["data"]
    115       UI.message("BETA REVIEW already requested: #{sub["data"]["attributes"]["betaReviewState"]}")
    116     else
    117       c, r = asc(:post, "/v1/betaAppReviewSubmissions", { data: { type: "betaAppReviewSubmissions",
    118         relationships: { build: { data: { type: "builds", id: build["id"] } } } } })
    119       UI.message("BETA REVIEW submitted -> #{c} #{(r["errors"] || []).map { |e| e["detail"] }.join(" ; ")}")
    120     end
    121   end
    122 
    123   desc "Invites an external tester (email:...): \"Externes\" group, latest build attached, beta review"
    124   lane :invite do |opts|
    125     api_key
    126     email = opts[:email] or UI.user_error!("email: missing")
    127     app = Spaceship::ConnectAPI::App.find(APP_ID)
    128     err = ->(r) { (r["errors"] || []).map { |e| e["detail"] }.join(" ; ") }
    129 
    130     # Beta review details: copied from Sonodrill (same account) when they are missing here.
    131     _, mine = asc(:get, "/v1/betaAppReviewDetails/#{app.id}")
    132     attrs = mine.dig("data", "attributes") || {}
    133     if attrs["contactEmail"].to_s.empty?
    134       sono = Spaceship::ConnectAPI::App.find("org.schurger.sonodrill")
    135       _, src = asc(:get, "/v1/betaAppReviewDetails/#{sono.id}")
    136       a = src.dig("data", "attributes") || {}
    137       body = { data: { type: "betaAppReviewDetails", id: app.id, attributes: {
    138         contactFirstName: a["contactFirstName"], contactLastName: a["contactLastName"],
    139         contactEmail: a["contactEmail"], contactPhone: a["contactPhone"], demoAccountRequired: false,
    140         notes: "No account needed. The app controls a Bluetooth dive housing; without one, tap 'Simulate a housing' on the first screen to try every feature with on-screen housing buttons." } } }
    141       c, r = asc(:patch, "/v1/betaAppReviewDetails/#{app.id}", body)
    142       UI.message("BETA REVIEW details -> #{c} #{err.(r)}")
    143     end
    144 
    145     _, groups = asc(:get, "/v1/apps/#{app.id}/betaGroups")
    146     group = groups["data"].find { |g| g["attributes"]["name"] == "Externes" }
    147     unless group
    148       c, r = asc(:post, "/v1/betaGroups", { data: { type: "betaGroups", attributes: { name: "Externes" },
    149         relationships: { app: { data: { type: "apps", id: app.id } } } } })
    150       UI.message("GROUP Externes -> #{c} #{err.(r)}")
    151       group = r["data"]
    152     end
    153 
    154     _, testers = asc(:get, "/v1/betaTesters?filter[email]=#{email}&filter[apps]=#{app.id}")
    155     if testers["data"].empty?
    156       c, r = asc(:post, "/v1/betaTesters", { data: { type: "betaTesters", attributes: { email: email },
    157         relationships: { betaGroups: { data: [{ type: "betaGroups", id: group["id"] }] } } } })
    158       UI.message("TESTER #{email} -> #{c} #{err.(r)}")
    159     else
    160       c, r = asc(:post, "/v1/betaGroups/#{group["id"]}/relationships/betaTesters", { data: [{ type: "betaTesters", id: testers["data"][0]["id"] }] })
    161       UI.message("TESTER #{email} already known, added to the group -> #{c} #{err.(r)}")
    162     end
    163 
    164     _, builds = asc(:get, "/v1/builds?filter[app]=#{app.id}&sort=-uploadedDate&limit=1")
    165     build = builds["data"].first or UI.user_error!("no build")
    166     share_external(app, build)
    167   end
    168 
    169   desc "TestFlight: internal group \"Interne\" (all builds) with the internal tester, fr/en beta texts, \"What to test\" of the latest build"
    170   lane :beta_setup do
    171     api_key
    172     app = Spaceship::ConnectAPI::App.find(APP_ID)
    173     _, groups = asc(:get, "/v1/apps/#{app.id}/betaGroups")
    174     group = groups["data"].find { |g| g["attributes"]["name"] == "Interne" }
    175     unless group
    176       # Raw POST: spaceship sends publicLinkLimitEnabled, which is refused for an internal group.
    177       c, r = asc(:post, "/v1/betaGroups", { data: { type: "betaGroups",
    178         attributes: { name: "Interne", isInternalGroup: true, hasAccessToAllBuilds: true },
    179         relationships: { app: { data: { type: "apps", id: app.id } } } } })
    180       UI.message("GROUP Interne -> #{c} #{(r["errors"] || []).map { |e| e["detail"] }.join(" ; ")}")
    181       group = r["data"]
    182     end
    183     # The internal tester comes from the build machine's environment, never from the repository.
    184     email = ENV["PERSO_APPLE_ID"] or UI.user_error!("PERSO_APPLE_ID is not set")
    185     first_name = ENV["PERSO_FIRST_NAME"] || "Internal"
    186     last_name = ENV["PERSO_LAST_NAME"] || "Tester"
    187     _, testers = asc(:get, "/v1/betaTesters?filter[email]=#{email}&filter[apps]=#{app.id}")
    188     if testers["data"].empty?
    189       c, r = asc(:post, "/v1/betaTesters", { data: { type: "betaTesters", attributes: { email: email, firstName: first_name, lastName: last_name },
    190         relationships: { betaGroups: { data: [{ type: "betaGroups", id: group["id"] }] } } } })
    191       UI.message("TESTER #{email} -> #{c} #{(r["errors"] || []).map { |e| e["detail"] }.join(" ; ")}")
    192     else
    193       UI.message("TESTER #{email} already there")
    194     end
    195     texts = {
    196       "fr-CA" => ["App libre et gratuite pour boîtier de plongée compatible : boutons, pompe à vide, capteurs, caméra.",
    197                   "0.22. Accueil sur fond noir, en plein écran et sans défilement ; le boîtier est cherché dès le lancement, « Simuler un boîtier » pour essayer sans boîtier. Les écrans de mise sous vide sont aussi sur fond noir. Ordinateur de plongée secondaire en option (désactivé par défaut, non certifié) : réglages sur l'accueil avant de fermer le boîtier, bandeau de plongée sur la caméra, page ordinateur par appui long en haut ou par le menu, alarmes plein écran. Les alarmes, dont l'alarme de fuite, sonnent même avec le bouton silencieux : vérifier aussi que les vidéos gardent leur son. Pour tout voir à sec : « Simuler un boîtier » puis « Simuler une plongée ». Profondeur du boîtier pas encore validée dans l'eau."],
    198       "en-CA" => ["Free, open-source app for compatible dive housings: buttons, vacuum pump, sensors, camera.",
    199                   "0.22. Home screen on a black background, full screen and without scrolling; the housing is looked for from launch, \"Simulate a housing\" to try without one. The vacuum screens are on black too. Optional backup dive computer (off by default, not certified): settings on the home screen before closing the housing, dive band over the camera, computer page with a long press on up or from the menu, full-screen alarms. Alarms, including the leak alarm, now sound even with the silent switch on: please also check that videos keep their sound. To see it all dry: \"Simulate a housing\" then \"Simulate a dive\". The housing depth reading is not yet validated in water."],
    200     }
    201     _, locs = asc(:get, "/v1/apps/#{app.id}/betaAppLocalizations")
    202     texts.each do |locale, (description, _)|
    203       existing = locs["data"].find { |l| l["attributes"]["locale"] == locale }
    204       attrs = { description: description, feedbackEmail: email }
    205       c, r = if existing
    206         asc(:patch, "/v1/betaAppLocalizations/#{existing["id"]}", { data: { type: "betaAppLocalizations", id: existing["id"], attributes: attrs } })
    207       else
    208         asc(:post, "/v1/betaAppLocalizations", { data: { type: "betaAppLocalizations", attributes: attrs.merge(locale: locale),
    209           relationships: { app: { data: { type: "apps", id: app.id } } } } })
    210       end
    211       UI.message("BETA #{locale} -> #{c} #{(r["errors"] || []).map { |e| e["detail"] }.join(" ; ")}")
    212     end
    213     _, builds = asc(:get, "/v1/builds?filter[app]=#{app.id}&sort=-uploadedDate&limit=1")
    214     build = builds["data"].first
    215     UI.user_error!("No build visible yet") unless build
    216     UI.message("BUILD #{build["attributes"]["version"]} #{build["attributes"]["processingState"]}")
    217     _, blocs = asc(:get, "/v1/builds/#{build["id"]}/betaBuildLocalizations")
    218     texts.each do |locale, (_, what)|
    219       existing = blocs["data"].find { |l| l["attributes"]["locale"] == locale }
    220       c, r = if existing
    221         asc(:patch, "/v1/betaBuildLocalizations/#{existing["id"]}", { data: { type: "betaBuildLocalizations", id: existing["id"], attributes: { whatsNew: what } } })
    222       else
    223         asc(:post, "/v1/betaBuildLocalizations", { data: { type: "betaBuildLocalizations", attributes: { locale: locale, whatsNew: what },
    224           relationships: { build: { data: { type: "builds", id: build["id"] } } } } })
    225       end
    226       UI.message("WHAT TO TEST #{locale} -> #{c} #{(r["errors"] || []).map { |e| e["detail"] }.join(" ; ")}")
    227     end
    228     share_external(app, build) if build["attributes"]["processingState"] == "VALID"
    229   end
    230 end