repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/spec/tunes/iap_spec.rb | spaceship/spec/tunes/iap_spec.rb | describe Spaceship::Tunes::IAP do
before { TunesStubbing.itc_stub_iap }
include_examples "common spaceship login"
let(:client) { Spaceship::Tunes.client }
let(:app) { Spaceship::Application.all.find { |a| a.apple_id == "898536088" } }
describe "returns all purchases" do
it "returns as IAPList" do
expect(app.in_app_purchases.all.first.class).to eq(Spaceship::Tunes::IAPList)
end
it "Finds shared secret key" do
secret = app.in_app_purchases.get_shared_secret
expect(secret.class).to eq(String)
expect(secret.length).to be(32)
end
it "Generates new shared secret key" do
old_secret = app.in_app_purchases.get_shared_secret
new_secret = app.in_app_purchases.generate_shared_secret
expect(old_secret).not_to(eq(new_secret))
expect(new_secret.class).to eq(String)
expect(new_secret.length).to be(32)
end
it "Finds a specific product" do
expect(app.in_app_purchases.find("go.find.me")).not_to(eq(nil))
expect(app.in_app_purchases.find("go.find.me").reference_name).to eq("localizeddemo")
end
it "Finds families" do
expect(app.in_app_purchases.families.class).to eq(Spaceship::Tunes::IAPFamilies)
expect(app.in_app_purchases.families.all.first.class).to eq(Spaceship::Tunes::IAPFamilyList)
expect(app.in_app_purchases.families.all.first.name).to eq("Product name1234")
end
describe "Create new IAP" do
it "create consumable" do
expect(client.du_client).to receive(:get_picture_type).and_return("SortedScreenShot")
expect(client.du_client).to receive(:upload_purchase_review_screenshot).and_return({ "token" => "tok", "height" => 100, "width" => 200, "md5" => "xxxx" })
expect(Spaceship::UploadFile).to receive(:from_path).with("ftl_FAKEMD5_screenshot1024.jpg").and_return(du_uploadimage_correct_screenshot)
app.in_app_purchases.create!(
type: Spaceship::Tunes::IAPType::CONSUMABLE,
versions: {
'en-US' => {
name: "test name1",
description: "Description has at least 10 characters"
},
'de-DE' => {
name: "test name german1",
description: "German has at least 10 characters"
}
},
reference_name: "localizeddemo",
product_id: "x.a.a.b.b.c.d.x.y.f",
cleared_for_sale: true,
review_notes: "Some Review Notes here bla bla bla",
review_screenshot: "ftl_FAKEMD5_screenshot1024.jpg",
pricing_intervals:
[
{
country: "WW",
begin_date: nil,
end_date: nil,
tier: 1
}
]
)
end
it "create auto renewable subscription with pricing" do
pricing_intervals = [
{
country: "WW",
begin_date: nil,
end_date: nil,
tier: 1
}
]
transformed_pricing_intervals = pricing_intervals.map do |interval|
{
"value" => {
"tierStem" => interval[:tier],
"priceTierEffectiveDate" => interval[:begin_date],
"priceTierEndDate" => interval[:end_date],
"country" => interval[:country] || "WW",
"grandfathered" => interval[:grandfathered]
}
}
end
expect(client).to receive(:update_recurring_iap_pricing!).with(app_id: '898536088', purchase_id: "1195137657", pricing_intervals: transformed_pricing_intervals)
app.in_app_purchases.create!(
type: Spaceship::Tunes::IAPType::RECURRING,
versions: {
'en-US' => {
name: "test name2",
description: "Description has at least 10 characters"
},
'de-DE' => {
name: "test name german2",
description: "German has at least 10 characters"
}
},
reference_name: "localizeddemo",
product_id: "x.a.a.b.b.c.d.x.y.z",
cleared_for_sale: true,
review_notes: "Some Review Notes here bla bla bla",
pricing_intervals: pricing_intervals
)
end
it "create auto renewable subscription with subscription price target" do
subscription_price_target = {
currency: "EUR",
tier: 1
}
price_goal = TunesStubbing.itc_read_fixture_file('iap_price_goal_calc.json')
transformed_pricing_intervals = JSON.parse(price_goal)["data"].map do |language_code, value|
{
"value" => {
"tierStem" => value["tierStem"],
"priceTierEffectiveDate" => value["priceTierEffectiveDate"],
"priceTierEndDate" => value["priceTierEndDate"],
"country" => language_code,
"grandfathered" => { "value" => "FUTURE_NONE" }
}
}
end
expect(client).to receive(:update_recurring_iap_pricing!).with(app_id: '898536088',
purchase_id: "1195137657", pricing_intervals: transformed_pricing_intervals)
app.in_app_purchases.create!(
type: Spaceship::Tunes::IAPType::RECURRING,
versions: {
'en-US' => {
name: "test name2",
description: "Description has at least 10 characters"
},
'de-DE' => {
name: "test name german2",
description: "German has at least 10 characters"
}
},
reference_name: "localizeddemo",
product_id: "x.a.a.b.b.c.d.x.y.z",
cleared_for_sale: true,
review_notes: "Some Review Notes here bla bla bla",
subscription_price_target: subscription_price_target
)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/spec/tunes/territory_spec.rb | spaceship/spec/tunes/territory_spec.rb | describe Spaceship::Tunes::Territory do
include_examples "common spaceship login"
let(:client) { Spaceship::AppVersion.client }
describe "supported_territories" do
it "inspect works" do
supported_territories = client.supported_territories
expect(supported_territories.inspect).to include("Tunes::Territory")
end
it "correctly creates all territories" do
supported_territories = client.supported_territories
expect(supported_territories.length).to eq(155)
end
it "correctly parses the territories" do
territory_0 = client.supported_territories[0]
expect(territory_0).not_to(be_nil)
expect(territory_0.code).to eq('AL')
expect(territory_0.currency_code).to eq('USD')
expect(territory_0.name).to eq('Albania')
expect(territory_0.region).to eq('Europe')
expect(territory_0.region_locale_key).to eq('ITC.region.EUR')
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/spec/tunes/app_ratings_spec.rb | spaceship/spec/tunes/app_ratings_spec.rb | describe Spaceship::Tunes::AppRatings do
include_examples "common spaceship login"
let(:app) { Spaceship::Application.all.find { |a| a.apple_id == "898536088" } }
let(:client) { Spaceship::Application.client }
describe "successfully loads rating summary" do
it "contains the right information" do
TunesStubbing.itc_stub_ratings
expect(app.ratings.rating_count).to eq(1457)
expect(app.ratings.one_star_rating_count).to eq(219)
expect(app.ratings.two_star_rating_count).to eq(67)
expect(app.ratings.three_star_rating_count).to eq(174)
expect(app.ratings.four_star_rating_count).to eq(393)
expect(app.ratings.five_star_rating_count).to eq(604)
expect(app.ratings(storefront: "US").rating_count).to eq(1300)
end
end
describe "successfully calculates the average" do
it "the average is correct" do
TunesStubbing.itc_stub_ratings
expect(app.ratings.average_rating).to eq(3.75)
expect(app.ratings(storefront: "US").average_rating).to eq(4.34)
end
end
describe "successfully loads reviews" do
it "contains the right information" do
TunesStubbing.itc_stub_ratings
ratings = app.ratings
reviews = ratings.reviews("US")
expect(reviews.count).to eq(4)
expect(reviews.first.store_front).to eq("NZ")
expect(reviews.first.id).to eq(1_000_000_000)
expect(reviews.first.rating).to eq(2)
expect(reviews.first.title).to eq("Title 1")
expect(reviews.first.review).to eq("Review 1")
expect(reviews.first.last_modified).to eq(1_463_887_020_000)
expect(reviews.first.nickname).to eq("Reviewer1")
end
it "contains the right information with version id" do
TunesStubbing.itc_stub_ratings
ratings = app.ratings
reviews = ratings.reviews("", "1")
expect(reviews.count).to eq(4)
expect(reviews.first.store_front).to eq("NZ")
expect(reviews.first.id).to eq(1_000_000_000)
expect(reviews.first.rating).to eq(2)
expect(reviews.first.title).to eq("Title 1")
expect(reviews.first.review).to eq("Review 1")
expect(reviews.first.last_modified).to eq(1_463_887_020_000)
expect(reviews.first.nickname).to eq("Reviewer1")
end
it "contains the right information with upto_date" do
TunesStubbing.itc_stub_ratings
ratings = app.ratings
reviews = ratings.reviews("US", "", "2016-03-27")
expect(reviews.count).to eq(2)
expect(reviews.first.store_front).to eq("NZ")
expect(reviews.first.id).to eq(1_000_000_000)
expect(reviews.first.rating).to eq(2)
expect(reviews.first.title).to eq("Title 1")
expect(reviews.first.review).to eq("Review 1")
expect(reviews.first.last_modified).to eq(1_463_887_020_000)
expect(reviews.first.nickname).to eq("Reviewer1")
expect(reviews.last.store_front).to eq("NZ")
expect(reviews.last.id).to eq(1_000_000_001)
expect(reviews.last.rating).to eq(2)
expect(reviews.last.title).to eq("Title 2")
expect(reviews.last.review).to eq("Review 2")
expect(reviews.last.last_modified).to eq(1_459_152_540_000)
expect(reviews.last.nickname).to eq("Reviewer2")
end
end
describe "Manages Developer Response" do
it "Can Read Response" do
TunesStubbing.itc_stub_ratings
review = app.ratings.reviews("US").first
expect(review.responded?).to eq(true)
expect(review.developer_response.response).to eq("Thank You")
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/spec/tunes/login_spec.rb | spaceship/spec/tunes/login_spec.rb | describe Spaceship::Tunes do
describe ".login" do
it "works with valid data" do
client = Spaceship::Tunes.login
expect(client).to be_instance_of(Spaceship::TunesClient)
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/spec/tunes/availability_spec.rb | spaceship/spec/tunes/availability_spec.rb | describe Spaceship::Tunes::Availability do
include_examples "common spaceship login"
before { TunesStubbing.itc_stub_app_pricing_intervals }
let(:client) { Spaceship::AppVersion.client }
let(:app) { Spaceship::Application.all.find { |a| a.apple_id == "898536088" } }
describe "availability" do
it "inspect works" do
availability = client.availability(app.apple_id)
expect(availability.inspect).to include("Tunes::Availability")
end
it "correctly parses include_future_territories" do
availability = client.availability(app.apple_id)
expect(availability.include_future_territories).to be_truthy
end
it "correctly parses b2b app enabled" do
availability = client.availability(app.apple_id)
expect(availability.b2b_app_enabled).to be(false)
end
it "correctly parses b2b app flag enabled" do
availability = client.availability(app.apple_id)
expect(availability.b2b_unavailable).to be(false)
end
it "correctly parses the territories" do
availability = client.availability(app.apple_id)
expect(availability.territories.length).to eq(2)
territory_0 = availability.territories[0]
expect(territory_0).not_to(be_nil)
expect(territory_0.code).to eq('GB')
expect(territory_0.currency_code).to eq('GBP')
expect(territory_0.name).to eq('United Kingdom')
expect(territory_0.region).to eq('Europe')
expect(territory_0.region_locale_key).to eq('ITC.region.EUR')
end
it "correctly parses b2b users" do
TunesStubbing.itc_stub_app_pricing_intervals_vpp
availability = client.availability(app.apple_id)
expect(availability.b2b_users.length).to eq(2)
b2b_user_0 = availability.b2b_users[0]
expect(b2b_user_0).not_to(be_nil)
expect(b2b_user_0.ds_username).to eq('b2b1@abc.com')
end
end
it "correctly parses b2b organizations" do
TunesStubbing.itc_stub_app_pricing_intervals_vpp
availability = client.availability(app.apple_id)
expect(availability.b2b_organizations.length).to eq(1)
b2b_org_0 = availability.b2b_organizations[0]
expect(b2b_org_0).not_to(be_nil)
expect(b2b_org_0.name).to eq('the best company')
end
describe "update_availability!" do
it "inspect works" do
TunesStubbing.itc_stub_app_remove_territory
# currently countries in list are US and GB
availability = Spaceship::Tunes::Availability.from_territories(["US"])
availability = client.update_availability!(app.apple_id, availability)
expect(availability.inspect).to include("Tunes::Availability")
expect(availability.inspect).to include("Tunes::Territory")
end
describe "with countries as strings" do
it "correctly adds a country" do
TunesStubbing.itc_stub_app_add_territory
# currently countries in list are US and GB
availability = Spaceship::Tunes::Availability.from_territories(["FR", "GB", "US"])
availability = client.update_availability!(app.apple_id, availability)
expect(availability.territories.length).to eq(3)
expect(availability.territories[0].code).to eq("FR")
expect(availability.territories[1].code).to eq("GB")
expect(availability.territories[2].code).to eq("US")
end
it "correctly removes a country" do
TunesStubbing.itc_stub_app_remove_territory
# currently countries in list are US and GB
availability = Spaceship::Tunes::Availability.from_territories(["US"])
availability = client.update_availability!(app.apple_id, availability)
expect(availability.territories.length).to eq(1)
expect(availability.territories[0].code).to eq("US")
end
it "correctly sets preorder with no app available date" do
TunesStubbing.itc_stub_set_preorder_cleared
# sets cleared for preorder to true
availability = Spaceship::Tunes::Availability.from_territories(["US"], cleared_for_preorder: true)
availability = client.update_availability!(app.apple_id, availability)
expect(availability.cleared_for_preorder).to eq(true)
expect(availability.app_available_date).to eq(nil)
end
it "correctly sets preorder with app available date" do
TunesStubbing.itc_stub_set_preorder_cleared_with_date
# sets cleared for preorder to true
availability = Spaceship::Tunes::Availability.from_territories(["US"], cleared_for_preorder: true, app_available_date: "2020-02-20")
availability = client.update_availability!(app.apple_id, availability)
expect(availability.cleared_for_preorder).to eq(true)
expect(availability.app_available_date).to eq("2020-02-20")
end
end
describe "with countries as Territories" do
it "correctly adds a country" do
TunesStubbing.itc_stub_app_add_territory
# currently countries in list are US and GB
new_territories_codes = ["FR", "GB", "US"]
all_territories = client.supported_territories
territories = all_territories.select { |territory| new_territories_codes.include?(territory.code) }
availability = Spaceship::Tunes::Availability.from_territories(territories)
availability = client.update_availability!(app.apple_id, availability)
expect(availability.territories.length).to eq(3)
expect(availability.territories[0].code).to eq("FR")
expect(availability.territories[1].code).to eq("GB")
expect(availability.territories[2].code).to eq("US")
end
it "correctly removes a country" do
TunesStubbing.itc_stub_app_remove_territory
# currently countries in list are US and GB
new_territories_codes = ["US"]
all_territories = client.supported_territories
territories = all_territories.select { |territory| new_territories_codes.include?(territory.code) }
availability = Spaceship::Tunes::Availability.from_territories(territories)
availability = client.update_availability!(app.apple_id, availability)
expect(availability.territories.length).to eq(1)
expect(availability.territories[0].code).to eq("US")
end
end
it "correctly unincludes all future territories" do
TunesStubbing.itc_stub_app_uninclude_future_territories
# currently countries in list are US and GB
availability = Spaceship::Tunes::Availability.from_territories(["GB", "US"], include_future_territories: false)
availability = client.update_availability!(app.apple_id, availability)
expect(availability.include_future_territories).to be_falsey
end
describe "enable_b2b_app!" do
it "throws exception if b2b cannot be enabled" do
TunesStubbing.itc_stub_app_pricing_intervals_b2b_disabled
availability = client.availability(app.apple_id)
expect { availability.enable_b2b_app! }.to raise_error("Not possible to enable b2b on this app")
end
it "works correctly" do
availability = client.availability(app.apple_id)
new_availability = availability.enable_b2b_app!
expect(new_availability.b2b_app_enabled).to eq(true)
expect(new_availability.educational_discount).to eq(false)
end
end
describe "add_b2b_users" do
it "throws exception if b2b app not enabled" do
availability = client.availability(app.apple_id)
expect { availability.add_b2b_users(["abc@def.com"]) }.to raise_error("Cannot add b2b users if b2b is not enabled")
end
it "works correctly" do
TunesStubbing.itc_stub_app_pricing_intervals_vpp
availability = client.availability(app.apple_id)
new_availability = availability.add_b2b_users(["abc@def.com"])
expect(new_availability).to be_an_instance_of(Spaceship::Tunes::Availability)
expect(new_availability.b2b_users.length).to eq(1)
expect(new_availability.b2b_users[0].ds_username).to eq("abc@def.com")
end
end
describe "update_b2b_users" do
it "throws exception if b2b app not enabled" do
availability = client.availability(app.apple_id)
expect { availability.add_b2b_users(["abc@def.com"]) }.to raise_error("Cannot add b2b users if b2b is not enabled")
end
it "does not do anything for same b2b_user_list" do
TunesStubbing.itc_stub_app_pricing_intervals_vpp
availability = client.availability(app.apple_id)
old_b2b_users = availability.b2b_users
new_availability = availability.update_b2b_users(%w(b2b1@abc.com b2b2@def.com))
expect(new_availability).to be_an_instance_of(Spaceship::Tunes::Availability)
new_b2b_users = new_availability.b2b_users
expect(new_b2b_users).to eq(old_b2b_users)
end
it "removes existing user" do
TunesStubbing.itc_stub_app_pricing_intervals_vpp
availability = client.availability(app.apple_id)
new_availability = availability.update_b2b_users(%w(b2b1@abc.com))
expect(new_availability).to be_an_instance_of(Spaceship::Tunes::Availability)
expect(new_availability.b2b_users.length).to eq(2)
expect(new_availability.b2b_users[0].ds_username).to eq("b2b1@abc.com")
expect(new_availability.b2b_users[0].add).to eq(false)
expect(new_availability.b2b_users[0].delete).to eq(false)
expect(new_availability.b2b_users[1].ds_username).to eq("b2b2@def.com")
expect(new_availability.b2b_users[1].add).to eq(false)
expect(new_availability.b2b_users[1].delete).to eq(true)
end
it "adds new user" do
TunesStubbing.itc_stub_app_pricing_intervals_vpp
availability = client.availability(app.apple_id)
new_availability = availability.update_b2b_users(%w(b2b1@abc.com b2b2@def.com jkl@mno.com))
expect(new_availability).to be_an_instance_of(Spaceship::Tunes::Availability)
expect(new_availability.b2b_users.length).to eq(3)
expect(new_availability.b2b_users[0].ds_username).to eq("b2b1@abc.com")
expect(new_availability.b2b_users[0].add).to eq(false)
expect(new_availability.b2b_users[0].delete).to eq(false)
expect(new_availability.b2b_users[1].ds_username).to eq("b2b2@def.com")
expect(new_availability.b2b_users[1].add).to eq(false)
expect(new_availability.b2b_users[1].delete).to eq(false)
expect(new_availability.b2b_users[2].ds_username).to eq("jkl@mno.com")
expect(new_availability.b2b_users[2].add).to eq(true)
expect(new_availability.b2b_users[2].delete).to eq(false)
end
it "adds and removes appropriate users" do
TunesStubbing.itc_stub_app_pricing_intervals_vpp
availability = client.availability(app.apple_id)
new_availability = availability.update_b2b_users(%w(b2b1@abc.com jkl@mno.com))
expect(new_availability).to be_an_instance_of(Spaceship::Tunes::Availability)
expect(new_availability.b2b_users.length).to eq(3)
expect(new_availability.b2b_users[0].ds_username).to eq("b2b1@abc.com")
expect(new_availability.b2b_users[0].add).to eq(false)
expect(new_availability.b2b_users[0].delete).to eq(false)
expect(new_availability.b2b_users[1].ds_username).to eq("jkl@mno.com")
expect(new_availability.b2b_users[1].add).to eq(true)
expect(new_availability.b2b_users[1].delete).to eq(false)
expect(new_availability.b2b_users[2].ds_username).to eq("b2b2@def.com")
expect(new_availability.b2b_users[2].add).to eq(false)
expect(new_availability.b2b_users[2].delete).to eq(true)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/spec/tunes/testers_spec.rb | spaceship/spec/tunes/testers_spec.rb | describe Spaceship::Tunes::SandboxTester do
include_examples "common spaceship login"
let(:client) { Spaceship::AppSubmission.client }
let(:app) { Spaceship::Application.all.first }
describe "Sandbox testers" do
describe "listing" do
it 'loads sandbox testers correctly' do
testers = Spaceship::Tunes::SandboxTester.all
expect(testers.count).to eq(1)
t = testers[0]
expect(t.class).to eq(Spaceship::Tunes::SandboxTester)
expect(t.email).to eq("test@test.com")
expect(t.first_name).to eq("Test")
expect(t.last_name).to eq("McTestington")
expect(t.country).to eq("GB")
end
end
describe "creation" do
before { allow(SecureRandom).to receive(:hex).and_return('so_secret') }
it 'creates sandbox testers correctly' do
t = Spaceship::Tunes::SandboxTester.create!(
email: 'test2@test.com',
password: 'Passwordtest1',
country: 'US',
first_name: 'Steve',
last_name: 'Brule'
)
expect(t.class).to eq(Spaceship::Tunes::SandboxTester)
expect(t.email).to eq("test2@test.com")
expect(t.first_name).to eq("Steve")
expect(t.last_name).to eq("Brule")
expect(t.country).to eq("US")
end
end
describe "deletion" do
it 'deletes a user' do
expect { Spaceship::Tunes::SandboxTester.delete!(['test@test.com']) }.not_to(raise_error)
end
it 'deletes all users' do
expect { Spaceship::Tunes::SandboxTester.delete_all! }.not_to(raise_error)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/spec/tunes/device_type_spec.rb | spaceship/spec/tunes/device_type_spec.rb | describe Spaceship::Tunes::DeviceType do
describe "type identifiers" do
before(:each) do
# Let's catch those calls to avoid polluting the output
# Note: Warning.warn() has a different signature depending on the Ruby version, hence why we need more than one allow(...)
allow(Warning).to receive(:warn).with(/Spaceship::Tunes::DeviceType has been deprecated./)
allow(Warning).to receive(:warn).with(/Spaceship::Tunes::DeviceType has been deprecated./, { category: nil })
end
it "should be checkable using singleton functions" do
expect(Spaceship::Tunes::DeviceType.exists?("iphone6")).to be_truthy
end
it "should return an array of string device types" do
Spaceship::Tunes::DeviceType.types.each do |identifier|
expect(identifier).to be_a(String)
end
end
it "should contain all old identifiers" do
old_types = [
# iPhone
'iphone35',
'iphone4',
'iphone6', # 4.7-inch Display
'iphone6Plus', # 5.5-inch Display
'iphone58', # iPhone XS
'iphone65', # iPhone XS Max
# iPad
'ipad', # 9.7-inch Display
'ipad105',
'ipadPro',
'ipadPro11',
'ipadPro129',
# Apple Watch
'watch', # series 3
'watchSeries4',
# Apple TV
'appleTV',
# Mac
'desktop'
]
types = Spaceship::Tunes::DeviceType.types
old_types.each do |identifier|
expect(types).to include(identifier)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/spec/tunes/application_spec.rb | spaceship/spec/tunes/application_spec.rb | describe Spaceship::Application do
include_examples "common spaceship login"
let(:client) { Spaceship::Application.client }
let(:app) { Spaceship::Application.all.find { |a| a.apple_id == "898536088" } }
describe "successfully loads and parses all apps" do
it "inspect works" do
expect(app.inspect).to include("Tunes::Application")
end
it "the number is correct" do
expect(Spaceship::Application.all.count).to eq(5)
end
it "parses application correctly" do
expect(app.apple_id).to eq('898536088')
expect(app.name).to eq('App Name 1')
expect(app.platform).to eq('ios')
expect(app.bundle_id).to eq('net.sunapps.107')
expect(app.raw_data['versionSets'].count).to eq(1)
end
it "#url" do
expect(app.url).to eq('https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/ng/app/898536088')
end
describe "#find" do
describe "find using bundle identifier" do
it "returns the application if available" do
a = Spaceship::Application.find('net.sunapps.107')
expect(a.class).to eq(Spaceship::Application)
expect(a.apple_id).to eq('898536088')
end
it "returns the application if available ignoring case" do
a = Spaceship::Application.find('net.sunAPPs.107')
expect(a.class).to eq(Spaceship::Application)
expect(a.apple_id).to eq('898536088')
end
it "returns nil if not available" do
a = Spaceship::Application.find('netnot.available')
expect(a).to eq(nil)
end
end
describe "find using Apple ID" do
it "returns the application if available" do
a = Spaceship::Application.find('898536088')
expect(a.class).to eq(Spaceship::Application)
expect(a.bundle_id).to eq('net.sunapps.107')
end
it "supports int parameters too" do
a = Spaceship::Application.find(898_536_088)
expect(a.class).to eq(Spaceship::Application)
expect(a.bundle_id).to eq('net.sunapps.107')
end
end
end
describe "#create!" do
it "works with valid data and defaults to English" do
Spaceship::Tunes::Application.create!(name: "My name",
sku: "SKU123",
bundle_id: "net.sunapps.123")
end
it "raises an error if something is wrong" do
TunesStubbing.itc_stub_broken_create
expect do
Spaceship::Tunes::Application.create!(name: "My Name",
sku: "SKU123",
bundle_id: "net.sunapps.123")
end.to raise_error("You must choose a primary language. You must choose a primary language.")
end
it "raises an error if bundle is wildcard and bundle_id_suffix has not specified" do
TunesStubbing.itc_stub_broken_create_wildcard
expect do
Spaceship::Tunes::Application.create!(name: "My Name",
sku: "SKU123",
bundle_id: "net.sunapps.*")
end.to raise_error("You must enter a Bundle ID Suffix. You must enter a Bundle ID Suffix.")
end
end
describe "#create! first app (company name required)" do
it "works with valid data and defaults to English" do
TunesStubbing.itc_stub_applications_first_create
Spaceship::Tunes::Application.create!(name: "My Name",
sku: "SKU123",
bundle_id: "net.sunapps.123",
company_name: "SunApps GmbH")
end
it "raises an error if something is wrong" do
TunesStubbing.itc_stub_applications_broken_first_create
expect do
Spaceship::Tunes::Application.create!(name: "My Name",
sku: "SKU123",
bundle_id: "net.sunapps.123")
end.to raise_error("You must provide a company name to use on the App Store. You must provide a company name to use on the App Store.")
end
end
describe '#available_bundle_ids' do
it "returns the list of bundle ids" do
TunesStubbing.itc_stub_applications_first_create
bundle_ids = Spaceship::Tunes::Application.available_bundle_ids
expect(bundle_ids.length).to eq(5)
expect(bundle_ids[0]).to eq("com.krausefx.app_name")
expect(bundle_ids[1]).to eq("net.sunapps.*")
expect(bundle_ids[2]).to eq("net.sunapps.947474")
expect(bundle_ids[3]).to eq("*")
expect(bundle_ids[4]).to eq("net.sunapps.100")
end
end
describe "#resolution_center" do
it "when the app was rejected" do
TunesStubbing.itc_stub_resolution_center
result = app.resolution_center
expect(result['appNotes']['threads'].first['messages'].first['body']).to include('Your app declares support for audio in the UIBackgroundModes')
end
it "when the app was not rejected" do
TunesStubbing.itc_stub_resolution_center_valid
expect(app.resolution_center).to eq({ "sectionErrorKeys" => [], "sectionInfoKeys" => [], "sectionWarningKeys" => [], "replyConstraints" => { "minLength" => 1, "maxLength" => 4000 }, "appNotes" => { "threads" => [] }, "betaNotes" => { "threads" => [] }, "appMessages" => { "threads" => [] } })
end
end
describe "#builds" do
let(:mock_client) { double('MockClient') }
require 'spec_helper'
require_relative '../mock_servers'
before do
allow(Spaceship::TestFlight::Base).to receive(:client).and_return(mock_client)
allow(mock_client).to receive(:team_id).and_return('')
mock_client_response(:get_build_trains) do
['1.0', '1.1']
end
mock_client_response(:get_builds_for_train, with: hash_including(train_version: '1.0')) do
[
{
id: 1,
appAdamId: 10,
trainVersion: '1.0',
uploadDate: '2017-01-01T12:00:00.000+0000',
externalState: 'testflight.build.state.export.compliance.missing'
}
]
end
mock_client_response(:get_builds_for_train, with: hash_including(train_version: '1.1')) do
[
{
id: 2,
appAdamId: 10,
trainVersion: '1.1',
uploadDate: '2017-01-02T12:00:00.000+0000',
externalState: 'testflight.build.state.submit.ready'
},
{
id: 3,
appAdamId: 10,
trainVersion: '1.1',
uploadDate: '2017-01-03T12:00:00.000+0000',
externalState: 'testflight.build.state.processing'
}
]
end
end
it "supports block parameter" do
# count = 0
# app.builds do |current|
# count += 1
# expect(current.class).to eq(Spaceship::TestFlight::Build)
# end
# expect(count).to eq(3)
end
it "returns a standard array" do
# expect(app.builds.count).to eq(3)
# expect(app.builds.first.class).to eq(Spaceship::TestFlight::Build)
end
end
describe "Access app_versions" do
describe "#edit_version" do
it "returns the edit version if there is an edit version" do
v = app.edit_version
expect(v.class).to eq(Spaceship::AppVersion)
expect(v.application).to eq(app)
expect(v.description['German']).to eq("My title")
expect(v.is_live).to eq(false)
end
end
describe "#latest_version" do
it "returns the edit_version if available" do
expect(app.latest_version.class).to eq(Spaceship::Tunes::AppVersion)
end
end
describe "#live_version" do
it "there is always a live version" do
v = app.live_version
expect(v.class).to eq(Spaceship::AppVersion)
expect(v.is_live).to eq(true)
end
end
describe "#live_version weirdities" do
it "no live version if app isn't yet uploaded" do
app = Spaceship::Application.find(1_000_000_000)
expect(app.live_version).to eq(nil)
expect(app.edit_version.is_live).to eq(false)
expect(app.latest_version.is_live).to eq(false)
end
end
end
describe "Create new version" do
it "raises an exception if there already is a new version" do
expect do
app.create_version!('0.1')
end.to raise_error("Cannot create a new version for this app as there already is an `edit_version` available")
end
end
describe "Version history" do
it "Parses history" do
history = app.versions_history
expect(history.count).to eq(9)
v = history[0]
expect(v.version_string).to eq("1.0")
expect(v.version_id).to eq(812_627_411)
v = history[7]
expect(v.version_string).to eq("1.3")
expect(v.version_id).to eq(815_048_522)
expect(v.items.count).to eq(6)
expect(v.items[1].state_key).to eq("waitingForReview")
expect(v.items[1].user_name).to eq("joe@wewanttoknow.com")
expect(v.items[1].user_email).to eq("joe@wewanttoknow.com")
expect(v.items[1].date).to eq(1_449_330_388_000)
v = history[8]
expect(v.version_string).to eq("1.4.1")
expect(v.version_id).to eq(815_259_390)
expect(v.items.count).to eq(7)
expect(v.items[3].state_key).to eq("pendingDeveloperRelease")
expect(v.items[3].user_name).to eq("Apple")
expect(v.items[3].user_email).to eq(nil)
expect(v.items[3].date).to eq(1_450_461_891_000)
end
end
describe "Promo codes" do
it "fetches remaining promocodes" do
promocodes = app.promocodes
expect(promocodes.count).to eq(1)
expect(promocodes[0].app_id).to eq(816_549_081)
expect(promocodes[0].app_name).to eq('DragonBox Numbers')
expect(promocodes[0].version).to eq('1.5.0')
expect(promocodes[0].platform).to eq('ios')
expect(promocodes[0].number_of_codes).to eq(2)
expect(promocodes[0].maximum_number_of_codes).to eq(100)
expect(promocodes[0].contract_file_name).to eq('promoCodes/ios/spqr5/PromoCodeHolderTermsDisplay_en_us.html')
end
it "fetches promocodes history", focus: true do
promocodes = app.promocodes_history
expect(promocodes.count).to eq(7)
promocodes = promocodes[4]
expect(promocodes.effective_date).to eq(1_457_864_552_000)
expect(promocodes.expiration_date).to eq(1_460_283_752_000)
expect(promocodes.username).to eq('joe@wewanttoknow.com')
expect(promocodes.codes.count).to eq(1)
expect(promocodes.codes[0]).to eq('6J49JFRP----')
expect(promocodes.version.app_id).to eq(816_549_081)
expect(promocodes.version.app_name).to eq('DragonBox Numbers')
expect(promocodes.version.version).to eq('1.5.0')
expect(promocodes.version.platform).to eq('ios')
expect(promocodes.version.number_of_codes).to eq(7)
expect(promocodes.version.maximum_number_of_codes).to eq(100)
expect(promocodes.version.contract_file_name).to eq('promoCodes/ios/spqr5/PromoCodeHolderTermsDisplay_en_us.html')
end
end
describe "#availability" do
before { TunesStubbing.itc_stub_app_pricing_intervals }
it "inspect works" do
availability = app.availability
expect(availability.inspect).to include("Tunes::Availability")
end
end
describe "#update_availability" do
before { TunesStubbing.itc_stub_app_pricing_intervals }
it "inspect works" do
TunesStubbing.itc_stub_app_uninclude_future_territories
availability = app.availability
availability.include_future_territories = false
availability = app.update_availability!(availability)
expect(availability.inspect).to include("Tunes::Availability")
end
end
describe "#update_price_tier" do
let(:effective_date) { 1_525_488_436 }
before { TunesStubbing.itc_stub_app_pricing_intervals }
it "inspect works" do
allow_any_instance_of(Time).to receive(:to_i).and_return(effective_date)
TunesStubbing.itc_stub_update_price_tier
app.update_price_tier!(3)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/spec/tunes/tunes_stubbing.rb | spaceship/spec/tunes/tunes_stubbing.rb | # rubocop:disable Metrics/ClassLength
class TunesStubbing
class << self
def itc_read_fixture_file(filename)
File.read(File.join('spaceship', 'spec', 'tunes', 'fixtures', filename))
end
# Necessary, as we're now running this in a different context
def stub_request(*args)
WebMock::API.stub_request(*args)
end
def itc_stub_login
# Retrieving the current login URL
itc_service_key_path = File.expand_path("~/Library/Caches/spaceship_itc_service_key.txt")
File.delete(itc_service_key_path) if File.exist?(itc_service_key_path)
stub_request(:get, 'https://appstoreconnect.apple.com/itc/static-resources/controllers/_cntrl.js').
to_return(status: 200, body: itc_read_fixture_file('login_cntrl.js'))
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa").
to_return(status: 200, body: "")
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/wa").
to_return(status: 200, body: "")
stub_request(:get, "https://appstoreconnect.apple.com/olympus/v1/session").
to_return(status: 200, body: itc_read_fixture_file('olympus_session.json'), headers: { 'Content-Type' => 'application/json' })
stub_request(:get, "https://appstoreconnect.apple.com/olympus/v1/app/config?hostname=itunesconnect.apple.com").
to_return(status: 200, body: { authServiceKey: 'e0abc' }.to_json, headers: { 'Content-Type' => 'application/json' })
stub_request(:post, "https://appstoreconnect.apple.com/olympus/v1/session").
with(body: "{\"provider\":{\"providerId\":5678}}",
headers: { 'Content-Type' => 'application/json', 'X-Requested-With' => 'olympus-ui' }).
to_return(status: 200, body: "", headers: {})
# Actual login
stub_request(:get, "https://idmsa.apple.com/appleauth/auth/signin?widgetKey=e0abc").
to_return(status: 200, body: '', headers: { 'x-apple-hc-bits' => "12", 'x-apple-hc-challenge' => "f8b58554b2f22960fc0dc99aea342276" })
stub_request(:post, "https://idmsa.apple.com/appleauth/auth/signin").
with(body: { "accountName" => "spaceship@krausefx.com", "password" => "so_secret", "rememberMe" => true }.to_json).
to_return(status: 200, body: '{}', headers: { 'Set-Cookie' => "myacinfo=abcdef;" })
# SIRP login
stub_request(:post, "https://idmsa.apple.com/appleauth/auth/signin/init").
with(
body: "{\"a\":\"jzDOg7Zg8Dq7D4VwwjXg4eHThgoiIwSs8Y6Ym9wGXckioUHm2kVj8FWGYFsOEFNdh1yn4Prn/hA" \
"M/lMzdPKaqoA837LGGU9FhIXof3aYj2zdqhgpMJQ44aqatlKxfPwIH/9ANWyzrzXGIenze6bioD5qu" \
"sWmv+GN20iUErfFY1UpLmw1X4hZJw0EBjuEPSPB73UDw8XdLFZ0AQGj71v+xr/x5txV4/cIQKg6lde" \
"z0gqzUNBHKAnOh6Tjwp7ZaF63ch3Ie6v629nmXnXV31VUe8/5hxHd6ue44ebb9Snpb3yqS4MLQ1dc3" \
"cUs68OflSL4XL8zrDXuWfZvSBCcEvu3jQ==\",\"accountName\":\"spaceship@krausefx.com\",\"protocols\":[\"s2k\",\"s2k_fo\"]}"
).
to_return(status: 200, body: itc_read_fixture_file('signin_init.json'), headers: { 'Content-Type' => 'application/json' })
stub_request(:post, "https://idmsa.apple.com/appleauth/auth/signin/complete?isRememberMeEnabled=false").
with(
body: "{\"accountName\":\"spaceship@krausefx.com\",\"c\":\"d-227-a6ae7b06-8e82-11ef-8ba6-e5527b74d559:PRN\",\"m1\":\"EjQ=\",\"m2\":\"\",\"rememberMe\":false}"
).
to_return(status: 200, body: "", headers: { 'Set-Cookie' => "myacinfo=abcdef;" })
# SIRP login failed
stub_request(:post, "https://idmsa.apple.com/appleauth/auth/signin/init").
with(
body: "{\"a\":\"jzDOg7Zg8Dq7D4VwwjXg4eHThgoiIwSs8Y6Ym9wGXckioUHm2kVj8FWGYFsOEFNdh1yn4Prn/hAM/" \
"lMzdPKaqoA837LGGU9FhIXof3aYj2zdqhgpMJQ44aqatlKxfPwIH/9ANWyzrzXGIenze6bioD5qusWmv+" \
"GN20iUErfFY1UpLmw1X4hZJw0EBjuEPSPB73UDw8XdLFZ0AQGj71v+xr/x5txV4/cIQKg6ldez0gqzUN" \
"BHKAnOh6Tjwp7ZaF63ch3Ie6v629nmXnXV31VUe8/5hxHd6ue44ebb9Snpb3yqS4MLQ1dc3cUs68OflS" \
"L4XL8zrDXuWfZvSBCcEvu3jQ==\",\"accountName\":\"bad-username\",\"protocols\":[\"s2k\",\"s2k_fo\"]}"
).
to_return(status: 401, body: '{}', headers: { 'Set-Cookie' => 'session=invalid' })
# Failed login attempts
stub_request(:post, "https://idmsa.apple.com/appleauth/auth/signin").
with(body: { "accountName" => "bad-username", "password" => "bad-password", "rememberMe" => true }.to_json).
to_return(status: 401, body: '{}', headers: { 'Set-Cookie' => 'session=invalid' })
# 2FA: Request security code to trusted phone
[1, 2].each do |id|
stub_request(:put, "https://idmsa.apple.com/appleauth/auth/verify/phone").
with(body: "{\"phoneNumber\":{\"id\":#{id}},\"mode\":\"sms\"}").
to_return(status: 200, body: "", headers: {})
end
# 2FA: Submit security code from trusted phone for verification
[1, 2].each do |id|
stub_request(:post, "https://idmsa.apple.com/appleauth/auth/verify/phone/securitycode").
with(body: "{\"securityCode\":{\"code\":\"123\"},\"phoneNumber\":{\"id\":#{id}},\"mode\":\"sms\"}").
to_return(status: 200, body: "", headers: {})
end
# 2FA: Request and Submit code via voice
stub_request(:put, "https://idmsa.apple.com/appleauth/auth/verify/phone").
with(body: "{\"phoneNumber\":{\"id\":3},\"mode\":\"voice\"}").
to_return(status: 200, body: "", headers: {})
stub_request(:post, "https://idmsa.apple.com/appleauth/auth/verify/phone/securitycode").
with(body: "{\"securityCode\":{\"code\":\"123\"},\"phoneNumber\":{\"id\":3},\"mode\":\"voice\"}").
to_return(status: 200, body: "", headers: {})
# 2FA: Submit security code from trusted phone with voice for verification
stub_request(:post, "https://idmsa.apple.com/appleauth/auth/verify/phone/securitycode").
with(body: "{\"securityCode\":{\"code\":\"123\"},\"phoneNumber\":{\"id\":1},\"mode\":\"voice\"}").
to_return(status: 200, body: "", headers: {})
# 2FA: Submit security code from trusted device for verification
stub_request(:post, "https://idmsa.apple.com/appleauth/auth/verify/trusteddevice/securitycode").
with(body: "{\"securityCode\":{\"code\":\"123\"}}").
to_return(status: 200, body: "", headers: {})
# 2FA: Trust computer
stub_request(:get, "https://idmsa.apple.com/appleauth/auth/2sv/trust").
to_return(status: 200, body: "", headers: {})
end
def itc_stub_applications
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/manageyourapps/summary/v2").
to_return(status: 200, body: itc_read_fixture_file('app_summary.json'), headers: { 'Content-Type' => 'application/json' })
# Create Version stubbing
stub_request(:post, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/version/create/1013943394").
with(body: "{\"version\":\"0.1\"}").
to_return(status: 200, body: itc_read_fixture_file('create_version_success.json'), headers: { 'Content-Type' => 'application/json' })
# Create Application
# Pre-Fill request
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/create/v2/?platformString=ios").
to_return(status: 200, body: itc_read_fixture_file('create_application_prefill_request.json'), headers: { 'Content-Type' => 'application/json' })
# Actual success request
stub_request(:post, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/create/v2").
to_return(status: 200, body: itc_read_fixture_file('create_application_success.json'), headers: { 'Content-Type' => 'application/json' })
# Overview of application to get the versions
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/1013943394/overview").
to_return(status: 200, body: itc_read_fixture_file('app_overview.json'), headers: { 'Content-Type' => 'application/json' })
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/overview").
to_return(status: 200, body: itc_read_fixture_file('app_overview.json'), headers: { 'Content-Type' => 'application/json' })
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/1000000000/overview").
to_return(status: 200, body: itc_read_fixture_file('app_overview_stuckinprepare.json'), headers: { 'Content-Type' => 'application/json' })
# App Details
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/details").
to_return(status: 200, body: itc_read_fixture_file('app_details.json'), headers: { 'Content-Type' => 'application/json' })
# Versions History
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/stateHistory?platform=ios").
to_return(status: 200, body: itc_read_fixture_file('app_versions_history.json'), headers: { 'Content-Type' => 'application/json' })
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/versions/814624685/stateHistory?platform=ios").
to_return(status: 200, body: itc_read_fixture_file('app_version_states_history.json'), headers: { 'Content-Type' => 'application/json' })
end
def itc_stub_ratings
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/platforms/ios/reviews/summary").
to_return(status: 200, body: itc_read_fixture_file('ratings.json'), headers: { 'Content-Type' => 'application/json' })
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/platforms/ios/reviews/summary?storefront=US").
to_return(status: 200, body: itc_read_fixture_file('ratings_US.json'), headers: { 'Content-Type' => 'application/json' })
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/platforms/ios/reviews?index=0&sort=REVIEW_SORT_ORDER_MOST_RECENT&storefront=US").
to_return(status: 200, body: itc_read_fixture_file('review_by_storefront.json'), headers: { 'Content-Type' => 'application/json' })
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/platforms/ios/reviews?index=0&sort=REVIEW_SORT_ORDER_MOST_RECENT&versionId=1").
to_return(status: 200, body: itc_read_fixture_file('review_by_version_id.json'), headers: { 'Content-Type' => 'application/json' })
end
def itc_stub_build_details
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/buildHistory?platform=ios").
to_return(status: 200, body: itc_read_fixture_file('build_history.json'), headers: { 'Content-Type' => 'application/json' })
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/trains/2.0.1/buildHistory?platform=ios").
to_return(status: 200, body: itc_read_fixture_file('build_history_for_train.json'), headers: { 'Content-Type' => 'application/json' })
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/platforms/ios/trains/2.0.1/builds/4/details").
to_return(status: 200, body: itc_read_fixture_file('build_details.json'), headers: { 'Content-Type' => 'application/json' })
end
def itc_stub_candidate_builds
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/versions/812106519/candidateBuilds").
to_return(status: 200, body: itc_read_fixture_file('candidate_builds.json'), headers: { 'Content-Type' => 'application/json' })
end
def itc_stub_applications_first_create
# Create First Application
# Pre-Fill request
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/create/v2/?platformString=ios").
to_return(status: 200, body: itc_read_fixture_file('create_application_prefill_first_request.json'), headers: { 'Content-Type' => 'application/json' })
end
def itc_stub_applications_broken_first_create
stub_request(:post, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/create/v2").
to_return(status: 200, body: itc_read_fixture_file('create_application_first_broken.json'), headers: { 'Content-Type' => 'application/json' })
end
def itc_stub_broken_create
stub_request(:post, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/create/v2").
to_return(status: 200, body: itc_read_fixture_file('create_application_broken.json'), headers: { 'Content-Type' => 'application/json' })
end
def itc_stub_broken_create_wildcard
stub_request(:post, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/create/v2").
to_return(status: 200, body: itc_read_fixture_file('create_application_wildcard_broken.json'), headers: { 'Content-Type' => 'application/json' })
end
def itc_stub_app_versions
# Receiving app version
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/platforms/ios/versions/813314674").
to_return(status: 200, body: itc_read_fixture_file('app_version.json'), headers: { 'Content-Type' => 'application/json' })
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/platforms/ios/versions/113314675").
to_return(status: 200, body: itc_read_fixture_file('app_version.json'), headers: { 'Content-Type' => 'application/json' })
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/1000000000/platforms/ios/versions/800000000").
to_return(status: 200, body: itc_read_fixture_file('app_version.json'), headers: { 'Content-Type' => 'application/json' })
end
def itc_stub_app_attachment
# Receiving app version
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/platforms/ios/versions/813314674").
to_return(status: 200, body: itc_read_fixture_file('app_review_attachment.json'), headers: { 'Content-Type' => 'application/json' })
end
def itc_stub_app_submissions
# Start app submission
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/versions/812106519/submit/summary").
to_return(status: 200, body: itc_read_fixture_file('app_submission/start_success.json'), headers: { 'Content-Type' => 'application/json' })
# Complete app submission
stub_request(:post, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/versions/812106519/submit/complete").
to_return(status: 200, body: itc_read_fixture_file('app_submission/complete_success.json'), headers: { 'Content-Type' => 'application/json' })
end
def itc_stub_app_submissions_already_submitted
# Start app submission
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/versions/812106519/submit/summary").
to_return(status: 200, body: itc_read_fixture_file('app_submission/start_success.json'), headers: { 'Content-Type' => 'application/json' })
# Complete app submission
stub_request(:post, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/versions/812106519/submit/complete").
to_return(status: 200, body: itc_read_fixture_file('app_submission/complete_failed.json'), headers: { 'Content-Type' => 'application/json' })
end
def itc_stub_app_submissions_invalid
# Start app submission
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/versions/812106519/submit/summary").
to_return(status: 200, body: itc_read_fixture_file('app_submission/start_failed.json'), headers: { 'Content-Type' => 'application/json' })
end
def itc_stub_resolution_center
# Called from the specs to simulate invalid server responses
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/resolutionCenter?v=latest").
to_return(status: 200, body: itc_read_fixture_file('app_resolution_center.json'), headers: { 'Content-Type' => 'application/json' })
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/platforms/ios/resolutionCenter?v=latest").
to_return(status: 200, body: itc_read_fixture_file('app_resolution_center.json'), headers: { 'Content-Type' => 'application/json' })
end
def itc_stub_build_trains
%w(internal external).each do |type|
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/trains/?platform=ios&testingType=#{type}").
to_return(status: 200, body: itc_read_fixture_file('build_trains.json'), headers: { 'Content-Type' => 'application/json' })
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/trains/?platform=appletvos&testingType=#{type}").
to_return(status: 200, body: itc_read_fixture_file('build_trains.json'), headers: { 'Content-Type' => 'application/json' })
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/trains/?testingType=#{type}").
to_return(status: 200, body: itc_read_fixture_file('build_trains.json'), headers: { 'Content-Type' => 'application/json' })
# Update build trains
stub_request(:post, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/testingTypes/#{type}/trains/").
to_return(status: 200, body: itc_read_fixture_file('build_trains.json'), headers: { 'Content-Type' => 'application/json' })
end
end
def itc_stub_testers
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/users/pre/int").
to_return(status: 200, body: itc_read_fixture_file('testers/get_internal.json'), headers: { 'Content-Type' => 'application/json' })
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/users/pre/ext").
to_return(status: 200, body: itc_read_fixture_file('testers/get_external.json'), headers: { 'Content-Type' => 'application/json' })
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/user/internalTesters/898536088/").
to_return(status: 200, body: itc_read_fixture_file('testers/existing_internal_testers.json'), headers: { 'Content-Type' => 'application/json' })
# Creating new testers is stubbed in `testers_spec.rb`
end
def itc_stub_testflight
%w(appletvos ios).each do |type|
# Test information
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/platforms/#{type}/trains/1.0/builds/10/testInformation").
to_return(status: 200, body: itc_read_fixture_file("testflight_build_info_#{type}.json"), headers: { 'Content-Type' => 'application/json' })
# Reject review
stub_request(:post, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/platforms/#{type}/trains/1.0/builds/10/reject").
with(body: "{}").
to_return(status: 200, body: "{}", headers: { 'Content-Type' => 'application/json' })
# Submission
stub_request(:post, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/platforms/#{type}/trains/1.0/builds/10/review/submit").
to_return(status: 200, body: itc_read_fixture_file("testflight_submission_submit_#{type}.json"), headers: { 'Content-Type' => 'application/json' })
end
end
def itc_stub_resolution_center_valid
# Called from the specs to simulate valid server responses
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/resolutionCenter?v=latest").
to_return(status: 200, body: itc_read_fixture_file('app_resolution_center_valid.json'), headers: { 'Content-Type' => 'application/json' })
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/platforms/ios/resolutionCenter?v=latest").
to_return(status: 200, body: itc_read_fixture_file('app_resolution_center_valid.json'), headers: { 'Content-Type' => 'application/json' })
end
def itc_stub_invalid_update
# Called from the specs to simulate invalid server responses
stub_request(:post, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/platforms/ios/versions/812106519").
to_return(status: 200, body: itc_read_fixture_file('update_app_version_failed.json'), headers: { 'Content-Type' => 'application/json' })
end
def itc_stub_valid_update
# Called from the specs to simulate valid server responses
stub_request(:post, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/platforms/ios/versions/812106519").
to_return(status: 200, body: itc_read_fixture_file("update_app_version_success.json"),
headers: { "Content-Type" => "application/json" })
end
def itc_stub_valid_version_update_with_autorelease_and_release_on_datetime
# Called from the specs to simulate valid server responses
stub_request(:post, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/platforms/ios/versions/812106519").
to_return(status: 200, body: itc_read_fixture_file("update_app_version_with_autorelease_overwrite_success.json"),
headers: { "Content-Type" => "application/json" })
end
def itc_stub_app_version_ref
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/version/ref").
to_return(status: 200, body: itc_read_fixture_file("app_version_ref.json"),
headers: { "Content-Type" => "application/json" })
end
def itc_stub_user_detail
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/user/detail").
to_return(status: 200, body: itc_read_fixture_file("user_detail.json"),
headers: { "Content-Type" => "application/json" })
end
def itc_stub_sandbox_testers
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/users/iap").
to_return(status: 200, body: itc_read_fixture_file("sandbox_testers.json"),
headers: { "Content-Type" => "application/json" })
end
def itc_stub_create_sandbox_tester
stub_request(:post, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/users/iap/add").
with(body: JSON.parse(itc_read_fixture_file("create_sandbox_tester_payload.json"))).
to_return(status: 200, body: itc_read_fixture_file("create_sandbox_tester.json"),
headers: { "Content-Type" => "application/json" })
end
def itc_stub_delete_sandbox_tester
body = JSON.parse(itc_read_fixture_file("delete_sandbox_tester_payload.json"))
stub_request(:post, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/users/iap/delete").
with(body: JSON.parse(itc_read_fixture_file("delete_sandbox_tester_payload.json")).to_json).
to_return(status: 200, body: itc_read_fixture_file("delete_sandbox_tester.json"),
headers: { "Content-Type" => "application/json" })
end
def itc_stub_pricing_tiers
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/iaps/pricing/matrix").
to_return(status: 200, body: itc_read_fixture_file("pricing_tiers.json"),
headers: { "Content-Type" => "application/json" })
end
def itc_stub_release_to_store
stub_request(:post, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/versions/812106519/releaseToStore").
with(body: "898536088").
to_return(status: 200, body: itc_read_fixture_file("update_app_version_success.json"),
headers: { "Content-Type" => "application/json" })
end
def itc_stub_release_to_all_users
stub_request(:post, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/versions/812106519/phasedRelease/state/COMPLETE").
with(body: "898536088").
to_return(status: 200, body: itc_read_fixture_file("update_app_version_success.json"),
headers: { "Content-Type" => "application/json" })
end
def itc_stub_promocodes
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/promocodes/versions").
to_return(status: 200, body: itc_read_fixture_file("promocodes.json"),
headers: { "Content-Type" => "application/json" })
end
def itc_stub_generate_promocodes
stub_request(:post, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/promocodes/versions").
to_return(status: 200, body: itc_read_fixture_file("promocodes_generated.json"),
headers: { "Content-Type" => "application/json" })
end
def itc_stub_promocodes_history
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/promocodes/history").
to_return(status: 200, body: itc_read_fixture_file("promocodes_history.json"),
headers: { "Content-Type" => "application/json" })
end
def itc_stub_iap
# pricing goal calculator
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/iaps/1195137656/pricing/equalize/EUR/1").
to_return(status: 200, body: itc_read_fixture_file("iap_price_goal_calc.json"),
headers: { "Content-Type" => "application/json" })
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/iaps/1195137657/pricing/equalize/EUR/1").
to_return(status: 200, body: itc_read_fixture_file("iap_price_goal_calc.json"),
headers: { "Content-Type" => "application/json" })
# get shared secret
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/iaps/appSharedSecret").
to_return(status: 200, body: itc_read_fixture_file("iap_shared_secret_1.json"),
headers: { "Content-Type" => "application/json" })
# generate new shared secret
stub_request(:post, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/iaps/appSharedSecret").
to_return(status: 200, body: itc_read_fixture_file("iap_shared_secret_2.json"),
headers: { "Content-Type" => "application/json" })
# delete iap
stub_request(:delete, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/iaps/1194457865").
to_return(status: 200, body: "", headers: {})
# create consumable iap
stub_request(:post, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/iaps").
with(body: itc_read_fixture_file("iap_create.json")).
to_return(status: 200, body: itc_read_fixture_file("iap_detail.json"),
headers: { "Content-Type" => "application/json" })
# create recurring iap
stub_request(:post, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/iaps").
with(body: itc_read_fixture_file("iap_create_recurring.json")).
to_return(status: 200, body: itc_read_fixture_file("iap_detail_recurring.json"),
headers: { "Content-Type" => "application/json" })
# create recurring iap without pricing
stub_request(:post, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/iaps").
with(body: itc_read_fixture_file("iap_create_recurring_without_pricing.json")).
to_return(status: 200, body: itc_read_fixture_file("iap_detail_recurring.json"),
headers: { "Content-Type" => "application/json" })
# iap consumable template
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/iaps/consumable/template").
to_return(status: 200, body: itc_read_fixture_file("iap_consumable_template.json"),
headers: { "Content-Type" => "application/json" })
# iap recurring template
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/iaps/recurring/template").
to_return(status: 200, body: itc_read_fixture_file("iap_recurring_template.json"),
headers: { "Content-Type" => "application/json" })
# iap edit family
stub_request(:put, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/iaps/family/20373395/").
with(body: itc_read_fixture_file("iap_family_edit_versions.json")).
to_return(status: 200, body: itc_read_fixture_file("iap_family_detail.json"),
headers: { "Content-Type" => "application/json" })
# iap edit family
stub_request(:put, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/iaps/family/20373395/").
with(body: itc_read_fixture_file("iap_family_edit.json")).
to_return(status: 200, body: itc_read_fixture_file("iap_family_detail.json"),
headers: { "Content-Type" => "application/json" })
# iap edit family
stub_request(:put, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/iaps/family/20373395/").
with(body: itc_read_fixture_file("iap_family_edit_with_de.json")).
to_return(status: 200, body: itc_read_fixture_file("iap_family_detail.json"),
headers: { "Content-Type" => "application/json" })
# iap family detail
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/iaps/family/20372345").
to_return(status: 200, body: itc_read_fixture_file("iap_family_detail.json"),
headers: { "Content-Type" => "application/json" })
# create IAP family
stub_request(:post, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/iaps/family/").
with(body: JSON.parse(itc_read_fixture_file("iap_family_create.json"))).
to_return(status: 200, body: itc_read_fixture_file("iap_family_create_success.json"), headers: { "Content-Type" => "application/json" })
# load IAP Family Template
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/iaps/family/template").
to_return(status: 200, body: itc_read_fixture_file("iap_family_template.json"),
headers: { "Content-Type" => "application/json" })
# update IAP
stub_request(:put, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/iaps/1195137656").
with(body: JSON.parse(itc_read_fixture_file("iap_update.json"))).
to_return(status: 200, body: itc_read_fixture_file("iap_detail.json"),
headers: { "Content-Type" => "application/json" })
# update IAP recurring
stub_request(:put, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/iaps/1195137657").
with(body: JSON.parse(itc_read_fixture_file("iap_update_recurring.json"))).
to_return(status: 200, body: itc_read_fixture_file("iap_detail_recurring.json"),
headers: { "Content-Type" => "application/json" })
# iap details
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/iaps/1194457865").
to_return(status: 200, body: itc_read_fixture_file("iap_detail.json"),
headers: { "Content-Type" => "application/json" })
# iap details recurring
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/898536088/iaps/1195137657").
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | true |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/spec/tunes/iap_family_details_spec.rb | spaceship/spec/tunes/iap_family_details_spec.rb | describe Spaceship::Tunes::IAPFamilyList do
before { TunesStubbing.itc_stub_iap }
include_examples "common spaceship login"
let(:client) { Spaceship::Application.client }
let(:app) { Spaceship::Application.all.find { |a| a.apple_id == "898536088" } }
let(:purchase) { app.in_app_purchases }
describe "IAP FamilyDetail" do
it "Creates a Object" do
element = app.in_app_purchases.families.all.first.edit
expect(element.class).to eq(Spaceship::Tunes::IAPFamilyDetails)
expect(element.name).to eq("Family Name")
expect(element.versions["de-DE".to_sym][:name]).to eq("dasdsads")
end
it "can save version" do
edit_version = app.in_app_purchases.families.all.first.edit
edit_version.save!
expect(edit_version.class).to eq(Spaceship::Tunes::IAPFamilyDetails)
expect(edit_version.family_id).to eq("20373395")
end
it "can change versions" do
edit_version = app.in_app_purchases.families.all.first.edit
edit_version.versions = {
"de-DE" => {
subscription_name: "subscr name",
name: "localized name",
id: 12_345
}
}
edit_version.save!
expect(edit_version.class).to eq(Spaceship::Tunes::IAPFamilyDetails)
expect(edit_version.family_id).to eq("20373395")
expect(edit_version.versions).to eq({ "de-DE": { subscription_name: "subscr name", name: "localized name", id: 12_345, status: nil } })
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/spec/tunes/member_spec.rb | spaceship/spec/tunes/member_spec.rb | describe Spaceship::Tunes::Members do
include_examples "common spaceship login"
before { TunesStubbing.itc_stub_members }
let(:client) { Spaceship::AppVersion.client }
describe "Member Object" do
it "parses selected apps" do
member = Spaceship::Members.find("helmut@januschka.com")
expect(member.has_all_apps).to eq(true)
member = Spaceship::Members.find("hjanuschka+no-accept@gmail.com")
expect(member.has_all_apps).to eq(false)
expect(member.selected_apps.find { |a| a.apple_id == "898536088" }.name).to eq("App Name 1")
end
it "checks if invitation is accepted" do
member = Spaceship::Members.find("hjanuschka+no-accept@gmail.com")
expect(member.not_accepted_invitation).to eq(true)
end
it "parses currency" do
member = Spaceship::Members.find("hjanuschka+no-accept@gmail.com")
expect(member.preferred_currency).to eq({ name: "Euro", code: "EUR", country: "Austria", country_code: "AUT" })
end
it "parses roles" do
member = Spaceship::Members.find("helmut@januschka.com")
expect(member.roles).to eq(["legal", "admin"])
end
it "finds one member by email" do
member = Spaceship::Members.find("helmut@januschka.com")
expect(member.class).to eq(Spaceship::Tunes::Member)
expect(member.email_address).to eq("helmut@januschka.com")
end
it "resends invitation" do
member = Spaceship::Members.find("helmut@januschka.com")
expect(client).to receive(:reinvite_member).with("helmut@januschka.com")
member.resend_invitation
end
it "deletes a member" do
member = Spaceship::Members.find("helmut@januschka.com")
expect(client).to receive(:delete_member!).with("283226505", "helmut@januschka.com")
member.delete!
end
describe "creates a new member" do
it "role: admin, apps: all" do
Spaceship::Members.create!(firstname: "Helmut", lastname: "Januschka", email_address: "helmut@januschka.com")
end
it "role: developer apps: all" do
Spaceship::Members.create!(firstname: "Helmut", lastname: "Januschka", email_address: "helmut@januschka.com", roles: ["developer"])
end
it "role: appmanager, apps: 12344444" do
Spaceship::Members.create!(firstname: "Helmut", lastname: "Januschka", email_address: "helmut@januschka.com", roles: ["appmanager"], apps: ["898536088"])
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/spec/tunes/tunes_client_spec.rb | spaceship/spec/tunes/tunes_client_spec.rb | require 'fastlane-sirp'
describe Spaceship::TunesClient do
include_examples "common spaceship login", true
before do
# Prevent loading from file saved ssession
allow_any_instance_of(Spaceship::Client).to receive(:load_session_from_file).and_return(false)
end
describe '#login' do
it 'raises an exception if authentication failed' do
expect do
subject.login('bad-username', 'bad-password')
end.to raise_exception(Spaceship::Client::InvalidUserCredentialsError, "Invalid username and password combination. Used 'bad-username' as the username.")
end
end
describe 'client' do
it 'exposes the session cookie' do
begin
subject.login('bad-username', 'bad-password')
rescue Spaceship::Client::InvalidUserCredentialsError
expect(subject.cookie).to eq('session=invalid')
end
end
end
describe 'exception if Apple ID & Privacy not acknowledged' do
subject { Spaceship::Tunes.client }
let(:username) { 'spaceship@krausefx.com' }
let(:password) { 'so_secret' }
before(:each) do
# Don't need to test hashcash here
allow_any_instance_of(Spaceship::Client).to receive(:fetch_hashcash)
end
it 'has authType is sa' do
expect_any_instance_of(Spaceship::Client).to receive(:request).twice.and_call_original
response_second = double
allow(response_second).to receive(:status).and_return(412)
allow(response_second).to receive(:body).and_return({ "authType" => "sa" })
expect_any_instance_of(Spaceship::Client).to receive(:request).once.and_return(response_second)
expect do
Spaceship::Tunes.login(username, password)
end.to raise_exception(Spaceship::AppleIDAndPrivacyAcknowledgementNeeded, "Need to acknowledge to Apple's Apple ID and Privacy statement. Please manually log into https://appleid.apple.com (or https://appstoreconnect.apple.com) to acknowledge the statement. " \
"Your account might also be asked to upgrade to 2FA. Set SPACESHIP_SKIP_2FA_UPGRADE=1 for fastlane to automatically bypass 2FA upgrade if possible.")
end
it 'has authType of hsa' do
expect_any_instance_of(Spaceship::Client).to receive(:request).twice.and_call_original
response_second = double
allow(response_second).to receive(:status).and_return(412)
allow(response_second).to receive(:body).and_return({ "authType" => "hsa" })
expect_any_instance_of(Spaceship::Client).to receive(:request).once.and_return(response_second)
expect do
Spaceship::Tunes.login(username, password)
end.to raise_exception(Spaceship::AppleIDAndPrivacyAcknowledgementNeeded, "Need to acknowledge to Apple's Apple ID and Privacy statement. Please manually log into https://appleid.apple.com (or https://appstoreconnect.apple.com) to acknowledge the statement. " \
"Your account might also be asked to upgrade to 2FA. Set SPACESHIP_SKIP_2FA_UPGRADE=1 for fastlane to automatically bypass 2FA upgrade if possible.")
end
it 'has authType of non-sa' do
expect_any_instance_of(Spaceship::Client).to receive(:request).twice.and_call_original
response_second = double
allow(response_second).to receive(:status).and_return(412)
allow(response_second).to receive(:body).and_return({ "authType" => "hsa" })
expect_any_instance_of(Spaceship::Client).to receive(:request).once.and_return(response_second)
expect do
Spaceship::Tunes.login(username, password)
end.to raise_exception(Spaceship::AppleIDAndPrivacyAcknowledgementNeeded, "Need to acknowledge to Apple's Apple ID and Privacy statement. Please manually log into https://appleid.apple.com (or https://appstoreconnect.apple.com) to acknowledge the statement. " \
"Your account might also be asked to upgrade to 2FA. Set SPACESHIP_SKIP_2FA_UPGRADE=1 for fastlane to automatically bypass 2FA upgrade if possible.")
end
it 'has authType of hsa2' do
expect_any_instance_of(Spaceship::Client).to receive(:request).twice.and_call_original
response_second = double
allow(response_second).to receive(:status).and_return(412)
allow(response_second).to receive(:body).and_return({ "authType" => "hsa2" })
expect_any_instance_of(Spaceship::Client).to receive(:request).once.and_return(response_second)
expect do
Spaceship::Tunes.login(username, password)
end.to raise_exception(Spaceship::AppleIDAndPrivacyAcknowledgementNeeded, "Need to acknowledge to Apple's Apple ID and Privacy statement. Please manually log into https://appleid.apple.com (or https://appstoreconnect.apple.com) to acknowledge the statement. " \
"Your account might also be asked to upgrade to 2FA. Set SPACESHIP_SKIP_2FA_UPGRADE=1 for fastlane to automatically bypass 2FA upgrade if possible.")
end
end
describe "Logged in" do
subject { Spaceship::Tunes.client }
let(:username) { 'spaceship@krausefx.com' }
let(:password) { 'so_secret' }
before do
Spaceship::Tunes.login(username, password)
end
it 'stores the username' do
expect(subject.user).to eq('spaceship@krausefx.com')
end
it "#hostname" do
expect(subject.class.hostname).to eq('https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/')
end
describe "#handle_itc_response" do
it "raises an exception if something goes wrong" do
data = JSON.parse(TunesStubbing.itc_read_fixture_file('update_app_version_failed.json'))['data']
expect do
subject.handle_itc_response(data)
end.to raise_error("[German]: The App Name you entered has already been used. [English]: The App Name you entered has already been used. You must provide an address line. There are errors on the page and for 2 of your localizations.")
end
it "does nothing if everything works as expected and returns the original data" do
data = JSON.parse(TunesStubbing.itc_read_fixture_file('update_app_version_success.json'))['data']
expect(subject.handle_itc_response(data)).to eq(data)
end
it "identifies try again later responses" do
data = JSON.parse(TunesStubbing.itc_read_fixture_file('update_app_version_temporarily_unable.json'))['data']
expect do
subject.handle_itc_response(data)
end.to raise_error(Spaceship::TunesClient::ITunesConnectTemporaryError, "We're temporarily unable to save your changes. Please try again later.")
end
end
describe "associated to multiple teams" do
let(:user_details_data) do
{
'availableProviders' => [
{ 'name' => 'Tom', 'providerId' => 1234, 'contentProviderPublicId' => '1111-2222-3333-4444' },
{ 'name' => 'Harry', 'providerId' => 5678, 'contentProviderPublicId' => '2222-3333-4444-5555' }
],
'provider' => { 'providerId' => 1234 }
}
end
it "#team_id picks team indicated by the sessionToken if select_team not called" do
allow(subject).to receive(:user_details_data).and_return(user_details_data)
expect(subject.team_id).to eq(1234)
end
it "returns team_id from legitimate team_name parameter" do
allow(subject).to receive(:user_details_data).and_return(user_details_data)
expect(subject.select_team(team_name: 'Harry')).to eq('5678')
end
it "returns team_id from environment variable" do
stub_const('ENV', { 'FASTLANE_ITC_TEAM_NAME' => 'Harry' })
allow(subject).to receive(:user_details_data).and_return(user_details_data)
expect(subject.select_team).to eq('5678')
end
end
describe "in-app-purchase methods" do
before do
stub_request(:post, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/123/iaps/abc/submission")
.and_return(status: 200, body: TunesStubbing.itc_read_fixture_file("iap_submission.json"), headers: { "Content-Type" => "application/json" })
end
it "submits an in-app-purchase for review" do
response = subject.submit_iap!(app_id: "123", purchase_id: "abc")
# the response does not include any data when it is successful.
expect(response).to eq(nil)
end
end
describe "iOS app bundle methods" do
before do
stub_request(:get, "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/appbundles/metadetail/1234567890")
.and_return(status: 200, body: TunesStubbing.itc_read_fixture_file("bundle_details.json"), headers: { "Content-Type" => "application/json" })
end
it "requests iOS app bundle details" do
response = subject.bundle_details(1_234_567_890)
expect(response["adamId"]).to eq(1_234_567_890)
expect(response["details"][0]["name"]).to eq("Fancy Bundle")
end
end
end
describe "CI" do
it "crashes when running in non-interactive shell" do
expect(FastlaneCore::Helper).to receive(:ci?).and_return(true)
provider = { 'contentProvider' => { 'name' => 'Tom', 'contentProviderId' => 1234 } }
allow(subject).to receive(:teams).and_return([provider, provider]) # pass it twice, to call the team selection
expect { subject.select_team }.to raise_error("Multiple App Store Connect Teams found; unable to choose, terminal not interactive!")
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/spec/tunes/app_analytics_spec.rb | spaceship/spec/tunes/app_analytics_spec.rb | require 'spec_helper'
describe Spaceship::Tunes::AppAnalytics do
include_examples "common spaceship login"
let(:app) { Spaceship::Application.all.find { |a| a.apple_id == "898536088" } }
describe "App Analytics Grabbed Properly" do
it "accesses live analytics details" do
start_time, end_time = app.analytics.time_last_7_days
TunesStubbing.itc_stub_analytics(start_time, end_time)
analytics = app.analytics
units = analytics.app_units
expect(units['size']).to eq(1)
val = units['results'].find do |a|
a['adamId'].include?('898536088')
end
expect(val['meetsThreshold']).to eq(true)
views = analytics.app_views
expect(views['size']).to eq(1)
val = views['results'].find do |a|
a['adamId'].include?('898536088')
end
expect(val['meetsThreshold']).to eq(true)
in_app_purchases = analytics.app_in_app_purchases
expect(in_app_purchases['size']).to eq(1)
val = in_app_purchases['results'].find do |a|
a['adamId'].include?('898536088')
end
expect(val['meetsThreshold']).to eq(true)
sales = analytics.app_sales
expect(sales['size']).to eq(1)
val = sales['results'].find do |a|
a['adamId'].include?('898536088')
end
expect(val['meetsThreshold']).to eq(true)
paying_users = analytics.app_paying_users
expect(paying_users['size']).to eq(1)
val = paying_users['results'].find do |a|
a['adamId'].include?('898536088')
end
expect(val['meetsThreshold']).to eq(true)
installs = analytics.app_installs
expect(installs['size']).to eq(1)
val = installs['results'].find do |a|
a['adamId'].include?('898536088')
end
expect(val['meetsThreshold']).to eq(true)
sessions = analytics.app_sessions
expect(sessions['size']).to eq(1)
val = sessions['results'].find do |a|
a['adamId'].include?('898536088')
end
expect(val['meetsThreshold']).to eq(true)
active_devices = analytics.app_active_devices
expect(active_devices['size']).to eq(1)
val = active_devices['results'].find do |a|
a['adamId'].include?('898536088')
end
expect(val['meetsThreshold']).to eq(true)
crashes = analytics.app_crashes
expect(crashes['size']).to eq(1)
val = crashes['results'].find do |a|
a['adamId'].include?('898536088')
end
expect(val['meetsThreshold']).to eq(true)
measure_installs = analytics.app_measure_interval(start_time, end_time, 'installs')
expect(measure_installs['size']).to eq(1)
val = measure_installs['results'].find do |a|
a['adamId'].include?('898536088')
end
expect(val['meetsThreshold']).to eq(true)
end
it "grabs live analytics split by view_by" do
start_time, end_time = app.analytics.time_last_7_days
TunesStubbing.itc_stub_analytics(start_time, end_time)
analytics = app.analytics
measure_installs_by_source = analytics.app_measure_interval(start_time, end_time, 'installs', 'source')
expect(measure_installs_by_source['size']).to eq(5)
val = measure_installs_by_source['results'].find do |a|
a['adamId'].include?('898536088')
end
expect(val['meetsThreshold']).to eq(true)
end
it "accesses non-live analytics details" do
start_time, end_time = app.analytics.time_last_7_days
TunesStubbing.itc_stub_analytics(start_time, end_time)
TunesStubbing.itc_stub_no_live_version
expect do
analytics = app.analytics
end.to raise_error("Analytics are only available for live apps.")
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/spec/du/utilities_spec.rb | spaceship/spec/du/utilities_spec.rb | describe Spaceship::Utilities do
describe '#content_type' do
it 'recognizes the .jpg extension' do
expect(Spaceship::Utilities.content_type('blah.jpg')).to eq('image/jpeg')
end
it 'recognizes the .jpeg extension' do
expect(Spaceship::Utilities.content_type('blah.jpeg')).to eq('image/jpeg')
end
it 'recognizes the .png extension' do
expect(Spaceship::Utilities.content_type('blah.png')).to eq('image/png')
end
it 'recognizes the .geojson extension' do
expect(Spaceship::Utilities.content_type('blah.geojson')).to eq('application/json')
end
it 'recognizes the .mov extension' do
expect(Spaceship::Utilities.content_type('blah.mov')).to eq('video/quicktime')
end
it 'recognizes the .m4v extension' do
expect(Spaceship::Utilities.content_type('blah.m4v')).to eq('video/mp4')
end
it 'recognizes the .mp4 extension' do
expect(Spaceship::Utilities.content_type('blah.mp4')).to eq('video/mp4')
end
it 'raises an exception for unknown extensions' do
expect { Spaceship::Utilities.content_type('blah.unknown') }.to raise_error("Unknown content-type for file blah.unknown")
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/spec/du/du_stubbing.rb | spaceship/spec/du/du_stubbing.rb | def du_fixture_file_path(filename)
File.join('spaceship', 'spec', 'du', 'fixtures', filename)
end
def du_read_fixture_file(filename)
File.read(du_fixture_file_path(filename))
end
# those represent UploadFile structures
def du_uploadimage_correct_screenshot
mock_jpg = double
allow(mock_jpg).to receive(:file_name).and_return('ftl_FAKEMD5_screenshot1024.jpg')
allow(mock_jpg).to receive(:file_size).and_return(1_234_520)
allow(mock_jpg).to receive(:content_type).and_return('image/jpeg')
allow(mock_jpg).to receive(:bytes).and_return("the screenshot...")
mock_jpg
end
def du_uploadimage_correct_jpg
mock_jpg = double
allow(mock_jpg).to receive(:file_name).and_return('ftl_FAKEMD5_icon1024.jpg')
allow(mock_jpg).to receive(:file_size).and_return(520)
allow(mock_jpg).to receive(:content_type).and_return('image/jpeg')
allow(mock_jpg).to receive(:bytes).and_return("binary image...")
mock_jpg
end
def du_uploadtrailer_correct_mov
mock_jpg = double
allow(mock_jpg).to receive(:file_name).and_return('ftl_FAKEMD5_trailer-en-US.mov')
allow(mock_jpg).to receive(:file_size).and_return(123_456)
allow(mock_jpg).to receive(:content_type).and_return('video/quicktime')
allow(mock_jpg).to receive(:bytes).and_return("binary video...")
mock_jpg
end
def du_uploadtrailer_preview_correct_jpg
mock_jpg = double
allow(mock_jpg).to receive(:file_name).and_return('ftl_FAKEMD5_trailer-en-US_preview.jpg')
allow(mock_jpg).to receive(:file_size).and_return(12_345)
allow(mock_jpg).to receive(:content_type).and_return('image/jpg')
allow(mock_jpg).to receive(:bytes).and_return("trailer preview...")
mock_jpg
end
def du_uploadimage_invalid_png
mock_jpg = double
allow(mock_jpg).to receive(:file_name).and_return('ftl_FAKEMD5_icon1024.jpg')
allow(mock_jpg).to receive(:file_size).and_return(520)
allow(mock_jpg).to receive(:content_type).and_return('image/png')
allow(mock_jpg).to receive(:bytes).and_return("invalid binary image...")
mock_jpg
end
def du_read_upload_geojson_response_success
du_read_fixture_file('upload_geojson_response_success.json')
end
def du_read_upload_geojson_response_failed
du_read_fixture_file('upload_geojson_response_failed.json')
end
def du_upload_valid_geojson
Spaceship::UploadFile.from_path(du_fixture_file_path('upload_valid.geojson'))
end
def du_upload_invalid_geojson
Spaceship::UploadFile.from_path(du_fixture_file_path('upload_invalid.GeoJSON'))
end
def du_read_upload_screenshot_response_success
du_read_fixture_file('upload_screenshot_response_success.json')
end
def du_read_upload_trailer_preview_response_success
du_read_fixture_file('upload_trailer_preview_response_success.json')
end
def du_read_upload_trailer_preview_2_response_success
du_read_fixture_file('upload_trailer_preview_2_response_success.json')
end
def du_upload_large_image_success
stub_request(:post, "https://du-itc.itunes.apple.com/upload/image").
with(body: "binary image...",
headers: { 'Accept' => 'application/json, text/plain, */*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Connection' => 'keep-alive', 'Content-Length' => '520', 'Content-Type' => 'image/jpeg', 'Referrer' => 'https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/ng/app/898536088',
'X-Apple-Jingle-Correlation-Key' => 'iOS App:AdamId=898536088:Version=0.9.13', 'X-Apple-Upload-Appleid' => '898536088', 'X-Apple-Upload-Contentproviderid' => '4321', 'X-Apple-Upload-Itctoken' => 'sso token for image',
'X-Apple-Upload-Referrer' => 'https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/ng/app/898536088', 'X-Apple-Upload-Validation-Rulesets' => 'MZPFT.LargeApplicationIcon', 'X-Original-Filename' => 'ftl_FAKEMD5_icon1024.jpg' }).
to_return(status: 201, body: du_read_fixture_file('upload_image_success.json'), headers: { 'Content-Type' => 'application/json' })
end
def du_upload_watch_image_failure
stub_request(:post, "https://du-itc.itunes.apple.com/upload/image").
with(body: "invalid binary image...",
headers: { 'Accept' => 'application/json, text/plain, */*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Connection' => 'keep-alive', 'Content-Length' => '520', 'Content-Type' => 'image/png', 'Referrer' => 'https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/ng/app/898536088',
'X-Apple-Jingle-Correlation-Key' => 'iOS App:AdamId=898536088:Version=0.9.13', 'X-Apple-Upload-Appleid' => '898536088', 'X-Apple-Upload-Contentproviderid' => '4321', 'X-Apple-Upload-Itctoken' => 'sso token for image',
'X-Apple-Upload-Referrer' => 'https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/ng/app/898536088', 'X-Apple-Upload-Validation-Rulesets' => 'MZPFT.GizmoAppIcon', 'X-Original-Filename' => 'ftl_FAKEMD5_icon1024.jpg' }).
to_return(status: 400, body: du_read_fixture_file('upload_image_failed.json'), headers: { 'Content-Type' => 'application/json' })
end
def du_upload_geojson_success
stub_request(:post, "https://du-itc.itunes.apple.com/upload/geo-json").
with(body: du_upload_valid_geojson.bytes,
headers: { 'Accept' => 'application/json, text/plain, */*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Connection' => 'keep-alive', 'Content-Length' => du_upload_valid_geojson.file_size, 'Content-Type' => 'application/json', 'Referrer' => 'https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/ng/app/898536088',
'X-Apple-Jingle-Correlation-Key' => 'iOS App:AdamId=898536088:Version=0.9.13', 'X-Apple-Upload-Appleid' => '898536088', 'X-Apple-Upload-Contentproviderid' => '4321', 'X-Apple-Upload-Itctoken' => 'sso token for image',
'X-Apple-Upload-Referrer' => 'https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/ng/app/898536088', 'X-Original-Filename' => 'ftl_FAKEMD5_upload_valid.geojson' }).
to_return(status: 201, body: du_read_upload_geojson_response_success, headers: { 'Content-Type' => 'application/json' })
end
def du_upload_geojson_failure
stub_request(:post, "https://du-itc.itunes.apple.com/upload/geo-json").
with(body: du_upload_invalid_geojson.bytes,
headers: { 'Accept' => 'application/json, text/plain, */*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Connection' => 'keep-alive', 'Content-Length' => du_upload_invalid_geojson.file_size, 'Content-Type' => 'application/json', 'Referrer' => 'https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/ng/app/898536088',
'X-Apple-Jingle-Correlation-Key' => 'iOS App:AdamId=898536088:Version=0.9.13', 'X-Apple-Upload-Appleid' => '898536088', 'X-Apple-Upload-Contentproviderid' => '4321', 'X-Apple-Upload-Itctoken' => 'sso token for image',
'X-Apple-Upload-Referrer' => 'https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/ng/app/898536088', 'X-Original-Filename' => 'ftl_FAKEMD5_upload_invalid.GeoJSON' }).
to_return(status: 400, body: du_read_upload_geojson_response_failed, headers: { 'Content-Type' => 'application/json' })
end
def du_upload_screenshot_success
stub_request(:post, "https://du-itc.itunes.apple.com/upload/image").
with(body: "the screenshot...",
headers: { 'Accept' => 'application/json, text/plain, */*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Connection' => 'keep-alive', 'Content-Length' => '1234520', 'Content-Type' => 'image/jpeg', 'Referrer' => 'https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/ng/app/898536088',
'X-Apple-Jingle-Correlation-Key' => 'iOS App:AdamId=898536088:Version=0.9.13', 'X-Apple-Upload-Appleid' => '898536088', 'X-Apple-Upload-Contentproviderid' => '4321', 'X-Apple-Upload-Itctoken' => 'the_sso_token_for_image',
'X-Apple-Upload-Referrer' => 'https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/ng/app/898536088', 'X-Apple-Upload-Validation-Rulesets' => 'MZPFT.SortedN41ScreenShot', 'X-Original-Filename' => 'ftl_FAKEMD5_screenshot1024.jpg' }).
to_return(status: 201, body: du_read_upload_screenshot_response_success, headers: { 'Content-Type' => 'application/json' })
stub_request(:post, "https://du-itc.itunes.apple.com/upload/image").
with(body: "the screenshot...",
headers: { 'Accept' => 'application/json, text/plain, */*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Connection' => 'keep-alive', 'Content-Length' => '1234520', 'Content-Type' => 'image/jpeg', 'Referrer' => 'https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/ng/app/898536088',
'User-Agent' => "Spaceship #{Fastlane::VERSION}", 'X-Apple-Jingle-Correlation-Key' => 'iOS App:AdamId=898536088:Version=0.9.13', 'X-Apple-Upload-Appleid' => '898536088', 'X-Apple-Upload-Contentproviderid' => '4321',
'X-Apple-Upload-Itctoken' => 'the_sso_token_for_image', 'X-Apple-Upload-Referrer' => 'https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/ng/app/898536088', 'X-Apple-Upload-Validation-Rulesets' => 'MZPFT.SortedScreenShot', 'X-Original-Filename' => 'ftl_FAKEMD5_screenshot1024.jpg' }).
to_return(status: 201, body: du_read_upload_screenshot_response_success, headers: { 'Content-Type' => 'application/json' })
end
def du_upload_messages_screenshot_success
stub_request(:post, "https://du-itc.itunes.apple.com/upload/image").
with(body: "the screenshot...",
headers: { 'Accept' => 'application/json, text/plain, */*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Connection' => 'keep-alive', 'Content-Length' => '1234520', 'Content-Type' => 'image/jpeg', 'Referrer' => 'https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/ng/app/898536088',
'X-Apple-Jingle-Correlation-Key' => 'iOS App:AdamId=898536088:Version=0.9.13', 'X-Apple-Upload-Appleid' => '898536088', 'X-Apple-Upload-Contentproviderid' => '4321', 'X-Apple-Upload-Itctoken' => 'the_sso_token_for_image',
'X-Apple-Upload-Referrer' => 'https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/ng/app/898536088', 'X-Apple-Upload-Validation-Rulesets' => 'MZPFT.SortedN41MessagesScreenShot', 'X-Original-Filename' => 'ftl_FAKEMD5_screenshot1024.jpg' }).
to_return(status: 201, body: du_read_upload_screenshot_response_success, headers: { 'Content-Type' => 'application/json' })
stub_request(:post, "https://du-itc.itunes.apple.com/upload/image").
with(body: "the screenshot...",
headers: { 'Accept' => 'application/json, text/plain, */*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Connection' => 'keep-alive', 'Content-Length' => '1234520', 'Content-Type' => 'image/jpeg', 'Referrer' => 'https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/ng/app/898536088',
'User-Agent' => "Spaceship #{Fastlane::VERSION}", 'X-Apple-Jingle-Correlation-Key' => 'iOS App:AdamId=898536088:Version=0.9.13', 'X-Apple-Upload-Appleid' => '898536088', 'X-Apple-Upload-Contentproviderid' => '4321',
'X-Apple-Upload-Itctoken' => 'the_sso_token_for_image', 'X-Apple-Upload-Referrer' => 'https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/ng/app/898536088', 'X-Apple-Upload-Validation-Rulesets' => 'MZPFT.SortedScreenShot', 'X-Original-Filename' => 'ftl_FAKEMD5_screenshot1024.jpg' }).
to_return(status: 201, body: du_read_upload_screenshot_response_success, headers: { 'Content-Type' => 'application/json' })
end
# def du_upload_video_preview_success
# stub_request(:post, "https://du-itc.itunes.apple.com/upload/app-screenshot-image").
# with(body: "trailer preview...",
# headers: {'Accept' => 'application/json, text/plain, */*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Connection' => 'keep-alive', 'Content-Length' => '12345', 'Content-Type' => 'image/joeg', 'Referrer' => 'https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/ng/app/898536088',
# 'User-Agent' => 'spaceship', 'X-Apple-Jingle-Correlation-Key' => 'iOS App:AdamId=898536088:Version=0.9.13', 'X-Apple-Upload-Appleid' => '898536088', 'X-Apple-Upload-Contentproviderid' => '4321', 'X-Apple-Upload-Itctoken' => 'the_sso_token_for_image',
# 'X-Apple-Upload-Referrer' => 'https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/ng/app/898536088', 'X-Original-Filename' => 'ftl_FAKEMD5_trailer-en-US_preview.jpg'}).
# to_return(status: 201, body: du_read_upload_trailer_preview_response_success, headers: {'Content-Type' => 'application/json'})
# end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/spec/du/du_client_spec.rb | spaceship/spec/du/du_client_spec.rb | describe Spaceship::DUClient, :du do
before { Spaceship::Tunes.login }
let(:client) { Spaceship::AppVersion.client }
let(:app) { Spaceship::Application.all.find { |a| a.apple_id == "898536088" } }
let(:contentProviderId) { "4321" }
let(:ssoTokenForImage) { "sso token for image" }
let(:version) { app.edit_version }
subject { Spaceship::DUClient.new }
before do
allow(Spaceship::Utilities).to receive(:md5digest).and_return("FAKEMD5")
end
describe "#upload_large_icon and #upload_watch_icon" do
let(:correct_jpg_image) { du_uploadimage_correct_jpg }
let(:bad_png_image) { du_uploadimage_invalid_png }
it "handles successful upload request using #upload_large_icon" do
du_upload_large_image_success
data = subject.upload_large_icon(version, correct_jpg_image, contentProviderId, ssoTokenForImage)
expect(data['token']).to eq('Purple7/v4/65/04/4d/65044dae-15b0-a5e0-d021-5aa4162a03a3/pr_source.jpg')
end
it "handles failed upload request using #upload_watch_icon" do
du_upload_watch_image_failure
error_text = "[IMG_ALPHA_NOT_ALLOWED] Alpha is not allowed. Please edit the image to remove alpha and re-save it."
expect do
data = subject.upload_watch_icon(version, bad_png_image, contentProviderId, ssoTokenForImage)
end.to raise_error(Spaceship::Client::UnexpectedResponse, error_text)
end
end
describe "#upload_geojson" do
let(:valid_geojson) { du_upload_valid_geojson }
let(:invalid_geojson) { du_upload_invalid_geojson }
it "handles successful upload request" do
du_upload_geojson_success
data = subject.upload_geojson(version, valid_geojson, contentProviderId, ssoTokenForImage)
expect(data['token']).to eq('Purple1/v4/45/50/9d/45509d39-6a5d-7f55-f919-0fbc7436be61/pr_source.geojson')
expect(data['dsId']).to eq(1_206_675_732)
expect(data['type']).to eq('SMGameCenterAvatarImageType.SOURCE')
end
it "handles failed upload request" do
du_upload_geojson_failure
error_text = "[FILE_GEOJSON_FIELD_NOT_SUPPORTED] The routing app coverage file is in the wrong format. For more information, see the Location and Maps Programming Guide in the iOS Developer Library."
expect do
data = subject.upload_geojson(version, invalid_geojson, contentProviderId, ssoTokenForImage)
end.to raise_error(Spaceship::Client::UnexpectedResponse, error_text)
end
end
describe "#upload_screenshot" do
# we voluntary skip tests for this method, it's mostly covered by other functions
end
# These tests were created when we migrated the mappings from several files
# to `spaceship/lib/assets/displayFamilies.json`.
# They make sure our logic to parse that file works as expected.
describe "mapping migrations" do
it "matches the picture_type_map prior to using DisplayFamily" do
expect(subject.send(:picture_type_map).sort).to eq({
ipad: "MZPFT.SortedTabletScreenShot",
ipad105: "MZPFT.SortedJ207ScreenShot",
ipadPro: "MZPFT.SortedJ99ScreenShot",
ipadPro11: "MZPFT.SortedJ317ScreenShot",
ipadPro129: "MZPFT.SortedJ320ScreenShot",
iphone35: "MZPFT.SortedScreenShot",
iphone4: "MZPFT.SortedN41ScreenShot",
iphone6: "MZPFT.SortedN61ScreenShot",
iphone6Plus: "MZPFT.SortedN56ScreenShot",
iphone58: "MZPFT.SortedD22ScreenShot",
iphone65: "MZPFT.SortedD33ScreenShot",
watch: "MZPFT.SortedN27ScreenShot",
watchSeries4: "MZPFT.SortedN131ScreenShot",
appleTV: "MZPFT.SortedATVScreenShot",
desktop: "MZPFT.SortedDesktopScreenShot"
}.sort)
end
it "matches the messages_picture_type_map prior to using DisplayFamily" do
expect(subject.send(:messages_picture_type_map).sort).to eq({
ipad: "MZPFT.SortedTabletMessagesScreenShot",
ipad105: "MZPFT.SortedJ207MessagesScreenShot",
ipadPro: "MZPFT.SortedJ99MessagesScreenShot",
ipadPro11: "MZPFT.SortedJ317MessagesScreenShot",
ipadPro129: "MZPFT.SortedJ320MessagesScreenShot",
iphone4: "MZPFT.SortedN41MessagesScreenShot",
iphone6: "MZPFT.SortedN61MessagesScreenShot",
iphone6Plus: "MZPFT.SortedN56MessagesScreenShot",
iphone58: "MZPFT.SortedD22MessagesScreenShot",
iphone65: "MZPFT.SortedD33MessagesScreenShot"
}.sort)
end
it "matches the device_resolution_map prior to using DisplayFamily" do
device_resolution_map = subject.send(:device_resolution_map)
old_device_resolution_map = {
watch: [[312, 390]],
watchSeries4: [[368, 448]],
ipad: [[1024, 748], [1024, 768], [2048, 1496], [2048, 1536], [768, 1004], [768, 1024], [1536, 2008], [1536, 2048]],
ipad105: [[1668, 2224], [2224, 1668]],
ipadPro: [[2048, 2732], [2732, 2048]],
ipadPro11: [[1668, 2388], [2388, 1668]],
ipadPro129: [[2048, 2732], [2732, 2048]],
iphone35: [[640, 960], [640, 920], [960, 600], [960, 640]],
iphone4: [[640, 1096], [640, 1136], [1136, 600], [1136, 640]],
iphone6: [[750, 1334], [1334, 750]],
iphone6Plus: [[1242, 2208], [2208, 1242]],
iphone58: [[1125, 2436], [2436, 1125]],
iphone65: [[1242, 2688], [2688, 1242]],
appleTV: [[1920, 1080], [3840, 2160]],
desktop: [[1280, 800], [1440, 900], [2560, 1600], [2880, 1800]]
}
expect(device_resolution_map.count).to eq(old_device_resolution_map.count)
device_resolution_map.each do |k, v|
expect(v.sort).to eq(old_device_resolution_map[k].sort)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/spec/test_flight/build_trains_spec.rb | spaceship/spec/test_flight/build_trains_spec.rb | require 'spec_helper'
require_relative '../mock_servers'
describe Spaceship::TestFlight::BuildTrains do
let(:mock_client) { double('MockClient') }
before do
allow(Spaceship::TestFlight::Base).to receive(:client).and_return(mock_client)
allow(mock_client).to receive(:team_id).and_return('')
mock_client_response(:get_build_trains, with: { app_id: 'some-app-id', platform: 'ios' }) do
['1.0', '1.1']
end
mock_client_response(:get_builds_for_train, with: hash_including(train_version: '1.0')) do
[
{
id: 1,
appAdamId: 10,
trainVersion: '1.0',
uploadDate: '2017-01-01T12:00:00.000+0000',
externalState: 'testflight.build.state.export.compliance.missing'
}
]
end
mock_client_response(:get_builds_for_train, with: hash_including(train_version: '1.1')) do
[
{
id: 2,
appAdamId: 10,
trainVersion: '1.1',
uploadDate: '2017-01-02T12:00:00.000+0000',
externalState: 'testflight.build.state.submit.ready'
},
{
id: 3,
appAdamId: 10,
trainVersion: '1.1',
uploadDate: '2017-01-03T12:00:00.000+0000',
externalState: 'testflight.build.state.processing'
}
]
end
end
context '.all' do
it 'returns versions and builds' do
# build_trains = Spaceship::TestFlight::BuildTrains.all(app_id: 'some-app-id', platform: 'ios')
# expect(build_trains['1.0'].size).to eq(1)
# expect(build_trains['1.1'].size).to eq(2)
# expect(build_trains.values.flatten.size).to eq(3)
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/spec/test_flight/group_spec.rb | spaceship/spec/test_flight/group_spec.rb | require 'spec_helper'
describe Spaceship::TestFlight::Group do
let(:mock_client) { double('MockClient') }
before do
allow(Spaceship::TestFlight::Base).to receive(:client).and_return(mock_client)
allow(mock_client).to receive(:team_id).and_return('')
end
context 'attr_mapping' do
let(:group) do
Spaceship::TestFlight::Group.new({
'id' => 1,
'name' => 'Group 1',
'appAdamId' => 123,
'isDefaultExternalGroup' => false
})
end
it 'has them' do
expect(group.id).to eq(1)
expect(group.name).to eq('Group 1')
expect(group.app_id).to eq(123)
expect(group.is_default_external_group).to eq(false)
end
end
context 'collections' do
before do
mock_client_response(:get_groups, with: { app_id: 'app-id' }) do
[
{
id: 1,
name: 'Group 1',
isDefaultExternalGroup: true
},
{
id: 2,
name: 'Group 2',
isDefaultExternalGroup: false
}
]
end
mock_client_response(:create_group_for_app, with: { app_id: 'app-id', group_name: 'group-name' }) do
{
id: 3,
name: 'group-name',
isDefaultExternalGroup: false
}
end
end
context '.all' do
it 'returns all of the groups' do
groups = Spaceship::TestFlight::Group.all(app_id: 'app-id')
expect(groups.size).to eq(2)
expect(groups.first).to be_instance_of(Spaceship::TestFlight::Group)
end
end
context '.find' do
it 'returns a Group by group_name' do
group = Spaceship::TestFlight::Group.find(app_id: 'app-id', group_name: 'Group 1')
expect(group).to be_instance_of(Spaceship::TestFlight::Group)
expect(group.name).to eq('Group 1')
end
it 'returns nil if no group matches' do
group = Spaceship::TestFlight::Group.find(app_id: 'app-id', group_name: 'Group NaN')
expect(group).to be_nil
end
end
context '.create!' do
it 'returns an existing group with the same name' do
group = Spaceship::TestFlight::Group.create!(app_id: 'app-id', group_name: 'Group 1')
expect(group.name).to eq('Group 1')
expect(group.id).to eq(1)
expect(group).to be_instance_of(Spaceship::TestFlight::Group)
end
it 'creates the group for correct parameters' do
group = Spaceship::TestFlight::Group.create!(app_id: 'app-id', group_name: 'group-name')
expect(group.name).to eq('group-name')
expect(group.id).to eq(3)
expect(group).to be_instance_of(Spaceship::TestFlight::Group)
end
end
context '.delete!' do
it 'removes a group for correct parameters' do
expect(mock_client).to receive(:delete_group_for_app).with(app_id: 'app-id', group_id: 2)
Spaceship::TestFlight::Group.delete!(app_id: 'app-id', group_name: 'Group 2')
end
end
context '.default_external_group' do
it 'returns the default external group' do
group = Spaceship::TestFlight::Group.default_external_group(app_id: 'app-id')
expect(group).to be_instance_of(Spaceship::TestFlight::Group)
expect(group.id).to eq(1)
end
end
context '.filter_groups' do
it 'applies block and returns filtered groups' do
groups = Spaceship::TestFlight::Group.filter_groups(app_id: 'app-id') { |group| group.name == 'Group 1' }
expect(groups).to be_instance_of(Array)
expect(groups.size).to eq(1)
expect(groups.first.id).to eq(1)
end
end
end
context 'instances' do
let(:group) { Spaceship::TestFlight::Group.new('appAdamId' => 1, 'id' => 2, 'isDefaultExternalGroup' => true) }
let(:tester) { double('Tester', tester_id: 'some-tester-id', first_name: 'first name', last_name: 'last name', email: 'some email') }
context '#add_tester!' do
it 'adds a tester via client' do
expect(mock_client).to receive(:create_app_level_tester)
.with(app_id: 1, first_name: tester.first_name, last_name: tester.last_name, email: tester.email)
.and_return('id' => 'some-tester-id')
expect(mock_client).to receive(:post_tester_to_group)
.with(group_id: 2,
email: tester.email,
first_name: tester.first_name,
last_name: tester.last_name,
app_id: 1)
group.add_tester!(tester)
end
end
context '#remove_tester!' do
it 'removes a tester via client' do
expect(mock_client).to receive(:delete_tester_from_group).with(group_id: 2, tester_id: 'some-tester-id', app_id: 1)
group.remove_tester!(tester)
end
end
context '#default_external_group?' do
it 'returns default_external_group' do
expect(group).to receive(:is_default_external_group).and_call_original
expect(group.default_external_group?).to be(true)
end
end
context '#builds' do
before do
mock_client_response(:builds_for_group, with: { app_id: 1, group_id: 2 }) do
[
{
id: 1,
appAdamId: 10,
trainVersion: '1.0',
uploadDate: '2017-01-01T12:00:00.000+0000',
externalState: 'testflight.build.state.export.compliance.missing'
}
]
end
end
it 'gets the builds for this group via client' do
expect(mock_client).to receive(:builds_for_group).with(app_id: 1, group_id: 2)
builds = group.builds
expect(builds.size).to eq(1)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/spec/test_flight/build_spec.rb | spaceship/spec/test_flight/build_spec.rb | require 'spec_helper'
require_relative '../mock_servers'
describe Spaceship::TestFlight::Build do
let(:mock_client) { double('MockClient') }
before do
# Use a simple client for all data models
allow(Spaceship::TestFlight::Base).to receive(:client).and_return(mock_client)
allow(mock_client).to receive(:team_id).and_return('')
end
context '.find' do
it 'finds a build by a build_id' do
mock_client_response(:get_build) do
{
id: 456,
bundleId: 'com.foo.bar',
trainVersion: '1.0'
}
end
build = Spaceship::TestFlight::Build.find(app_id: 123, build_id: 456)
expect(build).to be_instance_of(Spaceship::TestFlight::Build)
expect(build.id).to eq(456)
expect(build.bundle_id).to eq('com.foo.bar')
end
it 'returns raises when the build cannot be found' do
mock_client_response(:get_build).and_raise(Spaceship::Client::UnexpectedResponse)
expect do
Spaceship::TestFlight::Build.find(app_id: 123, build_id: 456)
end.to raise_error(Spaceship::Client::UnexpectedResponse)
end
end
context 'collections' do
before do
mock_client_response(:get_build_trains) do
['1.0', '1.1']
end
mock_client_response(:get_builds_for_train, with: hash_including(train_version: '1.0')) do
[
{
id: 1,
appAdamId: 10,
trainVersion: '1.0',
uploadDate: '2017-01-01T12:00:00.000+0000',
externalState: 'testflight.build.state.export.compliance.missing'
}
]
end
mock_client_response(:get_builds_for_train, with: hash_including(train_version: '1.1')) do
[
{
id: 2,
appAdamId: 10,
trainVersion: '1.1',
uploadDate: '2017-01-02T12:00:00.000+0000',
externalState: 'testflight.build.state.submit.ready'
},
{
id: 3,
appAdamId: 10,
trainVersion: '1.1',
uploadDate: '2017-01-03T12:00:00.000+0000',
externalState: 'testflight.build.state.processing'
},
{
id: 4,
appAdamId: 10,
trainVersion: '1.1',
uploadDate: '2017-01-04T12:00:00.000+0000',
externalState: 'testflight.build.state.review.waiting'
}
]
end
end
context '.all' do
it 'contains all of the builds across all build trains' do
# builds = Spaceship::TestFlight::Build.all(app_id: 10, platform: 'ios')
# expect(builds.size).to eq(4)
# expect(builds.sample).to be_instance_of(Spaceship::TestFlight::Build)
# expect(builds.map(&:train_version).uniq).to eq(['1.0', '1.1'])
end
end
context '.builds_for_train' do
it 'returns the builds for a given train version' do
# builds = Spaceship::TestFlight::Build.builds_for_train(app_id: 10, platform: 'ios', train_version: '1.0')
# expect(builds.size).to eq(1)
# expect(builds.map(&:train_version)).to eq(['1.0'])
end
end
context '.all_processing_builds' do
it 'returns a collection of builds that are processing' do
# builds = Spaceship::TestFlight::Build.all_processing_builds(app_id: 10, platform: 'ios')
# expect(builds.size).to eq(1)
# expect(builds.sample.id).to eq(3)
end
end
context '.all_waiting_for_review' do
it 'returns a collection of builds that are waiting for review' do
# builds = Spaceship::TestFlight::Build.all_waiting_for_review(app_id: 10, platform: 'ios')
# expect(builds.size).to eq(1)
# expect(builds.sample.id).to eq(4)
end
end
context '.latest' do
it 'returns the latest build across all build trains' do
# latest_build = Spaceship::TestFlight::Build.latest(app_id: 10, platform: 'ios')
# expect(latest_build.upload_date).to eq(Time.utc(2017, 1, 4, 12))
end
end
end
context 'instances' do
let(:build) { Spaceship::TestFlight::Build.find(app_id: 'some-app-id', build_id: 'some-build-id') }
before do
mock_client_response(:get_build) do
{
id: 1,
bundleId: 'some-bundle-id',
appAdamId: 'some-app-id',
uploadDate: '2017-01-01T12:00:00.000+0000',
betaReviewInfo: {
contactFirstName: 'Dev',
contactLastName: 'Toolio',
contactEmail: 'dev-toolio@fabric.io'
},
exportCompliance: {
usesEncryption: true,
encryptionUpdated: false
},
testInfo: [
{
locale: 'en-US',
description: 'test info',
feedbackEmail: 'email@example.com',
whatsNew: 'this is new!'
}
],
dSYMUrl: 'https://some_dsym_url.com',
includesSymbols: false,
buildSdk: '13A340',
fileName: 'AppName.ipa',
containsODR: false,
numberOfAssetPacks: 1
}
end
end
it 'reloads a build' do
build = Spaceship::TestFlight::Build.new
build.id = 1
build.app_id = 2
expect do
build.reload
end.to change(build, :bundle_id).from(nil).to('some-bundle-id')
end
context 'submission state' do
it 'is ready to submit' do
mock_client_response(:get_build) do
{
'externalState' => 'testflight.build.state.submit.ready'
}
end
expect(build).to be_ready_to_submit
end
it 'is ready to test' do
mock_client_response(:get_build) do
{
'externalState' => 'testflight.build.state.testing.ready'
}
end
expect(build).to be_ready_to_test
end
it 'is active' do
mock_client_response(:get_build) do
{
'externalState' => 'testflight.build.state.testing.active'
}
end
expect(build).to be_active
end
it 'is processing' do
mock_client_response(:get_build) do
{
'externalState' => 'testflight.build.state.processing'
}
end
expect(build).to be_processing
end
it 'is has missing export compliance' do
mock_client_response(:get_build) do
{
'externalState' => 'testflight.build.state.export.compliance.missing'
}
end
expect(build).to be_export_compliance_missing
end
it 'is processed on active' do
mock_client_response(:get_build) do
{
'externalState' => 'testflight.build.state.testing.active'
}
end
expect(build).to be_processed
end
it 'is processed on ready to submit' do
mock_client_response(:get_build) do
{
'externalState' => 'testflight.build.state.submit.ready'
}
end
expect(build).to be_processed
end
it 'is processed on export compliance missing' do
mock_client_response(:get_build) do
{
'externalState' => 'testflight.build.state.export.compliance.missing'
}
end
expect(build).to be_processed
end
it 'is processed on review rejected' do
mock_client_response(:get_build) do
{
'externalState' => 'testflight.build.state.review.rejected'
}
end
expect(build).to be_processed
end
it "access build details and dSYM URL" do
expect(build.dsym_url).to eq("https://some_dsym_url.com")
expect(build.include_symbols).to eq(false)
expect(build.number_of_asset_packs).to eq(1)
expect(build.contains_odr).to eq(false)
expect(build.build_sdk).to eq("13A340")
expect(build.file_name).to eq("AppName.ipa")
end
end
context '#upload_date' do
it 'parses the string value' do
expect(build.upload_date).to eq(Time.utc(2017, 1, 1, 12))
end
end
context 'lazy loading attribute' do
let(:build) { Spaceship::TestFlight::Build.new('bundleId' => 1, 'appAdamId' => 1) }
it 'loads TestInfo' do
expect(build).to receive(:reload).once.and_call_original
expect(build.test_info).to be_instance_of(Spaceship::TestFlight::TestInfo)
end
it 'loads BetaReviewInfo' do
expect(build).to receive(:reload).once.and_call_original
expect(build.beta_review_info).to be_instance_of(Spaceship::TestFlight::BetaReviewInfo)
end
it 'loads ExportCompliance' do
expect(build).to receive(:reload).once.and_call_original
expect(build.export_compliance).to be_instance_of(Spaceship::TestFlight::ExportCompliance)
end
end
context '#save!' do
it 'saves via the client' do
expect(build.client).to receive(:put_build).with(app_id: 'some-app-id', build_id: 1, build: instance_of(Spaceship::TestFlight::Build))
build.test_info.whats_new = 'changes!'
build.save!
end
end
RSpec::Matchers.define(:same_test_info) do |other_test_info|
match do |args|
args[:build].test_info.to_s == other_test_info.to_s
end
end
context '#update_build_information!' do
it 'updates description' do
updated_test_info = build.test_info.deep_copy
updated_test_info.description = 'a newer description'
expect(build.client).to receive(:put_build).with(same_test_info(updated_test_info))
build.update_build_information!(description: 'a newer description')
end
it 'updates feedback_email' do
updated_test_info = build.test_info.deep_copy
updated_test_info.feedback_email = 'new_email@example.com'
expect(build.client).to receive(:put_build).with(same_test_info(updated_test_info))
build.update_build_information!(feedback_email: 'new_email@example.com')
end
it 'updates whats_new' do
updated_test_info = build.test_info.deep_copy
updated_test_info.whats_new = 'this fixture data is new'
expect(build.client).to receive(:put_build).with(same_test_info(updated_test_info))
build.update_build_information!(whats_new: 'this fixture data is new')
end
it 'does nothing if nothing is passed' do
updated_test_info = build.test_info.deep_copy
expect(build.client).to receive(:put_build).with(same_test_info(updated_test_info))
build.update_build_information!
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/spec/test_flight/client_spec.rb | spaceship/spec/test_flight/client_spec.rb | require 'spec_helper'
require_relative '../mock_servers'
##
# subclass the client we want to test so we can make test-methods easier
class TestFlightTestClient < Spaceship::TestFlight::Client
def test_request(some_param: nil, another_param: nil)
assert_required_params(__method__, binding)
end
def handle_response(response)
super(response)
end
end
describe Spaceship::TestFlight::Client do
subject { TestFlightTestClient.new(current_team_id: 'fake-team-id') }
let(:app_id) { 'some-app-id' }
let(:platform) { 'ios' }
context '#assert_required_params' do
it 'requires named parameters to be passed' do
expect do
subject.test_request(some_param: 1)
end.to raise_error(NameError)
end
end
context '#handle_response' do
it 'handles successful responses with json' do
response = double('Response', status: 200)
allow(response).to receive(:body).and_return({ 'data' => 'value' })
expect(subject.handle_response(response)).to eq('value')
end
it 'handles successful responses with no data' do
response = double('Response', body: '', status: 201)
expect(subject.handle_response(response)).to eq(nil)
end
it 'raises an exception on an API error' do
response = double('Response', status: 400)
allow(response).to receive(:body).and_return({ 'data' => nil, 'error' => 'Bad Request' })
expect do
subject.handle_response(response)
end.to raise_error(Spaceship::Client::UnexpectedResponse)
end
it 'raises an exception on a HTTP error' do
response = double('Response', body: '<html>Server Error</html>', status: 400)
expect do
subject.handle_response(response)
end.to raise_error(Spaceship::Client::UnexpectedResponse)
end
it 'raises an InternalServerError exception on a HTTP 500 error' do
response = double('Response', body: '<html>Server Error</html>', status: 500)
expect do
subject.handle_response(response)
end.to raise_error(Spaceship::Client::InternalServerError)
end
end
##
# @!group Build Trains API
##
context '#get_build_trains' do
it 'executes the request' do
MockAPI::TestFlightServer.get('/testflight/v2/providers/fake-team-id/apps/some-app-id/platforms/ios/trains') {}
subject.get_build_trains(app_id: app_id, platform: platform)
expect(WebMock).to have_requested(:get, 'https://appstoreconnect.apple.com/testflight/v2/providers/fake-team-id/apps/some-app-id/platforms/ios/trains')
end
end
context '#get_builds_for_train' do
it 'executes the request' do
MockAPI::TestFlightServer.get('/testflight/v2/providers/fake-team-id/apps/some-app-id/platforms/ios/trains/1.0/builds') {}
subject.get_builds_for_train(app_id: app_id, platform: platform, train_version: '1.0')
expect(WebMock).to have_requested(:get, 'https://appstoreconnect.apple.com/testflight/v2/providers/fake-team-id/apps/some-app-id/platforms/ios/trains/1.0/builds')
end
it 'retries requests' do
allow(subject).to receive(:request) { raise Faraday::ParsingError, 'Boom!' }
expect(subject).to receive(:request).exactly(2).times
begin
subject.get_builds_for_train(app_id: app_id, platform: platform, train_version: '1.0', retry_count: 2)
rescue
end
end
end
##
# @!group Builds API
##
context '#get_build' do
it 'executes the request' do
MockAPI::TestFlightServer.get('/testflight/v2/providers/fake-team-id/apps/some-app-id/builds/1') {}
subject.get_build(app_id: app_id, build_id: 1)
expect(WebMock).to have_requested(:get, 'https://appstoreconnect.apple.com/testflight/v2/providers/fake-team-id/apps/some-app-id/builds/1')
end
end
context '#put_build' do
let(:build) { double('Build', to_json: "") }
it 'executes the request' do
MockAPI::TestFlightServer.put('/testflight/v2/providers/fake-team-id/apps/some-app-id/builds/1') {}
subject.put_build(app_id: app_id, build_id: 1, build: build)
expect(WebMock).to have_requested(:put, 'https://appstoreconnect.apple.com/testflight/v2/providers/fake-team-id/apps/some-app-id/builds/1')
end
end
context '#expire_build' do
let(:build) { double('Build', to_json: "") }
it 'executes the request' do
MockAPI::TestFlightServer.post('/testflight/v2/providers/fake-team-id/apps/some-app-id/builds/1/expire') {}
subject.expire_build(app_id: app_id, build_id: 1, build: build)
expect(WebMock).to have_requested(:post, 'https://appstoreconnect.apple.com/testflight/v2/providers/fake-team-id/apps/some-app-id/builds/1/expire')
end
end
##
# @!group Groups API
##
context '#create_group_for_app' do
let(:group_name) { 'some-group-name' }
it 'executes the request' do
MockAPI::TestFlightServer.post('/testflight/v2/providers/fake-team-id/apps/some-app-id/groups') {}
subject.create_group_for_app(app_id: app_id, group_name: group_name)
expect(WebMock).to have_requested(:post, 'https://appstoreconnect.apple.com/testflight/v2/providers/fake-team-id/apps/some-app-id/groups')
end
end
context '#delete_group_for_app' do
it 'executes the request' do
MockAPI::TestFlightServer.delete('/testflight/v2/providers/fake-team-id/apps/some-app-id/groups/fake-group-id') {}
subject.delete_group_for_app(app_id: app_id, group_id: 'fake-group-id')
expect(WebMock).to have_requested(:delete, 'https://appstoreconnect.apple.com/testflight/v2/providers/fake-team-id/apps/some-app-id/groups/fake-group-id')
end
end
context '#get_groups' do
it 'executes the request' do
MockAPI::TestFlightServer.get('/testflight/v2/providers/fake-team-id/apps/some-app-id/groups') {}
subject.get_groups(app_id: app_id)
expect(WebMock).to have_requested(:get, 'https://appstoreconnect.apple.com/testflight/v2/providers/fake-team-id/apps/some-app-id/groups')
end
end
context '#add_group_to_build' do
it 'executes the request' do
MockAPI::TestFlightServer.put('/testflight/v2/providers/fake-team-id/apps/some-app-id/groups/fake-group-id/builds/fake-build-id') {}
subject.add_group_to_build(app_id: app_id, group_id: 'fake-group-id', build_id: 'fake-build-id')
expect(WebMock).to have_requested(:put, 'https://appstoreconnect.apple.com/testflight/v2/providers/fake-team-id/apps/some-app-id/groups/fake-group-id/builds/fake-build-id')
end
end
##
# @!Internal Testers
##
context '#internal_users_for_app' do
it 'executes the request' do
MockAPI::TestFlightServer.get('/testflight/v2/providers/fake-team-id/apps/some-app-id/internalUsers') { '{"data" : ""}' }
subject.internal_users(app_id: app_id)
expect(WebMock).to have_requested(:get, 'https://appstoreconnect.apple.com/testflight/v2/providers/fake-team-id/apps/some-app-id/internalUsers')
end
end
##
# @!group Testers API
##
context '#testers_for_app' do
it 'executes the request' do
MockAPI::TestFlightServer.get('/testflight/v2/providers/fake-team-id/apps/some-app-id/testers') {}
subject.testers_for_app(app_id: app_id)
expect(WebMock).to have_requested(:get, 'https://appstoreconnect.apple.com/testflight/v2/providers/fake-team-id/apps/some-app-id/testers?limit=40&order=asc&sort=default')
end
end
context '#search_for_tester_in_app' do
it 'executes the request' do
MockAPI::TestFlightServer.get('/testflight/v2/providers/fake-team-id/apps/some-app-id/testers') {}
subject.search_for_tester_in_app(app_id: app_id, text: "fake+tester+text")
expect(WebMock).to have_requested(:get, 'https://appstoreconnect.apple.com/testflight/v2/providers/fake-team-id/apps/some-app-id/testers?order=asc&search=fake%2Btester%2Btext&sort=status')
end
end
context '#delete_tester_from_app' do
it 'executes the request' do
MockAPI::TestFlightServer.delete('/testflight/v2/providers/fake-team-id/apps/some-app-id/testers/fake-tester-id') {}
subject.delete_tester_from_app(app_id: app_id, tester_id: 'fake-tester-id')
expect(WebMock).to have_requested(:delete, 'https://appstoreconnect.apple.com/testflight/v2/providers/fake-team-id/apps/some-app-id/testers/fake-tester-id')
end
end
context '#create_app_level_tester' do
let(:tester) { double('Tester', email: 'fake@email.com', first_name: 'Fake', last_name: 'Name') }
it 'executes the request' do
MockAPI::TestFlightServer.post('/testflight/v2/providers/fake-team-id/apps/some-app-id/testers') {}
subject.create_app_level_tester(app_id: app_id, first_name: tester.first_name, last_name: tester.last_name, email: tester.email)
expect(WebMock).to have_requested(:post, 'https://appstoreconnect.apple.com/testflight/v2/providers/fake-team-id/apps/some-app-id/testers')
end
end
context '#remove_testers_from_testflight' do
it 'executes the request' do
MockAPI::TestFlightServer.post('/testflight/v2/providers/fake-team-id/apps/some-app-id/deleteTesters') {}
subject.remove_testers_from_testflight(app_id: app_id, tester_ids: [1, 2])
expect(WebMock).to have_requested(:post, 'https://appstoreconnect.apple.com/testflight/v2/providers/fake-team-id/apps/some-app-id/deleteTesters')
end
end
context '#post_tester_to_group' do
it 'executes the request' do
MockAPI::TestFlightServer.post('/testflight/v2/providers/fake-team-id/apps/some-app-id/groups/fake-group-id/testers') {}
tester = OpenStruct.new({ first_name: "Josh", last_name: "Taquitos", email: "taquitos@google.com" })
subject.post_tester_to_group(app_id: app_id,
email: tester.email,
first_name: tester.first_name,
last_name: tester.last_name,
group_id: 'fake-group-id')
expect(WebMock).to have_requested(:post, 'https://appstoreconnect.apple.com/testflight/v2/providers/fake-team-id/apps/some-app-id/groups/fake-group-id/testers').
with(body: '[{"email":"taquitos@google.com","firstName":"Josh","lastName":"Taquitos"}]')
end
end
context '#delete_tester_from_group' do
it 'executes the request' do
MockAPI::TestFlightServer.delete('/testflight/v2/providers/fake-team-id/apps/some-app-id/groups/fake-group-id/testers/fake-tester-id') {}
subject.delete_tester_from_group(app_id: app_id, tester_id: 'fake-tester-id', group_id: 'fake-group-id')
expect(WebMock).to have_requested(:delete, 'https://appstoreconnect.apple.com/testflight/v2/providers/fake-team-id/apps/some-app-id/groups/fake-group-id/testers/fake-tester-id')
end
end
context '#builds_for_group' do
it 'executes the request' do
MockAPI::TestFlightServer.get('/testflight/v2/providers/fake-team-id/apps/some-app-id/groups/fake-group-id/builds') {}
subject.builds_for_group(app_id: app_id, group_id: 'fake-group-id')
expect(WebMock).to have_requested(:get, 'https://appstoreconnect.apple.com/testflight/v2/providers/fake-team-id/apps/some-app-id/groups/fake-group-id/builds')
end
end
##
# @!group AppTestInfo
##
context '#get_app_test_info' do
it 'executes the request' do
MockAPI::TestFlightServer.get('/testflight/v2/providers/fake-team-id/apps/some-app-id/testInfo') {}
subject.get_app_test_info(app_id: app_id)
expect(WebMock).to have_requested(:get, 'https://appstoreconnect.apple.com/testflight/v2/providers/fake-team-id/apps/some-app-id/testInfo')
end
end
context '#put_app_test_info' do
let(:app_test_info) { double('AppTestInfo', to_json: '') }
it 'executes the request' do
MockAPI::TestFlightServer.put('/testflight/v2/providers/fake-team-id/apps/some-app-id/testInfo') {}
subject.put_app_test_info(app_id: app_id, app_test_info: app_test_info)
expect(WebMock).to have_requested(:put, 'https://appstoreconnect.apple.com/testflight/v2/providers/fake-team-id/apps/some-app-id/testInfo')
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/spec/test_flight/test_info_spec.rb | spaceship/spec/test_flight/test_info_spec.rb | require 'spec_helper'
describe Spaceship::TestFlight::TestInfo do
let(:test_info) do
Spaceship::TestFlight::TestInfo.new([
{
'locale' => 'en-US',
'description' => 'en-US description',
'feedbackEmail' => 'enUS@email.com',
'whatsNew' => 'US News',
'marketingUrl' => 'www.markingurl.com/en',
'privacyPolicyUrl' => 'www.privacypolicy.com/en'
},
{
'locale' => 'de-DE',
'description' => 'de-DE description',
'feedbackEmail' => 'deDE@email.com',
'whatsNew' => 'German News',
'marketingUrl' => 'www.markingurl.com/de',
'privacyPolicyUrl' => 'www.privacypolicy.com/de'
},
{
'locale' => 'de-AT',
'description' => 'de-AT description',
'feedbackEmail' => 'deAT@email.com',
'whatsNew' => 'Austrian News',
'marketingUrl' => 'www.markingurl.com/at',
'privacyPolicyUrl' => 'www.privacypolicy.com/at'
}
])
end
let(:mock_client) { double('MockClient') }
before do
# Use a simple client for all data models
allow(Spaceship::TestFlight::Base).to receive(:client).and_return(mock_client)
allow(mock_client).to receive(:team_id).and_return('')
end
it 'gets the value from the first locale' do
expect(test_info.feedback_email).to eq('enUS@email.com')
expect(test_info.description).to eq('en-US description')
expect(test_info.whats_new).to eq('US News')
expect(test_info.marketing_url).to eq('www.markingurl.com/en')
expect(test_info.privacy_policy_url).to eq('www.privacypolicy.com/en')
end
it 'sets values to all locales' do
test_info.whats_new = 'News!'
expect(test_info.raw_data.all? { |locale| locale['whatsNew'] == 'News!' }).to eq(true)
end
it 'copies its contents' do
new_test_info = test_info.deep_copy
expect(new_test_info.object_id).to_not(eq(test_info.object_id))
# make sure it is a deep copy, but the contents are the same
new_test_info.raw_data.zip(test_info.raw_data).each do |sub_array|
new_item = sub_array.first
item = sub_array.last
expect(new_item.object_id).to_not(eq(item.object_id))
expect(new_item.to_s).to eq(item.to_s)
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/spec/test_flight/app_test_info_spec.rb | spaceship/spec/test_flight/app_test_info_spec.rb | require 'spec_helper'
describe Spaceship::TestFlight::AppTestInfo do
let(:app_test_info) do
Spaceship::TestFlight::AppTestInfo.new({
'primaryLocale' => 'en-US',
'details' => [{
'locale' => 'en-US',
'feedbackEmail' => 'feedback@email.com',
'description' => 'Beta app description',
'whatsNew' => 'What is new'
}],
'betaReviewInfo' => {
'contactFirstName' => 'First',
'contactLastName' => 'Last',
'contactPhone' => '1234567890',
'contactEmail' => 'contact@email.com',
'demoAccountName' => 'User Name',
'demoAccountPassword' => 'Password',
'demoAccountRequired' => false,
'notes' => 'notes!!'
}
})
end
let(:test_info) do
Spaceship::TestFlight::TestInfo.new([
{
'locale' => 'en-US',
'description' => 'en-US description',
'feedbackEmail' => 'enUS@email.com',
'whatsNew' => 'US News'
},
{
'locale' => 'de-DE',
'description' => 'de-DE description',
'feedbackEmail' => 'deDE@email.com',
'whatsNew' => 'German News'
},
{
'locale' => 'de-AT',
'description' => 'de-AT description',
'feedbackEmail' => 'deAT@email.com',
'whatsNew' => 'Austrian News'
}
])
end
let(:beta_review_info) do
Spaceship::TestFlight::BetaReviewInfo.new({
'contactFirstName' => 'Test_First',
'contactLastName' => 'Test_Last',
'contactPhone' => '2345678901',
'contactEmail' => 'test_contact@email.com',
'demoAccountName' => 'Test User Name',
'demoAccountPassword' => 'Test_Password',
'demoAccountRequired' => true,
'notes' => 'test_notes!!'
})
end
let(:mock_client) { double('MockClient') }
before do
# Use a simple client for all data models
allow(Spaceship::TestFlight::Base).to receive(:client).and_return(mock_client)
allow(mock_client).to receive(:team_id).and_return('')
end
it 'gets the TestInfo' do
expect(app_test_info.test_info).to be_instance_of(Spaceship::TestFlight::TestInfo)
expect(app_test_info.test_info.feedback_email).to eq("feedback@email.com")
expect(app_test_info.test_info.description).to eq("Beta app description")
expect(app_test_info.test_info.whats_new).to eq('What is new')
end
it 'sets the TestInfo' do
app_test_info.test_info = test_info
expect(app_test_info.raw_data['details']).to eq(test_info.raw_data)
end
it 'gets beta review info' do
expect(app_test_info.beta_review_info).to be_instance_of(Spaceship::TestFlight::BetaReviewInfo)
expect(app_test_info.beta_review_info.contact_first_name).to eq("First")
expect(app_test_info.beta_review_info.contact_last_name).to eq("Last")
expect(app_test_info.beta_review_info.contact_phone).to eq("1234567890")
expect(app_test_info.beta_review_info.contact_email).to eq("contact@email.com")
expect(app_test_info.beta_review_info.demo_account_name).to eq("User Name")
expect(app_test_info.beta_review_info.demo_account_password).to eq("Password")
expect(app_test_info.beta_review_info.demo_account_required).to eq(false)
expect(app_test_info.beta_review_info.notes).to eq("notes!!")
end
it 'sets beta review info' do
app_test_info.beta_review_info = beta_review_info
expect(app_test_info.raw_data['betaReviewInfo']).to eq(beta_review_info.raw_data)
end
context 'client interactions' do
it 'find app test info on the server' do
mock_client_response(:get_app_test_info, with: hash_including(app_id: 'app-id')) do
app_test_info.raw_data
end
found_app_test_info = Spaceship::TestFlight::AppTestInfo.find(app_id: 'app-id')
expect(found_app_test_info).to be_instance_of(Spaceship::TestFlight::AppTestInfo)
# use to_h.to_s to compare raw_data, since they are different instances
expect(found_app_test_info.raw_data.to_h.to_s).to eq(app_test_info.raw_data.to_h.to_s)
end
RSpec::Matchers.define(:same_app_test_info) do |other_app_test_info|
match do |args|
args[:app_test_info].raw_data.to_h.to_s == other_app_test_info.raw_data.to_h.to_s
end
end
it 'updates app test info on the server' do
expect(app_test_info.client).to receive(:put_app_test_info).with(same_app_test_info(app_test_info))
app_test_info.save_for_app!(app_id: 'app-id')
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/spec/test_flight/tester_spec.rb | spaceship/spec/test_flight/tester_spec.rb | require 'spec_helper'
describe Spaceship::TestFlight::Tester do
let(:mock_client) { double('MockClient') }
before do
allow(Spaceship::TestFlight::Base).to receive(:client).and_return(mock_client)
allow(mock_client).to receive(:team_id).and_return('')
end
context 'attr_mapping' do
let(:tester) do
Spaceship::TestFlight::Tester.new({
'id' => 1,
'email' => 'email@domain.com'
})
end
it 'has them' do
expect(tester.tester_id).to eq(1)
expect(tester.email).to eq('email@domain.com')
end
end
context 'collections' do
before do
mock_client_response(:testers_for_app, with: { app_id: 'app-id' }) do
[
{
id: 1,
email: "email_1@domain.com"
},
{
id: 2,
email: 'email_2@domain.com'
}
]
end
mock_client_response(:search_for_tester_in_app, with: { app_id: 'app-id', text: 'email_1@domain.com' }) do
[
{
id: 1,
email: "email_1@domain.com"
}
]
end
mock_client_response(:search_for_tester_in_app, with: { app_id: 'app-id', text: 'EmAiL_3@domain.com' }) do
[
{
id: 3,
email: "EmAiL_3@domain.com"
},
{
id: 4,
email: "tacos_email_3@domain.com"
}
]
end
mock_client_response(:search_for_tester_in_app, with: { app_id: 'app-id', text: 'taquito' }) do
[
{
id: 1,
email: "taquito@domain.com"
},
{
id: 2,
email: "taquitos@domain.com"
}
]
end
mock_client_response(:search_for_tester_in_app, with: { app_id: 'app-id', text: 'NaN@domain.com' }) do
[]
end
end
context '.all' do
it 'returns all of the testers' do
groups = Spaceship::TestFlight::Tester.all(app_id: 'app-id')
expect(groups.size).to eq(2)
expect(groups).to all(be_instance_of(Spaceship::TestFlight::Tester))
end
end
context '.find' do
it 'returns a Tester by email address' do
tester = Spaceship::TestFlight::Tester.find(app_id: 'app-id', email: 'email_1@domain.com')
expect(tester).to be_instance_of(Spaceship::TestFlight::Tester)
expect(tester.tester_id).to be(1)
end
it 'returns nil if no Tester matches' do
tester = Spaceship::TestFlight::Tester.find(app_id: 'app-id', email: 'NaN@domain.com')
expect(tester).to be_nil
end
end
context '.search' do
it 'returns a Tester by email address' do
testers = Spaceship::TestFlight::Tester.search(app_id: 'app-id', text: 'email_1@domain.com')
expect(testers.length).to be(1)
expect(testers.first).to be_instance_of(Spaceship::TestFlight::Tester)
expect(testers.first.tester_id).to be(1)
end
it 'returns a Tester by email address if exact match case-insensitive' do
testers = Spaceship::TestFlight::Tester.search(app_id: 'app-id', text: 'EmAiL_3@domain.com', is_email_exact_match: true)
expect(testers.length).to be(1)
expect(testers.first).to be_instance_of(Spaceship::TestFlight::Tester)
expect(testers.first.tester_id).to be(3)
expect(testers.first.email).to eq("EmAiL_3@domain.com")
end
it 'returns empty array if no Tester matches' do
testers = Spaceship::TestFlight::Tester.search(app_id: 'app-id', text: 'NaN@domain.com')
expect(testers.length).to be(0)
end
it 'returns two testers if two testers match full-text search' do
testers = Spaceship::TestFlight::Tester.search(app_id: 'app-id', text: 'taquito')
expect(testers.length).to be(2)
expect(testers).to all(be_instance_of(Spaceship::TestFlight::Tester))
end
end
end
context 'instances' do
let(:tester) { Spaceship::TestFlight::Tester.new('id' => 2, 'email' => 'email@domain.com') }
context '.remove_from_app!' do
it 'removes a tester from the app' do
expect(mock_client).to receive(:delete_tester_from_app).with(app_id: 'app-id', tester_id: 2)
tester.remove_from_app!(app_id: 'app-id')
end
end
context '.remove_from_testflight!' do
it 'removes a tester from TestFlight' do
expect(mock_client).to receive(:remove_testers_from_testflight).with(app_id: 'app-id', tester_ids: [2])
tester.remove_from_testflight!(app_id: 'app-id')
end
end
end
context 'invites' do
let(:tester) { Spaceship::TestFlight::Tester.new('id' => 'tester-id') }
context '.resend_invite' do
it 'succeeds' do
expect(mock_client).to receive(:resend_invite_to_external_tester).with(app_id: 'app-id', tester_id: 'tester-id')
tester.resend_invite(app_id: 'app-id')
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship.rb | spaceship/lib/spaceship.rb | require_relative 'spaceship/globals'
require_relative 'spaceship/base'
require_relative 'spaceship/client'
require_relative 'spaceship/provider'
require_relative 'spaceship/launcher'
require_relative 'spaceship/hashcash'
# Middleware
require_relative 'spaceship/stats_middleware'
# Dev Portal
require_relative 'spaceship/portal/portal'
require_relative 'spaceship/portal/spaceship'
# App Store Connect
require_relative 'spaceship/tunes/tunes'
require_relative 'spaceship/tunes/spaceship'
require_relative 'spaceship/test_flight'
require_relative 'spaceship/connect_api'
require_relative 'spaceship/connect_api/spaceship'
require_relative 'spaceship/spaceauth_runner'
require_relative 'spaceship/module'
# Support for legacy wrappers
require_relative 'spaceship/portal/legacy_wrapper'
require_relative 'spaceship/tunes/legacy_wrapper'
# For basic user inputs
require 'highline/import'
require 'colored'
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/provider.rb | spaceship/lib/spaceship/provider.rb | module Spaceship
class Provider
attr_accessor :provider_id
attr_accessor :name
attr_accessor :content_types
def initialize(provider_hash: nil)
self.provider_id = provider_hash['providerId']
self.name = provider_hash['name']
self.content_types = provider_hash['contentTypes']
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/ui.rb | spaceship/lib/spaceship/ui.rb | paths = Dir[File.expand_path("**/ui/*.rb", File.dirname(__FILE__))]
raise "Could not find UI classes to import" unless paths.count > 0
paths.each do |file|
require file
end
module Spaceship
class Client
# All User Interface related code lives in this class
class UserInterface
# Access the client this UserInterface object is for
attr_reader :client
# Is called by the client to generate one instance of UserInterface
def initialize(c)
@client = c
end
end
# Public getter for all UI related code
# rubocop:disable Naming/MethodName
def UI
UserInterface.new(self)
end
# rubocop:enable Naming/MethodName
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/globals.rb | spaceship/lib/spaceship/globals.rb | module Spaceship
class Globals
class << self
attr_writer(:check_session)
end
# if spaceship is run with a FastlaneCore available respect the global state there
# otherwise fallback to $verbose
def self.verbose?
if Object.const_defined?("FastlaneCore")
return FastlaneCore::Globals.verbose? # rubocop:disable Require/MissingRequireStatement
end
return $verbose
end
# if spaceship is run with the --check_session flag this value will be set to true
def self.check_session
return @check_session
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/errors.rb | spaceship/lib/spaceship/errors.rb | module Spaceship
# Base class for errors that want to present their message as
# preferred error info for fastlane error handling. See:
# fastlane_core/lib/fastlane_core/ui/fastlane_runner.rb
class BasicPreferredInfoError < StandardError
TITLE = 'The request could not be completed because:'.freeze
def preferred_error_info
message ? [TITLE, message] : nil
end
end
# Invalid user credentials were provided
class InvalidUserCredentialsError < BasicPreferredInfoError; end
# Raised when no user credentials were passed at all
class NoUserCredentialsError < BasicPreferredInfoError; end
class ProgramLicenseAgreementUpdated < BasicPreferredInfoError
def show_github_issues
false
end
end
class AppleIDAndPrivacyAcknowledgementNeeded < BasicPreferredInfoError
def show_github_issues
false
end
end
# User doesn't have enough permission for given action
class InsufficientPermissions < BasicPreferredInfoError
TITLE = 'Insufficient permissions for your Apple ID:'.freeze
def preferred_error_info
message ? [TITLE, message] : nil
end
# We don't want to show similar GitHub issues, as the error message
# should be pretty clear
def show_github_issues
false
end
end
# User doesn't have enough permission for given action
class SIRPAuthenticationError < BasicPreferredInfoError
TITLE = 'Authentication issue validating secrets:'.freeze
def preferred_error_info
message ? [TITLE, message] : nil
end
# We don't want to show similar GitHub issues, as the error message
# should be pretty clear
def show_github_issues
false
end
end
# Raised when 429 is received from App Store Connect
class TooManyRequestsError < BasicPreferredInfoError
attr_reader :retry_after
attr_reader :rate_limit_user
def initialize(resp_hash)
headers = resp_hash[:response_headers] || {}
@retry_after = (headers['retry-after'] || 60).to_i
@rate_limit_user = headers['x-daiquiri-rate-limit-user']
message = 'Apple 429 detected'
message += " - #{rate_limit_user}" if rate_limit_user
super(message)
end
def show_github_issues
false
end
end
class UnexpectedResponse < StandardError
attr_reader :error_info
def initialize(error_info = nil)
super(error_info)
@error_info = error_info
end
def preferred_error_info
return nil unless @error_info.kind_of?(Hash) && @error_info['resultString']
[
"Apple provided the following error info:",
@error_info['resultString'],
@error_info['userString']
].compact.uniq # sometimes 'resultString' and 'userString' are the same value
end
end
# Raised when 302 is received from portal request
class AppleTimeoutError < BasicPreferredInfoError; end
# Raised when 401 is received from portal request
class UnauthorizedAccessError < BasicPreferredInfoError; end
# Raised when 500 is received from App Store Connect
class InternalServerError < BasicPreferredInfoError; end
# Raised when 502 is received from App Store Connect
class BadGatewayError < BasicPreferredInfoError; end
# Raised when 504 is received from App Store Connect
class GatewayTimeoutError < BasicPreferredInfoError; end
# Raised when 403 is received from portal request
class AccessForbiddenError < BasicPreferredInfoError; end
# Base class for errors coming from App Store Connect locale changes
class AppStoreLocaleError < BasicPreferredInfoError
def initialize(locale, error)
error_message = error.respond_to?(:message) ? error.message : error.to_s
locale_str = locale || "unknown"
@message = "An exception has occurred for locale: #{locale_str}.\nError: #{error_message}"
super(@message)
end
# no need to search github issues since the error is specific
def show_github_issues
false
end
end
# Raised for localized text errors from App Store Connect
class AppStoreLocalizationError < AppStoreLocaleError
def preferred_error_info
"#{@message}\nCheck the localization requirements here: https://developer.apple.com/help/app-store-connect/manage-app-information/localize-app-information"
end
end
# Raised for localized screenshots errors from App Store Connect
class AppStoreScreenshotError < AppStoreLocaleError
def preferred_error_info
"#{@message}\nCheck the screenshot requirements here: https://developer.apple.com/help/app-store-connect/reference/screenshot-specifications"
end
end
# Raised for localized app preview errors from App Store Connect
class AppStoreAppPreviewError < AppStoreLocaleError
def preferred_error_info
"#{@message}\nCheck the app preview requirements here: https://developer.apple.com/help/app-store-connect/reference/app-preview-specifications"
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/spaceauth_runner.rb | spaceship/lib/spaceship/spaceauth_runner.rb | require 'colored'
require 'credentials_manager/appfile_config'
require 'yaml'
require 'fastlane_core'
require_relative 'tunes/tunes_client'
module Spaceship
class SpaceauthRunner
def initialize(username: nil, copy_to_clipboard: nil)
@username = username
@username ||= CredentialsManager::AppfileConfig.try_fetch_value(:apple_id)
@username ||= ask("Username: ")
@copy_to_clipboard = copy_to_clipboard
end
def run
begin
puts("Logging into to App Store Connect (#{@username})...") unless Spaceship::Globals.check_session
Spaceship::Tunes.login(@username)
puts("Successfully logged in to App Store Connect".green)
puts("")
rescue => ex
puts("Could not login to App Store Connect".red)
puts("Please check your credentials and try again.".yellow)
puts("This could be an issue with App Store Connect,".yellow)
puts("Please try unsetting the FASTLANE_SESSION environment variable by calling 'unset FASTLANE_SESSION'".yellow)
puts("(if it is set) and re-run `fastlane spaceauth`".yellow)
puts("")
puts("Exception type: #{ex.class}")
raise ex
end
itc_cookie_content = Spaceship::Tunes.client.store_cookie
# The only value we actually need is the "DES5c148586daa451e55afb017aa62418f91" cookie
# We're not sure if the key changes
#
# Example:
# name: DES5c148586daa451e55afb017aa62418f91
# value: HSARMTKNSRVTWFlaF/ek8asaa9lymMA0dN8JQ6pY7B3F5kdqTxJvMT19EVEFX8EQudB/uNwBHOHzaa30KYTU/eCP/UF7vGTgxs6PAnlVWKscWssOVHfP2IKWUPaa4Dn+I6ilA7eAFQsiaaVT
cookies = load_cookies(itc_cookie_content)
# We remove all the un-needed cookies
cookies.select! do |cookie|
cookie.name.start_with?("myacinfo") || cookie.name == "dqsid" || cookie.name.start_with?("DES")
end
@yaml = cookies.to_yaml.gsub("\n", "\\n")
puts("---")
puts("")
puts("Pass the following via the FASTLANE_SESSION environment variable:")
puts(@yaml.cyan.underline)
puts("")
puts("")
puts("Example:")
puts("export FASTLANE_SESSION='#{@yaml}'".cyan.underline)
if @copy_to_clipboard == false
puts("Skipped asking to copy the session string into your clipboard ⏭️".green)
elsif @copy_to_clipboard || (mac? && Spaceship::Client::UserInterface.interactive? && agree("🙄 Should fastlane copy the cookie into your clipboard, so you can easily paste it? (y/n)", true))
FastlaneCore::Clipboard.copy(content: @yaml)
puts("Successfully copied the session string into your clipboard 🎨".green)
end
return self
end
def load_cookies(content)
# When Ruby 2.5 support is dropped, we can safely get rid of the latter branch.
if YAML.name == 'Psych' && Gem::Version.new(Psych::VERSION) >= Gem::Version.new('3.1')
YAML.safe_load(
content,
permitted_classes: [HTTP::Cookie, Time],
aliases: true
)
else
YAML.safe_load(
content,
[HTTP::Cookie, Time], # classes allowlist
[], # symbols allowlist
true # allow YAML aliases
)
end
end
def session_string
FastlaneCore::UI.user_error!("`#{__method__}` method called before calling `run` in `SpaceauthRunner`") unless @yaml
@yaml
end
def mac?
(/darwin/ =~ RUBY_PLATFORM) != nil
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/stats_middleware.rb | spaceship/lib/spaceship/stats_middleware.rb | require 'faraday'
require_relative 'globals'
module Spaceship
class StatsMiddleware < Faraday::Middleware
ServiceOption = Struct.new(:name, :url, :auth_type)
URLLog = Struct.new(:url, :auth_type)
class << self
def services
return @services if @services
require_relative 'tunes/tunes_client'
require_relative 'portal/portal_client'
require_relative 'connect_api/testflight/client'
require_relative 'connect_api/provisioning/client'
@services ||= [
ServiceOption.new("App Store Connect API (official)", "api.appstoreconnect.apple.com", "JWT"),
ServiceOption.new("App Store Connect API (web session)", Spaceship::ConnectAPI::TestFlight::Client.hostname.gsub("https://", ""), "Web session"),
ServiceOption.new("Enterprise Program API (official)", "api.enterprise.developer.apple.com", "JWT"),
ServiceOption.new("Legacy iTunesConnect Auth", "idmsa.apple.com", "Web session"),
ServiceOption.new("Legacy iTunesConnect Auth", "appstoreconnect.apple.com/olympus/v1/", "Web session"),
ServiceOption.new("Legacy iTunesConnect", Spaceship::TunesClient.hostname.gsub("https://", ""), "Web session"),
ServiceOption.new("Legacy iTunesConnect Developer Portal", Spaceship::PortalClient.hostname.gsub("https://", ""), "Web session"),
ServiceOption.new("App Store Connect API (web session)", Spaceship::ConnectAPI::Provisioning::Client.hostname.gsub("https://", ""), "Web session")
]
end
def service_stats
@service_stats ||= Hash.new(0)
end
def request_logs
@request_logs ||= []
@request_logs
end
end
def initialize(app)
super(app)
end
def call(env)
log(env)
@app.call(env)
end
def log(env)
return false unless env && env.url && (uri = URI.parse(env.url.to_s))
service = StatsMiddleware.services.find do |s|
uri.to_s.include?(s.url)
end
service = ServiceOption.new("Unknown", uri.host, "Unknown") if service.nil?
StatsMiddleware.service_stats[service] += 1
StatsMiddleware.request_logs << URLLog.new(uri.to_s, service.auth_type)
return true
rescue => e
puts("Failed to log spaceship stats - #{e.message}") if Spaceship::Globals.verbose?
return false
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/test_flight.rb | spaceship/lib/spaceship/test_flight.rb | require 'spaceship/test_flight/client'
require 'spaceship/test_flight/base'
require 'spaceship/test_flight/app_test_info'
require 'spaceship/test_flight/build'
require 'spaceship/test_flight/build_trains'
require 'spaceship/test_flight/beta_review_info'
require 'spaceship/test_flight/export_compliance'
require 'spaceship/test_flight/test_info'
require 'spaceship/test_flight/group'
require 'spaceship/test_flight/tester'
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/upgrade_2fa_later_client.rb | spaceship/lib/spaceship/upgrade_2fa_later_client.rb | require_relative 'globals'
require_relative 'tunes/tunes_client'
module Spaceship
class Client
def try_upgrade_2fa_later(response)
if ENV['SPACESHIP_SKIP_2FA_UPGRADE'].nil?
return false
end
puts("This account is being prompted to upgrade to 2FA")
puts("Attempting to automatically bypass the upgrade until a later date")
puts("To disable this, remove SPACESHIP_SKIP_2FA_UPGRADE=1 environment variable")
# Get URL that requests a repair and gets the widget key
widget_key_location = response.headers['location']
uri = URI.parse(widget_key_location)
params = CGI.parse(uri.query)
widget_key = params.dig('widgetKey', 0)
if widget_key.nil?
STDERR.puts("Couldn't find widgetKey to continue with requests")
return false
end
# Step 1 - Request repair
response_repair = request(:get) do |req|
req.url(widget_key_location)
end
# Step 2 - Request repair options
response_repair_options = request(:get) do |req|
req.url("https://appleid.apple.com/account/manage/repair/options")
req.headers['scnt'] = response_repair.headers['scnt']
req.headers['X-Apple-Id-Session-Id'] = response.headers['X-Apple-Id-Session-Id']
req.headers['X-Apple-Session-Token'] = response.headers['X-Apple-Repair-Session-Token']
req.headers['X-Apple-Skip-Repair-Attributes'] = '[]'
req.headers['X-Apple-Widget-Key'] = widget_key
req.headers['Content-Type'] = 'application/json'
req.headers['X-Requested-With'] = 'XMLHttpRequest'
req.headers['Accept'] = 'application/json, text/javascript'
end
# Step 3 - Request setup later
request(:get) do |req|
req.url("https://appleid.apple.com/account/security/upgrade/setuplater")
req.headers['scnt'] = response_repair_options.headers['scnt']
req.headers['X-Apple-Id-Session-Id'] = response.headers['X-Apple-Id-Session-Id']
req.headers['X-Apple-Session-Token'] = response_repair_options.headers['x-apple-session-token']
req.headers['X-Apple-Skip-Repair-Attributes'] = '[]'
req.headers['X-Apple-Widget-Key'] = widget_key
req.headers['Content-Type'] = 'application/json'
req.headers['X-Requested-With'] = 'XMLHttpRequest'
req.headers['Accept'] = 'application/json, text/javascript'
end
# Step 4 - Post complete
response_repair_complete = request(:post) do |req|
req.url("https://idmsa.apple.com/appleauth/auth/repair/complete")
req.body = ''
req.headers['scnt'] = response.headers['scnt']
req.headers['X-Apple-Id-Session-Id'] = response.headers['X-Apple-Id-Session-Id']
req.headers['X-Apple-Repair-Session-Token'] = response_repair_options.headers['X-Apple-Session-Token']
req.headers['X-Apple-Widget-Key'] = widget_key
req.headers['Content-Type'] = 'application/json'
req.headers['X-Requested-With'] = 'XMLHttpRequest'
req.headers['Accept'] = 'application/json;charset=utf-8'
end
if response_repair_complete.status == 204
return true
else
STDERR.puts("Failed with status code of #{response_repair_complete.status}")
return false
end
rescue => error
STDERR.puts(error.backtrace)
STDERR.puts("Failed to bypass 2FA upgrade")
STDERR.puts("To disable this from trying again, set SPACESHIP_SKIP_UPGRADE_2FA_LATER=1")
return false
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api.rb | spaceship/lib/spaceship/connect_api.rb | require 'spaceship/connect_api/model'
require 'spaceship/connect_api/response'
require 'spaceship/connect_api/token'
require 'spaceship/connect_api/file_uploader'
require 'spaceship/connect_api/provisioning/provisioning'
require 'spaceship/connect_api/testflight/testflight'
require 'spaceship/connect_api/users/users'
require 'spaceship/connect_api/tunes/tunes'
require 'spaceship/connect_api/models/bundle_id_capability'
require 'spaceship/connect_api/models/bundle_id'
require 'spaceship/connect_api/models/capabilities'
require 'spaceship/connect_api/models/certificate'
require 'spaceship/connect_api/models/device'
require 'spaceship/connect_api/models/profile'
require 'spaceship/connect_api/models/user'
require 'spaceship/connect_api/models/user_invitation'
require 'spaceship/connect_api/models/app'
require 'spaceship/connect_api/models/beta_app_localization'
require 'spaceship/connect_api/models/beta_build_localization'
require 'spaceship/connect_api/models/beta_build_metric'
require 'spaceship/connect_api/models/beta_app_review_detail'
require 'spaceship/connect_api/models/beta_app_review_submission'
require 'spaceship/connect_api/models/beta_feedback'
require 'spaceship/connect_api/models/beta_group'
require 'spaceship/connect_api/models/beta_screenshot'
require 'spaceship/connect_api/models/beta_tester'
require 'spaceship/connect_api/models/beta_tester_metric'
require 'spaceship/connect_api/models/build'
require 'spaceship/connect_api/models/build_delivery'
require 'spaceship/connect_api/models/build_beta_detail'
require 'spaceship/connect_api/models/build_bundle'
require 'spaceship/connect_api/models/build_bundle_file_sizes'
require 'spaceship/connect_api/models/custom_app_organization'
require 'spaceship/connect_api/models/custom_app_user'
require 'spaceship/connect_api/models/pre_release_version'
require 'spaceship/connect_api/models/app_availability'
require 'spaceship/connect_api/models/territory_availability'
require 'spaceship/connect_api/models/app_data_usage'
require 'spaceship/connect_api/models/app_data_usage_category'
require 'spaceship/connect_api/models/app_data_usage_data_protection'
require 'spaceship/connect_api/models/app_data_usage_grouping'
require 'spaceship/connect_api/models/app_data_usage_purposes'
require 'spaceship/connect_api/models/app_data_usages_publish_state'
require 'spaceship/connect_api/models/age_rating_declaration'
require 'spaceship/connect_api/models/app_category'
require 'spaceship/connect_api/models/app_info'
require 'spaceship/connect_api/models/app_info_localization'
require 'spaceship/connect_api/models/app_preview_set'
require 'spaceship/connect_api/models/app_preview'
require 'spaceship/connect_api/models/app_price'
require 'spaceship/connect_api/models/app_price_point'
require 'spaceship/connect_api/models/app_price_tier'
require 'spaceship/connect_api/models/app_store_review_attachment'
require 'spaceship/connect_api/models/app_store_review_detail'
require 'spaceship/connect_api/models/app_store_version_release_request'
require 'spaceship/connect_api/models/app_store_version_submission'
require 'spaceship/connect_api/models/app_screenshot_set'
require 'spaceship/connect_api/models/app_screenshot'
require 'spaceship/connect_api/models/app_store_version_localization'
require 'spaceship/connect_api/models/app_store_version_phased_release'
require 'spaceship/connect_api/models/app_store_version'
require 'spaceship/connect_api/models/review_submission'
require 'spaceship/connect_api/models/review_submission_item'
require 'spaceship/connect_api/models/reset_ratings_request'
require 'spaceship/connect_api/models/sandbox_tester'
require 'spaceship/connect_api/models/territory'
require 'spaceship/connect_api/models/resolution_center_message'
require 'spaceship/connect_api/models/resolution_center_thread'
require 'spaceship/connect_api/models/review_rejection'
require 'spaceship/connect_api/models/actor'
module Spaceship
class ConnectAPI
MAX_OBJECTS_PER_PAGE_LIMIT = 200
# Defined in the App Store Connect API docs:
# https://developer.apple.com/documentation/appstoreconnectapi/platform
#
# Used for query param filters
module Platform
IOS = "IOS"
MAC_OS = "MAC_OS"
TV_OS = "TV_OS"
VISION_OS = "VISION_OS"
WATCH_OS = "WATCH_OS"
ALL = [IOS, MAC_OS, TV_OS, VISION_OS, WATCH_OS]
def self.map(platform)
return platform if ALL.include?(platform)
# Map from fastlane input and Spaceship::TestFlight platform values
case platform.to_sym
when :appletvos, :tvos
return Spaceship::ConnectAPI::Platform::TV_OS
when :osx, :macos, :mac
return Spaceship::ConnectAPI::Platform::MAC_OS
when :ios
return Spaceship::ConnectAPI::Platform::IOS
when :xros, :visionos
return Spaceship::ConnectAPI::Platform::VISION_OS
else
raise "Cannot find a matching platform for '#{platform}' - valid values are #{ALL.join(', ')}"
end
end
end
# Defined in the App Store Connect API docs:
#
# Used for creating BundleId and Device
module BundleIdPlatform
IOS = "IOS"
MAC_OS = "MAC_OS"
ALL = [IOS, MAC_OS]
def self.map(platform)
return platform if ALL.include?(platform)
# Map from fastlane input and Spaceship::TestFlight platform values
case platform.to_sym
when :osx, :macos, :mac
return Spaceship::ConnectAPI::Platform::MAC_OS
when :ios, :xros, :visionos
return Spaceship::ConnectAPI::Platform::IOS
else
raise "Cannot find a matching platform for '#{platform}' - valid values are #{ALL.join(', ')}"
end
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/commands_generator.rb | spaceship/lib/spaceship/commands_generator.rb | require 'highline'
HighLine.track_eof = false
require 'fastlane/version'
require 'fastlane_core/ui/help_formatter'
require_relative 'playground'
require_relative 'spaceauth_runner'
module Spaceship
class CommandsGenerator
include Commander::Methods
def self.start
self.new.run
end
def run
program :name, 'spaceship'
program :version, Fastlane::VERSION
program :description, Spaceship::DESCRIPTION
program :help, 'Author', 'Felix Krause <spaceship@krausefx.com>'
program :help, 'Website', 'https://fastlane.tools'
program :help, 'GitHub', 'https://github.com/fastlane/fastlane/tree/master/spaceship'
program :help_formatter, FastlaneCore::HelpFormatter
global_option('-u', '--user USERNAME', 'Specify the Apple ID you want to log in with')
global_option('--verbose') { FastlaneCore::Globals.verbose = true }
global_option('--env STRING[,STRING2]', String, 'Add environment(s) to use with `dotenv`')
command :playground do |c|
c.syntax = 'fastlane spaceship playground'
c.description = 'Run an interactive shell that connects you to Apple web services'
c.action do |args, options|
Spaceship::Playground.new(username: options.user).run
end
end
command :spaceauth do |c|
c.syntax = 'fastlane spaceship spaceauth'
c.description = 'Authentication helper for spaceship/fastlane to work with Apple 2-Step/2FA'
c.option('--copy_to_clipboard', 'Whether the session string should be copied to clipboard. For more info see https://docs.fastlane.tools/best-practices/continuous-integration/#storing-a-manually-verified-session-using-spaceauth`')
c.option('--check_session', 'Check to see if there is a valid session (either in the cache or via FASTLANE_SESSION). Sets the exit code to 0 if the session is valid or 1 if not.') { Spaceship::Globals.check_session = true }
c.action do |args, options|
Spaceship::SpaceauthRunner.new(username: options.user, copy_to_clipboard: options.copy_to_clipboard).run
end
end
default_command(:playground)
run!
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/base.rb | spaceship/lib/spaceship/base.rb | require_relative 'globals'
module Spaceship
##
# Spaceship::Base is the superclass for models in Apple Developer Portal.
# It's mainly responsible for mapping responses to objects.
#
# A class-level attribute `client` is used to maintain the spaceship which we
# are using to talk to ADP.
#
# Example of creating a new ADP model:
#
# class Widget < Spaceship::Base
# attr_accessor :id, :name, :foo_bar, :wiz_baz
# attr_mapping({
# 'name' => :name,
# 'fooBar' => :foo_bar,
# 'wizBaz' => :wiz_baz
# })
# end
#
# When you want to instantiate a model pass in the parsed response: `Widget.new(widget_json)`
class Base
class DataHash
include Enumerable
def initialize(hash)
@hash = hash || {}
end
def key?(key)
@hash.key?(key)
end
def get(*keys)
lookup(keys)
end
alias [] get
def set(keys, value)
raise "'keys' must be an array, got #{keys.class} instead" unless keys.kind_of?(Array)
last = keys.pop
ref = lookup(keys) || @hash
ref[last] = value
end
def delete(key)
@hash.delete(key)
end
def lookup(keys)
head, *tail = *keys
if tail.empty?
@hash[head]
else
DataHash.new(@hash[head]).lookup(tail)
end
end
def each(&block)
@hash.each(&block)
end
def to_json(*a)
h = @hash.dup
h.delete(:application)
h.to_json(*a)
rescue JSON::GeneratorError => e
puts("Failed to jsonify #{h} (#{a})") if Spaceship::Globals.verbose?
raise e
end
def to_h
@hash.dup
end
end
class << self
attr_accessor :client
##
# The client used to make requests.
# @return (Spaceship::Client) Defaults to the singleton
def client
raise "`client` must be implemented in subclasses"
end
##
# Sets client and returns self for chaining.
# @return (Spaceship::Base)
# rubocop:disable Naming/AccessorMethodName
def set_client(client)
self.client = client
self
end
# rubocop:enable Naming/AccessorMethodName
##
# Binds attributes getters and setters to underlying data returned from the API.
# Setting any properties will alter the `raw_data` hash.
#
# @return (Module) with the mapped getters and setters defined. Can be `include`, `extend`, or `prepend` into a class or object
def mapping_module(attr_mapping)
Module.new do
attr_mapping.each do |source, dest|
getter = dest.to_sym
setter = "#{dest}=".to_sym
define_method(getter) do
raw_data.get(*source.split('.'))
end
define_method(setter) do |value|
self.raw_data ||= DataHash.new({})
raw_data.set(source.split('.'), value)
end
end
end
end
##
# Defines the attribute mapping between the response from Apple and our model objects.
# Keys are to match keys in the response and the values are to match attributes on the model.
#
# Example of using `attr_mapping`
#
# class Widget < Spaceship::Base
# attr_accessor :id, :name, :foo_bar, :wiz_baz
# attr_mapping({
# 'name' => :name,
# 'fooBar' => :foo_bar,
# 'wizBaz' => :wiz_baz
# })
# end
def attr_mapping(attr_map = nil)
if attr_map
@attr_mapping = attr_map
@attr_mapping.values.each do |method_name|
getter = method_name.to_sym
setter = "#{method_name}=".to_sym
# Seems like the `public_instance_methods.include?` doesn't always work
# More context https://github.com/fastlane/fastlane/issues/11481
# That's why we have the `begin` `rescue` code here
begin
remove_method(getter) if public_instance_methods.include?(getter)
rescue NameError
end
begin
remove_method(setter) if public_instance_methods.include?(setter)
rescue NameError
end
end
include(mapping_module(@attr_mapping))
else
begin
@attr_mapping ||= ancestors[1].attr_mapping
rescue NoMethodError
rescue NameError
end
end
return @attr_mapping
end
##
# Call a method to return a subclass constant.
#
# If `method_sym` is an underscored name of a class,
# return the class with the current client passed into it.
# If the method does not match, NoMethodError is raised.
#
# Example:
#
# Certificate.production_push
# #=> Certificate::ProductionPush
#
# ProvisioningProfile.ad_hoc
# #=> ProvisioningProfile::AdHoc
#
# ProvisioningProfile.some_other_method
# #=> NoMethodError: undefined method `some_other_method' for ProvisioningProfile
def method_missing(method_sym, *args, &block)
module_name = method_sym.to_s
module_name.sub!(/^[a-z\d]/) { $&.upcase }
module_name.gsub!(%r{(?:_|(/))([a-z\d])}) { $2.upcase }
if const_defined?(module_name)
klass = const_get(module_name)
klass.set_client(@client)
else
super
end
end
##
# The factory class-method. This should only be used or overridden in very specific use-cases
#
# The only time it makes sense to use or override this method is when we want a base class
# to return a sub-class based on attributes.
#
# Here, we define the method to be the same as `Spaceship::Base.new(attrs)`, be it should
# be used only by classes that override it.
#
# Example:
#
# Certificate.factory(attrs)
# #=> #<PushCertificate ... >
#
def factory(attrs, existing_client = nil)
self.new(attrs, existing_client)
end
end
##
# @return (Spaceship::Client) The current spaceship client used by the model to make requests.
attr_reader :client
##
# @return (Hash/Array) Holds the raw data we got from Apple's
# server to use it later
attr_accessor :raw_data
##
# The initialize method accepts a parsed response from Apple and sets all
# attributes that are defined by `attr_mapping`
#
# Do not override `initialize` in your own models.
def initialize(attrs = {}, existing_client = nil)
attrs.each do |key, val|
self.send("#{key}=", val) if respond_to?("#{key}=")
end
self.raw_data = DataHash.new(attrs)
@client = existing_client || self.class.client
self.setup
end
# This method can be used by subclasses to do additional initialisation
# using the `raw_data`
def setup; end
#####################################################
# @!group Storing the `attr_accessor`
#####################################################
# From https://stackoverflow.com/questions/2487333/fastest-one-liner-way-to-list-attr-accessors-in-ruby
# This will store a list of defined attr_accessors to easily access them when inspecting the values
def self.attr_accessor(*vars)
@attributes ||= []
@attributes.concat(vars)
super(*vars)
end
def self.attributes
@attributes ||= []
par = []
par = (self.superclass.attributes || []) unless self == Base
@attributes + par
end
def attributes
self.class.attributes
end
#####################################################
# @!group Inspect related code
#####################################################
def inspect
# To avoid circular references, we keep track of the references
# of all objects already inspected from the first call to inspect
# in this call stack
# We use a Thread local storage for multi-thread friendliness
thread = Thread.current
tree_root = thread[:inspected_objects].nil?
thread[:inspected_objects] = Set.new if tree_root
if thread[:inspected_objects].include?(self)
# already inspected objects have a default value,
# let's follow Ruby's convention for circular references
value = "#<Object ...>"
else
thread[:inspected_objects].add(self)
begin
value = inspect_value
ensure
thread[:inspected_objects] = nil if tree_root
end
end
"<#{self.class.name} \n#{value}>"
end
def inspect_value
self.attributes.map do |k|
v = self.send(k).inspect
v = v.gsub("\n", "\n\t") # to align nested elements
"\t#{k}=#{v}"
end.join(", \n")
end
def to_s
self.inspect
end
private :inspect_value
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/playground.rb | spaceship/lib/spaceship/playground.rb | require "colored"
require "credentials_manager"
require_relative 'tunes/tunes'
require_relative 'portal/portal'
module Spaceship
class Playground
def initialize(username: nil)
# Make sure the user has pry installed
begin
Gem::Specification.find_by_name("pry")
rescue Gem::LoadError
puts("Could not find gem 'pry'".red)
puts("")
puts("If you installed spaceship using `gem install spaceship` run")
puts(" gem install pry".yellow)
puts("to install the missing gem")
puts("")
puts("If you use a Gemfile add this to your Gemfile:")
puts(" gem 'pry'".yellow)
puts("and run " + "`bundle install`".yellow)
abort
end
require 'pry'
@username = username
@username ||= CredentialsManager::AppfileConfig.try_fetch_value(:apple_id)
@username ||= ask("Username: ")
end
def run
begin
puts("Logging into to App Store Connect (#{@username})...")
Spaceship::Tunes.login(@username)
puts("Successfully logged in to App Store Connect".green)
puts("")
rescue
puts("Could not login to App Store Connect...".red)
end
begin
puts("Logging into the Developer Portal (#{@username})...")
Spaceship::Portal.login(@username)
puts("Successfully logged in to the Developer Portal".green)
puts("")
rescue
puts("Could not login to the Developer Portal...".red)
end
puts("---------------------------------------".green)
puts("| Welcome to the spaceship playground |".green)
puts("---------------------------------------".green)
puts("")
puts("Enter #{'docs'.yellow} to open up the documentation")
puts("Enter #{'exit'.yellow} to exit the spaceship playground")
puts("Enter #{'_'.yellow} to access the return value of the last executed command")
puts("")
puts("Just enter the commands and confirm with Enter".green)
# rubocop:disable Lint/Debugger
binding.pry(quiet: true)
# rubocop:enable Lint/Debugger
puts("") # Fixes https://github.com/fastlane/fastlane/issues/3493
end
def docs
url = 'https://github.com/fastlane/fastlane/tree/master/spaceship/docs'
`open '#{url}'`
url
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/launcher.rb | spaceship/lib/spaceship/launcher.rb | require_relative 'portal/portal_client'
module Spaceship
class Launcher
attr_accessor :client
# Launch a new spaceship, which can be used to maintain multiple instances of
# spaceship. You can call `.new` without any parameters, but you'll have to call
# `.login` at a later point. If you prefer, you can pass the login credentials
# here already.
#
# Authenticates with Apple's web services. This method has to be called once
# to generate a valid session. The session will automatically be used from then
# on.
#
# This method will automatically use the username from the Appfile (if available)
# and fetch the password from the Keychain (if available)
#
# @param user (String) (optional): The username (usually the email address)
# @param password (String) (optional): The password
#
# @raise InvalidUserCredentialsError: raised if authentication failed
def initialize(user = nil, password = nil)
@client = PortalClient.new
if user || password
@client.login(user, password)
end
end
#####################################################
# @!group Login Helper
#####################################################
# Authenticates with Apple's web services. This method has to be called once
# to generate a valid session. The session will automatically be used from then
# on.
#
# This method will automatically use the username from the Appfile (if available)
# and fetch the password from the Keychain (if available)
#
# @param user (String) (optional): The username (usually the email address)
# @param password (String) (optional): The password
#
# @raise InvalidUserCredentialsError: raised if authentication failed
#
# @return (Spaceship::Client) The client the login method was called for
def login(user, password)
@client.login(user, password)
end
# Open up the team selection for the user (if necessary).
#
# If the user is in multiple teams, a team selection is shown.
# The user can then select a team by entering the number
#
# Additionally, the team ID is shown next to each team name
# so that the user can use the environment variable `FASTLANE_TEAM_ID`
# for future user.
#
# @param team_id (String) (optional): The ID of a Developer Portal team
# @param team_name (String) (optional): The name of a Developer Portal team
#
# @return (String) The ID of the select team. You also get the value if
# the user is only in one team.
def select_team(team_id: nil, team_name: nil)
@client.select_team(team_id: team_id, team_name: team_name)
end
#####################################################
# @!group Helper methods for managing multiple instances of spaceship
#####################################################
# @return (Class) Access the apps for this spaceship
def app
Spaceship::Portal::App.set_client(@client)
end
# @return (Class) Access the app groups for this spaceship
def app_group
Spaceship::Portal::AppGroup.set_client(@client)
end
# @return (Class) Access the devices for this spaceship
def device
Spaceship::Portal::Device.set_client(@client)
end
# @return (Class) Access the certificates for this spaceship
def certificate
Spaceship::Portal::Certificate.set_client(@client)
end
# @return (Class) Access the provisioning profiles for this spaceship
def provisioning_profile
Spaceship::Portal::ProvisioningProfile.set_client(@client)
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/hashcash.rb | spaceship/lib/spaceship/hashcash.rb | require 'digest'
module Spaceship
module Hashcash
# This App Store Connect hashcash spec was generously donated by...
#
# __ _
# __ _ _ __ _ __ / _|(_) __ _ _ _ _ __ ___ ___
# / _` || '_ \ | '_ \ | |_ | | / _` || | | || '__|/ _ \/ __|
# | (_| || |_) || |_) || _|| || (_| || |_| || | | __/\__ \
# \__,_|| .__/ | .__/ |_| |_| \__, | \__,_||_| \___||___/
# |_| |_| |___/
#
#
# <summary>
# 1:11:20230223170600:4d74fb15eb23f465f1f6fcbf534e5877::6373
# X-APPLE-HC: 1:11:20230223170600:4d74fb15eb23f465f1f6fcbf534e5877::6373
# ^ ^ ^ ^ ^
# | | | | +-- Counter
# | | | +-- Resource
# | | +-- Date YYMMDD[hhmm[ss]]
# | +-- Bits (number of leading zeros)
# +-- Version
#
# We can't use an off-the-shelf Hashcash because Apple's implementation is not quite the same as the spec/convention.
# 1. The spec calls for a nonce called "Rand" to be inserted between the Ext and Counter. They don't do that at all.
# 2. The Counter conventionally encoded as base-64 but Apple just uses the decimal number's string representation.
#
# Iterate from Counter=0 to Counter=N finding an N that makes the SHA1(X-APPLE-HC) lead with Bits leading zero bits
#
#
# We get the "Resource" from the X-Apple-HC-Challenge header and Bits from X-Apple-HC-Bits
#
# </summary>
def self.make(bits:, challenge:)
version = 1
date = Time.now.strftime("%Y%m%d%H%M%S")
counter = 0
loop do
hc = [
version, bits, date, challenge, ":#{counter}"
].join(":")
if Digest::SHA1.digest(hc).unpack1('B*')[0, bits.to_i].to_i == 0
return hc
end
counter += 1
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/client.rb | spaceship/lib/spaceship/client.rb | require 'babosa'
require 'faraday' # HTTP Client
require 'faraday-cookie_jar'
require 'faraday_middleware'
require 'logger'
require 'tmpdir'
require 'cgi'
require 'tempfile'
require 'openssl'
require 'fastlane/version'
require_relative 'helper/net_http_generic_request'
require_relative 'helper/plist_middleware'
require_relative 'helper/rels_middleware'
require_relative 'ui'
require_relative 'errors'
require_relative 'tunes/errors'
require_relative 'globals'
require_relative 'provider'
require_relative 'stats_middleware'
require_relative 'hashcash'
Faraday::Utils.default_params_encoder = Faraday::FlatParamsEncoder
module Spaceship
# rubocop:disable Metrics/ClassLength
class Client
PROTOCOL_VERSION = "QH65B2"
USER_AGENT = "Spaceship #{Fastlane::VERSION}"
AUTH_TYPES = ["sa", "hsa", "non-sa", "hsa2"]
attr_reader :client
# The user that is currently logged in
attr_accessor :user
# The email of the user that is currently logged in
attr_accessor :user_email
# The logger in which all requests are logged
# /tmp/spaceship[time]_[pid].log by default
attr_accessor :logger
attr_accessor :csrf_tokens
attr_accessor :additional_headers
attr_accessor :provider
# legacy support
BasicPreferredInfoError = Spaceship::BasicPreferredInfoError
InvalidUserCredentialsError = Spaceship::InvalidUserCredentialsError
NoUserCredentialsError = Spaceship::NoUserCredentialsError
ProgramLicenseAgreementUpdated = Spaceship::ProgramLicenseAgreementUpdated
InsufficientPermissions = Spaceship::InsufficientPermissions
UnexpectedResponse = Spaceship::UnexpectedResponse
AppleTimeoutError = Spaceship::AppleTimeoutError
UnauthorizedAccessError = Spaceship::UnauthorizedAccessError
GatewayTimeoutError = Spaceship::GatewayTimeoutError
InternalServerError = Spaceship::InternalServerError
BadGatewayError = Spaceship::BadGatewayError
AccessForbiddenError = Spaceship::AccessForbiddenError
TooManyRequestsError = Spaceship::TooManyRequestsError
def self.hostname
raise "You must implement self.hostname"
end
#####################################################
# @!group Teams + User
#####################################################
# @return (Array) A list of all available teams
def teams
user_details_data['availableProviders'].sort_by do |team|
[
team['name'],
team['providerId']
]
end
end
# Fetch the general information of the user, is used by various methods across spaceship
# Sample return value
# => {"associatedAccounts"=>
# [{"contentProvider"=>{"contentProviderId"=>11142800, "name"=>"Felix Krause", "contentProviderTypes"=>["Purple Software"]}, "roles"=>["Developer"], "lastLogin"=>1468784113000}],
# "sessionToken"=>{"dsId"=>"8501011116", "contentProviderId"=>18111111, "expirationDate"=>nil, "ipAddress"=>nil},
# "permittedActivities"=>
# {"EDIT"=>
# ["UserManagementSelf",
# "GameCenterTestData",
# "AppAddonCreation"],
# "REPORT"=>
# ["UserManagementSelf",
# "AppAddonCreation"],
# "VIEW"=>
# ["TestFlightAppExternalTesterManagement",
# ...
# "HelpGeneral",
# "HelpApplicationLoader"]},
# "preferredCurrencyCode"=>"EUR",
# "preferredCountryCode"=>nil,
# "countryOfOrigin"=>"AT",
# "isLocaleNameReversed"=>false,
# "feldsparToken"=>nil,
# "feldsparChannelName"=>nil,
# "hasPendingFeldsparBindingRequest"=>false,
# "isLegalUser"=>false,
# "userId"=>"1771111155",
# "firstname"=>"Detlef",
# "lastname"=>"Mueller",
# "isEmailInvalid"=>false,
# "hasContractInfo"=>false,
# "canEditITCUsersAndRoles"=>false,
# "canViewITCUsersAndRoles"=>true,
# "canEditIAPUsersAndRoles"=>false,
# "transporterEnabled"=>false,
# "contentProviderFeatures"=>["APP_SILOING", "PROMO_CODE_REDESIGN", ...],
# "contentProviderType"=>"Purple Software",
# "displayName"=>"Detlef",
# "contentProviderId"=>"18742800",
# "userFeatures"=>[],
# "visibility"=>true,
# "DYCVisibility"=>false,
# "contentProvider"=>"Felix Krause",
# "userName"=>"detlef@krausefx.com"}
def user_details_data
return @_cached_user_details if @_cached_user_details
r = request(:get, "https://appstoreconnect.apple.com/olympus/v1/session")
@_cached_user_details = parse_response(r)
end
# @return (String) The currently selected Team ID
def team_id
return @current_team_id if @current_team_id
if teams.count > 1
puts("The current user is in #{teams.count} teams. Pass a team ID or call `select_team` to choose a team. Using the first one for now.")
end
@current_team_id ||= user_details_data['provider']['providerId']
end
# Set a new team ID which will be used from now on
def team_id=(team_id)
# First, we verify the team actually exists, because otherwise iTC would return the
# following confusing error message
#
# invalid content provider id
available_teams = teams.collect do |team|
{
team_id: team["providerId"],
public_team_id: team["publicProviderId"],
team_name: team["name"]
}
end
result = available_teams.find do |available_team|
team_id.to_s == available_team[:team_id].to_s
end
unless result
error_string = "Could not set team ID to '#{team_id}', only found the following available teams:\n\n#{available_teams.map { |team| "- #{team[:team_id]} (#{team[:team_name]})" }.join("\n")}\n"
raise Tunes::Error.new, error_string
end
response = request(:post) do |req|
req.url("https://appstoreconnect.apple.com/olympus/v1/session")
req.body = { "provider": { "providerId": result[:team_id] } }.to_json
req.headers['Content-Type'] = 'application/json'
req.headers['X-Requested-With'] = 'olympus-ui'
end
handle_itc_response(response.body)
# clear user_details_data cache, as session switch will have changed sessionToken attribute
@_cached_user_details = nil
@current_team_id = team_id
end
# @return (Hash) Fetches all information of the currently used team
def team_information
teams.find do |t|
t['teamId'] == team_id
end
end
# @return (String) Fetches name from currently used team
def team_name
(team_information || {})['name']
end
#####################################################
# @!group Client Init
#####################################################
# Instantiates a client but with a cookie derived from another client.
#
# HACK: since the `@cookie` is not exposed, we use this hacky way of sharing the instance.
def self.client_with_authorization_from(another_client)
self.new(cookie: another_client.instance_variable_get(:@cookie), current_team_id: another_client.team_id)
end
def initialize(cookie: nil, current_team_id: nil, csrf_tokens: nil, timeout: nil)
options = {
request: {
timeout: (ENV["SPACESHIP_TIMEOUT"] || timeout || 300).to_i,
open_timeout: (ENV["SPACESHIP_TIMEOUT"] || timeout || 300).to_i
}
}
@current_team_id = current_team_id
@csrf_tokens = csrf_tokens
@cookie = cookie || HTTP::CookieJar.new
@client = Faraday.new(self.class.hostname, options) do |c|
c.response(:json, content_type: /\bjson$/)
c.response(:plist, content_type: /\bplist$/)
c.use(:cookie_jar, jar: @cookie)
c.use(FaradayMiddleware::RelsMiddleware)
c.use(Spaceship::StatsMiddleware)
c.adapter(Faraday.default_adapter)
if ENV['SPACESHIP_DEBUG']
# for debugging only
# This enables tracking of networking requests using Charles Web Proxy
c.proxy = "https://127.0.0.1:8888"
c.ssl[:verify_mode] = OpenSSL::SSL::VERIFY_NONE
elsif ENV["SPACESHIP_PROXY"]
c.proxy = ENV["SPACESHIP_PROXY"]
c.ssl[:verify_mode] = OpenSSL::SSL::VERIFY_NONE if ENV["SPACESHIP_PROXY_SSL_VERIFY_NONE"]
end
if ENV["DEBUG"]
puts("To run spaceship through a local proxy, use SPACESHIP_DEBUG")
end
end
end
#####################################################
# @!group Request Logger
#####################################################
# The logger in which all requests are logged
# /tmp/spaceship[time]_[pid]_["threadid"].log by default
def logger
unless @logger
if ENV["VERBOSE"]
@logger = Logger.new(STDOUT)
else
# Log to file by default
path = "/tmp/spaceship#{Time.now.to_i}_#{Process.pid}_#{Thread.current.object_id}.log"
@logger = Logger.new(path)
end
@logger.formatter = proc do |severity, datetime, progname, msg|
severity = format('%-5.5s', severity)
"#{severity} [#{datetime.strftime('%H:%M:%S')}]: #{msg}\n"
end
end
@logger
end
#####################################################
# @!group Session Cookie
#####################################################
##
# Return the session cookie.
#
# @return (String) the cookie-string in the RFC6265 format: https://tools.ietf.org/html/rfc6265#section-4.2.1
def cookie
@cookie.map(&:to_s).join(';')
end
def store_cookie(path: nil)
path ||= persistent_cookie_path
FileUtils.mkdir_p(File.expand_path("..", path))
# really important to specify the session to true
# otherwise myacinfo and more won't be stored
@cookie.save(path, :yaml, session: true)
return File.read(path)
end
# This is a duplicate method of fastlane_core/fastlane_core.rb#fastlane_user_dir
def fastlane_user_dir
path = File.expand_path(File.join(Dir.home, ".fastlane"))
FileUtils.mkdir_p(path) unless File.directory?(path)
return path
end
# Returns preferred path for storing cookie
# for two step verification.
def persistent_cookie_path
if ENV["SPACESHIP_COOKIE_PATH"]
path = File.expand_path(File.join(ENV["SPACESHIP_COOKIE_PATH"], "spaceship", self.user, "cookie"))
else
[File.join(self.fastlane_user_dir, "spaceship"), "~/.spaceship", "/var/tmp/spaceship", "#{Dir.tmpdir}/spaceship"].each do |dir|
dir_parts = File.split(dir)
if directory_accessible?(File.expand_path(dir_parts.first))
path = File.expand_path(File.join(dir, self.user, "cookie"))
break
end
end
end
return path
end
#####################################################
# @!group Automatic Paging
#####################################################
# The page size we want to request, defaults to 500
def page_size
@page_size ||= 500
end
# Handles the paging for you... for free
# Just pass a block and use the parameter as page number
def paging
page = 0
results = []
loop do
page += 1
current = yield(page)
results += current
break if (current || []).count < page_size # no more results
end
return results
end
#####################################################
# @!group Login and Team Selection
#####################################################
# Authenticates with Apple's web services. This method has to be called once
# to generate a valid session. The session will automatically be used from then
# on.
#
# This method will automatically use the username from the Appfile (if available)
# and fetch the password from the Keychain (if available)
#
# @param user (String) (optional): The username (usually the email address)
# @param password (String) (optional): The password
#
# @raise InvalidUserCredentialsError: raised if authentication failed
#
# @return (Spaceship::Client) The client the login method was called for
def self.login(user = nil, password = nil)
instance = self.new
if instance.login(user, password)
instance
else
raise InvalidUserCredentialsError.new, "Invalid User Credentials"
end
end
# Authenticates with Apple's web services. This method has to be called once
# to generate a valid session. The session will automatically be used from then
# on.
#
# This method will automatically use the username from the Appfile (if available)
# and fetch the password from the Keychain (if available)
#
# @param user (String) (optional): The username (usually the email address)
# @param password (String) (optional): The password
#
# @raise InvalidUserCredentialsError: raised if authentication failed
#
# @return (Spaceship::Client) The client the login method was called for
def login(user = nil, password = nil)
if user.to_s.empty? || password.to_s.empty?
require 'credentials_manager/account_manager'
puts("Reading keychain entry, because either user or password were empty") if Spaceship::Globals.verbose?
keychain_entry = CredentialsManager::AccountManager.new(user: user, password: password)
user ||= keychain_entry.user
password = keychain_entry.password(ask_if_missing: !Spaceship::Globals.check_session)
end
if user.to_s.strip.empty? || password.to_s.strip.empty?
exit_with_session_state(user, false) if Spaceship::Globals.check_session
raise NoUserCredentialsError.new, "No login data provided"
end
self.user = user
@password = password
begin
do_login(user, password) # calls `send_login_request` in sub class (which then will redirect back here to `send_shared_login_request`, below)
rescue InvalidUserCredentialsError => ex
raise ex unless keychain_entry
if keychain_entry.invalid_credentials
login(user)
else
raise ex
end
end
end
# Check if we have a cached/valid session
#
# Background:
# December 4th 2017 Apple introduced a rate limit - which is of course fine by itself -
# but unfortunately also rate limits successful logins. If you call multiple tools in a
# lane (e.g. call match 5 times), this would lock you out of the account for a while.
# By loading existing sessions and checking if they're valid, we're sending less login requests.
# More context on why this change was necessary https://github.com/fastlane/fastlane/pull/11108
#
def has_valid_session
# If there was a successful manual login before, we have a session on disk
if load_session_from_file
# Check if the session is still valid here
begin
# We use the olympus session to determine if the old session is still valid
# As this will raise an exception if the old session has expired
# If the old session is still valid, we don't have to do anything else in this method
# that's why we return true
return true if fetch_olympus_session
rescue
# If the `fetch_olympus_session` method raises an exception
# we'll land here, and therefore continue doing a full login process
# This happens if the session we loaded from the cache isn't valid any more
# which is common, as the session automatically invalidates after x hours (we don't know x)
# In this case we don't actually care about the exact exception, and why it was failing
# because either way, we'll have to do a fresh login, where we do the actual error handling
puts("Available session is not valid anymore. Continuing with normal login.")
end
end
#
# The user can pass the session via environment variable (Mainly used in CI environments)
if load_session_from_env
# see above
begin
# see above
return true if fetch_olympus_session
rescue
puts("Session loaded from environment variable is not valid. Continuing with normal login.")
# see above
end
end
#
# After this point, we sure have no valid session any more and have to create a new one
#
return false
end
def do_sirp(user, password, modified_cookie)
require 'fastlane-sirp'
require 'base64'
client = SIRP::Client.new(2048)
a = client.start_authentication
data = {
a: Base64.strict_encode64(to_byte(a)),
accountName: user,
protocols: ['s2k', 's2k_fo']
}
response = request(:post) do |req|
req.url("https://idmsa.apple.com/appleauth/auth/signin/init")
req.body = data.to_json
req.headers['Content-Type'] = 'application/json'
req.headers['X-Requested-With'] = 'XMLHttpRequest'
req.headers['X-Apple-Widget-Key'] = self.itc_service_key
req.headers['Accept'] = 'application/json, text/javascript'
req.headers["Cookie"] = modified_cookie if modified_cookie
end
puts("Received SIRP signin init response: #{response.body}") if Spaceship::Globals.verbose?
body = response.body
unless body.kind_of?(Hash)
raise UnexpectedResponse, "Expected JSON response, but got #{body.class}: #{body.to_s[0..1000]}"
end
if body["serviceErrors"]
raise UnexpectedResponse, body
end
iterations = body["iteration"]
salt = Base64.strict_decode64(body["salt"])
b = Base64.strict_decode64(body["b"])
c = body["c"]
key_length = 32
encrypted_password = pbkdf2(password, salt, iterations, key_length)
m1 = client.process_challenge(
user,
to_hex(encrypted_password),
to_hex(salt),
to_hex(b),
is_password_encrypted: true
)
m2 = client.H_AMK
if m1 == false
puts("Error processing SIRP challenge") if Spaceship::Globals.verbose?
raise SIRPAuthenticationError
end
data = {
accountName: user,
c: c,
m1: Base64.encode64(to_byte(m1)).strip,
m2: Base64.encode64(to_byte(m2)).strip,
rememberMe: false
}
hashcash = self.fetch_hashcash
response = request(:post) do |req|
req.url("https://idmsa.apple.com/appleauth/auth/signin/complete?isRememberMeEnabled=false")
req.body = data.to_json
req.headers['Content-Type'] = 'application/json'
req.headers['X-Requested-With'] = 'XMLHttpRequest'
req.headers['X-Apple-Widget-Key'] = self.itc_service_key
req.headers['Accept'] = 'application/json, text/javascript'
req.headers["Cookie"] = modified_cookie if modified_cookie
req.headers["X-Apple-HC"] = hashcash if hashcash
end
puts("Completed SIRP authentication with status of #{response.status}") if Spaceship::Globals.verbose?
return response
end
def pbkdf2(password, salt, iterations, key_length, digest = OpenSSL::Digest::SHA256.new)
require 'openssl'
password = OpenSSL::Digest::SHA256.digest(password)
OpenSSL::PKCS5.pbkdf2_hmac(password, salt, iterations, key_length, digest)
end
def to_hex(str)
str.unpack1('H*')
end
def to_byte(str)
[str].pack('H*')
end
# This method is used for both the Apple Dev Portal and App Store Connect
# This will also handle 2 step verification and 2 factor authentication
#
# It is called in `send_login_request` of sub classes (which the method `login`, above, transferred over to via `do_login`)
# rubocop:disable Metrics/PerceivedComplexity
def send_shared_login_request(user, password)
# Check if the cache or FASTLANE_SESSION is still valid
has_valid_session = self.has_valid_session
# Exit if `--check_session` flag was passed
exit_with_session_state(user, has_valid_session) if Spaceship::Globals.check_session
# If the session is valid no need to attempt to generate a new one.
return true if has_valid_session
begin
# The below workaround is only needed for 2 step verified machines
# Due to escaping of cookie values we have a little workaround here
# By default the cookie jar would generate the following header
# DES5c148...=HSARM.......xaA/O69Ws/CHfQ==SRVT
# However we need the following
# DES5c148...="HSARM.......xaA/O69Ws/CHfQ==SRVT"
# There is no way to get the cookie jar value with " around the value
# so we manually modify the cookie (only this one) to be properly escaped
# Afterwards we pass this value manually as a header
# It's not enough to just modify @cookie, it needs to be done after self.cookie
# as a string operation
important_cookie = @cookie.store.entries.find { |a| a.name.include?("DES") }
if important_cookie
modified_cookie = self.cookie # returns a string of all cookies
unescaped_important_cookie = "#{important_cookie.name}=#{important_cookie.value}"
escaped_important_cookie = "#{important_cookie.name}=\"#{important_cookie.value}\""
modified_cookie.gsub!(unescaped_important_cookie, escaped_important_cookie)
end
response = perform_login_method(user, password, modified_cookie)
rescue UnauthorizedAccessError
raise InvalidUserCredentialsError.new, "Invalid username and password combination. Used '#{user}' as the username."
end
# Now we know if the login is successful or if we need to do 2 factor
case response.status
when 403
raise InvalidUserCredentialsError.new, "Invalid username and password combination. Used '#{user}' as the username."
when 200
fetch_olympus_session
return response
when 409
# 2 step/factor is enabled for this account, first handle that
handle_two_step_or_factor(response)
# and then get the olympus session
fetch_olympus_session
return true
else
if (response.body || "").include?('invalid="true"')
# User Credentials are wrong
raise InvalidUserCredentialsError.new, "Invalid username and password combination. Used '#{user}' as the username."
elsif response.status == 412 && AUTH_TYPES.include?(response.body["authType"])
if try_upgrade_2fa_later(response)
store_cookie
return true
end
# Need to acknowledge Apple ID and Privacy statement - https://github.com/fastlane/fastlane/issues/12577
# Looking for status of 412 might be enough but might be safer to keep looking only at what is being reported
raise AppleIDAndPrivacyAcknowledgementNeeded.new, "Need to acknowledge to Apple's Apple ID and Privacy statement. " \
"Please manually log into https://appleid.apple.com (or https://appstoreconnect.apple.com) to acknowledge the statement. " \
"Your account might also be asked to upgrade to 2FA. " \
"Set SPACESHIP_SKIP_2FA_UPGRADE=1 for fastlane to automatically bypass 2FA upgrade if possible."
elsif (response['Set-Cookie'] || "").include?("itctx")
raise "Looks like your Apple ID is not enabled for App Store Connect, make sure to be able to login online"
else
info = [response.body, response['Set-Cookie']]
raise Tunes::Error.new, info.join("\n")
end
end
end
# rubocop:enable Metrics/PerceivedComplexity
def perform_login_method(user, password, modified_cookie)
do_legacy_signin = ENV['FASTLANE_USE_LEGACY_PRE_SIRP_AUTH']
if do_legacy_signin
puts("Starting legacy Apple ID login") if Spaceship::Globals.verbose?
# Fixes issue https://github.com/fastlane/fastlane/issues/21071
# On 2023-02-23, Apple added a custom implementation
# of hashcash to their auth flow
# hashcash = nil
hashcash = self.fetch_hashcash
data = {
accountName: user,
password: password,
rememberMe: true
}
return request(:post) do |req|
req.url("https://idmsa.apple.com/appleauth/auth/signin")
req.body = data.to_json
req.headers['Content-Type'] = 'application/json'
req.headers['X-Requested-With'] = 'XMLHttpRequest'
req.headers['X-Apple-Widget-Key'] = self.itc_service_key
req.headers['Accept'] = 'application/json, text/javascript'
req.headers["Cookie"] = modified_cookie if modified_cookie
req.headers["X-Apple-HC"] = hashcash if hashcash
end
else
# Fixes issue https://github.com/fastlane/fastlane/issues/26368#issuecomment-2424190032
puts("Starting SIRP Apple ID login") if Spaceship::Globals.verbose?
return do_sirp(user, password, modified_cookie)
end
end
def fetch_hashcash
response = request(:get, "https://idmsa.apple.com/appleauth/auth/signin?widgetKey=#{self.itc_service_key}")
headers = response.headers
bits = headers["X-Apple-HC-Bits"]
challenge = headers["X-Apple-HC-Challenge"]
if bits.nil? || challenge.nil?
puts("Unable to find 'X-Apple-HC-Bits' and 'X-Apple-HC-Challenge' to make hashcash")
return nil
end
return Spaceship::Hashcash.make(bits: bits, challenge: challenge)
end
# Get the `itctx` from the new (22nd May 2017) API endpoint "olympus"
# Update (29th March 2019) olympus migrates to new appstoreconnect API
def fetch_olympus_session
response = request(:get, "https://appstoreconnect.apple.com/olympus/v1/session")
body = response.body
if body
body = JSON.parse(body) if body.kind_of?(String)
user_map = body["user"]
if user_map
self.user_email = user_map["emailAddress"]
end
provider = body["provider"]
if provider
self.provider = Spaceship::Provider.new(provider_hash: provider)
return true
end
end
return false
end
# This method is used to log if the session is valid or not and then exit
# It is called when the `--check_session` flag is passed
def exit_with_session_state(user, has_valid_session)
puts("#{has_valid_session ? 'Valid' : 'No valid'} session found (#{user}). Exiting.")
exit(has_valid_session)
end
def itc_service_key
return @service_key if @service_key
# Check if we have a local cache of the key
itc_service_key_path = "/tmp/spaceship_itc_service_key.txt"
return File.read(itc_service_key_path) if File.exist?(itc_service_key_path)
# Fixes issue https://github.com/fastlane/fastlane/issues/13281
# Even though we are using https://appstoreconnect.apple.com, the service key needs to still use a
# hostname through itunesconnect.apple.com
response = request(:get, "https://appstoreconnect.apple.com/olympus/v1/app/config?hostname=itunesconnect.apple.com")
@service_key = response.body["authServiceKey"].to_s
raise "Service key is empty" if @service_key.length == 0
# Cache the key locally
File.write(itc_service_key_path, @service_key)
return @service_key
rescue => ex
puts(ex.to_s)
raise AppleTimeoutError.new, "Could not receive latest API key from App Store Connect, this might be a server issue."
end
#####################################################
# @!group Session
#####################################################
def load_session_from_file
begin
if File.exist?(persistent_cookie_path)
puts("Loading session from '#{persistent_cookie_path}'") if Spaceship::Globals.verbose?
@cookie.load(persistent_cookie_path)
return true
end
rescue => ex
puts(ex.to_s)
puts("Continuing with normal login.")
end
return false
end
def load_session_from_env
return if self.class.spaceship_session_env.to_s.length == 0
puts("Loading session from environment variable") if Spaceship::Globals.verbose?
file = Tempfile.new('cookie.yml')
file.write(self.class.spaceship_session_env.gsub("\\n", "\n"))
file.close
begin
@cookie.load(file.path)
rescue => ex
puts("Error loading session from environment")
puts("Make sure to pass the session in a valid format")
raise ex
ensure
file.unlink
end
end
# Fetch the session cookie from the environment
# (if exists)
def self.spaceship_session_env
ENV["FASTLANE_SESSION"] || ENV["SPACESHIP_SESSION"]
end
# Get contract messages from App Store Connect's "olympus" endpoint
def fetch_program_license_agreement_messages
all_messages = []
messages_request = request(:get, "https://appstoreconnect.apple.com/olympus/v1/contractMessages")
body = messages_request.body
if body
body = JSON.parse(body) if body.kind_of?(String)
body.map do |messages|
all_messages.push(messages["message"])
end
end
return all_messages
end
#####################################################
# @!group Helpers
#####################################################
def with_retry(tries = 5, &_block)
return yield
rescue \
Faraday::ConnectionFailed,
Faraday::TimeoutError,
BadGatewayError,
AppleTimeoutError,
GatewayTimeoutError,
AccessForbiddenError => ex
tries -= 1
unless tries.zero?
msg = "Timeout received: '#{ex.class}', '#{ex.message}'. Retrying after 3 seconds (remaining: #{tries})..."
puts(msg) if Spaceship::Globals.verbose?
logger.warn(msg)
sleep(3) unless Object.const_defined?("SpecHelper")
retry
end
raise ex # re-raise the exception
rescue TooManyRequestsError => ex
tries -= 1
unless tries.zero?
msg = "Timeout received: '#{ex.class}', '#{ex.message}'. Retrying after #{ex.retry_after} seconds (remaining: #{tries})..."
puts(msg) if Spaceship::Globals.verbose?
logger.warn(msg)
sleep(ex.retry_after) unless Object.const_defined?("SpecHelper")
retry
end
raise ex # re-raise the exception
rescue \
Faraday::ParsingError, # <h2>Internal Server Error</h2> with content type json
InternalServerError => ex
tries -= 1
unless tries.zero?
msg = "Internal Server Error received: '#{ex.class}', '#{ex.message}'. Retrying after 3 seconds (remaining: #{tries})..."
puts(msg) if Spaceship::Globals.verbose?
logger.warn(msg)
sleep(3) unless Object.const_defined?("SpecHelper")
retry
end
raise ex # re-raise the exception
rescue UnauthorizedAccessError => ex
if @loggedin && !(tries -= 1).zero?
msg = "Auth error received: '#{ex.class}', '#{ex.message}'. Login in again then retrying after 3 seconds (remaining: #{tries})..."
puts(msg) if Spaceship::Globals.verbose?
logger.warn(msg)
if self.class.spaceship_session_env.to_s.length > 0
raise UnauthorizedAccessError.new, "Authentication error, you passed an invalid session using the environment variable FASTLANE_SESSION or SPACESHIP_SESSION"
end
do_login(self.user, @password)
sleep(3) unless Object.const_defined?("SpecHelper")
retry
end
raise ex # re-raise the exception
end
# memorize the last csrf tokens from responses
def csrf_tokens
@csrf_tokens || {}
end
def additional_headers
@additional_headers || {}
end
def request(method, url_or_path = nil, params = nil, headers = {}, auto_paginate = false, &block)
headers.merge!(csrf_tokens)
headers.merge!(additional_headers)
headers['User-Agent'] = USER_AGENT
# Before encoding the parameters, log them
log_request(method, url_or_path, params, headers, &block)
# form-encode the params only if there are params, and the block is not supplied.
# this is so that certain requests can be made using the block for more control
if method == :post && params && !block_given?
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | true |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/module.rb | spaceship/lib/spaceship/module.rb | module Spaceship
# Requiring pathname is required here if not using bundler and requiring spaceship directly
# https://github.com/fastlane/fastlane/issues/14661
require 'pathname'
ROOT = Pathname.new(File.expand_path('../../..', __FILE__))
DESCRIPTION = "Ruby library to access the Apple Dev Center and App Store Connect".freeze
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/two_step_or_factor_client.rb | spaceship/lib/spaceship/two_step_or_factor_client.rb | require_relative 'globals'
require_relative 'tunes/tunes_client'
module Spaceship
class Client
def handle_two_step_or_factor(response)
raise "2FA can only be performed in interactive mode" if ENV["SPACESHIP_ONLY_ALLOW_INTERACTIVE_2FA"] == "true" && ENV["FASTLANE_IS_INTERACTIVE"] == "false"
# extract `x-apple-id-session-id` and `scnt` from response, to be used by `update_request_headers`
@x_apple_id_session_id = response["x-apple-id-session-id"]
@scnt = response["scnt"]
# get authentication options
r = request(:get) do |req|
req.url("https://idmsa.apple.com/appleauth/auth")
update_request_headers(req)
end
if r.body.kind_of?(Hash) && r.body["trustedDevices"].kind_of?(Array)
handle_two_step(r)
elsif r.body.kind_of?(Hash) && r.body["trustedPhoneNumbers"].kind_of?(Array) && r.body["trustedPhoneNumbers"].first.kind_of?(Hash)
handle_two_factor(r)
else
raise "Although response from Apple indicated activated Two-step Verification or Two-factor Authentication, spaceship didn't know how to handle this response: #{r.body}"
end
end
def handle_two_step(response)
if response.body.fetch("securityCode", {})["tooManyCodesLock"].to_s.length > 0
raise Tunes::Error.new, "Too many verification codes have been sent. Enter the last code you received, use one of your devices, or try again later."
end
puts("Two-step Verification (4 digits code) is enabled for account '#{self.user}'")
puts("More information about Two-step Verification: https://support.apple.com/en-us/HT204152")
puts("")
puts("Please select a trusted device to verify your identity")
available = response.body["trustedDevices"].collect do |current|
"#{current['name']}\t#{current['modelName'] || 'SMS'}\t(#{current['id']})"
end
result = choose(*available)
device_id = result.match(/.*\t.*\t\((.*)\)/)[1]
handle_two_step_for_device(device_id)
end
# this is extracted into its own method so it can be called multiple times (see end)
def handle_two_step_for_device(device_id)
# Request token to device
r = request(:put) do |req|
req.url("https://idmsa.apple.com/appleauth/auth/verify/device/#{device_id}/securitycode")
update_request_headers(req)
end
# we use `Spaceship::TunesClient.new.handle_itc_response`
# since this might be from the Dev Portal, but for 2 step
Spaceship::TunesClient.new.handle_itc_response(r.body)
puts("Successfully requested notification")
code = ask("Please enter the 4 digit code: ")
puts("Requesting session...")
# Send token to server to get a valid session
r = request(:post) do |req|
req.url("https://idmsa.apple.com/appleauth/auth/verify/phone/securitycode")
req.headers['Content-Type'] = 'application/json'
req.body = {
"phoneNumber": {
"id": device_id
},
"securityCode": {
"code" => code.to_s
},
"mode": "sms"
}.to_json
update_request_headers(req)
end
begin
Spaceship::TunesClient.new.handle_itc_response(r.body) # this will fail if the code is invalid
rescue => ex
# If the code was entered wrong
# {
# "securityCode": {
# "code": "1234"
# },
# "securityCodeLocked": false,
# "recoveryKeyLocked": false,
# "recoveryKeySupported": true,
# "manageTrustedDevicesLinkName": "appleid.apple.com",
# "suppressResend": false,
# "authType": "hsa",
# "accountLocked": false,
# "validationErrors": [{
# "code": "-21669",
# "title": "Incorrect Verification Code",
# "message": "Incorrect verification code."
# }]
# }
if ex.to_s.include?("verification code") # to have a nicer output
puts("Error: Incorrect verification code")
return handle_two_step_for_device(device_id)
end
raise ex
end
store_session
return true
end
def handle_two_factor(response, depth = 0)
if depth == 0
puts("Two-factor Authentication (6 digits code) is enabled for account '#{self.user}'")
puts("More information about Two-factor Authentication: https://support.apple.com/en-us/HT204915")
puts("")
two_factor_url = "https://github.com/fastlane/fastlane/tree/master/spaceship#2-step-verification"
puts("If you're running this in a non-interactive session (e.g. server or CI)")
puts("check out #{two_factor_url}")
end
# "verification code" has already be pushed to devices
security_code = response.body["securityCode"]
# "securityCode": {
# "length": 6,
# "tooManyCodesSent": false,
# "tooManyCodesValidated": false,
# "securityCodeLocked": false
# },
code_length = security_code["length"]
puts("")
env_2fa_sms_default_phone_number = ENV["SPACESHIP_2FA_SMS_DEFAULT_PHONE_NUMBER"]
if env_2fa_sms_default_phone_number
raise Tunes::Error.new, "Environment variable SPACESHIP_2FA_SMS_DEFAULT_PHONE_NUMBER is set, but empty." if env_2fa_sms_default_phone_number.empty?
puts("Environment variable `SPACESHIP_2FA_SMS_DEFAULT_PHONE_NUMBER` is set, automatically requesting 2FA token via SMS to that number")
puts("SPACESHIP_2FA_SMS_DEFAULT_PHONE_NUMBER = #{env_2fa_sms_default_phone_number}")
puts("")
phone_number = env_2fa_sms_default_phone_number
phone_id = phone_id_from_number(response.body["trustedPhoneNumbers"], phone_number)
push_mode = push_mode_from_number(response.body["trustedPhoneNumbers"], phone_number)
# don't request sms if no trusted devices and env default is the only trusted number,
# code was automatically sent
should_request_code = !sms_automatically_sent(response)
code_type = 'phone'
body = request_two_factor_code_from_phone(phone_id, phone_number, code_length, push_mode, should_request_code)
elsif sms_automatically_sent(response) # sms fallback, code was automatically sent
fallback_number = response.body["trustedPhoneNumbers"].first
phone_number = fallback_number["numberWithDialCode"]
phone_id = fallback_number["id"]
push_mode = fallback_number['pushMode']
code_type = 'phone'
body = request_two_factor_code_from_phone(phone_id, phone_number, code_length, push_mode, false)
elsif sms_fallback(response) # sms fallback but code wasn't sent bec > 1 phone number
code_type = 'phone'
body = request_two_factor_code_from_phone_choose(response.body["trustedPhoneNumbers"], code_length)
else
puts("(Input `sms` to escape this prompt and select a trusted phone number to send the code as a text message)")
puts("")
puts("(You can also set the environment variable `SPACESHIP_2FA_SMS_DEFAULT_PHONE_NUMBER` to automate this)")
puts("(Read more at: https://github.com/fastlane/fastlane/blob/master/spaceship/docs/Authentication.md#auto-select-sms-via-spaceship_2fa_sms_default_phone_number)")
puts("")
code = ask_for_2fa_code("Please enter the #{code_length} digit code:")
code_type = 'trusteddevice'
body = { "securityCode" => { "code" => code.to_s } }.to_json
# User exited by entering `sms` and wants to choose phone number for SMS
if code.casecmp?("sms")
code_type = 'phone'
body = request_two_factor_code_from_phone_choose(response.body["trustedPhoneNumbers"], code_length)
end
end
puts("Requesting session...")
# Send "verification code" back to server to get a valid session
r = request(:post) do |req|
req.url("https://idmsa.apple.com/appleauth/auth/verify/#{code_type}/securitycode")
req.headers['Content-Type'] = 'application/json'
req.body = body
update_request_headers(req)
end
begin
# we use `Spaceship::TunesClient.new.handle_itc_response`
# since this might be from the Dev Portal, but for 2 factor
Spaceship::TunesClient.new.handle_itc_response(r.body) # this will fail if the code is invalid
rescue => ex
# If the code was entered wrong
# {
# "service_errors": [{
# "code": "-21669",
# "title": "Incorrect Verification Code",
# "message": "Incorrect verification code."
# }],
# "hasError": true
# }
if ex.to_s.include?("verification code") # to have a nicer output
puts("Error: Incorrect verification code")
depth += 1
return handle_two_factor(response, depth)
end
raise ex
end
store_session
return true
end
# For reference in case auth behavior changes:
# The "noTrustedDevices" field is only present
# in the response for `GET /appleauth/auth`
# Account is not signed into any devices that can display a verification code
def sms_fallback(response)
response.body["noTrustedDevices"]
end
# see `sms_fallback` + account has only one trusted number for receiving an sms
def sms_automatically_sent(response)
(response.body["trustedPhoneNumbers"] || []).count == 1 && sms_fallback(response)
end
# extracted into its own method for testing
def ask_for_2fa_code(text)
ask(text)
end
# extracted into its own method for testing
def choose_phone_number(opts)
choose(*opts)
end
def phone_id_from_number(phone_numbers, phone_number)
phone_numbers.each do |phone|
return phone['id'] if match_phone_to_masked_phone(phone_number, phone['numberWithDialCode'])
end
# Handle case of phone_number not existing in phone_numbers because ENV var is wrong or matcher is broken
raise Tunes::Error.new, %(
Could not find a matching phone number to #{phone_number} in #{phone_numbers}.
Make sure your environment variable is set to the correct phone number.
If it is, please open an issue at https://github.com/fastlane/fastlane/issues/new and include this output so we can fix our matcher. Thanks.
)
end
def push_mode_from_number(phone_numbers, phone_number)
phone_numbers.each do |phone|
return phone['pushMode'] if match_phone_to_masked_phone(phone_number, phone['numberWithDialCode'])
end
# If no pushMode was supplied, assume sms
return "sms"
end
def match_phone_to_masked_phone(phone_number, masked_number)
characters_to_remove_from_phone_numbers = ' \-()"'
# start with e.g. +49 162 1234585 or +1-123-456-7866
phone_number = phone_number.tr(characters_to_remove_from_phone_numbers, '')
# cleaned: +491621234585 or +11234567866
# rubocop:disable Style/AsciiComments
# start with: +49 •••• •••••85 or +1 (•••) •••-••66
number_with_dialcode_masked = masked_number.tr(characters_to_remove_from_phone_numbers, '')
# cleaned: +49•••••••••85 or +1••••••••66
# rubocop:enable Style/AsciiComments
maskings_count = number_with_dialcode_masked.count('•') # => 9 or 8
pattern = /^([0-9+]{2,4})([•]{#{maskings_count}})([0-9]{2})$/
# following regex: range from maskings_count-2 because sometimes the masked number has 1 or 2 dots more than the actual number
# e.g. https://github.com/fastlane/fastlane/issues/14969
replacement = "\\1([0-9]{#{maskings_count - 2},#{maskings_count}})\\3"
number_with_dialcode_regex_part = number_with_dialcode_masked.gsub(pattern, replacement)
# => +49([0-9]{8,9})85 or +1([0-9]{7,8})66
backslash = '\\'
number_with_dialcode_regex_part = backslash + number_with_dialcode_regex_part
number_with_dialcode_regex = /^#{number_with_dialcode_regex_part}$/
# => /^\+49([0-9]{8})85$/ or /^\+1([0-9]{7,8})66$/
return phone_number =~ number_with_dialcode_regex
# +491621234585 matches /^\+49([0-9]{8})85$/
end
def phone_id_from_masked_number(phone_numbers, masked_number)
phone_numbers.each do |phone|
return phone['id'] if phone['numberWithDialCode'] == masked_number
end
end
def push_mode_from_masked_number(phone_numbers, masked_number)
phone_numbers.each do |phone|
return phone['pushMode'] if phone['numberWithDialCode'] == masked_number
end
# If no pushMode was supplied, assume sms
return "sms"
end
def request_two_factor_code_from_phone_choose(phone_numbers, code_length)
puts("Please select a trusted phone number to send code to:")
available = phone_numbers.collect do |current|
current['numberWithDialCode']
end
chosen = choose_phone_number(available)
phone_id = phone_id_from_masked_number(phone_numbers, chosen)
push_mode = push_mode_from_masked_number(phone_numbers, chosen)
request_two_factor_code_from_phone(phone_id, chosen, code_length, push_mode)
end
# this is used in two places: after choosing a phone number and when a phone number is set via ENV var
def request_two_factor_code_from_phone(phone_id, phone_number, code_length, push_mode = "sms", should_request_code = true)
if should_request_code
# Request code
r = request(:put) do |req|
req.url("https://idmsa.apple.com/appleauth/auth/verify/phone")
req.headers['Content-Type'] = 'application/json'
req.body = { "phoneNumber" => { "id" => phone_id }, "mode" => push_mode }.to_json
update_request_headers(req)
end
# we use `Spaceship::TunesClient.new.handle_itc_response`
# since this might be from the Dev Portal, but for 2 step
Spaceship::TunesClient.new.handle_itc_response(r.body)
puts("Successfully requested text message to #{phone_number}")
end
code = ask_for_2fa_code("Please enter the #{code_length} digit code you received at #{phone_number}:")
return { "securityCode" => { "code" => code.to_s }, "phoneNumber" => { "id" => phone_id }, "mode" => push_mode }.to_json
end
def store_session
# If the request was successful, r.body is actually nil
# The previous request will fail if the user isn't on a team
# on App Store Connect, but it still works, so we're good
# Tell iTC that we are trustworthy (obviously)
# This will update our local cookies to something new
# They probably have a longer time to live than the other poor cookies
# Changed Keys
# - myacinfo
# - DES5c148586dfd451e55afb0175f62418f91
# We actually only care about the DES value
request(:get) do |req|
req.url("https://idmsa.apple.com/appleauth/auth/2sv/trust")
update_request_headers(req)
end
# This request will fail if the user isn't added to a team on iTC
# However we don't really care, this request will still return the
# correct DES... cookie
self.store_cookie
end
# Responsible for setting all required header attributes for the requests
# to succeed
def update_request_headers(req)
req.headers["X-Apple-Id-Session-Id"] = @x_apple_id_session_id
req.headers["X-Apple-Widget-Key"] = self.itc_service_key
req.headers["Accept"] = "application/json"
req.headers["scnt"] = @scnt
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/response.rb | spaceship/lib/spaceship/connect_api/response.rb | require_relative './model'
module Spaceship
class ConnectAPI
class Response
include Enumerable
attr_reader :body
attr_reader :status
attr_reader :headers
attr_reader :client
def initialize(body: nil, status: nil, headers: nil, client: nil)
@body = body
@status = status
@headers = headers
@client = client
end
def next_url
return nil if body.nil?
links = body["links"] || {}
return links["next"]
end
def next_page(&block)
url = next_url
return nil if url.nil?
if block_given?
return yield(url)
else
return client.get(url)
end
end
def next_pages(count: 1, &block)
if !count.nil? && count < 0
count = 0
end
responses = [self]
counter = 0
resp = self
loop do
resp = resp.next_page(&block)
break if resp.nil?
responses << resp
counter += 1
break if !count.nil? && counter >= count
end
return responses
end
def all_pages(&block)
return next_pages(count: nil, &block)
end
def to_models
return [] if body.nil?
model_or_models = Spaceship::ConnectAPI::Models.parse(body)
return [model_or_models].flatten
end
def each(&block)
to_models.each do |model|
yield(model)
end
end
def all_pages_each(&block)
to_models.each do |model|
yield(model)
end
resp = self
loop do
resp = resp.next_page
break if resp.nil?
resp.each(&block)
end
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/token_refresh_middleware.rb | spaceship/lib/spaceship/connect_api/token_refresh_middleware.rb | require 'faraday'
require_relative 'token'
require_relative '../globals'
module Spaceship
class TokenRefreshMiddleware < Faraday::Middleware
def initialize(app, token)
@token = token
super(app)
end
def call(env)
if @token.expired?
puts("App Store Connect API token expired at #{@token.expiration}... refreshing") if Spaceship::Globals.verbose?
@token.refresh!
end
env.request_headers["Authorization"] = "Bearer #{@token.text}"
@app.call(env)
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/spaceship.rb | spaceship/lib/spaceship/connect_api/spaceship.rb | require_relative './client'
require_relative './testflight/testflight'
module Spaceship
class ConnectAPI
class << self
# This client stores the global client when using the lazy syntax
attr_accessor :client
# Forward class calls to the global client
# This is implemented for backwards compatibility
extend(Forwardable)
def_delegators(:client, *Spaceship::ConnectAPI::Provisioning::API.instance_methods(false))
def_delegators(:client, *Spaceship::ConnectAPI::TestFlight::API.instance_methods(false))
def_delegators(:client, *Spaceship::ConnectAPI::Tunes::API.instance_methods(false))
def_delegators(:client, *Spaceship::ConnectAPI::Users::API.instance_methods(false))
def client
# Always look for a client set explicitly by the client first
return @client if @client
# A client may not always be explicitly set (specially when running tools like match, sigh, pilot, etc)
# In that case, create a new client based on existing sessions
# Note: This does not perform logins on the user. It is only reusing the cookies and selected teams
return nil if Spaceship::Tunes.client.nil? && Spaceship::Portal.client.nil?
implicit_client = ConnectAPI::Client.new(tunes_client: Spaceship::Tunes.client, portal_client: Spaceship::Portal.client)
return implicit_client
end
def token=(token)
@client = ConnectAPI::Client.new(token: token)
end
def token
return nil if @client.nil?
return @client.token
end
def token?
(@client && @client.token)
end
# Initializes client with Apple's App Store Connect JWT auth key.
#
# This method will automatically use the arguments from environment
# variables if not given.
#
# The key_id, issuer_id and either filepath or key are needed to authenticate.
#
# @param key_id (String) (optional): The key id
# @param issuer_id (String) (optional): The issuer id
# @param filepath (String) (optional): The filepath
# @param key (String) (optional): The key
# @param duration (Integer) (optional): How long this session should last
# @param in_house (Boolean) (optional): Whether this session is an Enterprise one
#
# @raise InvalidUserCredentialsError: raised if authentication failed
#
# @return (Spaceship::ConnectAPI::Client) The client the login method was called for
def auth(key_id: nil, issuer_id: nil, filepath: nil, key: nil, duration: nil, in_house: nil)
@client = ConnectAPI::Client.auth(key_id: key_id, issuer_id: issuer_id, filepath: filepath, key: key, duration: duration, in_house: in_house)
end
# Authenticates with Apple's web services. This method has to be called once
# to generate a valid session.
#
# This method will automatically use the username from the Appfile (if available)
# and fetch the password from the Keychain (if available)
#
# @param user (String) (optional): The username (usually the email address)
# @param password (String) (optional): The password
# @param use_portal (Boolean) (optional): Whether to log in to Spaceship::Portal or not
# @param use_tunes (Boolean) (optional): Whether to log in to Spaceship::Tunes or not
# @param portal_team_id (String) (optional): The Spaceship::Portal team id
# @param tunes_team_id (String) (optional): The Spaceship::Tunes team id
# @param team_name (String) (optional): The team name
# @param skip_select_team (Boolean) (optional): Whether to skip automatic selection or prompt for team
#
# @raise InvalidUserCredentialsError: raised if authentication failed
#
# @return (Spaceship::ConnectAPI::Client) The client the login method was called for
def login(user = nil, password = nil, use_portal: true, use_tunes: true, portal_team_id: nil, tunes_team_id: nil, team_name: nil, skip_select_team: false)
@client = ConnectAPI::Client.login(user, password, use_portal: use_portal, use_tunes: use_tunes, portal_team_id: portal_team_id, tunes_team_id: tunes_team_id, team_name: team_name, skip_select_team: skip_select_team)
end
# Open up the team selection for the user (if necessary).
#
# If the user is in multiple teams, a team selection is shown.
# The user can then select a team by entering the number
#
# @param portal_team_id (String) (optional): The Spaceship::Portal team id
# @param tunes_team_id (String) (optional): The Spaceship::Tunes team id
# @param team_name (String) (optional): The name of an App Store Connect team
def select_team(portal_team_id: nil, tunes_team_id: nil, team_name: nil)
return if client.nil?
client.select_team(portal_team_id: portal_team_id, tunes_team_id: tunes_team_id, team_name: team_name)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/client.rb | spaceship/lib/spaceship/connect_api/client.rb | require_relative './token'
require_relative './provisioning/provisioning'
require_relative './testflight/testflight'
require_relative './tunes/tunes'
require_relative './users/users'
module Spaceship
class ConnectAPI
class Client
attr_accessor :token
attr_accessor :tunes_client
attr_accessor :portal_client
# Initializes client with Apple's App Store Connect JWT auth key.
#
# This method will automatically use the arguments from environment
# variables if not given.
#
# The key_id, issuer_id and either filepath or key are needed to authenticate.
#
# @param key_id (String) (optional): The key id
# @param issuer_id (String) (optional): The issuer id
# @param filepath (String) (optional): The filepath
# @param key (String) (optional): The key
# @param duration (Integer) (optional): How long this session should last
# @param in_house (Boolean) (optional): Whether this session is an Enterprise one
#
# @raise InvalidUserCredentialsError: raised if authentication failed
#
# @return (Spaceship::ConnectAPI::Client) The client the login method was called for
def self.auth(key_id: nil, issuer_id: nil, filepath: nil, key: nil, duration: nil, in_house: nil)
token = Spaceship::ConnectAPI::Token.create(key_id: key_id, issuer_id: issuer_id, filepath: filepath, key: key, duration: duration, in_house: in_house)
return ConnectAPI::Client.new(token: token)
end
# Authenticates with Apple's web services. This method has to be called once
# to generate a valid session.
#
# This method will automatically use the username from the Appfile (if available)
# and fetch the password from the Keychain (if available)
#
# @param user (String) (optional): The username (usually the email address)
# @param password (String) (optional): The password
# @param use_portal (Boolean) (optional): Whether to log in to Spaceship::Portal or not
# @param use_tunes (Boolean) (optional): Whether to log in to Spaceship::Tunes or not
# @param portal_team_id (String) (optional): The Spaceship::Portal team id
# @param tunes_team_id (String) (optional): The Spaceship::Tunes team id
# @param team_name (String) (optional): The team name
# @param skip_select_team (Boolean) (optional): Whether to skip automatic selection or prompt for team
#
# @raise InvalidUserCredentialsError: raised if authentication failed
#
# @return (Spaceship::ConnectAPI::Client) The client the login method was called for
def self.login(user = nil, password = nil, use_portal: true, use_tunes: true, portal_team_id: nil, tunes_team_id: nil, team_name: nil, skip_select_team: false)
portal_client = Spaceship::Portal.login(user, password) if use_portal
tunes_client = Spaceship::Tunes.login(user, password) if use_tunes
unless skip_select_team
# Check if environment variables are set for Spaceship::Portal or Spaceship::Tunes to select team
portal_team_id ||= ENV['FASTLANE_TEAM_ID']
portal_team_name = team_name || ENV['FASTLANE_TEAM_NAME']
tunes_team_id ||= ENV['FASTLANE_ITC_TEAM_ID']
tunes_team_name = team_name || ENV['FASTLANE_ITC_TEAM_NAME']
# The clients will prompt for a team selection if:
# 1. client exists
# 2. team_id and team_name are nil and user belongs to multiple teams
portal_client.select_team(team_id: portal_team_id, team_name: portal_team_name) if portal_client
tunes_client.select_team(team_id: tunes_team_id, team_name: tunes_team_name) if tunes_client
end
return ConnectAPI::Client.new(tunes_client: tunes_client, portal_client: portal_client)
end
def initialize(cookie: nil, current_team_id: nil, token: nil, tunes_client: nil, portal_client: nil)
@token = token
# If using web session...
# Spaceship::Tunes is needed for TestFlight::API, Tunes::API, and Users::API
# Spaceship::Portal is needed for Provisioning::API
@tunes_client = tunes_client
@portal_client = portal_client
# Extending this instance to add API endpoints from these modules
# Each of these modules adds a new setter method for an instance
# of an ConnectAPI::APIClient
# These get set in set_individual_clients
self.extend(Spaceship::ConnectAPI::TestFlight::API)
self.extend(Spaceship::ConnectAPI::Tunes::API)
self.extend(Spaceship::ConnectAPI::Provisioning::API)
self.extend(Spaceship::ConnectAPI::Users::API)
set_individual_clients(
cookie: cookie,
current_team_id: current_team_id,
token: token,
tunes_client: @tunes_client,
portal_client: @portal_client
)
end
def portal_team_id
if token
message = [
"Cannot determine portal team id via the App Store Connect API (yet)",
"Look to see if you can get the portal team id from somewhere else",
"View more info in the docs at https://docs.fastlane.tools/app-store-connect-api/"
]
raise message.join('. ')
elsif @portal_client
return @portal_client.team_id
else
raise "No App Store Connect API token or Portal Client set"
end
end
def tunes_team_id
return nil if @tunes_client.nil?
return @tunes_client.team_id
end
def portal_teams
return nil if @portal_client.nil?
return @portal_client.teams
end
def tunes_teams
return nil if @tunes_client.nil?
return @tunes_client.teams
end
def in_house?
if token
if token.in_house.nil?
message = [
"Cannot determine if team is App Store or Enterprise via the App Store Connect API (yet)",
"Set 'in_house' on your Spaceship::ConnectAPI::Token",
"Or set 'in_house' in your App Store Connect API key JSON file",
"Or set the 'SPACESHIP_CONNECT_API_IN_HOUSE' environment variable to 'true'",
"View more info in the docs at https://docs.fastlane.tools/app-store-connect-api/"
]
raise message.join('. ')
end
return !!token.in_house
elsif @portal_client
return @portal_client.in_house?
else
raise "No App Store Connect API token or Portal Client set"
end
end
def select_team(portal_team_id: nil, tunes_team_id: nil, team_name: nil)
@portal_client.select_team(team_id: portal_team_id, team_name: team_name) unless @portal_client.nil?
@tunes_client.select_team(team_id: tunes_team_id, team_name: team_name) unless @tunes_client.nil?
# Updating the tunes and portal clients requires resetting
# of the clients in the API modules
set_individual_clients(
cookie: nil,
current_team_id: nil,
token: nil,
tunes_client: tunes_client,
portal_client: portal_client
)
end
private
def set_individual_clients(cookie: nil, current_team_id: nil, token: nil, tunes_client: nil, portal_client: nil)
# This was added by Spaceship::ConnectAPI::TestFlight::API and is required
# to be set for API methods to have a client to send request on
if cookie || token || tunes_client
self.test_flight_request_client = Spaceship::ConnectAPI::TestFlight::Client.new(
cookie: cookie,
current_team_id: current_team_id,
token: token,
another_client: tunes_client
)
end
# This was added by Spaceship::ConnectAPI::Tunes::API and is required
# to be set for API methods to have a client to send request on
if cookie || token || tunes_client
self.tunes_request_client = Spaceship::ConnectAPI::Tunes::Client.new(
cookie: cookie,
current_team_id: current_team_id,
token: token,
another_client: tunes_client
)
end
# This was added by Spaceship::ConnectAPI::Provisioning::API and is required
# to be set for API methods to have a client to send request on
if cookie || token || portal_client
self.provisioning_request_client = Spaceship::ConnectAPI::Provisioning::Client.new(
cookie: cookie,
current_team_id: current_team_id,
token: token,
another_client: portal_client
)
end
# This was added by Spaceship::ConnectAPI::Users::API and is required
# to be set for API methods to have a client to send request on
if cookie || token || tunes_client
self.users_request_client = Spaceship::ConnectAPI::Users::Client.new(
cookie: cookie,
current_team_id: current_team_id,
token: token,
another_client: tunes_client
)
end
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/token.rb | spaceship/lib/spaceship/connect_api/token.rb | require 'jwt'
require 'base64'
require 'openssl'
# extract pem from .p8
# openssl pkcs8 -topk8 -outform PEM -in AuthKey.p8 -out key.pem -nocrypt
# compute public key
# openssl ec -in key.pem -pubout -out public_key.pem -aes256
module Spaceship
class ConnectAPI
class Token
# maximum expiration supported by AppStore (20 minutes)
MAX_TOKEN_DURATION = 1200
DEFAULT_TOKEN_DURATION = 500
attr_reader :key_id
attr_reader :issuer_id
attr_reader :text
attr_reader :duration
attr_reader :expiration
attr_reader :key_raw
# Temporary attribute not needed to create the JWT text
# There is no way to determine if the team associated with this
# key is for App Store or Enterprise so this is the temporary workaround
attr_accessor :in_house
def self.from(hash: nil, filepath: nil)
# FIXME: Ensure `in_house` value is a boolean.
api_token ||= self.create(**hash.transform_keys(&:to_sym)) if hash
api_token ||= self.from_json_file(filepath) if filepath
return api_token
end
def self.from_json_file(filepath)
json = JSON.parse(File.read(filepath), { symbolize_names: true })
missing_keys = []
missing_keys << 'key_id' unless json.key?(:key_id)
missing_keys << 'key' unless json.key?(:key)
unless missing_keys.empty?
raise "App Store Connect API key JSON is missing field(s): #{missing_keys.join(', ')}"
end
self.create(**json)
end
def self.create(key_id: nil, issuer_id: nil, filepath: nil, key: nil, is_key_content_base64: false, duration: nil, in_house: nil, **)
key_id ||= ENV['SPACESHIP_CONNECT_API_KEY_ID']
issuer_id ||= ENV['SPACESHIP_CONNECT_API_ISSUER_ID']
filepath ||= ENV['SPACESHIP_CONNECT_API_KEY_FILEPATH']
duration ||= ENV['SPACESHIP_CONNECT_API_TOKEN_DURATION']
in_house_env = ENV['SPACESHIP_CONNECT_API_IN_HOUSE']
in_house ||= !["", "no", "false", "off", "0"].include?(in_house_env) if in_house_env
key ||= ENV['SPACESHIP_CONNECT_API_KEY']
key ||= File.binread(filepath)
if !key.nil? && is_key_content_base64
key = Base64.decode64(key)
end
self.new(
key_id: key_id,
issuer_id: issuer_id,
key: OpenSSL::PKey::EC.new(key),
key_raw: key,
duration: duration,
in_house: in_house
)
end
def initialize(key_id: nil, issuer_id: nil, key: nil, key_raw: nil, duration: nil, in_house: nil)
@key_id = key_id
@key = key
@key_raw = key_raw
@issuer_id = issuer_id
@duration = duration
@in_house = in_house
@duration ||= DEFAULT_TOKEN_DURATION
@duration = @duration.to_i if @duration
refresh!
end
def refresh!
now = Time.now
@expiration = now + @duration
header = {
kid: key_id,
typ: 'JWT'
}
payload = {
# Reduce the issued-at-time in case our time is slighly ahead of Apple's servers, which causes the token to be rejected.
iat: now.to_i - 60,
exp: @expiration.to_i,
aud: @in_house ? 'apple-developer-enterprise-v1' : 'appstoreconnect-v1'
}
if issuer_id
payload[:iss] = issuer_id
else
# Consider the key as individual key.
# https://developer.apple.com/documentation/appstoreconnectapi/generating_tokens_for_api_requests#4313913
payload[:sub] = 'user'
end
@text = JWT.encode(payload, @key, 'ES256', header)
end
def expired?
@expiration < Time.now
end
def write_key_to_file(path)
File.open(path, 'w') { |f| f.write(@key_raw) }
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/api_client.rb | spaceship/lib/spaceship/connect_api/api_client.rb |
require_relative '../client'
require_relative './response'
require_relative '../client'
require_relative './response'
require_relative './token_refresh_middleware'
require_relative '../stats_middleware'
module Spaceship
class ConnectAPI
class APIClient < Spaceship::Client
attr_accessor :token
#####################################################
# @!group Client Init
#####################################################
# Instantiates a client with cookie session or a JWT token.
def initialize(cookie: nil, current_team_id: nil, token: nil, csrf_tokens: nil, another_client: nil)
params_count = [cookie, token, another_client].compact.size
if params_count != 1
raise "Must initialize with one of :cookie, :token, or :another_client"
end
if token.nil?
if another_client.nil?
super(cookie: cookie, current_team_id: current_team_id, csrf_tokens: csrf_tokens, timeout: 1200)
return
end
super(cookie: another_client.instance_variable_get(:@cookie), current_team_id: another_client.team_id, csrf_tokens: another_client.csrf_tokens)
else
options = {
request: {
timeout: (ENV["SPACESHIP_TIMEOUT"] || 300).to_i,
open_timeout: (ENV["SPACESHIP_TIMEOUT"] || 300).to_i
}
}
@token = token
@current_team_id = current_team_id
@client = Faraday.new(hostname, options) do |c|
c.response(:json, content_type: /\bjson$/)
c.response(:plist, content_type: /\bplist$/)
c.use(FaradayMiddleware::RelsMiddleware)
c.use(Spaceship::StatsMiddleware)
c.use(Spaceship::TokenRefreshMiddleware, token)
c.adapter(Faraday.default_adapter)
if ENV['SPACESHIP_DEBUG']
# for debugging only
# This enables tracking of networking requests using Charles Web Proxy
c.proxy = "https://127.0.0.1:8888"
c.ssl[:verify_mode] = OpenSSL::SSL::VERIFY_NONE
elsif ENV["SPACESHIP_PROXY"]
c.proxy = ENV["SPACESHIP_PROXY"]
c.ssl[:verify_mode] = OpenSSL::SSL::VERIFY_NONE if ENV["SPACESHIP_PROXY_SSL_VERIFY_NONE"]
end
if ENV["DEBUG"]
puts("To run spaceship through a local proxy, use SPACESHIP_DEBUG")
end
end
end
end
# Instance level hostname only used when creating
# App Store Connect API Faraday client.
# Forwarding to class level if using web session.
def hostname
if @token
return @token.in_house ? "https://api.enterprise.developer.apple.com/" : "https://api.appstoreconnect.apple.com/"
end
return self.class.hostname
end
def self.hostname
# Implemented in subclass
not_implemented(__method__)
end
#
# Helpers
#
def web_session?
return @token.nil?
end
def build_params(filter: nil, includes: nil, fields: nil, limit: nil, sort: nil, cursor: nil)
params = {}
filter = filter.delete_if { |k, v| v.nil? } if filter
params[:filter] = filter if filter && !filter.empty?
params[:include] = includes if includes
params[:fields] = fields if fields
params[:limit] = limit if limit
params[:sort] = sort if sort
params[:cursor] = cursor if cursor
return params
end
def get(url_or_path, params = nil)
response = with_asc_retry do
request(:get) do |req|
req.url(url_or_path)
req.options.params_encoder = Faraday::NestedParamsEncoder
req.params = params if params
req.headers['Content-Type'] = 'application/json'
end
end
handle_response(response)
end
def post(url_or_path, body, tries: 5)
response = with_asc_retry(tries) do
request(:post) do |req|
req.url(url_or_path)
req.body = body.to_json
req.headers['Content-Type'] = 'application/json'
end
end
handle_response(response)
end
def patch(url_or_path, body)
response = with_asc_retry do
request(:patch) do |req|
req.url(url_or_path)
req.body = body.to_json
req.headers['Content-Type'] = 'application/json'
end
end
handle_response(response)
end
def delete(url_or_path, params = nil, body = nil)
response = with_asc_retry do
request(:delete) do |req|
req.url(url_or_path)
req.options.params_encoder = Faraday::NestedParamsEncoder if params
req.params = params if params
req.body = body.to_json if body
req.headers['Content-Type'] = 'application/json' if body
end
end
handle_response(response)
end
protected
class TimeoutRetryError < StandardError
def initialize(msg)
super
end
end
class TooManyRequestsError < StandardError
def initialize(msg)
super
end
end
def with_asc_retry(tries = 5, backoff = 1, &_block)
response = yield
status = response.status if response
if [500, 504].include?(status)
msg = "Timeout received! Retrying after 3 seconds (remaining: #{tries})..."
raise TimeoutRetryError, msg
end
if status == 429
raise TooManyRequestsError, "Too many requests, backing off #{backoff} seconds"
end
return response
rescue UnauthorizedAccessError => error
tries -= 1
puts(error) if Spaceship::Globals.verbose?
if tries.zero?
raise error
else
msg = "Token has expired, issued-at-time is in the future, or has been revoked! Trying to refresh..."
puts(msg) if Spaceship::Globals.verbose?
@token.refresh!
retry
end
rescue TimeoutRetryError => error
tries -= 1
puts(error) if Spaceship::Globals.verbose?
if tries.zero?
return response
else
retry
end
rescue TooManyRequestsError => error
if backoff > 3600
raise TooManyRequestsError, "Too many requests, giving up after backing off for > 3600 seconds."
end
puts(error) if Spaceship::Globals.verbose?
Kernel.sleep(backoff)
backoff *= 2
retry
end
def handle_response(response)
if (200...300).cover?(response.status) && (response.body.nil? || response.body.empty?)
return
end
raise InternalServerError, "Server error got #{response.status}" if (500...600).cover?(response.status)
unless response.body.kind_of?(Hash)
raise UnexpectedResponse, response.body
end
raise UnexpectedResponse, response.body['error'] if response.body['error']
raise UnexpectedResponse, format_errors(response) if response.body['errors']
raise UnexpectedResponse, "Temporary App Store Connect error: #{response.body}" if response.body['statusCode'] == 'ERROR'
store_csrf_tokens(response)
return Spaceship::ConnectAPI::Response.new(body: response.body, status: response.status, headers: response.headers, client: self)
end
# Overridden from Spaceship::Client
def handle_error(response)
body = response.body.empty? ? {} : response.body
# Setting body nil if invalid JSON which can happen if 502
begin
body = JSON.parse(body) if body.kind_of?(String)
rescue
nil
end
case response.status.to_i
when 401
raise UnauthorizedAccessError, format_errors(response)
when 403
error = (body['errors'] || []).first || {}
error_code = error['code']
if error_code == "FORBIDDEN.REQUIRED_AGREEMENTS_MISSING_OR_EXPIRED"
raise ProgramLicenseAgreementUpdated, format_errors(response)
else
raise AccessForbiddenError, format_errors(response)
end
when 502
# Issue - https://github.com/fastlane/fastlane/issues/19264
# This 502 with "Could not process this request" body sometimes
# work and sometimes doesn't
# Usually retrying once or twice will solve the issue
if body && body.include?("Could not process this request")
raise BadGatewayError, "Could not process this request"
end
end
end
def format_errors(response)
# Example error format
# {
# "errors":[
# {
# "id":"cbfd8674-4802-4857-bfe8-444e1ea36e32",
# "status":"409",
# "code":"STATE_ERROR",
# "title":"The request cannot be fulfilled because of the state of another resource.",
# "detail":"Submit for review errors found.",
# "meta":{
# "associatedErrors":{
# "/v1/appScreenshots/":[
# {
# "id":"23d1734f-b81f-411a-98e4-6d3e763d54ed",
# "status":"409",
# "code":"STATE_ERROR.SCREENSHOT_REQUIRED.APP_WATCH_SERIES_4",
# "title":"App screenshot missing (APP_WATCH_SERIES_4)."
# },
# {
# "id":"db993030-0a93-48e9-9fd7-7e5676633431",
# "status":"409",
# "code":"STATE_ERROR.SCREENSHOT_REQUIRED.APP_WATCH_SERIES_4",
# "title":"App screenshot missing (APP_WATCH_SERIES_4)."
# }
# ],
# "/v1/builds/d710b6fa-5235-4fe4-b791-2b80d6818db0":[
# {
# "id":"e421fe6f-0e3b-464b-89dc-ba437e7bb77d",
# "status":"409",
# "code":"ENTITY_ERROR.ATTRIBUTE.REQUIRED",
# "title":"The provided entity is missing a required attribute",
# "detail":"You must provide a value for the attribute 'usesNonExemptEncryption' with this request",
# "source":{
# "pointer":"/data/attributes/usesNonExemptEncryption"
# }
# }
# ]
# }
# }
# }
# ]
# }
# Detail is missing in this response making debugging super hard
# {"errors" =>
# [
# {
# "id"=>"80ea6cff-0043-4543-9cd1-3e26b0fce383",
# "status"=>"409",
# "code"=>"ENTITY_ERROR.RELATIONSHIP.INVALID",
# "title"=>"The provided entity includes a relationship with an invalid value",
# "source"=>{
# "pointer"=>"/data/relationships/primarySubcategoryOne"
# }
# }
# ]
# }
# Membership expired
# {
# "errors" : [
# {
# "id" : "UUID",
# "status" : "403",
# "code" : "FORBIDDEN_ERROR",
# "title" : "This request is forbidden for security reasons",
# "detail" : "Team ID: 'ID' is not associated with an active membership. To check your teams membership status, sign in your account on the developer website. https://developer.apple.com/account/"
# }
# ]
# }
body = response.body.empty? ? {} : response.body
body = JSON.parse(body) if body.kind_of?(String)
formatted_errors = (body['errors'] || []).map do |error|
messages = [[error['title'], error['detail'], error.dig("source", "pointer")].compact.join(" - ")]
meta = error["meta"] || {}
associated_errors = meta["associatedErrors"] || {}
messages + associated_errors.values.flatten.map do |associated_error|
[[associated_error["title"], associated_error["detail"]].compact.join(" - ")]
end
end.flatten.join("\n")
if formatted_errors.empty?
formatted_errors << "Unknown error"
end
return formatted_errors
end
private
def local_variable_get(binding, name)
if binding.respond_to?(:local_variable_get)
binding.local_variable_get(name)
else
binding.eval(name.to_s)
end
end
def provider_id
return team_id if self.provider.nil?
self.provider.provider_id
end
end
end
# rubocop:enable Metrics/ClassLength
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/file_uploader.rb | spaceship/lib/spaceship/connect_api/file_uploader.rb | require 'faraday' # HTTP Client
require 'faraday-cookie_jar'
require 'faraday_middleware'
require 'spaceship/globals'
require 'openssl'
module Spaceship
class ConnectAPI
module FileUploader
def self.upload(upload_operations, bytes)
# {
# "method": "PUT",
# "url": "https://some-url-apple-gives-us",
# "length": 57365,
# "offset": 0,
# "requestHeaders": [
# {
# "name": "Content-Type",
# "value": "image/png"
# }
# ]
# }
upload_operations.each_with_index do |upload_operation, index|
headers = {}
upload_operation["requestHeaders"].each do |hash|
headers[hash["name"]] = hash["value"]
end
offset = upload_operation["offset"]
length = upload_operation["length"]
puts("Uploading file (part #{index + 1})...") if Spaceship::Globals.verbose?
with_retry do
client.send(
upload_operation["method"].downcase,
upload_operation["url"],
bytes[offset, length],
headers
)
end
end
puts("Uploading complete!") if Spaceship::Globals.verbose?
end
def self.with_retry(tries = 5, &_block)
tries = 1 if Object.const_defined?("SpecHelper")
response = yield
tries -= 1
unless (200...300).cover?(response.status)
msg = "Received status of #{response.status}! Retrying after 3 seconds (remaining: #{tries})..."
raise msg
end
return response
rescue => error
puts(error) if Spaceship::Globals.verbose?
if tries.zero?
raise "Failed to upload file after retries... Received #{response.status}"
else
retry
end
end
def self.client
options = {
request: {
timeout: (ENV["SPACESHIP_TIMEOUT"] || 300).to_i,
open_timeout: (ENV["SPACESHIP_TIMEOUT"] || 300).to_i
}
}
@client ||= Faraday.new(options) do |c|
c.response(:json, content_type: /\bjson$/)
c.response(:plist, content_type: /\bplist$/)
c.adapter(Faraday.default_adapter)
if ENV['SPACESHIP_DEBUG']
# for debugging only
# This enables tracking of networking requests using Charles Web Proxy
c.proxy = "https://127.0.0.1:8888"
c.ssl[:verify_mode] = OpenSSL::SSL::VERIFY_NONE
elsif ENV["SPACESHIP_PROXY"]
c.proxy = ENV["SPACESHIP_PROXY"]
c.ssl[:verify_mode] = OpenSSL::SSL::VERIFY_NONE if ENV["SPACESHIP_PROXY_SSL_VERIFY_NONE"]
end
if ENV["DEBUG"]
puts("To run spaceship through a local proxy, use SPACESHIP_DEBUG")
end
end
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/model.rb | spaceship/lib/spaceship/connect_api/model.rb | module Spaceship
class ConnectAPI
module Model
def self.included(base)
Spaceship::ConnectAPI::Models.types ||= []
Spaceship::ConnectAPI::Models.types << base
base.extend(Spaceship::ConnectAPI::Model)
end
attr_accessor :id
attr_accessor :reverse_attr_map
def initialize(id, attributes)
self.id = id
update_attributes(attributes)
end
def update_attributes(attributes)
(attributes || []).each do |key, value|
method = "#{key}=".to_sym
self.send(method, value) if self.respond_to?(method)
end
end
#
# Example:
# { "minOsVersion" => "min_os_version" }
#
# Creates attr_write and attr_reader for :min_os_version
# Creates alias for :minOsVersion to :min_os_version
#
def attr_mapping(attr_map)
self.reverse_attr_map ||= attr_map.invert.transform_keys(&:to_sym)
attr_map.each do |key, value|
# Actual
reader = value.to_sym
writer = "#{value}=".to_sym
has_reader = instance_methods.include?(reader)
has_writer = instance_methods.include?(writer)
send(:attr_reader, value) unless has_reader
send(:attr_writer, value) unless has_writer
# Alias
key_reader = key.to_sym
key_writer = "#{key}=".to_sym
# Alias the API response name to attribute name
alias_method(key_reader, reader)
alias_method(key_writer, writer)
end
end
def reverse_attr_mapping(attributes)
return nil if attributes.nil?
# allows for getting map from either an instance or class execution
map = self.reverse_attr_map || self.class.reverse_attr_map
attributes.each_with_object({}) do |(k, v), memo|
key = map[k.to_sym] || k.to_sym
memo[key] = v
end
end
def to_json(*options)
instance_variables.map do |var|
[var.to_s[1..-1], instance_variable_get(var)]
end.to_h.to_json(*options)
end
end
module Models
class << self
attr_accessor :types
attr_accessor :types_cache
end
def self.parse(json)
data = json["data"]
raise "No data" unless data
included = json["included"] || []
if data.kind_of?(Hash)
inflate_model(data, included)
elsif data.kind_of?(Array)
return data.map do |model_data|
inflate_model(model_data, included)
end
else
raise "'data' is neither a hash nor an array"
end
end
def self.find_class(model_data)
# Initialize cache
@types_cache ||= {}
# Find class in cache
type_string = model_data["type"]
type_class = @types_cache[type_string]
return type_class if type_class
# Find class in array
type_class = @types.find do |type|
type.type == type_string
end
# Cache and return class
@types_cache[type_string] = type_class
return type_class
end
def self.inflate_model(model_data, included)
# Find class
type_class = find_class(model_data)
raise "No type class found for #{model_data['type']}" unless type_class
# Get id and attributes needed for inflating
id = model_data["id"]
attributes = model_data["attributes"]
# Instantiate object and inflate relationships
relationships = model_data["relationships"] || []
type_instance = type_class.new(id, attributes)
type_instance = inflate_model_relationships(type_instance, relationships, included)
return type_instance
end
def self.inflate_model_relationships(type_instance, relationships, included)
# Relationship attributes to set
attributes = {}
# 1. Iterate over relationships
# 2. Find id and type
# 3. Find matching id and type in included
# 4. Inflate matching data and set in attributes
relationships.each do |key, value|
# Validate data exists
value_data_or_datas = value["data"]
next unless value_data_or_datas
# Map an included data object
map_data = lambda do |value_data|
id = value_data["id"]
type = value_data["type"]
relationship_data = included.find do |included_data|
id == included_data["id"] && type == included_data["type"]
end
inflate_model(relationship_data, included) if relationship_data
end
# Map a hash or an array of data
if value_data_or_datas.kind_of?(Hash)
attributes[key] = map_data.call(value_data_or_datas)
elsif value_data_or_datas.kind_of?(Array)
attributes[key] = value_data_or_datas.map(&map_data)
end
end
type_instance.update_attributes(attributes)
return type_instance
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/provisioning/client.rb | spaceship/lib/spaceship/connect_api/provisioning/client.rb | require_relative '../api_client'
require_relative './provisioning'
require_relative '../../portal/portal_client'
module Spaceship
class ConnectAPI
module Provisioning
class Client < Spaceship::ConnectAPI::APIClient
def initialize(cookie: nil, current_team_id: nil, token: nil, another_client: nil)
another_client ||= Spaceship::Portal.client if cookie.nil? && token.nil?
super(cookie: cookie, current_team_id: current_team_id, token: token, another_client: another_client)
self.extend(Spaceship::ConnectAPI::Provisioning::API)
self.provisioning_request_client = self
end
def self.hostname
'https://developer.apple.com/services-account/'
end
#
# Helpers
#
def get(url_or_path, params = nil)
# The Provisioning App Store Connect API needs to be proxied through a
# POST request if using web session
return proxy_get(url_or_path, params) if web_session?
super(url_or_path, params)
end
def post(url_or_path, body)
# The Provisioning App Store Connect API needs teamId added to the body of
# each post if using web session
return proxy_post(url_or_path, body) if web_session?
super(url_or_path, body)
end
def delete(url_or_path, params = nil)
# The Provisioning App Store Connect API needs to be proxied through a
# POST request if using web session
return proxy_delete(url_or_path, params) if web_session?
super(url_or_path, params)
end
def proxy_get(url_or_path, params = nil)
encoded_params = Faraday::NestedParamsEncoder.encode(params)
body = { "urlEncodedQueryParams" => encoded_params, "teamId" => team_id }
response = request(:post) do |req|
req.url(url_or_path)
req.body = body.to_json
req.headers['Content-Type'] = 'application/vnd.api+json'
req.headers['X-HTTP-Method-Override'] = 'GET'
req.headers['X-Requested-With'] = 'XMLHttpRequest'
end
handle_response(response)
end
def proxy_post(url_or_path, body)
body[:data][:attributes][:teamId] = team_id
response = request(:post) do |req|
req.url(url_or_path)
req.body = body.to_json
req.headers['Content-Type'] = 'application/vnd.api+json'
req.headers['X-Requested-With'] = 'XMLHttpRequest'
end
handle_response(response)
end
def proxy_delete(url_or_path, params = nil)
encoded_params = Faraday::NestedParamsEncoder.encode(params)
body = { "urlEncodedQueryParams" => encoded_params, "teamId" => team_id }
response = request(:post) do |req|
req.url(url_or_path)
req.body = body.to_json
req.headers['Content-Type'] = 'application/vnd.api+json'
req.headers['X-HTTP-Method-Override'] = 'DELETE'
req.headers['X-Requested-With'] = 'XMLHttpRequest'
end
handle_response(response)
end
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/provisioning/provisioning.rb | spaceship/lib/spaceship/connect_api/provisioning/provisioning.rb | require 'spaceship/connect_api/provisioning/client'
module Spaceship
class ConnectAPI
module Provisioning
module API
module Version
V1 = "v1"
end
def provisioning_request_client=(provisioning_request_client)
@provisioning_request_client = provisioning_request_client
end
def provisioning_request_client
return @provisioning_request_client if @provisioning_request_client
raise TypeError, "You need to instantiate this module with provisioning_request_client"
end
#
# bundleIds
#
def get_bundle_ids(filter: {}, includes: nil, fields: nil, limit: nil, sort: nil)
params = provisioning_request_client.build_params(filter: filter, includes: includes, fields: fields, limit: limit, sort: sort)
provisioning_request_client.get("#{Version::V1}/bundleIds", params)
end
def get_bundle_id(bundle_id_id: {}, includes: nil)
params = provisioning_request_client.build_params(filter: nil, includes: includes, limit: nil, sort: nil)
provisioning_request_client.get("#{Version::V1}/bundleIds/#{bundle_id_id}", params)
end
def post_bundle_id(name:, platform:, identifier:, seed_id:)
attributes = {
name: name,
platform: platform,
identifier: identifier,
seedId: seed_id
}
body = {
data: {
attributes: attributes,
type: "bundleIds"
}
}
provisioning_request_client.post("#{Version::V1}/bundleIds", body)
end
#
# bundleIdCapability
#
def get_bundle_id_capabilities(bundle_id_id:, includes: nil, limit: nil, sort: nil)
params = provisioning_request_client.build_params(filter: nil, includes: includes, limit: limit, sort: sort)
provisioning_request_client.get("#{Version::V1}/bundleIds/#{bundle_id_id}/bundleIdCapabilities", params)
end
def get_available_bundle_id_capabilities(bundle_id_id:)
params = provisioning_request_client.build_params(filter: { bundleId: bundle_id_id })
provisioning_request_client.get("#{Version::V1}/capabilities", params)
end
def post_bundle_id_capability(bundle_id_id:, capability_type:, settings: [])
body = {
data: {
attributes: {
capabilityType: capability_type,
settings: settings
},
type: "bundleIdCapabilities",
relationships: {
bundleId: {
data: {
type: "bundleIds",
id: bundle_id_id
}
}
}
}
}
provisioning_request_client.post("#{Version::V1}/bundleIdCapabilities", body)
end
def patch_bundle_id_capability(bundle_id_id:, seed_id:, enabled: false, capability_type:, settings: [])
body = {
data: {
type: "bundleIds",
id: bundle_id_id,
attributes: {
permissions: {
edit: true,
delete: true
},
seedId: seed_id,
teamId: provisioning_request_client.team_id
},
relationships: {
bundleIdCapabilities: {
data: [
{
type: "bundleIdCapabilities",
attributes: {
enabled: enabled,
settings: settings
},
relationships: {
capability: {
data: {
type: "capabilities",
id: capability_type
}
}
}
}
]
}
}
}
}
provisioning_request_client.patch("#{Version::V1}/bundleIds/#{bundle_id_id}", body)
end
def delete_bundle_id_capability(bundle_id_capability_id:)
provisioning_request_client.delete("#{Version::V1}/bundleIdCapabilities/#{bundle_id_capability_id}")
end
#
# certificates
#
def get_certificates(profile_id: nil, filter: {}, includes: nil, fields: nil, limit: nil, sort: nil)
params = provisioning_request_client.build_params(filter: filter, includes: includes, fields: fields, limit: limit, sort: sort)
if profile_id.nil?
provisioning_request_client.get("#{Version::V1}/certificates", params)
else
provisioning_request_client.get("#{Version::V1}/profiles/#{profile_id}/certificates", params)
end
end
def get_certificate(certificate_id: nil, includes: nil)
params = provisioning_request_client.build_params(filter: nil, includes: includes, limit: nil, sort: nil)
provisioning_request_client.get("#{Version::V1}/certificates/#{certificate_id}", params)
end
def post_certificate(attributes: {})
body = {
data: {
attributes: attributes,
type: "certificates"
}
}
provisioning_request_client.post("#{Version::V1}/certificates", body)
end
def delete_certificate(certificate_id: nil)
raise "Certificate id is nil" if certificate_id.nil?
provisioning_request_client.delete("#{Version::V1}/certificates/#{certificate_id}")
end
#
# devices
#
def get_devices(profile_id: nil, filter: {}, includes: nil, fields: nil, limit: nil, sort: nil)
params = provisioning_request_client.build_params(filter: filter, includes: includes, fields: fields, limit: limit, sort: sort)
if profile_id.nil?
provisioning_request_client.get("#{Version::V1}/devices", params)
else
provisioning_request_client.get("#{Version::V1}/profiles/#{profile_id}/devices", params)
end
end
def post_device(name: nil, platform: nil, udid: nil)
attributes = {
name: name,
platform: platform,
udid: udid
}
body = {
data: {
attributes: attributes,
type: "devices"
}
}
provisioning_request_client.post("#{Version::V1}/devices", body)
end
def patch_device(id: nil, status: nil, new_name: nil)
raise "Device id is nil" if id.nil?
attributes = {
name: new_name,
status: status
}
body = {
data: {
attributes: attributes,
id: id,
type: "devices"
}
}
provisioning_request_client.patch("#{Version::V1}/devices/#{id}", body)
end
#
# profiles
#
def get_profiles(filter: {}, includes: nil, fields: nil, limit: nil, sort: nil)
params = provisioning_request_client.build_params(filter: filter, includes: includes, fields: fields, limit: limit, sort: sort)
provisioning_request_client.get("#{Version::V1}/profiles", params)
end
def post_profiles(bundle_id_id: nil, certificates: nil, devices: nil, attributes: {})
body = {
data: {
attributes: attributes,
type: "profiles",
relationships: {
bundleId: {
data: {
type: "bundleIds",
id: bundle_id_id
}
},
certificates: {
data: certificates.map do |certificate|
{
type: "certificates",
id: certificate
}
end
},
devices: {
data: (devices || []).map do |device|
{
type: "devices",
id: device
}
end
}
}
}
}
provisioning_request_client.post("#{Version::V1}/profiles", body)
end
def get_profile_bundle_id(profile_id: nil)
raise "Profile id is nil" if profile_id.nil?
provisioning_request_client.get("#{Version::V1}/profiles/#{profile_id}/bundleId")
end
def delete_profile(profile_id: nil)
raise "Profile id is nil" if profile_id.nil?
provisioning_request_client.delete("#{Version::V1}/profiles/#{profile_id}")
end
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/tunes/client.rb | spaceship/lib/spaceship/connect_api/tunes/client.rb | require_relative '../api_client'
require_relative './tunes'
require_relative '../../tunes/tunes_client'
module Spaceship
class ConnectAPI
module Tunes
class Client < Spaceship::ConnectAPI::APIClient
def initialize(cookie: nil, current_team_id: nil, token: nil, another_client: nil)
another_client ||= Spaceship::Tunes.client if cookie.nil? && token.nil?
super(cookie: cookie, current_team_id: current_team_id, token: token, another_client: another_client)
# Used by most iris requests starting in July 2021
@additional_headers = { 'x-csrf-itc': '[asc-ui]' } if another_client
self.extend(Spaceship::ConnectAPI::Tunes::API)
self.tunes_request_client = self
end
def self.hostname
'https://appstoreconnect.apple.com/iris/'
end
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/tunes/tunes.rb | spaceship/lib/spaceship/connect_api/tunes/tunes.rb | require 'spaceship/connect_api/tunes/client'
module Spaceship
class ConnectAPI
module Tunes
module API
module Version
V1 = "v1"
V2 = "v2"
V3 = "v3"
end
def tunes_request_client=(tunes_request_client)
@tunes_request_client = tunes_request_client
end
def tunes_request_client
return @tunes_request_client if @tunes_request_client
raise TypeError, "You need to instantiate this module with tunes_request_client"
end
#
# ageRatingDeclarations
#
def get_age_rating_declaration(app_info_id: nil, app_store_version_id: nil)
raise "Keyword 'app_store_version_id' is deprecated and 'app_info_id' is required" if app_store_version_id || app_info_id.nil?
params = tunes_request_client.build_params(filter: nil, includes: nil, limit: nil, sort: nil)
tunes_request_client.get("#{Version::V1}/appInfos/#{app_info_id}/ageRatingDeclaration", params)
end
def patch_age_rating_declaration(age_rating_declaration_id: nil, attributes: nil)
body = {
data: {
type: "ageRatingDeclarations",
id: age_rating_declaration_id,
attributes: attributes
}
}
tunes_request_client.patch("#{Version::V1}/ageRatingDeclarations/#{age_rating_declaration_id}", body)
end
#
# app
#
def post_app(name: nil, version_string: nil, sku: nil, primary_locale: nil, bundle_id: nil, platforms: nil, company_name: nil)
included = []
included << {
type: "appInfos",
id: "${new-appInfo-id}",
relationships: {
appInfoLocalizations: {
data: [
{
type: "appInfoLocalizations",
id: "${new-appInfoLocalization-id}"
}
]
}
}
}
included << {
type: "appInfoLocalizations",
id: "${new-appInfoLocalization-id}",
attributes: {
locale: primary_locale,
name: name
}
}
platforms.each do |platform|
included << {
type: "appStoreVersions",
id: "${store-version-#{platform}}",
attributes: {
platform: platform,
versionString: version_string
},
relationships: {
appStoreVersionLocalizations: {
data: [
{
type: "appStoreVersionLocalizations",
id: "${new-#{platform}VersionLocalization-id}"
}
]
}
}
}
included << {
type: "appStoreVersionLocalizations",
id: "${new-#{platform}VersionLocalization-id}",
attributes: {
locale: primary_locale
}
}
end
data_for_app_store_versions = platforms.map do |platform|
{
type: "appStoreVersions",
id: "${store-version-#{platform}}"
}
end
relationships = {
appStoreVersions: {
data: data_for_app_store_versions
},
appInfos: {
data: [
{
type: "appInfos",
id: "${new-appInfo-id}"
}
]
}
}
app_attributes = {
sku: sku,
primaryLocale: primary_locale,
bundleId: bundle_id
}
app_attributes[:companyName] = company_name if company_name
body = {
data: {
type: "apps",
attributes: app_attributes,
relationships: relationships
},
included: included
}
tunes_request_client.post("#{Version::V1}/apps", body)
end
# Updates app attributes, price tier, visibility in regions or countries.
# Use territory_ids with allow_removing_from_sale to remove app from sale
# @param territory_ids updates app visibility in regions or countries.
# Possible values:
# empty array will remove app from sale if allow_removing_from_sale is true,
# array with territory ids will set availability to territories with those ids,
# nil will leave app availability on AppStore as is
# @param allow_removing_from_sale allows for removing app from sale when territory_ids is an empty array
def patch_app(app_id: nil, attributes: {}, app_price_tier_id: nil, territory_ids: nil, allow_removing_from_sale: false)
relationships = {}
included = []
# Price tier
unless app_price_tier_id.nil?
relationships[:prices] = {
data: [
{
type: "appPrices",
id: "${price1}"
}
]
}
included << {
type: "appPrices",
id: "${price1}",
relationships: {
app: {
data: {
type: "apps",
id: app_id
}
},
priceTier: {
data: {
type: "appPriceTiers",
id: app_price_tier_id.to_s
}
}
}
}
end
# Territories
unless territory_ids.nil?
territories_data = territory_ids.map do |id|
{ type: "territories", id: id }
end
if !territories_data.empty? || allow_removing_from_sale
relationships[:availableTerritories] = {
data: territories_data
}
end
end
# Data
data = {
type: "apps",
id: app_id
}
data[:relationships] = relationships unless relationships.empty?
if !attributes.nil? && !attributes.empty?
data[:attributes] = attributes
end
# Body
body = {
data: data
}
body[:included] = included unless included.empty?
tunes_request_client.patch("#{Version::V1}/apps/#{app_id}", body)
end
#
# appDataUsage
#
def get_app_data_usages(app_id: nil, filter: {}, includes: nil, limit: nil, sort: nil)
params = tunes_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort)
tunes_request_client.get("#{Version::V1}/apps/#{app_id}/dataUsages", params)
end
def post_app_data_usage(app_id:, app_data_usage_category_id: nil, app_data_usage_protection_id: nil, app_data_usage_purpose_id: nil)
raise "app_id is required " if app_id.nil?
relationships = {
app: {
data: {
type: "apps",
id: app_id
}
}
}
if app_data_usage_category_id
relationships[:category] = {
data: {
type: "appDataUsageCategories",
id: app_data_usage_category_id
}
}
end
if app_data_usage_protection_id
relationships[:dataProtection] = {
data: {
type: "appDataUsageDataProtections",
id: app_data_usage_protection_id
}
}
end
if app_data_usage_purpose_id
relationships[:purpose] = {
data: {
type: "appDataUsagePurposes",
id: app_data_usage_purpose_id
}
}
end
body = {
data: {
type: "appDataUsages",
relationships: relationships
}
}
tunes_request_client.post("#{Version::V1}/appDataUsages", body)
end
def delete_app_data_usage(app_data_usage_id: nil)
tunes_request_client.delete("#{Version::V1}/appDataUsages/#{app_data_usage_id}")
end
#
# appDataUsageCategory
#
def get_app_data_usage_categories(filter: {}, includes: nil, limit: nil, sort: nil)
params = tunes_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort)
tunes_request_client.get("#{Version::V1}/appDataUsageCategories", params)
end
#
# appDataUsagePurpose
#
def get_app_data_usage_purposes(filter: {}, includes: nil, limit: nil, sort: nil)
params = tunes_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort)
tunes_request_client.get("#{Version::V1}/appDataUsagePurposes", params)
end
#
# appDataUsagesPublishState
#
def get_app_data_usages_publish_state(app_id: nil)
params = tunes_request_client.build_params(filter: nil, includes: nil, limit: nil, sort: nil)
tunes_request_client.get("#{Version::V1}/apps/#{app_id}/dataUsagePublishState", params)
end
def patch_app_data_usages_publish_state(app_data_usages_publish_state_id: nil, published: nil)
body = {
data: {
type: "appDataUsagesPublishState",
id: app_data_usages_publish_state_id,
attributes: {
published: published
}
}
}
tunes_request_client.patch("#{Version::V1}/appDataUsagesPublishState/#{app_data_usages_publish_state_id}", body)
end
#
# appPreview
#
def get_app_preview(app_preview_id: nil)
params = tunes_request_client.build_params(filter: nil, includes: nil, limit: nil, sort: nil)
tunes_request_client.get("#{Version::V1}/appPreviews/#{app_preview_id}", params)
end
def post_app_preview(app_preview_set_id: nil, attributes: {})
body = {
data: {
type: "appPreviews",
attributes: attributes,
relationships: {
appPreviewSet: {
data: {
type: "appPreviewSets",
id: app_preview_set_id
}
}
}
}
}
tunes_request_client.post("#{Version::V1}/appPreviews", body)
end
def patch_app_preview(app_preview_id: nil, attributes: {})
body = {
data: {
type: "appPreviews",
id: app_preview_id,
attributes: attributes
}
}
tunes_request_client.patch("#{Version::V1}/appPreviews/#{app_preview_id}", body)
end
def delete_app_preview(app_preview_id: nil)
params = tunes_request_client.build_params(filter: nil, includes: nil, limit: nil, sort: nil)
tunes_request_client.delete("#{Version::V1}/appPreviews/#{app_preview_id}", params)
end
#
# appPreviewSets
#
def get_app_preview_sets(filter: {}, includes: nil, limit: nil, sort: nil)
params = tunes_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort)
tunes_request_client.get("#{Version::V1}/appPreviewSets", params)
end
def get_app_preview_set(app_preview_set_id: nil, filter: {}, includes: nil, limit: nil, sort: nil)
params = tunes_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort)
tunes_request_client.get("#{Version::V1}/appPreviewSets/#{app_preview_set_id}", params)
end
def post_app_preview_set(app_store_version_localization_id: nil, attributes: {})
body = {
data: {
type: "appPreviewSets",
attributes: attributes,
relationships: {
appStoreVersionLocalization: {
data: {
type: "appStoreVersionLocalizations",
id: app_store_version_localization_id
}
}
}
}
}
tunes_request_client.post("#{Version::V1}/appPreviewSets", body)
end
def delete_app_preview_set(app_preview_set_id: nil)
params = tunes_request_client.build_params(filter: nil, includes: nil, limit: nil, sort: nil)
tunes_request_client.delete("#{Version::V1}/appPreviewSets/#{app_preview_set_id}", params)
end
def patch_app_preview_set_previews(app_preview_set_id: nil, app_preview_ids: nil)
app_preview_ids ||= []
body = {
data: app_preview_ids.map do |app_preview_id|
{
type: "appPreviews",
id: app_preview_id
}
end
}
tunes_request_client.patch("#{Version::V1}/appPreviewSets/#{app_preview_set_id}/relationships/appPreviews", body)
end
#
# appAvailabilities
#
def get_app_availabilities(app_id: nil, filter: nil, includes: nil, limit: nil, sort: nil)
params = tunes_request_client.build_params(filter: nil, includes: includes, limit: limit, sort: nil)
tunes_request_client.get("#{Version::V2}/appAvailabilities/#{app_id}", params)
end
#
# availableTerritories
#
def get_available_territories(app_id: nil, filter: {}, includes: nil, limit: nil, sort: nil)
params = tunes_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort)
tunes_request_client.get("#{Version::V1}/apps/#{app_id}/availableTerritories", params)
end
#
# appPrices
#
def get_app_prices(app_id: nil, filter: {}, includes: nil, limit: nil, sort: nil)
params = tunes_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort)
tunes_request_client.get("#{Version::V1}/appPrices", params)
end
def get_app_price(app_price_id: nil, filter: {}, includes: nil, limit: nil, sort: nil)
params = tunes_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort)
tunes_request_client.get("#{Version::V1}/appPrices/#{app_price_id}", params)
end
#
# appPricePoints
#
def get_app_price_points(filter: {}, includes: nil, limit: nil, sort: nil)
params = tunes_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort)
tunes_request_client.get("#{Version::V1}/appPricePoints", params)
end
#
# appReviewAttachments
#
def post_app_store_review_attachment(app_store_review_detail_id: nil, attributes: {})
body = {
data: {
type: "appStoreReviewAttachments",
attributes: attributes,
relationships: {
appStoreReviewDetail: {
data: {
type: "appStoreReviewDetails",
id: app_store_review_detail_id
}
}
}
}
}
tunes_request_client.post("#{Version::V1}/appStoreReviewAttachments", body)
end
def patch_app_store_review_attachment(app_store_review_attachment_id: nil, attributes: {})
body = {
data: {
type: "appStoreReviewAttachments",
id: app_store_review_attachment_id,
attributes: attributes
}
}
tunes_request_client.patch("#{Version::V1}/appStoreReviewAttachments/#{app_store_review_attachment_id}", body)
end
def delete_app_store_review_attachment(app_store_review_attachment_id: nil)
params = tunes_request_client.build_params(filter: nil, includes: nil, limit: nil, sort: nil)
tunes_request_client.delete("#{Version::V1}/appStoreReviewAttachments/#{app_store_review_attachment_id}", params)
end
#
# appScreenshotSets
#
def get_app_screenshot_sets(app_store_version_localization_id: nil, filter: {}, includes: nil, limit: nil, sort: nil)
params = tunes_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort)
tunes_request_client.get("#{Version::V1}/appStoreVersionLocalizations/#{app_store_version_localization_id}/appScreenshotSets", params)
end
def get_app_screenshot_set(app_screenshot_set_id: nil, filter: {}, includes: nil, limit: nil, sort: nil)
params = tunes_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort)
tunes_request_client.get("#{Version::V1}/appScreenshotSets/#{app_screenshot_set_id}", params)
end
def post_app_screenshot_set(app_store_version_localization_id: nil, attributes: {})
body = {
data: {
type: "appScreenshotSets",
attributes: attributes,
relationships: {
appStoreVersionLocalization: {
data: {
type: "appStoreVersionLocalizations",
id: app_store_version_localization_id
}
}
}
}
}
tunes_request_client.post("#{Version::V1}/appScreenshotSets", body)
end
def patch_app_screenshot_set_screenshots(app_screenshot_set_id: nil, app_screenshot_ids: nil)
app_screenshot_ids ||= []
body = {
data: app_screenshot_ids.map do |app_screenshot_id|
{
type: "appScreenshots",
id: app_screenshot_id
}
end
}
tunes_request_client.patch("#{Version::V1}/appScreenshotSets/#{app_screenshot_set_id}/relationships/appScreenshots", body)
end
def delete_app_screenshot_set(app_screenshot_set_id: nil)
params = tunes_request_client.build_params(filter: nil, includes: nil, limit: nil, sort: nil)
tunes_request_client.delete("#{Version::V1}/appScreenshotSets/#{app_screenshot_set_id}", params)
end
#
# appScreenshots
#
def get_app_screenshot(app_screenshot_id: nil)
params = tunes_request_client.build_params(filter: nil, includes: nil, limit: nil, sort: nil)
tunes_request_client.get("#{Version::V1}/appScreenshots/#{app_screenshot_id}", params)
end
def post_app_screenshot(app_screenshot_set_id: nil, attributes: {})
body = {
data: {
type: "appScreenshots",
attributes: attributes,
relationships: {
appScreenshotSet: {
data: {
type: "appScreenshotSets",
id: app_screenshot_set_id
}
}
}
}
}
tunes_request_client.post("#{Version::V1}/appScreenshots", body, tries: 1)
end
def patch_app_screenshot(app_screenshot_id: nil, attributes: {})
body = {
data: {
type: "appScreenshots",
id: app_screenshot_id,
attributes: attributes
}
}
tunes_request_client.patch("#{Version::V1}/appScreenshots/#{app_screenshot_id}", body)
end
def delete_app_screenshot(app_screenshot_id: nil)
params = tunes_request_client.build_params(filter: nil, includes: nil, limit: nil, sort: nil)
tunes_request_client.delete("#{Version::V1}/appScreenshots/#{app_screenshot_id}", params)
end
#
# appInfos
#
def get_app_infos(app_id: nil, filter: {}, includes: nil, limit: nil, sort: nil)
params = tunes_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort)
tunes_request_client.get("#{Version::V1}/apps/#{app_id}/appInfos", params)
end
def patch_app_info(app_info_id: nil, attributes: {})
attributes ||= {}
data = {
type: "appInfos",
id: app_info_id
}
data[:attributes] = attributes unless attributes.empty?
body = {
data: data
}
tunes_request_client.patch("#{Version::V1}/appInfos/#{app_info_id}", body)
end
#
# Adding the key will create/update (if value) or delete if nil
# Not including a key will leave as is
# category_id_map: {
# primary_category_id: "GAMES",
# primary_subcategory_one_id: "PUZZLE",
# primary_subcategory_two_id: "STRATEGY",
# secondary_category_id: nil,
# secondary_subcategory_one_id: nil,
# secondary_subcategory_two_id: nil
# }
#
def patch_app_info_categories(app_info_id: nil, category_id_map: nil)
category_id_map ||= {}
primary_category_id = category_id_map[:primary_category_id]
primary_subcategory_one_id = category_id_map[:primary_subcategory_one_id]
primary_subcategory_two_id = category_id_map[:primary_subcategory_two_id]
secondary_category_id = category_id_map[:secondary_category_id]
secondary_subcategory_one_id = category_id_map[:secondary_subcategory_one_id]
secondary_subcategory_two_id = category_id_map[:secondary_subcategory_two_id]
relationships = {}
# Only update if key is included (otherwise category will be removed)
if category_id_map.include?(:primary_category_id)
relationships[:primaryCategory] = {
data: primary_category_id ? { type: "appCategories", id: primary_category_id } : nil
}
end
# Only update if key is included (otherwise category will be removed)
if category_id_map.include?(:primary_subcategory_one_id)
relationships[:primarySubcategoryOne] = {
data: primary_subcategory_one_id ? { type: "appCategories", id: primary_subcategory_one_id } : nil
}
end
# Only update if key is included (otherwise category will be removed)
if category_id_map.include?(:primary_subcategory_two_id)
relationships[:primarySubcategoryTwo] = {
data: primary_subcategory_two_id ? { type: "appCategories", id: primary_subcategory_two_id } : nil
}
end
# Only update if key is included (otherwise category will be removed)
if category_id_map.include?(:secondary_category_id)
relationships[:secondaryCategory] = {
data: secondary_category_id ? { type: "appCategories", id: secondary_category_id } : nil
}
end
# Only update if key is included (otherwise category will be removed)
if category_id_map.include?(:secondary_subcategory_one_id)
relationships[:secondarySubcategoryOne] = {
data: secondary_subcategory_one_id ? { type: "appCategories", id: secondary_subcategory_one_id } : nil
}
end
# Only update if key is included (otherwise category will be removed)
if category_id_map.include?(:secondary_subcategory_two_id)
relationships[:secondarySubcategoryTwo] = {
data: secondary_subcategory_two_id ? { type: "appCategories", id: secondary_subcategory_two_id } : nil
}
end
data = {
type: "appInfos",
id: app_info_id
}
data[:relationships] = relationships unless relationships.empty?
body = {
data: data
}
tunes_request_client.patch("#{Version::V1}/appInfos/#{app_info_id}", body)
end
def delete_app_info(app_info_id: nil)
params = tunes_request_client.build_params(filter: nil, includes: nil, limit: nil, sort: nil)
tunes_request_client.delete("#{Version::V1}/appInfos/#{app_info_id}", params)
end
#
# appInfoLocalizations
#
def get_app_info_localizations(app_info_id: nil, filter: {}, includes: nil, limit: nil, sort: nil)
params = tunes_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort)
tunes_request_client.get("#{Version::V1}/appInfos/#{app_info_id}/appInfoLocalizations", params)
end
def post_app_info_localization(app_info_id: nil, attributes: {})
body = {
data: {
type: "appInfoLocalizations",
attributes: attributes,
relationships: {
appStoreVersion: {
data: {
type: "appStoreVersions",
id: app_info_id
}
}
}
}
}
tunes_request_client.post("#{Version::V1}/appInfoLocalizations", body)
end
def patch_app_info_localization(app_info_localization_id: nil, attributes: {})
body = {
data: {
type: "appInfoLocalizations",
id: app_info_localization_id,
attributes: attributes
}
}
tunes_request_client.patch("#{Version::V1}/appInfoLocalizations/#{app_info_localization_id}", body)
end
#
# appStoreReviewDetails
#
def get_app_store_review_detail(app_store_version_id: nil, filter: {}, includes: nil, limit: nil, sort: nil)
params = tunes_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort)
tunes_request_client.get("#{Version::V1}/appStoreVersions/#{app_store_version_id}/appStoreReviewDetail", params)
end
def post_app_store_review_detail(app_store_version_id: nil, attributes: {})
body = {
data: {
type: "appStoreReviewDetails",
attributes: attributes,
relationships: {
appStoreVersion: {
data: {
type: "appStoreVersions",
id: app_store_version_id
}
}
}
}
}
tunes_request_client.post("#{Version::V1}/appStoreReviewDetails", body)
end
def patch_app_store_review_detail(app_store_review_detail_id: nil, attributes: {})
body = {
data: {
type: "appStoreReviewDetails",
id: app_store_review_detail_id,
attributes: attributes
}
}
tunes_request_client.patch("#{Version::V1}/appStoreReviewDetails/#{app_store_review_detail_id}", body)
end
#
# appStoreVersionLocalizations
#
def get_app_store_version_localizations(app_store_version_id: nil, filter: {}, includes: nil, limit: nil, sort: nil)
params = tunes_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort)
tunes_request_client.get("#{Version::V1}/appStoreVersions/#{app_store_version_id}/appStoreVersionLocalizations", params)
end
def get_app_store_version_localization(app_store_version_localization_id: nil, filter: {}, includes: nil, limit: nil, sort: nil)
params = tunes_request_client.build_params(filter: nil, includes: nil, limit: nil, sort: nil)
tunes_request_client.get("#{Version::V1}/appStoreVersionLocalizations/#{app_store_version_localization_id}", params)
end
def post_app_store_version_localization(app_store_version_id: nil, attributes: {})
body = {
data: {
type: "appStoreVersionLocalizations",
attributes: attributes,
relationships: {
appStoreVersion: {
data: {
type: "appStoreVersions",
id: app_store_version_id
}
}
}
}
}
tunes_request_client.post("#{Version::V1}/appStoreVersionLocalizations", body)
end
def patch_app_store_version_localization(app_store_version_localization_id: nil, attributes: {})
body = {
data: {
type: "appStoreVersionLocalizations",
id: app_store_version_localization_id,
attributes: attributes
}
}
tunes_request_client.patch("#{Version::V1}/appStoreVersionLocalizations/#{app_store_version_localization_id}", body)
end
def delete_app_store_version_localization(app_store_version_localization_id: nil)
params = tunes_request_client.build_params(filter: nil, includes: nil, limit: nil, sort: nil)
tunes_request_client.delete("#{Version::V1}/appStoreVersionLocalizations/#{app_store_version_localization_id}", params)
end
#
# appStoreVersionPhasedReleases
#
def get_app_store_version_phased_release(app_store_version_id: nil)
params = tunes_request_client.build_params(filter: nil, includes: nil, limit: nil, sort: nil)
tunes_request_client.get("#{Version::V1}/appStoreVersions/#{app_store_version_id}/appStoreVersionPhasedRelease", params)
end
def post_app_store_version_phased_release(app_store_version_id: nil, attributes: {})
body = {
data: {
type: "appStoreVersionPhasedReleases",
attributes: attributes,
relationships: {
appStoreVersion: {
data: {
type: "appStoreVersions",
id: app_store_version_id
}
}
}
}
}
tunes_request_client.post("#{Version::V1}/appStoreVersionPhasedReleases", body)
end
def patch_app_store_version_phased_release(app_store_version_phased_release_id: nil, attributes: {})
body = {
data: {
type: "appStoreVersionPhasedReleases",
attributes: attributes,
id: app_store_version_phased_release_id
}
}
tunes_request_client.patch("#{Version::V1}/appStoreVersionPhasedReleases/#{app_store_version_phased_release_id}", body)
end
def delete_app_store_version_phased_release(app_store_version_phased_release_id: nil)
params = tunes_request_client.build_params(filter: nil, includes: nil, limit: nil, sort: nil)
tunes_request_client.delete("#{Version::V1}/appStoreVersionPhasedReleases/#{app_store_version_phased_release_id}", params)
end
#
# appStoreVersions
#
def get_app_store_versions(app_id: nil, filter: {}, includes: nil, limit: nil, sort: nil)
params = tunes_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort)
tunes_request_client.get("#{Version::V1}/apps/#{app_id}/appStoreVersions", params)
end
def get_app_store_version(app_store_version_id: nil, includes: nil)
params = tunes_request_client.build_params(filter: nil, includes: includes, limit: nil, sort: nil)
tunes_request_client.get("#{Version::V1}/appStoreVersions/#{app_store_version_id}", params)
end
def post_app_store_version(app_id: nil, attributes: {})
body = {
data: {
type: "appStoreVersions",
attributes: attributes,
relationships: {
app: {
data: {
type: "apps",
id: app_id
}
}
}
}
}
tunes_request_client.post("#{Version::V1}/appStoreVersions", body)
end
def patch_app_store_version(app_store_version_id: nil, attributes: {})
body = {
data: {
type: "appStoreVersions",
id: app_store_version_id,
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | true |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/build_beta_detail.rb | spaceship/lib/spaceship/connect_api/models/build_beta_detail.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class BuildBetaDetail
include Spaceship::ConnectAPI::Model
attr_accessor :auto_notify_enabled
attr_accessor :did_notify
attr_accessor :internal_build_state
attr_accessor :external_build_state
module InternalState
PROCESSING = "PROCESSING"
PROCESSING_EXCEPTION = "PROCESSING_EXCEPTION"
MISSING_EXPORT_COMPLIANCE = "MISSING_EXPORT_COMPLIANCE"
READY_FOR_BETA_TESTING = "READY_FOR_BETA_TESTING"
IN_BETA_TESTING = "IN_BETA_TESTING"
EXPIRED = "EXPIRED"
IN_EXPORT_COMPLIANCE_REVIEW = "IN_EXPORT_COMPLIANCE_REVIEW"
end
module ExternalState
PROCESSING = "PROCESSING"
PROCESSING_EXCEPTION = "PROCESSING_EXCEPTION"
MISSING_EXPORT_COMPLIANCE = "MISSING_EXPORT_COMPLIANCE"
READY_FOR_BETA_TESTING = "READY_FOR_BETA_TESTING"
IN_BETA_TESTING = "IN_BETA_TESTING"
EXPIRED = "EXPIRED"
READY_FOR_BETA_SUBMISSION = "READY_FOR_BETA_SUBMISSION"
IN_EXPORT_COMPLIANCE_REVIEW = "IN_EXPORT_COMPLIANCE_REVIEW"
WAITING_FOR_BETA_REVIEW = "WAITING_FOR_BETA_REVIEW"
IN_BETA_REVIEW = "IN_BETA_REVIEW"
BETA_REJECTED = "BETA_REJECTED"
BETA_APPROVED = "BETA_APPROVED"
end
attr_mapping({
"autoNotifyEnabled" => "auto_notify_enabled",
"didNotify" => "did_notify",
"internalBuildState" => "internal_build_state",
"externalBuildState" => "external_build_state"
})
def self.type
return "buildBetaDetails"
end
#
# Helpers
#
#
def ready_for_internal_testing?
return internal_build_state == InternalState::READY_FOR_BETA_TESTING
end
def processed?
return internal_build_state != InternalState::PROCESSING && external_build_state != ExternalState::PROCESSING
end
def ready_for_beta_submission?
return external_build_state == ExternalState::READY_FOR_BETA_SUBMISSION
end
def missing_export_compliance?
return external_build_state == ExternalState::MISSING_EXPORT_COMPLIANCE
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/app_price_tier.rb | spaceship/lib/spaceship/connect_api/models/app_price_tier.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class AppPriceTier
include Spaceship::ConnectAPI::Model
def self.type
return "appPriceTiers"
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/beta_group.rb | spaceship/lib/spaceship/connect_api/models/beta_group.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class BetaGroup
include Spaceship::ConnectAPI::Model
attr_accessor :name
attr_accessor :created_date
attr_accessor :is_internal_group
attr_accessor :public_link_enabled
attr_accessor :public_link_id
attr_accessor :public_link_limit_enabled
attr_accessor :public_link_limit
attr_accessor :public_link
attr_accessor :beta_testers
attr_accessor :has_access_to_all_builds
attr_mapping({
"name" => "name",
"createdDate" => "created_date",
"isInternalGroup" => "is_internal_group",
"publicLinkEnabled" => "public_link_enabled",
"publicLinkId" => "public_link_id",
"publicLinkLimitEnabled" => "public_link_limit_enabled",
"publicLinkLimit" => "public_link_limit",
"publicLink" => "public_link",
"betaTesters" => "beta_testers",
"hasAccessToAllBuilds" => "has_access_to_all_builds",
})
def self.type
return "betaGroups"
end
#
# API
#
# beta_testers - [{email: "", firstName: "", lastName: ""}]
def post_bulk_beta_tester_assignments(client: nil, beta_testers: nil)
client ||= Spaceship::ConnectAPI
return client.post_bulk_beta_tester_assignments(beta_group_id: id, beta_testers: beta_testers)
end
def add_beta_testers(client: nil, beta_tester_ids:)
client ||= Spaceship::ConnectAPI
return client.add_beta_tester_to_group(beta_group_id: id, beta_tester_ids: beta_tester_ids)
end
def update(client: nil, attributes: nil)
return if attributes.empty?
client ||= Spaceship::ConnectAPI
attributes = reverse_attr_mapping(attributes)
return client.patch_group(group_id: id, attributes: attributes).first
end
def delete!
return Spaceship::ConnectAPI.delete_beta_group(group_id: id)
end
def fetch_builds
resps = Spaceship::ConnectAPI.get_builds_for_beta_group(group_id: id).all_pages
return resps.flat_map(&:to_models)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/review_submission_item.rb | spaceship/lib/spaceship/connect_api/models/review_submission_item.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class ReviewSubmissionItem
include Spaceship::ConnectAPI::Model
attr_accessor :state
attr_accessor :app_store_version_experiment
attr_accessor :app_store_version
attr_accessor :app_store_product_page_version
attr_accessor :app_event
attr_mapping({
"state" => "state",
"appStoreVersionExperiment" => "app_store_version_experiment",
"appStoreVersion" => "app_store_version",
"appCustomProductPageVersion" => "app_store_product_page_version",
"appEvent" => "app_event",
})
def self.type
return "reviewSubmissionItems"
end
#
# API
#
# appCustomProductPageVersion,appEvent,appStoreVersion,appStoreVersionExperiment
def self.all(client: nil, review_submission_id:, includes: nil, limit: nil, sort: nil)
client ||= Spaceship::ConnectAPI
resps = client.get_review_submission_items(review_submission_id: review_submission_id, includes: includes, limit: limit, sort: sort).all_pages
return resps.flat_map(&:to_models)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/app_screenshot_set.rb | spaceship/lib/spaceship/connect_api/models/app_screenshot_set.rb | require_relative '../model'
require_relative './app_screenshot'
module Spaceship
class ConnectAPI
class AppScreenshotSet
include Spaceship::ConnectAPI::Model
attr_accessor :screenshot_display_type
attr_accessor :app_screenshots
module DisplayType
APP_IPHONE_35 = "APP_IPHONE_35"
APP_IPHONE_40 = "APP_IPHONE_40"
APP_IPHONE_47 = "APP_IPHONE_47"
APP_IPHONE_55 = "APP_IPHONE_55"
APP_IPHONE_58 = "APP_IPHONE_58"
APP_IPHONE_61 = "APP_IPHONE_61"
APP_IPHONE_65 = "APP_IPHONE_65"
APP_IPHONE_67 = "APP_IPHONE_67"
APP_IPAD_97 = "APP_IPAD_97"
APP_IPAD_105 = "APP_IPAD_105"
APP_IPAD_PRO_3GEN_11 = "APP_IPAD_PRO_3GEN_11"
APP_IPAD_PRO_129 = "APP_IPAD_PRO_129"
APP_IPAD_PRO_3GEN_129 = "APP_IPAD_PRO_3GEN_129"
IMESSAGE_APP_IPHONE_40 = "IMESSAGE_APP_IPHONE_40"
IMESSAGE_APP_IPHONE_47 = "IMESSAGE_APP_IPHONE_47"
IMESSAGE_APP_IPHONE_55 = "IMESSAGE_APP_IPHONE_55"
IMESSAGE_APP_IPHONE_58 = "IMESSAGE_APP_IPHONE_58"
IMESSAGE_APP_IPHONE_61 = "IMESSAGE_APP_IPHONE_61"
IMESSAGE_APP_IPHONE_65 = "IMESSAGE_APP_IPHONE_65"
IMESSAGE_APP_IPHONE_67 = "IMESSAGE_APP_IPHONE_67"
IMESSAGE_APP_IPAD_97 = "IMESSAGE_APP_IPAD_97"
IMESSAGE_APP_IPAD_105 = "IMESSAGE_APP_IPAD_105"
IMESSAGE_APP_IPAD_PRO_129 = "IMESSAGE_APP_IPAD_PRO_129"
IMESSAGE_APP_IPAD_PRO_3GEN_11 = "IMESSAGE_APP_IPAD_PRO_3GEN_11"
IMESSAGE_APP_IPAD_PRO_3GEN_129 = "IMESSAGE_APP_IPAD_PRO_3GEN_129"
APP_WATCH_SERIES_3 = "APP_WATCH_SERIES_3"
APP_WATCH_SERIES_4 = "APP_WATCH_SERIES_4"
APP_WATCH_SERIES_7 = "APP_WATCH_SERIES_7"
APP_WATCH_SERIES_10 = "APP_WATCH_SERIES_10"
APP_WATCH_ULTRA = "APP_WATCH_ULTRA"
APP_APPLE_TV = "APP_APPLE_TV"
APP_DESKTOP = "APP_DESKTOP"
APP_APPLE_VISION_PRO = "APP_APPLE_VISION_PRO"
ALL_IMESSAGE = [
IMESSAGE_APP_IPHONE_40,
IMESSAGE_APP_IPHONE_47,
IMESSAGE_APP_IPHONE_55,
IMESSAGE_APP_IPHONE_58,
IMESSAGE_APP_IPHONE_61,
IMESSAGE_APP_IPHONE_65,
IMESSAGE_APP_IPHONE_67,
IMESSAGE_APP_IPAD_97,
IMESSAGE_APP_IPAD_105,
IMESSAGE_APP_IPAD_PRO_129,
IMESSAGE_APP_IPAD_PRO_3GEN_11,
IMESSAGE_APP_IPAD_PRO_3GEN_129
]
ALL = [
APP_IPHONE_35,
APP_IPHONE_40,
APP_IPHONE_47,
APP_IPHONE_55,
APP_IPHONE_58,
APP_IPHONE_61,
APP_IPHONE_65,
APP_IPHONE_67,
APP_IPAD_97,
APP_IPAD_105,
APP_IPAD_PRO_3GEN_11,
APP_IPAD_PRO_129,
APP_IPAD_PRO_3GEN_129,
IMESSAGE_APP_IPHONE_40,
IMESSAGE_APP_IPHONE_47,
IMESSAGE_APP_IPHONE_55,
IMESSAGE_APP_IPHONE_58,
IMESSAGE_APP_IPHONE_61,
IMESSAGE_APP_IPHONE_65,
IMESSAGE_APP_IPHONE_67,
IMESSAGE_APP_IPAD_97,
IMESSAGE_APP_IPAD_105,
IMESSAGE_APP_IPAD_PRO_129,
IMESSAGE_APP_IPAD_PRO_3GEN_11,
IMESSAGE_APP_IPAD_PRO_3GEN_129,
APP_WATCH_SERIES_3,
APP_WATCH_SERIES_4,
APP_WATCH_SERIES_7,
APP_WATCH_SERIES_10,
APP_WATCH_ULTRA,
APP_DESKTOP,
APP_APPLE_VISION_PRO
]
end
attr_mapping({
"screenshotDisplayType" => "screenshot_display_type",
"appScreenshots" => "app_screenshots"
})
def self.type
return "appScreenshotSets"
end
def apple_tv?
DisplayType::APP_APPLE_TV == screenshot_display_type
end
def imessage?
DisplayType::ALL_IMESSAGE.include?(screenshot_display_type)
end
#
# API
#
def self.all(client: nil, app_store_version_localization_id: nil, filter: {}, includes: nil, limit: nil, sort: nil)
client ||= Spaceship::ConnectAPI
resp = client.get_app_screenshot_sets(app_store_version_localization_id: app_store_version_localization_id, filter: filter, includes: includes, limit: limit, sort: sort)
return resp.to_models
end
def self.get(client: nil, app_screenshot_set_id: nil, includes: "appScreenshots")
client ||= Spaceship::ConnectAPI
return client.get_app_screenshot_set(app_screenshot_set_id: app_screenshot_set_id, filter: nil, includes: includes, limit: nil, sort: nil).first
end
def delete!(client: nil, filter: {}, includes: nil, limit: nil, sort: nil)
client ||= Spaceship::ConnectAPI
return client.delete_app_screenshot_set(app_screenshot_set_id: id)
end
def upload_screenshot(client: nil, path: nil, wait_for_processing: true, position: nil)
client ||= Spaceship::ConnectAPI
screenshot = Spaceship::ConnectAPI::AppScreenshot.create(client: client, app_screenshot_set_id: id, path: path, wait_for_processing: wait_for_processing)
# Reposition (if specified)
unless position.nil?
# Get all app preview ids
set = AppScreenshotSet.get(client: client, app_screenshot_set_id: id)
app_screenshot_ids = set.app_screenshots.map(&:id)
# Remove new uploaded screenshot
app_screenshot_ids.delete(screenshot.id)
# Insert screenshot at specified position
app_screenshot_ids = app_screenshot_ids.insert(position, screenshot.id).compact
# Reorder screenshots
reorder_screenshots(client: client, app_screenshot_ids: app_screenshot_ids)
end
return screenshot
end
def reorder_screenshots(client: nil, app_screenshot_ids: nil)
client ||= Spaceship::ConnectAPI
client.patch_app_screenshot_set_screenshots(app_screenshot_set_id: id, app_screenshot_ids: app_screenshot_ids)
return client.get_app_screenshot_set(app_screenshot_set_id: id, includes: "appScreenshots").first
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/capabilities.rb | spaceship/lib/spaceship/connect_api/models/capabilities.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class Capabilities
include Spaceship::ConnectAPI::Model
attr_accessor :name
attr_accessor :description
attr_mapping({
"name" => "name",
"description" => "description",
})
def self.type
return "capabilities"
end
def self.all(client: nil)
client ||= Spaceship::ConnectAPI
resp = client.get_available_bundle_id_capabilities(bundle_id_id: id).all_pages
return resp.flat_map(&:to_models)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/custom_app_organization.rb | spaceship/lib/spaceship/connect_api/models/custom_app_organization.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class CustomAppOrganization
include Spaceship::ConnectAPI::Model
attr_accessor :device_enrollment_program_id
attr_accessor :name
attr_mapping({
"deviceEnrollmentProgramId" => "device_enrollment_program_id",
"name" => "name"
})
def self.type
return "customAppOrganizations"
end
#
# API
#
def self.all(app_id: nil, filter: {}, includes: nil, limit: nil, sort: nil)
resps = Spaceship::ConnectAPI.get_custom_app_organization(
app_id: app_id,
filter: filter,
includes: includes,
limit: nil,
sort: nil
).all_pages
return resps.flat_map(&:to_models)
end
def self.create(app_id: nil, device_enrollment_program_id: nil, name: nil)
return Spaceship::ConnectAPI.post_custom_app_organization(app_id: app_id, device_enrollment_program_id: device_enrollment_program_id, name: name).first
end
def delete!
Spaceship::ConnectAPI.delete_custom_app_organization(custom_app_organization_id: id)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/app_store_review_detail.rb | spaceship/lib/spaceship/connect_api/models/app_store_review_detail.rb | require_relative '../model'
require_relative './app_store_review_attachment'
module Spaceship
class ConnectAPI
class AppStoreReviewDetail
include Spaceship::ConnectAPI::Model
attr_accessor :contact_first_name
attr_accessor :contact_last_name
attr_accessor :contact_phone
attr_accessor :contact_email
attr_accessor :demo_account_name
attr_accessor :demo_account_password
attr_accessor :demo_account_required
attr_accessor :notes
attr_accessor :app_store_review_attachments
attr_mapping({
"contactFirstName" => "contact_first_name",
"contactLastName" => "contact_last_name",
"contactPhone" => "contact_phone",
"contactEmail" => "contact_email",
"demoAccountName" => "demo_account_name",
"demoAccountPassword" => "demo_account_password",
"demoAccountRequired" => "demo_account_required",
"notes" => "notes",
"appStoreReviewAttachments" => "app_store_review_attachments"
})
def self.type
return "appStoreReviewDetails"
end
#
# API
#
def update(client: nil, attributes: nil)
client ||= Spaceship::ConnectAPI
attributes = reverse_attr_mapping(attributes)
return client.patch_app_store_review_detail(app_store_review_detail_id: id, attributes: attributes)
end
def upload_attachment(client: nil, path: nil)
client ||= Spaceship::ConnectAPI
return client::AppStoreReviewAttachment.create(app_store_review_detail_id: id, path: path)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/app_store_version_release_request.rb | spaceship/lib/spaceship/connect_api/models/app_store_version_release_request.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class AppStoreVersionReleaseRequest
include Spaceship::ConnectAPI::Model
def self.type
return "appStoreVersionReleaseRequests"
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/build_bundle.rb | spaceship/lib/spaceship/connect_api/models/build_bundle.rb | require_relative '../model'
require_relative './build_bundle_file_sizes'
module Spaceship
class ConnectAPI
class BuildBundle
include Spaceship::ConnectAPI::Model
attr_accessor :bundle_id
attr_accessor :bundle_type
attr_accessor :sdk_build
attr_accessor :platform_build
attr_accessor :file_name
attr_accessor :has_siri_kit
attr_accessor :has_on_demand_resources
attr_accessor :is_newsstand
attr_accessor :has_prerendered_icon
attr_accessor :uses_location_services
attr_accessor :is_ios_build_mac_app_store_compatible
attr_accessor :includes_symbols
attr_accessor :dsym_url
attr_accessor :supported_architectures
attr_accessor :required_capabilities
attr_accessor :device_protocols
attr_accessor :locales
attr_accessor :entitlements
attr_accessor :tracks_users
module BundleType
APP = "APP"
# APP_CLIP might be in here as well
end
attr_mapping({
"bundleId" => "bundle_id",
"bundleType" => "bundle_type",
"sdkBuild" => "sdk_build",
"platformBuild" => "platform_build",
"fileName" => "file_name",
"hasSirikit" => "has_siri_kit",
"hasOnDemandResources" => "has_on_demand_resources",
"isNewsstand" => "is_newsstand",
"hasPrerenderedIcon" => "has_prerendered_icon",
"usesLocationServices" => "uses_location_services",
"isIosBuildMacAppStoreCompatible" => "is_ios_build_mac_app_store_compatible",
"includesSymbols" => "includes_symbols",
"dSYMUrl" => "dsym_url",
"supportedArchitectures" => "supported_architectures",
"requiredCapabilities" => "required_capabilities",
"deviceProtocols" => "device_protocols",
"locales" => "locales",
"entitlements" => "entitlements",
"tracksUsers" => "tracks_users"
})
def self.type
return "buildBundles"
end
#
# API
#
def build_bundle_file_sizes(client: nil)
@build_bundle_file_sizes ||= BuildBundleFileSizes.all(client: client, build_bundle_id: id)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/beta_screenshot.rb | spaceship/lib/spaceship/connect_api/models/beta_screenshot.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class BetaScreenshot
include Spaceship::ConnectAPI::Model
attr_accessor :image_assets
attr_mapping({
"imageAssets" => "image_assets"
})
def self.type
return "betaScreenshots"
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/sandbox_tester.rb | spaceship/lib/spaceship/connect_api/models/sandbox_tester.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class SandboxTester
include Spaceship::ConnectAPI::Model
attr_accessor :first_name
attr_accessor :last_name
attr_accessor :email
attr_accessor :password
attr_accessor :confirm_password
attr_accessor :secret_question
attr_accessor :secret_answer
attr_accessor :birth_date # 1980-03-01
attr_accessor :app_store_territory
attr_accessor :apple_pay_compatible
attr_mapping({
"firstName" => "first_name",
"lastName" => "last_name",
"email" => "email",
"password" => "password",
"confirmPassword" => "confirm_password",
"secretQuestion" => "secret_question",
"secretAnswer" => "secret_answer",
"birthDate" => "birth_date",
"appStoreTerritory" => "app_store_territory",
"applePayCompatible" => "apple_pay_compatible"
})
def self.type
return "sandboxTesters"
end
#
# API
#
def self.all(client: nil, filter: {}, includes: nil, limit: 2000, sort: nil)
client ||= Spaceship::ConnectAPI
resps = client.get_sandbox_testers(filter: filter, includes: includes).all_pages
return resps.flat_map(&:to_models)
end
def self.create(client: nil, first_name: nil, last_name: nil, email: nil, password: nil, confirm_password: nil, secret_question: nil, secret_answer: nil, birth_date: nil, app_store_territory: nil)
client ||= Spaceship::ConnectAPI
attributes = {
firstName: first_name,
lastName: last_name,
email: email,
password: password,
confirmPassword: confirm_password,
secretQuestion: secret_question,
secretAnswer: secret_answer,
birthDate: birth_date,
appStoreTerritory: app_store_territory
}
return client.post_sandbox_tester(attributes: attributes).first
end
def delete!(client: nil)
client ||= Spaceship::ConnectAPI
client.delete_sandbox_tester(sandbox_tester_id: id)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/app_info_localization.rb | spaceship/lib/spaceship/connect_api/models/app_info_localization.rb | require_relative '../model'
require_relative '../../errors'
module Spaceship
class ConnectAPI
class AppInfoLocalization
include Spaceship::ConnectAPI::Model
attr_accessor :locale
attr_accessor :name
attr_accessor :subtitle
attr_accessor :privacy_policy_url
attr_accessor :privacy_choices_url
attr_accessor :privacy_policy_text
attr_mapping({
"locale" => "locale",
"name" => "name",
"subtitle" => "subtitle",
"privacyPolicyUrl" => "privacy_policy_url",
"privacyChoicesUrl" => "privacy_choices_url",
"privacyPolicyText" => "privacy_policy_text"
})
def self.type
return "appInfoLocalizations"
end
#
# API
#
def update(client: nil, attributes: nil)
client ||= Spaceship::ConnectAPI
attributes = reverse_attr_mapping(attributes)
client.patch_app_info_localization(app_info_localization_id: id, attributes: attributes)
rescue => error
raise Spaceship::AppStoreLocalizationError.new(@locale, error)
end
def delete!(client: nil, filter: {}, includes: nil, limit: nil, sort: nil)
client ||= Spaceship::ConnectAPI
client.delete_app_info_localization(app_info_localization_id: id)
rescue => error
raise Spaceship::AppStoreLocalizationError.new(@locale, error)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/build.rb | spaceship/lib/spaceship/connect_api/models/build.rb | require_relative '../model'
require 'spaceship/test_flight/build'
module Spaceship
class ConnectAPI
class Build
include Spaceship::ConnectAPI::Model
attr_accessor :version
attr_accessor :uploaded_date
attr_accessor :expiration_date
attr_accessor :expired
attr_accessor :min_os_version
attr_accessor :icon_asset_token
attr_accessor :processing_state
attr_accessor :uses_non_exempt_encryption
attr_accessor :app
attr_accessor :beta_app_review_submission
attr_accessor :beta_build_metrics
attr_accessor :beta_build_localizations
attr_accessor :build_beta_detail
attr_accessor :build_bundles
attr_accessor :pre_release_version
attr_accessor :individual_testers
attr_mapping({
"version" => "version",
"uploadedDate" => "uploaded_date",
"expirationDate" => "expiration_date",
"expired" => "expired",
"minOsVersion" => "min_os_version",
"iconAssetToken" => "icon_asset_token",
"processingState" => "processing_state",
"usesNonExemptEncryption" => "uses_non_exempt_encryption",
"app" => "app",
"betaAppReviewSubmission" => "beta_app_review_submission",
"betaBuildMetrics" => "beta_build_metrics",
"betaBuildLocalizations" => "beta_build_localizations",
"buildBetaDetail" => "build_beta_detail",
"preReleaseVersion" => "pre_release_version",
"individualTesters" => "individual_testers",
"buildBundles" => "build_bundles"
})
ESSENTIAL_INCLUDES = "app,buildBetaDetail,preReleaseVersion,buildBundles"
module ProcessingState
PROCESSING = "PROCESSING"
FAILED = "FAILED"
INVALID = "INVALID"
VALID = "VALID"
end
def self.type
return "builds"
end
#
# Helpers
#
def app_version
raise "No pre_release_version included" unless pre_release_version
return pre_release_version.version
end
def app_id
raise "No app included" unless app
return app.id
end
def bundle_id
raise "No app included" unless app
return app.bundle_id
end
def platform
raise "No pre_release_version included" unless pre_release_version
return pre_release_version.platform
end
def processed?
return processing_state != ProcessingState::PROCESSING
end
def ready_for_internal_testing?
return build_beta_detail.nil? == false && build_beta_detail.ready_for_internal_testing?
end
def ready_for_external_testing?
return build_beta_detail.nil? == false && build_beta_detail.ready_for_external_testing?
end
def ready_for_beta_submission?
raise "No build_beta_detail included" unless build_beta_detail
return build_beta_detail.ready_for_beta_submission?
end
def missing_export_compliance?
raise "No build_beta_detail included" unless build_beta_detail
return build_beta_detail.missing_export_compliance?
end
# This is here temporarily until the removal of Spaceship::TestFlight
def to_testflight_build
h = {
'id' => id,
'buildVersion' => version,
'uploadDate' => uploaded_date,
'externalState' => processed? ? Spaceship::TestFlight::Build::BUILD_STATES[:active] : Spaceship::TestFlight::Build::BUILD_STATES[:processing],
'appAdamId' => app_id,
'bundleId' => bundle_id,
'trainVersion' => app_version
}
return Spaceship::TestFlight::Build.new(h)
end
#
# API
#
def self.all(client: nil, app_id: nil, version: nil, build_number: nil, platform: nil, processing_states: "PROCESSING,FAILED,INVALID,VALID", includes: ESSENTIAL_INCLUDES, sort: "-uploadedDate", limit: 30)
client ||= Spaceship::ConnectAPI
resps = client.get_builds(
filter: { app: app_id, "preReleaseVersion.version" => version, version: build_number, processingState: processing_states },
includes: includes,
sort: sort,
limit: limit
).all_pages
models = resps.flat_map(&:to_models)
# Filtering after models are fetched since there is no way to do this in a query param filter
if platform
models = models.select do |build|
build.pre_release_version && build.pre_release_version.platform == platform
end
end
return models
end
def self.get(client: nil, build_id: nil, includes: ESSENTIAL_INCLUDES)
client ||= Spaceship::ConnectAPI
return client.get_build(build_id: build_id, includes: includes).first
end
def update(client: nil, attributes: nil)
client ||= Spaceship::ConnectAPI
attributes = reverse_attr_mapping(attributes)
return client.patch_builds(build_id: id, attributes: attributes).first
end
def add_beta_groups(client: nil, beta_groups: nil)
client ||= Spaceship::ConnectAPI
beta_groups ||= []
beta_group_ids = beta_groups.map(&:id)
return client.add_beta_groups_to_build(build_id: id, beta_group_ids: beta_group_ids)
end
def get_beta_build_localizations(client: nil, filter: {}, includes: nil, limit: nil, sort: nil)
client ||= Spaceship::ConnectAPI
resps = client.get_beta_build_localizations(
filter: { build: id },
includes: includes,
sort: sort,
limit: limit
).all_pages
return resps.flat_map(&:to_models)
end
def get_build_beta_details(client: nil, filter: {}, includes: nil, limit: nil, sort: nil)
client ||= Spaceship::ConnectAPI
resps = client.get_build_beta_details(
filter: { build: id },
includes: includes,
sort: sort,
limit: limit
).all_pages
return resps.flat_map(&:to_models)
end
def post_beta_app_review_submission(client: nil)
client ||= Spaceship::ConnectAPI
return client.post_beta_app_review_submissions(build_id: id)
end
def expire!(client: nil)
client ||= Spaceship::ConnectAPI
return client.patch_builds(build_id: id, attributes: { expired: true })
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/app_data_usage.rb | spaceship/lib/spaceship/connect_api/models/app_data_usage.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class AppDataUsage
include Spaceship::ConnectAPI::Model
attr_accessor :category
attr_accessor :grouping
attr_accessor :purpose
attr_accessor :data_protection
attr_mapping({
"category" => "category",
"grouping" => "grouping",
"dataProtection" => "data_protection"
})
def self.type
return "appDataUsages"
end
#
# Helpers
#
def is_not_collected?
return false unless data_protection
return data_protection.id == "DATA_NOT_COLLECTED"
end
#
# API
#
def self.all(app_id:, filter: {}, includes: nil, limit: nil, sort: nil)
raise "app_id is required " if app_id.nil?
resps = Spaceship::ConnectAPI.get_app_data_usages(app_id: app_id, filter: filter, includes: includes, limit: limit, sort: sort).all_pages
return resps.flat_map(&:to_models)
end
def self.create(app_id:, app_data_usage_category_id: nil, app_data_usage_protection_id: nil, app_data_usage_purpose_id: nil)
raise "app_id is required " if app_id.nil?
resp = Spaceship::ConnectAPI.post_app_data_usage(
app_id: app_id,
app_data_usage_category_id: app_data_usage_category_id,
app_data_usage_protection_id: app_data_usage_protection_id,
app_data_usage_purpose_id: app_data_usage_purpose_id
)
return resp.to_models.first
end
def delete!
Spaceship::ConnectAPI.delete_app_data_usage(app_data_usage_id: id)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/app_store_version.rb | spaceship/lib/spaceship/connect_api/models/app_store_version.rb | require_relative '../model'
require_relative './app_store_review_detail'
require_relative './app_store_version_localization'
module Spaceship
class ConnectAPI
class AppStoreVersion
include Spaceship::ConnectAPI::Model
attr_accessor :platform
attr_accessor :version_string
attr_accessor :app_store_state
attr_accessor :app_version_state
attr_accessor :store_icon
attr_accessor :watch_store_icon
attr_accessor :copyright
attr_accessor :release_type
attr_accessor :earliest_release_date # 2020-06-17T12:00:00-07:00
attr_accessor :is_watch_only
attr_accessor :downloadable
attr_accessor :created_date
attr_accessor :review_type
attr_accessor :app_store_version_submission
attr_accessor :app_store_version_phased_release
attr_accessor :app_store_review_detail
attr_accessor :app_store_version_localizations
# Deprecated in App Store Connect API specification 3.3
module AppStoreState
ACCEPTED = "ACCEPTED"
DEVELOPER_REJECTED = "DEVELOPER_REJECTED"
DEVELOPER_REMOVED_FROM_SALE = "DEVELOPER_REMOVED_FROM_SALE"
IN_REVIEW = "IN_REVIEW"
INVALID_BINARY = "INVALID_BINARY"
METADATA_REJECTED = "METADATA_REJECTED"
PENDING_APPLE_RELEASE = "PENDING_APPLE_RELEASE"
PENDING_CONTRACT = "PENDING_CONTRACT"
PENDING_DEVELOPER_RELEASE = "PENDING_DEVELOPER_RELEASE"
PREORDER_READY_FOR_SALE = "PREORDER_READY_FOR_SALE"
PREPARE_FOR_SUBMISSION = "PREPARE_FOR_SUBMISSION"
PROCESSING_FOR_APP_STORE = "PROCESSING_FOR_APP_STORE"
READY_FOR_REVIEW = "READY_FOR_REVIEW"
READY_FOR_SALE = "READY_FOR_SALE"
REJECTED = "REJECTED"
REMOVED_FROM_SALE = "REMOVED_FROM_SALE"
REPLACED_WITH_NEW_VERSION = "REPLACED_WITH_NEW_VERSION"
WAITING_FOR_EXPORT_COMPLIANCE = "WAITING_FOR_EXPORT_COMPLIANCE"
WAITING_FOR_REVIEW = "WAITING_FOR_REVIEW"
NOT_APPLICABLE = "NOT_APPLICABLE"
end
module AppVersionState
ACCEPTED = "ACCEPTED"
DEVELOPER_REJECTED = "DEVELOPER_REJECTED"
IN_REVIEW = "IN_REVIEW"
INVALID_BINARY = "INVALID_BINARY"
METADATA_REJECTED = "METADATA_REJECTED"
PENDING_APPLE_RELEASE = "PENDING_APPLE_RELEASE"
PENDING_DEVELOPER_RELEASE = "PENDING_DEVELOPER_RELEASE"
PREPARE_FOR_SUBMISSION = "PREPARE_FOR_SUBMISSION"
PROCESSING_FOR_DISTRIBUTION = "PROCESSING_FOR_DISTRIBUTION"
READY_FOR_DISTRIBUTION = "READY_FOR_DISTRIBUTION"
READY_FOR_REVIEW = "READY_FOR_REVIEW"
REJECTED = "REJECTED"
REPLACED_WITH_NEW_VERSION = "REPLACED_WITH_NEW_VERSION"
WAITING_FOR_EXPORT_COMPLIANCE = "WAITING_FOR_EXPORT_COMPLIANCE"
WAITING_FOR_REVIEW = "WAITING_FOR_REVIEW"
end
module ReleaseType
AFTER_APPROVAL = "AFTER_APPROVAL"
MANUAL = "MANUAL"
SCHEDULED = "SCHEDULED"
end
module ReviewType
APP_STORE = "APP_STORE"
NOTARIZATION = "NOTARIZATION"
end
attr_mapping({
"platform" => "platform",
"versionString" => "version_string",
"appStoreState" => "app_store_state",
"appVersionState" => "app_version_state",
"storeIcon" => "store_icon",
"watchStoreIcon" => "watch_store_icon",
"copyright" => "copyright",
"releaseType" => "release_type",
"earliestReleaseDate" => "earliest_release_date",
"isWatchOnly" => "is_watch_only",
"downloadable" => "downloadable",
"createdDate" => "created_date",
"reviewType" => "review_type",
"appStoreVersionSubmission" => "app_store_version_submission",
"build" => "build",
"appStoreVersionPhasedRelease" => "app_store_version_phased_release",
"appStoreReviewDetail" => "app_store_review_detail",
"appStoreVersionLocalizations" => "app_store_version_localizations"
})
ESSENTIAL_INCLUDES = [
"appStoreVersionSubmission",
"build"
].join(",")
def self.type
return "appStoreVersions"
end
def can_reject?
raise "No app_store_version_submission included" unless app_store_version_submission
return app_store_version_submission.can_reject
end
def reject!
return false unless can_reject?
app_store_version_submission.delete!
return true
end
#
# API
#
# app,routingAppCoverage,resetRatingsRequest,appStoreVersionSubmission,appStoreVersionPhasedRelease,ageRatingDeclaration,appStoreReviewDetail,gameCenterConfiguration
def self.get(client: nil, app_store_version_id: nil, includes: nil, limit: nil, sort: nil)
client ||= Spaceship::ConnectAPI
return client.get_app_store_version(
app_store_version_id: app_store_version_id,
includes: includes
).first
end
def update(client: nil, attributes: nil)
client ||= Spaceship::ConnectAPI
attributes = reverse_attr_mapping(attributes)
return client.patch_app_store_version(app_store_version_id: id, attributes: attributes).first
end
#
# Age Rating Declaration
#
# @deprecated
def fetch_age_rating_declaration(client: nil)
raise 'AppStoreVersion no longer has AgeRatingDeclaration as of App Store Connect API 1.3 - Use AppInfo instead'
end
#
# App Store Version Localizations
#
def create_app_store_version_localization(client: nil, attributes: nil)
client ||= Spaceship::ConnectAPI
resp = client.post_app_store_version_localization(app_store_version_id: id, attributes: attributes)
return resp.to_models.first
end
def get_app_store_version_localizations(client: nil, filter: {}, includes: nil, limit: nil, sort: nil)
client ||= Spaceship::ConnectAPI
return Spaceship::ConnectAPI::AppStoreVersionLocalization.all(client: client, app_store_version_id: id, filter: filter, includes: includes, limit: limit, sort: sort)
end
#
# App Store Review Detail
#
def create_app_store_review_detail(client: nil, attributes: nil)
client ||= Spaceship::ConnectAPI
attributes = Spaceship::ConnectAPI::AppStoreReviewDetail.reverse_attr_mapping(attributes)
resp = client.post_app_store_review_detail(app_store_version_id: id, attributes: attributes)
return resp.to_models.first
end
def fetch_app_store_review_detail(client: nil, includes: "appStoreReviewAttachments")
client ||= Spaceship::ConnectAPI
resp = client.get_app_store_review_detail(app_store_version_id: id, includes: includes)
return resp.to_models.first
end
#
# App Store Version Phased Releases
#
def fetch_app_store_version_phased_release(client: nil)
client ||= Spaceship::ConnectAPI
resp = client.get_app_store_version_phased_release(app_store_version_id: id)
return resp.to_models.first
end
def create_app_store_version_phased_release(client: nil, attributes: nil)
client ||= Spaceship::ConnectAPI
resp = client.post_app_store_version_phased_release(app_store_version_id: id, attributes: attributes)
return resp.to_models.first
end
#
# App Store Version Submissions
#
def fetch_app_store_version_submission(client: nil)
client ||= Spaceship::ConnectAPI
resp = client.get_app_store_version_submission(app_store_version_id: id)
return resp.to_models.first
end
def create_app_store_version_submission(client: nil)
client ||= Spaceship::ConnectAPI
resp = client.post_app_store_version_submission(app_store_version_id: id)
return resp.to_models.first
end
#
# App Store Version Release Requests
#
def create_app_store_version_release_request(client: nil)
client ||= Spaceship::ConnectAPI
resp = client.post_app_store_version_release_request(app_store_version_id: id)
return resp.to_models.first
end
#
# Build
#
def get_build(client: nil, build_id: nil)
client ||= Spaceship::ConnectAPI
resp = client.get_build(app_store_version_id: id, build_id: build_id)
return resp.to_models.first
end
def select_build(client: nil, build_id: nil)
client ||= Spaceship::ConnectAPI
resp = client.patch_app_store_version_with_build(app_store_version_id: id, build_id: build_id)
return resp.to_models.first
end
#
# Reset Ratings Requests
#
def fetch_reset_ratings_request(client: nil)
client ||= Spaceship::ConnectAPI
resp = client.get_reset_ratings_request(app_store_version_id: id)
return resp.to_models.first
end
def create_reset_ratings_request(client: nil)
client ||= Spaceship::ConnectAPI
resp = client.post_reset_ratings_request(app_store_version_id: id)
return resp.to_models.first
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/app_price.rb | spaceship/lib/spaceship/connect_api/models/app_price.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class AppPrice
include Spaceship::ConnectAPI::Model
attr_accessor :start_date
attr_accessor :price_tier
attr_mapping({
"startDate" => "start_date",
"priceTier" => "price_tier"
})
def self.type
return "appPrices"
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/beta_tester_metric.rb | spaceship/lib/spaceship/connect_api/models/beta_tester_metric.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class BetaTesterMetric
include Spaceship::ConnectAPI::Model
attr_accessor :install_count
attr_accessor :crash_count
attr_accessor :session_count
attr_accessor :beta_tester_state
attr_accessor :last_modified_date
attr_accessor :installed_cf_bundle_short_version_string
attr_accessor :installed_cf_bundle_version
attr_mapping({
"installCount" => "install_count",
"crashCount" => "crash_count",
"sessionCount" => "session_count",
"betaTesterState" => "beta_tester_state",
"lastModifiedDate" => "last_modified_date",
"installedCfBundleShortVersionString" => "installed_cf_bundle_short_version_string",
"installedCfBundleVersion" => "installed_cf_bundle_version"
})
module BetaTesterState
INSTALLED = "INSTALLED"
INVITED = "INVITED"
NO_BUILDS = "NO_BUILDS"
end
def self.type
return "betaTesterMetrics"
end
#
# Helpers
#
def installed?
return beta_tester_state == BetaTesterState::INSTALLED
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/app_price_point.rb | spaceship/lib/spaceship/connect_api/models/app_price_point.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class AppPricePoint
include Spaceship::ConnectAPI::Model
attr_accessor :customer_price
attr_accessor :proceeds
attr_accessor :price_tier
attr_accessor :territory
attr_mapping({
"customerPrice" => "customer_price",
"proceeds" => "proceeds",
"priceTier" => "price_tier",
"territory" => "territory"
})
def self.type
return "appPricePoints"
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/app_data_usages_publish_state.rb | spaceship/lib/spaceship/connect_api/models/app_data_usages_publish_state.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class AppDataUsagesPublishState
include Spaceship::ConnectAPI::Model
attr_accessor :published
attr_accessor :last_published
attr_accessor :last_published_by
attr_mapping({
"published" => "published",
"lastPublished" => "last_published",
"lastPublishedBy" => "last_published_by"
})
def self.type
return "appDataUsagesPublishState"
end
#
# API
#
def self.get(app_id: nil)
resp = Spaceship::ConnectAPI.get_app_data_usages_publish_state(app_id: app_id)
return resp.to_models.first
end
def publish!
resp = Spaceship::ConnectAPI.patch_app_data_usages_publish_state(app_data_usages_publish_state_id: id, published: true)
return resp.to_models.first
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/beta_tester.rb | spaceship/lib/spaceship/connect_api/models/beta_tester.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class BetaTester
include Spaceship::ConnectAPI::Model
attr_accessor :first_name
attr_accessor :last_name
attr_accessor :email
attr_accessor :invite_type
attr_accessor :beta_tester_state
attr_accessor :is_deleted
attr_accessor :last_modified_date
attr_accessor :installed_cf_bundle_short_version_string
attr_accessor :installed_cf_bundle_version
attr_accessor :remove_after_date
attr_accessor :installed_device
attr_accessor :installed_os_version
attr_accessor :number_of_installed_devices
attr_accessor :latest_expiring_cf_bundle_short_version_string
attr_accessor :latest_expiring_cf_bundle_version_string
attr_accessor :installed_device_platform
attr_accessor :latest_installed_device
attr_accessor :latest_installed_os_version
attr_accessor :latest_installed_device_platform
attr_accessor :apps
attr_accessor :beta_groups
attr_accessor :beta_tester_metrics
attr_accessor :builds
attr_mapping({
"firstName" => "first_name",
"lastName" => "last_name",
"email" => "email",
"inviteType" => "invite_type",
"betaTesterState" => "beta_tester_state",
"isDeleted" => "is_deleted",
"lastModifiedDate" => "last_modified_date",
"installedCfBundleShortVersionString" => "installed_cf_bundle_short_version_string",
"installedCfBundleVersion" => "installed_cf_bundle_version",
"removeAfterDate" => "remove_after_date",
"installedDevice" => "installed_device",
"installedOsVersion" => "installed_os_version",
"numberOfInstalledDevices" => "number_of_installed_devices",
"latestExpiringCfBundleShortVersionString" => "latest_expiring_cf_bundle_short_version_string",
"latestExpiringCfBundleVersionString" => "latest_expiring_cf_bundle_version_string",
"installedDevicePlatform" => "installed_device_platform",
"latestInstalledDevice" => "latest_installed_device",
"latestInstalledOsVersion" => "latest_installed_os_version",
"latestInstalledDevicePlatform" => "latest_installed_device_platform",
"apps" => "apps",
"betaGroups" => "beta_groups",
"betaTesterMetrics" => "beta_tester_metrics",
"builds" => "builds"
})
def self.type
return "betaTesters"
end
#
# API
#
def self.all(client: nil, filter: {}, includes: nil, limit: nil, sort: nil)
client ||= Spaceship::ConnectAPI
resps = client.get_beta_testers(filter: filter, includes: includes).all_pages
return resps.flat_map(&:to_models)
end
def self.find(client: nil, email: nil, includes: nil)
client ||= Spaceship::ConnectAPI
return all(client: client, filter: { email: email }, includes: includes).first
end
def delete_from_apps(client: nil, apps: nil)
client ||= Spaceship::ConnectAPI
app_ids = apps.map(&:id)
return client.delete_beta_tester_from_apps(beta_tester_id: id, app_ids: app_ids)
end
def delete_from_beta_groups(client: nil, beta_groups: nil)
client ||= Spaceship::ConnectAPI
beta_group_ids = beta_groups.map(&:id)
return client.delete_beta_tester_from_beta_groups(beta_tester_id: id, beta_group_ids: beta_group_ids)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/review_submission.rb | spaceship/lib/spaceship/connect_api/models/review_submission.rb | require_relative '../model'
require_relative './review_submission_item'
module Spaceship
class ConnectAPI
class ReviewSubmission
include Spaceship::ConnectAPI::Model
attr_accessor :platform
attr_accessor :state
attr_accessor :submitted_date
attr_accessor :app_store_version_for_review
attr_accessor :items
attr_accessor :last_updated_by_actor
attr_accessor :submitted_by_actor
module ReviewSubmissionState
CANCELING = "CANCELING"
COMPLETE = "COMPLETE"
IN_REVIEW = "IN_REVIEW"
READY_FOR_REVIEW = "READY_FOR_REVIEW"
UNRESOLVED_ISSUES = "UNRESOLVED_ISSUES"
WAITING_FOR_REVIEW = "WAITING_FOR_REVIEW"
end
attr_mapping({
"platform" => "platform",
"state" => "state",
"submittedDate" => "submitted_date",
"appStoreVersionForReview" => "app_store_version_for_review",
"items" => "items",
"lastUpdatedByActor" => "last_updated_by_actor",
"submittedByActor" => "submitted_by_actor",
})
def self.type
return "reviewSubmissions"
end
#
# API
#
# appStoreVersionForReview,items,submittedByActor,lastUpdatedByActor
def self.get(client: nil, review_submission_id:, includes: nil)
client ||= Spaceship::ConnectAPI
resp = client.get_review_submission(review_submission_id: review_submission_id, includes: includes)
return resp.to_models.first
end
def submit_for_review(client: nil)
client ||= Spaceship::ConnectAPI
attributes = { submitted: true }
resp = client.patch_review_submission(review_submission_id: id, attributes: attributes)
return resp.to_models.first
end
def cancel_submission(client: nil)
client ||= Spaceship::ConnectAPI
attributes = { canceled: true }
resp = client.patch_review_submission(review_submission_id: id, attributes: attributes)
return resp.to_models.first
end
def add_app_store_version_to_review_items(client: nil, app_store_version_id:)
client ||= Spaceship::ConnectAPI
resp = client.post_review_submission_item(review_submission_id: id, app_store_version_id: app_store_version_id)
return resp.to_models.first
end
def fetch_resolution_center_threads(client: nil)
client ||= Spaceship::ConnectAPI
resp = client.get_resolution_center_threads(filter: { reviewSubmission: id }, includes: 'reviewSubmission')
return resp.to_models
end
def latest_resolution_center_messages(client: nil)
client ||= Spaceship::ConnectAPI
threads = fetch_resolution_center_threads(client: client)
threads.first.fetch_messages(client: client)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/app_availability.rb | spaceship/lib/spaceship/connect_api/models/app_availability.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class AppAvailability
include Spaceship::ConnectAPI::Model
attr_accessor :app
attr_accessor :available_in_new_territories
attr_accessor :territoryAvailabilities
attr_mapping({
app: 'app',
availableInNewTerritories: 'available_in_new_territories',
territoryAvailabilities: 'territory_availabilities'
})
def self.type
return 'appAvailabilities'
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/resolution_center_thread.rb | spaceship/lib/spaceship/connect_api/models/resolution_center_thread.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class ResolutionCenterThread
include Spaceship::ConnectAPI::Model
attr_accessor :state
attr_accessor :can_developer_add_node
attr_accessor :objectionable_content
attr_accessor :thread_type
attr_accessor :created_date
attr_accessor :last_message_response_date
attr_accessor :resolution_center_messages
attr_accessor :app_store_version
module ThreadType
REJECTION_BINARY = 'REJECTION_BINARY'
REJECTION_METADATA = 'REJECTION_METADATA'
REJECTION_REVIEW_SUBMISSION = 'REJECTION_REVIEW_SUBMISSION'
APP_MESSAGE_ARC = 'APP_MESSAGE_ARC'
APP_MESSAGE_ARB = 'APP_MESSAGE_ARB'
APP_MESSAGE_COMM = 'APP_MESSAGE_COMM'
end
attr_mapping({
state: 'state',
canDeveloperAddNote: 'can_developer_add_node',
objectionableContent: 'objectionable_content',
threadType: 'thread_type',
createdDate: 'created_date',
lastMessageResponseDate: 'last_message_response_date',
# includes
resolutionCenterMessages: 'resolution_center_messages',
appStoreVersion: 'app_store_version'
})
def self.type
return "resolutionCenterThreads"
end
#
# API
#
def self.all(client: nil, filter:, includes: nil)
client ||= Spaceship::ConnectAPI
resps = client.get_resolution_center_threads(filter: filter, includes: includes).all_pages
return resps.flat_map(&:to_models)
end
def fetch_messages(client: nil, filter: {}, includes: nil)
client ||= Spaceship::ConnectAPI
resps = client.get_resolution_center_messages(thread_id: id, filter: filter, includes: includes).all_pages
return resps.flat_map(&:to_models)
end
def fetch_rejection_reasons(client: nil, includes: nil)
client ||= Spaceship::ConnectAPI
resp = client.get_review_rejection(filter: { 'resolutionCenterMessage.resolutionCenterThread': id }, includes: includes)
return resp.to_models
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/review_rejection.rb | spaceship/lib/spaceship/connect_api/models/review_rejection.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class ReviewRejection
include Spaceship::ConnectAPI::Model
attr_accessor :reasons
attr_mapping({
reasons: 'reasons'
})
def self.type
return 'reviewRejections'
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/user_invitation.rb | spaceship/lib/spaceship/connect_api/models/user_invitation.rb | require_relative '../model'
require_relative 'user'
module Spaceship
class ConnectAPI
class UserInvitation
include Spaceship::ConnectAPI::Model
attr_accessor :first_name
attr_accessor :last_name
attr_accessor :email
attr_accessor :roles
attr_accessor :all_apps_visible
attr_accessor :provisioning_allowed
attr_accessor :visible_apps
attr_mapping({
"firstName" => "first_name",
"lastName" => "last_name",
"email" => "email",
"roles" => "roles",
"allAppsVisible" => "all_apps_visible",
"provisioningAllowed" => "provisioning_allowed",
"visibleApps" => "visible_apps"
})
ESSENTIAL_INCLUDES = [
"visibleApps"
].join(",")
UserRole = Spaceship::ConnectAPI::User::UserRole
def self.type
return "userInvitations"
end
#
# Managing invitations
#
def self.all(client: nil, filter: {}, includes: ESSENTIAL_INCLUDES, sort: nil)
client ||= Spaceship::ConnectAPI
resps = client.get_user_invitations(filter: filter, includes: includes, sort: sort).all_pages
return resps.flat_map(&:to_models)
end
def self.find(client: nil, email: nil, includes: ESSENTIAL_INCLUDES)
client ||= Spaceship::ConnectAPI
return all(client: client, filter: { email: email }, includes: includes)
end
# Create and post user invitation
# App Store Connect allows for the following combinations of `all_apps_visible` and `visible_app_ids`:
# - if `all_apps_visible` is `nil`, you don't have to provide values for `visible_app_ids`
# - if `all_apps_visible` is false, you must provide values for `visible_app_ids`.
# - if `all_apps_visible` is true, you must not provide values for `visible_app_ids`.
def self.create(client: nil, email: nil, first_name: nil, last_name: nil, roles: [], provisioning_allowed: nil, all_apps_visible: nil, visible_app_ids: [])
client ||= Spaceship::ConnectAPI
resp = client.post_user_invitation(
email: email,
first_name: first_name,
last_name: last_name,
roles: roles,
provisioning_allowed: provisioning_allowed,
all_apps_visible: all_apps_visible,
visible_app_ids: visible_app_ids
)
return resp.to_models.first
end
def delete!(client: nil)
client ||= Spaceship::ConnectAPI
client.delete_user_invitation(user_invitation_id: id)
end
# Get visible apps for invited user
def get_visible_apps(client: nil, limit: nil)
client ||= Spaceship::ConnectAPI
resp = client.get_user_invitation_visible_apps(user_invitation_id: id, limit: limit)
return resp.to_models
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/beta_app_review_submission.rb | spaceship/lib/spaceship/connect_api/models/beta_app_review_submission.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class BetaAppReviewSubmission
include Spaceship::ConnectAPI::Model
attr_accessor :beta_review_state
attr_mapping({
"betaReviewState" => "beta_review_state"
})
def self.type
return "betaAppReviewSubmissions"
end
#
# API
#
def delete!(client: nil)
client ||= Spaceship::ConnectAPI
return client.delete_beta_app_review_submission(beta_app_review_submission_id: id)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/app_screenshot.rb | spaceship/lib/spaceship/connect_api/models/app_screenshot.rb | require_relative '../model'
require_relative '../file_uploader'
require_relative './app_screenshot_set'
require 'spaceship/globals'
require 'digest/md5'
module Spaceship
class ConnectAPI
class AppScreenshot
include Spaceship::ConnectAPI::Model
attr_accessor :file_size
attr_accessor :file_name
attr_accessor :source_file_checksum
attr_accessor :image_asset
attr_accessor :asset_token
attr_accessor :asset_type
attr_accessor :upload_operations
attr_accessor :asset_delivery_state
attr_accessor :uploaded
attr_mapping({
"fileSize" => "file_size",
"fileName" => "file_name",
"sourceFileChecksum" => "source_file_checksum",
"imageAsset" => "image_asset",
"assetToken" => "asset_token",
"assetType" => "asset_type",
"uploadOperations" => "upload_operations",
"assetDeliveryState" => "asset_delivery_state",
"uploaded" => "uploaded"
})
def self.type
return "appScreenshots"
end
def awaiting_upload?
(asset_delivery_state || {})["state"] == "AWAITING_UPLOAD"
end
def complete?
(asset_delivery_state || {})["state"] == "COMPLETE"
end
def error?
(asset_delivery_state || {})["state"] == "FAILED"
end
def error_messages
errors = (asset_delivery_state || {})["errors"]
(errors || []).map do |error|
[error["code"], error["description"]].compact.join(" - ")
end
end
# This does not download the source image (exact image that was uploaded)
# This downloads a modified version.
# This image won't have the same checksums as source_file_checksum.
#
# There is an open radar for allowing downloading of source file.
# https://openradar.appspot.com/radar?id=4980344105205760
def image_asset_url(width: nil, height: nil, type: "png")
return nil if image_asset.nil?
template_url = image_asset["templateUrl"]
width ||= image_asset["width"]
height ||= image_asset["height"]
return template_url
.gsub("{w}", width.to_s)
.gsub("{h}", height.to_s)
.gsub("{f}", type)
end
#
# API
#
#
def self.create(client: nil, app_screenshot_set_id: nil, path: nil, wait_for_processing: true)
client ||= Spaceship::ConnectAPI
require 'faraday'
filename = File.basename(path)
filesize = File.size(path)
bytes = File.binread(path)
post_attributes = {
fileSize: filesize,
fileName: filename
}
# Create placeholder to upload screenshot
begin
screenshot = client.post_app_screenshot(
app_screenshot_set_id: app_screenshot_set_id,
attributes: post_attributes
).first
rescue => error
# Sometimes creating a screenshot with the web session App Store Connect API
# will result in a false failure. The response will return a 503 but the database
# insert will eventually go through.
#
# When this is observed, we will poll until we find the matching screenshot that
# is awaiting for upload and file size
#
# https://github.com/fastlane/fastlane/pull/16842
time = Time.now.to_i
timeout_minutes = (ENV["SPACESHIP_SCREENSHOT_UPLOAD_TIMEOUT"] || 20).to_i
loop do
# This error handling needs to be revised since any error occurred can reach here.
# It should handle errors based on what status code is.
puts("Waiting for screenshots to appear before uploading. This is unlikely to be recovered unless it's 503 error. error=\"#{error}\"")
sleep(30)
screenshots = Spaceship::ConnectAPI::AppScreenshotSet
.get(client: client, app_screenshot_set_id: app_screenshot_set_id)
.app_screenshots
screenshot = screenshots.find do |s|
s.awaiting_upload? && s.file_size == filesize
end
break if screenshot
time_diff = Time.now.to_i - time
raise error if time_diff >= (60 * timeout_minutes)
end
end
# Upload the file
upload_operations = screenshot.upload_operations
Spaceship::ConnectAPI::FileUploader.upload(upload_operations, bytes)
# Update file uploading complete
patch_attributes = {
uploaded: true,
sourceFileChecksum: Digest::MD5.hexdigest(bytes)
}
# Patch screenshot that file upload is complete
# Catch error if patch retries due to 504. Original patch
# may go through by return response as 504.
begin
screenshot = Spaceship::ConnectAPI.patch_app_screenshot(
app_screenshot_id: screenshot.id,
attributes: patch_attributes
).first
rescue => error
puts("Failed to patch app screenshot. Update may have gone through so verifying") if Spaceship::Globals.verbose?
screenshot = client.get_app_screenshot(app_screenshot_id: screenshot.id).first
raise error unless screenshot.complete?
end
# Wait for processing
if wait_for_processing
loop do
if screenshot.complete?
puts("Screenshot processing complete!") if Spaceship::Globals.verbose?
break
elsif screenshot.error?
messages = ["Error processing screenshot '#{screenshot.file_name}'"] + screenshot.error_messages
raise messages.join(". ")
end
# Poll every 2 seconds
sleep_time = 2
puts("Waiting #{sleep_time} seconds before checking status of processing...") if Spaceship::Globals.verbose?
sleep(sleep_time)
screenshot = client.get_app_screenshot(app_screenshot_id: screenshot.id).first
end
end
return screenshot
end
def delete!(client: nil, filter: {}, includes: nil, limit: nil, sort: nil)
client ||= Spaceship::ConnectAPI
client.delete_app_screenshot(app_screenshot_id: id)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/age_rating_declaration.rb | spaceship/lib/spaceship/connect_api/models/age_rating_declaration.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class AgeRatingDeclaration
include Spaceship::ConnectAPI::Model
# Rating
attr_accessor :alcohol_tobacco_or_drug_use_or_references
attr_accessor :contests
attr_accessor :gambling_simulated
attr_accessor :guns_or_other_weapons
attr_accessor :horror_or_fear_themes
attr_accessor :mature_or_suggestive_themes
attr_accessor :medical_or_treatment_information
attr_accessor :profanity_or_crude_humor
attr_accessor :sexual_content_graphic_and_nudity
attr_accessor :sexual_content_or_nudity
attr_accessor :violence_cartoon_or_fantasy
attr_accessor :violence_realistic_prolonged_graphic_or_sadistic
attr_accessor :violence_realistic
# Boolean
attr_accessor :advertising
attr_accessor :age_assurance
attr_accessor :gambling
attr_accessor :health_or_wellness_topics
attr_accessor :loot_box
attr_accessor :messaging_and_chat
attr_accessor :parental_controls
attr_accessor :unrestricted_web_access
attr_accessor :user_generated_content
# AgeRating
attr_accessor :age_rating_override_v2
# KoreaAgeRating
attr_accessor :korea_age_rating_override
# KidsAge
attr_accessor :kids_age_band
# URL
attr_accessor :developer_age_rating_info_url
# Deprecated as of App Store Connect API 1.3
attr_accessor :gambling_and_contests
module Rating
NONE = "NONE"
INFREQUENT = "INFREQUENT"
INFREQUENT_OR_MILD = "INFREQUENT_OR_MILD"
FREQUENT = "FREQUENT"
FREQUENT_OR_INTENSE = "FREQUENT_OR_INTENSE"
end
module AgeRating
NONE = "NONE"
NINE_PLUS = "NINE_PLUS"
THIRTEEN_PLUS = "THIRTEEN_PLUS"
SIXTEEN_PLUS = "SIXTEEN_PLUS"
EIGHTEEN_PLUS = "EIGHTEEN_PLUS"
UNRATED = "UNRATED"
end
module KoreaAgeRating
NONE = "NONE"
FIFTEEN_PLUS = "FIFTEEN_PLUS"
NINETEEN_PLUS = "NINETEEN_PLUS"
end
module KidsAge
FIVE_AND_UNDER = "FIVE_AND_UNDER"
SIX_TO_EIGHT = "SIX_TO_EIGHT"
NINE_TO_ELEVEN = "NINE_TO_ELEVEN"
end
attr_mapping({
"advertising" => "advertising",
"ageAssurance" => "age_assurance",
"ageRatingOverrideV2" => "age_rating_override_v2",
"alcoholTobaccoOrDrugUseOrReferences" => "alcohol_tobacco_or_drug_use_or_references",
"contests" => "contests",
"developerAgeRatingInfoUrl" => "developer_age_rating_info_url",
"gambling" => "gambling",
"gamblingSimulated" => "gambling_simulated",
"gunsOrOtherWeapons" => "guns_or_other_weapons",
"healthOrWellnessTopics" => "health_or_wellness_topics",
"horrorOrFearThemes" => "horror_or_fear_themes",
"kidsAgeBand" => "kids_age_band",
"koreaAgeRatingOverride" => "korea_age_rating_override",
"lootBox" => "loot_box",
"matureOrSuggestiveThemes" => "mature_or_suggestive_themes",
"medicalOrTreatmentInformation" => "medical_or_treatment_information",
"messagingAndChat" => "messaging_and_chat",
"parentalControls" => "parental_controls",
"profanityOrCrudeHumor" => "profanity_or_crude_humor",
"sexualContentGraphicAndNudity" => "sexual_content_graphic_and_nudity",
"sexualContentOrNudity" => "sexual_content_or_nudity",
"unrestrictedWebAccess" => "unrestricted_web_access",
"userGeneratedContent" => "user_generated_content",
"violenceCartoonOrFantasy" => "violence_cartoon_or_fantasy",
"violenceRealisticProlongedGraphicOrSadistic" => "violence_realistic_prolonged_graphic_or_sadistic",
"violenceRealistic" => "violence_realistic",
# Deprecated as of App Store Connect API 1.3 - No longer accepted by API
"gamblingAndContests" => "gambling_and_contests",
})
def self.type
return "ageRatingDeclarations"
end
LEGACY_AGE_RATING_ITC_MAP = {
"CARTOON_FANTASY_VIOLENCE" => "violenceCartoonOrFantasy",
"REALISTIC_VIOLENCE" => "violenceRealistic",
"PROLONGED_GRAPHIC_SADISTIC_REALISTIC_VIOLENCE" => "violenceRealisticProlongedGraphicOrSadistic",
"PROFANITY_CRUDE_HUMOR" => "profanityOrCrudeHumor",
"MATURE_SUGGESTIVE" => "matureOrSuggestiveThemes",
"HORROR" => "horrorOrFearThemes",
"MEDICAL_TREATMENT_INFO" => "medicalOrTreatmentInformation",
"ALCOHOL_TOBACCO_DRUGS" => "alcoholTobaccoOrDrugUseOrReferences",
"GAMBLING" => "gamblingSimulated",
"SEXUAL_CONTENT_NUDITY" => "sexualContentOrNudity",
"GRAPHIC_SEXUAL_CONTENT_NUDITY" => "sexualContentGraphicAndNudity",
"UNRESTRICTED_WEB_ACCESS" => "unrestrictedWebAccess",
"GAMBLING_CONTESTS" => "gamblingAndContests"
}
LEGACY_RATING_VALUE_ITC_MAP = {
0 => Rating::NONE,
1 => Rating::INFREQUENT_OR_MILD,
2 => Rating::FREQUENT_OR_INTENSE
}
LEGACY_BOOLEAN_VALUE_ITC_MAP = {
0 => false,
1 => true
}
def self.map_deprecation_if_possible(attributes)
attributes = attributes.dup
messages = []
errors = []
value = attributes.delete('gamblingAndContests')
return attributes, messages, errors if value.nil?
messages << "Age Rating 'gamblingAndContests' has been deprecated and split into 'gambling' and 'contests'"
attributes['gambling'] = value
if value == true
errors << "'gamblingAndContests' could not be mapped to 'contests' - 'contests' requires a value of 'NONE', 'INFREQUENT_OR_MILD', or 'FREQUENT_OR_INTENSE'"
attributes['contests'] = value
else
attributes['contests'] = 'NONE'
end
return attributes, messages, errors
end
def self.map_key_from_itc(key)
key = key.gsub("MZGenre.", "")
return nil if key.empty?
LEGACY_AGE_RATING_ITC_MAP[key] || key
end
def self.map_value_from_itc(key, value)
boolean_keys = [
"advertising",
"ageAssurance",
"gambling",
"gamblingAndContests",
"healthOrWellnessTopics",
"lootBox",
"messagingAndChat",
"parentalControls",
"unrestrictedWebAccess",
"userGeneratedContent"
]
if boolean_keys.include?(key)
new_value = LEGACY_BOOLEAN_VALUE_ITC_MAP[value]
return value if new_value.nil?
return new_value
else
return LEGACY_RATING_VALUE_ITC_MAP[value] || value
end
return value
end
#
# API
#
def update(client: nil, attributes: nil)
client ||= Spaceship::ConnectAPI
attributes = reverse_attr_mapping(attributes)
client.patch_age_rating_declaration(age_rating_declaration_id: id, attributes: attributes)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/beta_feedback.rb | spaceship/lib/spaceship/connect_api/models/beta_feedback.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class BetaFeedback
include Spaceship::ConnectAPI::Model
attr_accessor :timestamp
attr_accessor :comment
attr_accessor :email_address
attr_accessor :device_model
attr_accessor :os_version
attr_accessor :bookmarked
attr_accessor :locale
attr_accessor :carrier
attr_accessor :timezone
attr_accessor :architecture
attr_accessor :connection_status
attr_accessor :paired_apple_watch
attr_accessor :app_up_time_millis
attr_accessor :available_disk_bytes
attr_accessor :total_disk_bytes
attr_accessor :network_type
attr_accessor :battery_percentage
attr_accessor :screen_width
attr_accessor :screen_height
attr_accessor :build
attr_accessor :tester
attr_accessor :screenshots
attr_mapping({
"timestamp" => "timestamp",
"comment" => "comment",
"emailAddress" => "email_address",
"contactEmail" => "contact_email",
"deviceModel" => "device_model",
"osVersion" => "os_version",
"bookmarked" => "bookmarked",
"locale" => "locale",
"carrier" => "carrier",
"timezone" => "timezone",
"architecture" => "architecture",
"connectionStatus" => "connection_status",
"pairedAppleWatch" => "paired_apple_watch",
"appUpTimeMillis" => "app_up_time_millis",
"availableDiskBytes" => "available_disk_bytes",
"totalDiskBytes" => "total_disk_bytes",
"networkType" => "network_type",
"batteryPercentage" => "battery_percentage",
"screenWidth" => "screen_width",
"screenHeight" => "screen_height",
"build" => "build",
"tester" => "tester",
"screenshots" => "screenshots"
})
def self.type
return "betaFeedbacks"
end
#
# API
#
def self.all(client: nil, filter: {}, includes: "tester,build,screenshots", limit: nil, sort: nil)
client ||= Spaceship::ConnectAPI
return client.get_beta_feedback(filter: filter, includes: includes, limit: limit, sort: sort)
end
def delete!(client: nil)
client ||= Spaceship::ConnectAPI
return client.delete_beta_feedback(feedback_id: self.id)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/app.rb | spaceship/lib/spaceship/connect_api/models/app.rb | require_relative '../model'
require_relative './build'
# rubocop:disable Metrics/ClassLength
module Spaceship
class ConnectAPI
class App
include Spaceship::ConnectAPI::Model
attr_accessor :name
attr_accessor :bundle_id
attr_accessor :sku
attr_accessor :primary_locale
attr_accessor :is_opted_in_to_distribute_ios_app_on_mac_app_store
attr_accessor :removed
attr_accessor :is_aag
attr_accessor :available_in_new_territories
attr_accessor :content_rights_declaration
attr_accessor :app_store_versions
attr_accessor :prices
# Only available with Apple ID auth
attr_accessor :distribution_type
attr_accessor :educationDiscountType
module ContentRightsDeclaration
USES_THIRD_PARTY_CONTENT = "USES_THIRD_PARTY_CONTENT"
DOES_NOT_USE_THIRD_PARTY_CONTENT = "DOES_NOT_USE_THIRD_PARTY_CONTENT"
end
module DistributionType
APP_STORE = "APP_STORE"
CUSTOM = "CUSTOM"
end
module EducationDiscountType
DISCOUNTED = "DISCOUNTED"
NOT_APPLICABLE = "NOT_APPLICABLE"
NOT_DISCOUNTED = "NOT_DISCOUNTED"
end
self.attr_mapping({
"name" => "name",
"bundleId" => "bundle_id",
"sku" => "sku",
"primaryLocale" => "primary_locale",
"isOptedInToDistributeIosAppOnMacAppStore" => "is_opted_in_to_distribute_ios_app_on_mac_app_store",
"removed" => "removed",
"isAAG" => "is_aag",
"availableInNewTerritories" => "available_in_new_territories",
"distributionType" => "distribution_type",
"educationDiscountType" => "education_discount_type",
"contentRightsDeclaration" => "content_rights_declaration",
"appStoreVersions" => "app_store_versions",
# This attribute is already deprecated. It will be removed in a future release.
"prices" => "prices"
})
ESSENTIAL_INCLUDES = [
"appStoreVersions"
].join(",")
def self.type
return "apps"
end
#
# Apps
#
def self.all(client: nil, filter: {}, includes: ESSENTIAL_INCLUDES, limit: nil, sort: nil)
client ||= Spaceship::ConnectAPI
resps = client.get_apps(filter: filter, includes: includes, limit: limit, sort: sort).all_pages
return resps.flat_map(&:to_models)
end
def self.find(bundle_id, client: nil)
client ||= Spaceship::ConnectAPI
return all(client: client, filter: { bundleId: bundle_id }).find do |app|
app.bundle_id == bundle_id
end
end
def self.create(client: nil, name: nil, version_string: nil, sku: nil, primary_locale: nil, bundle_id: nil, platforms: nil, company_name: nil)
client ||= Spaceship::ConnectAPI
client.post_app(
name: name,
version_string: version_string,
sku: sku,
primary_locale: primary_locale,
bundle_id: bundle_id,
platforms: platforms,
company_name: company_name
)
end
def self.get(client: nil, app_id: nil, includes: "appStoreVersions")
client ||= Spaceship::ConnectAPI
return client.get_app(app_id: app_id, includes: includes).first
end
# Updates app attributes, price tier and availability of an app in territories
# Check Tunes patch_app method for explanation how to use territory_ids parameter with allow_removing_from_sale to remove app from sale
def update(client: nil, attributes: nil, app_price_tier_id: nil, territory_ids: nil, allow_removing_from_sale: false)
client ||= Spaceship::ConnectAPI
attributes = reverse_attr_mapping(attributes)
return client.patch_app(app_id: id, attributes: attributes, app_price_tier_id: app_price_tier_id, territory_ids: territory_ids, allow_removing_from_sale: allow_removing_from_sale)
end
#
# App Info
#
def fetch_live_app_info(client: nil, includes: Spaceship::ConnectAPI::AppInfo::ESSENTIAL_INCLUDES)
client ||= Spaceship::ConnectAPI
states = [
Spaceship::ConnectAPI::AppInfo::State::READY_FOR_DISTRIBUTION,
Spaceship::ConnectAPI::AppInfo::State::PENDING_RELEASE,
Spaceship::ConnectAPI::AppInfo::State::IN_REVIEW
]
resp = client.get_app_infos(app_id: id, includes: includes)
return resp.to_models.select do |model|
states.include?(model.state)
end.first
end
def fetch_edit_app_info(client: nil, includes: Spaceship::ConnectAPI::AppInfo::ESSENTIAL_INCLUDES)
client ||= Spaceship::ConnectAPI
states = [
Spaceship::ConnectAPI::AppInfo::State::PREPARE_FOR_SUBMISSION,
Spaceship::ConnectAPI::AppInfo::State::DEVELOPER_REJECTED,
Spaceship::ConnectAPI::AppInfo::State::REJECTED,
Spaceship::ConnectAPI::AppInfo::State::WAITING_FOR_REVIEW
]
resp = client.get_app_infos(app_id: id, includes: includes)
return resp.to_models.select do |model|
states.include?(model.state)
end.first
end
def fetch_latest_app_info(client: nil, includes: Spaceship::ConnectAPI::AppInfo::ESSENTIAL_INCLUDES)
client ||= Spaceship::ConnectAPI
resp = client.get_app_infos(app_id: id, includes: includes)
return resp.to_models.first
end
#
# App Availabilities
#
def get_app_availabilities(client: nil, filter: {}, includes: "territoryAvailabilities", limit: { "territoryAvailabilities": 200 })
client ||= Spaceship::ConnectAPI
resp = client.get_app_availabilities(app_id: id, filter: filter, includes: includes, limit: limit, sort: nil)
return resp.to_models.first
end
#
# Available Territories
#
def fetch_available_territories(client: nil, filter: {}, includes: nil, limit: nil, sort: nil)
client ||= Spaceship::ConnectAPI
filter ||= {}
resps = client.get_available_territories(app_id: id, filter: filter, includes: includes, limit: limit, sort: sort).all_pages
return resps.flat_map(&:to_models)
end
#
# App Pricing
#
def fetch_app_prices(client: nil, filter: {}, includes: "priceTier", limit: nil, sort: nil)
client ||= Spaceship::ConnectAPI
resp = client.get_app_prices(app_id: id, filter: filter, includes: includes, limit: limit, sort: sort)
return resp.to_models
end
#
# App Store Versions
#
def reject_version_if_possible!(client: nil, platform: nil)
client ||= Spaceship::ConnectAPI
platform ||= Spaceship::ConnectAPI::Platform::IOS
filter = {
appVersionState: [
Spaceship::ConnectAPI::AppStoreVersion::AppVersionState::PENDING_APPLE_RELEASE,
Spaceship::ConnectAPI::AppStoreVersion::AppVersionState::PENDING_DEVELOPER_RELEASE,
Spaceship::ConnectAPI::AppStoreVersion::AppVersionState::IN_REVIEW,
Spaceship::ConnectAPI::AppStoreVersion::AppVersionState::WAITING_FOR_REVIEW
].join(","),
platform: platform
}
# Get the latest version
version = get_app_store_versions(client: client, filter: filter, includes: "appStoreVersionSubmission")
.sort_by { |v| Gem::Version.new(v.version_string) }
.last
return false if version.nil?
return version.reject!
end
# Will make sure the current edit_version matches the given version number
# This will either create a new version or change the version number
# from an existing version
# @return (Bool) Was something changed?
def ensure_version!(version_string, platform: nil, client: nil)
client ||= Spaceship::ConnectAPI
app_store_version = get_edit_app_store_version(client: client, platform: platform)
if app_store_version
if version_string != app_store_version.version_string
attributes = { versionString: version_string }
app_store_version.update(client: client, attributes: attributes)
return true
end
return false
else
attributes = { versionString: version_string, platform: platform }
client.post_app_store_version(app_id: id, attributes: attributes)
return true
end
end
def get_latest_app_store_version(client: nil, platform: nil, includes: nil)
client ||= Spaceship::ConnectAPI
platform ||= Spaceship::ConnectAPI::Platform::IOS
filter = {
platform: platform
}
# Get the latest version
return get_app_store_versions(client: client, filter: filter, includes: includes)
.sort_by { |v| Date.parse(v.created_date) }
.last
end
def get_live_app_store_version(client: nil, platform: nil, includes: Spaceship::ConnectAPI::AppStoreVersion::ESSENTIAL_INCLUDES)
client ||= Spaceship::ConnectAPI
platform ||= Spaceship::ConnectAPI::Platform::IOS
filter = {
appVersionState: [
Spaceship::ConnectAPI::AppStoreVersion::AppVersionState::READY_FOR_DISTRIBUTION,
Spaceship::ConnectAPI::AppStoreVersion::AppVersionState::PROCESSING_FOR_DISTRIBUTION
].join(","),
platform: platform
}
return get_app_store_versions(client: client, filter: filter, includes: includes).first
end
def get_edit_app_store_version(client: nil, platform: nil, includes: Spaceship::ConnectAPI::AppStoreVersion::ESSENTIAL_INCLUDES)
client ||= Spaceship::ConnectAPI
platform ||= Spaceship::ConnectAPI::Platform::IOS
filter = {
appVersionState: [
Spaceship::ConnectAPI::AppStoreVersion::AppVersionState::PREPARE_FOR_SUBMISSION,
Spaceship::ConnectAPI::AppStoreVersion::AppVersionState::DEVELOPER_REJECTED,
Spaceship::ConnectAPI::AppStoreVersion::AppVersionState::REJECTED,
Spaceship::ConnectAPI::AppStoreVersion::AppVersionState::METADATA_REJECTED,
Spaceship::ConnectAPI::AppStoreVersion::AppVersionState::WAITING_FOR_REVIEW,
Spaceship::ConnectAPI::AppStoreVersion::AppVersionState::INVALID_BINARY
].join(","),
platform: platform
}
# Get the latest version
return get_app_store_versions(client: client, filter: filter, includes: includes)
.sort_by { |v| Gem::Version.new(v.version_string) }
.last
end
def get_in_review_app_store_version(client: nil, platform: nil, includes: Spaceship::ConnectAPI::AppStoreVersion::ESSENTIAL_INCLUDES)
client ||= Spaceship::ConnectAPI
platform ||= Spaceship::ConnectAPI::Platform::IOS
filter = {
appVersionState: Spaceship::ConnectAPI::AppStoreVersion::AppVersionState::IN_REVIEW,
platform: platform
}
return get_app_store_versions(client: client, filter: filter, includes: includes).first
end
def get_pending_release_app_store_version(client: nil, platform: nil, includes: Spaceship::ConnectAPI::AppStoreVersion::ESSENTIAL_INCLUDES)
client ||= Spaceship::ConnectAPI
platform ||= Spaceship::ConnectAPI::Platform::IOS
filter = {
appVersionState: [
Spaceship::ConnectAPI::AppStoreVersion::AppVersionState::PENDING_APPLE_RELEASE,
Spaceship::ConnectAPI::AppStoreVersion::AppVersionState::PENDING_DEVELOPER_RELEASE
].join(','),
platform: platform
}
return get_app_store_versions(client: client, filter: filter, includes: includes).first
end
def get_app_store_versions(client: nil, filter: {}, includes: Spaceship::ConnectAPI::AppStoreVersion::ESSENTIAL_INCLUDES, limit: nil, sort: nil)
client ||= Spaceship::ConnectAPI
if limit.nil?
resps = client.get_app_store_versions(app_id: id, filter: filter, includes: includes, limit: limit, sort: sort).all_pages
return resps.flat_map(&:to_models)
else
resp = client.get_app_store_versions(app_id: id, filter: filter, includes: includes, limit: limit, sort: sort)
return resp.to_models
end
end
#
# B2B
#
def disable_b2b
update(attributes: {
distributionType: DistributionType::APP_STORE,
education_discount_type: EducationDiscountType::NOT_DISCOUNTED
})
end
def enable_b2b
update(attributes: {
distributionType: App::DistributionType::CUSTOM,
education_discount_type: EducationDiscountType::NOT_APPLICABLE
})
end
#
# Beta Feedback
#
def get_beta_feedback(client: nil, filter: {}, includes: "tester,build,screenshots", limit: nil, sort: nil)
client ||= Spaceship::ConnectAPI
filter ||= {}
filter["build.app"] = id
resps = client.get_beta_feedback(filter: filter, includes: includes, limit: limit, sort: sort).all_pages
return resps.flat_map(&:to_models)
end
#
# Beta Testers
#
def get_beta_testers(client: nil, filter: {}, includes: nil, limit: nil, sort: nil)
client ||= Spaceship::ConnectAPI
filter ||= {}
filter[:apps] = id
resps = client.get_beta_testers(filter: filter, includes: includes, limit: limit, sort: sort).all_pages
return resps.flat_map(&:to_models)
end
#
# Builds
#
def get_builds(client: nil, filter: {}, includes: nil, limit: nil, sort: nil)
client ||= Spaceship::ConnectAPI
filter ||= {}
filter[:app] = id
resps = client.get_builds(filter: filter, includes: includes, limit: limit, sort: sort).all_pages
return resps.flat_map(&:to_models)
end
def get_build_deliveries(client: nil, filter: {}, includes: nil, limit: nil, sort: nil)
client ||= Spaceship::ConnectAPI
filter ||= {}
resps = client.get_build_deliveries(app_id: id, filter: filter, includes: includes, limit: limit, sort: sort).all_pages
return resps.flat_map(&:to_models)
end
def get_beta_app_localizations(client: nil, filter: {}, includes: nil, limit: nil, sort: nil)
client ||= Spaceship::ConnectAPI
filter ||= {}
filter[:app] = id
resps = client.get_beta_app_localizations(filter: filter, includes: includes, limit: limit, sort: sort).all_pages
return resps.flat_map(&:to_models)
end
def get_beta_groups(client: nil, filter: {}, includes: nil, limit: nil, sort: nil)
client ||= Spaceship::ConnectAPI
filter ||= {}
filter[:app] = id
resps = client.get_beta_groups(filter: filter, includes: includes, limit: limit, sort: sort).all_pages
return resps.flat_map(&:to_models)
end
def create_beta_group(client: nil, group_name: nil, is_internal_group: false, public_link_enabled: false, public_link_limit: 10_000, public_link_limit_enabled: false, has_access_to_all_builds: nil)
client ||= Spaceship::ConnectAPI
resps = client.create_beta_group(
app_id: id,
group_name: group_name,
is_internal_group: is_internal_group,
public_link_enabled: public_link_enabled,
public_link_limit: public_link_limit,
public_link_limit_enabled: public_link_limit_enabled,
has_access_to_all_builds: has_access_to_all_builds
).all_pages
return resps.flat_map(&:to_models).first
end
#
# Education
#
def disable_educational_discount
update(attributes: {
education_discount_type: EducationDiscountType::NOT_DISCOUNTED
})
end
def enable_educational_discount
update(attributes: {
education_discount_type: EducationDiscountType::DISCOUNTED
})
end
#
# Review Submissions
#
def get_ready_review_submission(client: nil, platform:, includes: nil)
client ||= Spaceship::ConnectAPI
filter = {
state: [
Spaceship::ConnectAPI::ReviewSubmission::ReviewSubmissionState::READY_FOR_REVIEW
].join(","),
platform: platform
}
return get_review_submissions(client: client, filter: filter, includes: includes).first
end
def get_in_progress_review_submission(client: nil, platform:, includes: nil)
client ||= Spaceship::ConnectAPI
filter = {
state: [
Spaceship::ConnectAPI::ReviewSubmission::ReviewSubmissionState::WAITING_FOR_REVIEW,
Spaceship::ConnectAPI::ReviewSubmission::ReviewSubmissionState::IN_REVIEW,
Spaceship::ConnectAPI::ReviewSubmission::ReviewSubmissionState::UNRESOLVED_ISSUES
].join(","),
platform: platform
}
return get_review_submissions(client: client, filter: filter, includes: includes).first
end
# appStoreVersionForReview,items
def get_review_submissions(client: nil, filter: {}, includes: nil, limit: nil, sort: nil)
client ||= Spaceship::ConnectAPI
resps = client.get_review_submissions(app_id: id, filter: filter, includes: includes, limit: limit, sort: sort).all_pages
return resps.flat_map(&:to_models)
end
def create_review_submission(client: nil, platform:)
client ||= Spaceship::ConnectAPI
resp = client.post_review_submission(app_id: id, platform: platform)
return resp.to_models.first
end
#
# Users
#
def add_users(client: nil, user_ids: nil)
client ||= Spaceship::ConnectAPI
user_ids.each do |user_id|
client.add_user_visible_apps(user_id: user_id, app_ids: [id])
end
end
def remove_users(client: nil, user_ids: nil)
client ||= Spaceship::ConnectAPI
user_ids.each do |user_id|
client.delete_user_visible_apps(user_id: user_id, app_ids: [id])
end
end
end
end
end
# rubocop:enable Metrics/ClassLength
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/app_data_usage_grouping.rb | spaceship/lib/spaceship/connect_api/models/app_data_usage_grouping.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class AppDataUsageGrouping
include Spaceship::ConnectAPI::Model
attr_accessor :deleted
attr_mapping({
"deleted" => "deleted"
})
def self.type
return "appDataUsageGroupings"
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/app_data_usage_data_protection.rb | spaceship/lib/spaceship/connect_api/models/app_data_usage_data_protection.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class AppDataUsageDataProtection
include Spaceship::ConnectAPI::Model
attr_accessor :deleted
attr_mapping({
"deleted" => "deleted"
})
# Found at https://appstoreconnect.apple.com/iris/v1/appDataUsageDataProtections
module ID
DATA_USED_TO_TRACK_YOU = "DATA_USED_TO_TRACK_YOU"
DATA_LINKED_TO_YOU = "DATA_LINKED_TO_YOU"
DATA_NOT_LINKED_TO_YOU = "DATA_NOT_LINKED_TO_YOU"
DATA_NOT_COLLECTED = "DATA_NOT_COLLECTED"
end
def self.type
return "appDataUsageDataProtections"
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/reset_ratings_request.rb | spaceship/lib/spaceship/connect_api/models/reset_ratings_request.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class ResetRatingsRequest
include Spaceship::ConnectAPI::Model
attr_accessor :reset_date
attr_mapping({
"resetDate" => "reset_date"
})
def self.type
return "resetRatingsRequests"
end
#
# API
#
def delete!(client: nil, filter: {}, includes: nil, limit: nil, sort: nil)
client ||= Spaceship::ConnectAPI
client.delete_reset_ratings_request(reset_ratings_request_id: id)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/app_store_version_phased_release.rb | spaceship/lib/spaceship/connect_api/models/app_store_version_phased_release.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class AppStoreVersionPhasedRelease
include Spaceship::ConnectAPI::Model
attr_accessor :phased_release_state
attr_accessor :start_date
attr_accessor :total_pause_duration
attr_accessor :current_day_number
module PhasedReleaseState
INACTIVE = "INACTIVE"
ACTIVE = "ACTIVE"
PAUSED = "PAUSED"
COMPLETE = "COMPLETE"
end
attr_mapping({
"phasedReleaseState" => "phased_release_state",
"startDate" => "start_date",
"totalPauseDuration" => "total_pause_duration",
"currentDayNumber" => "current_day_number"
})
def self.type
return "appStoreVersionPhasedReleases"
end
#
# API
#
def pause
update(PhasedReleaseState::PAUSED)
end
def resume
update(PhasedReleaseState::ACTIVE)
end
def complete
update(PhasedReleaseState::COMPLETE)
end
def delete!(filter: {}, includes: nil, limit: nil, sort: nil)
Spaceship::ConnectAPI.delete_app_store_version_phased_release(app_store_version_phased_release_id: id)
end
private def update(state)
Spaceship::ConnectAPI.patch_app_store_version_phased_release(app_store_version_phased_release_id: id, attributes: {
phasedReleaseState: state
}).to_models.first
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/actor.rb | spaceship/lib/spaceship/connect_api/models/actor.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class Actor
include Spaceship::ConnectAPI::Model
attr_accessor :actor_type
attr_accessor :user_first_name
attr_accessor :user_last_name
attr_accessor :user_email
attr_accessor :api_key_id
attr_mapping({
actorType: 'actor_type',
userFirstName: 'user_first_name',
userLastName: 'user_last_name',
userEmail: 'user_email',
apiKeyId: 'api_key_id'
})
def self.type
return 'actors'
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/app_store_version_submission.rb | spaceship/lib/spaceship/connect_api/models/app_store_version_submission.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class AppStoreVersionSubmission
include Spaceship::ConnectAPI::Model
attr_accessor :can_reject
attr_mapping({
"canReject" => "can_reject"
})
def self.type
return "appStoreVersionSubmissions"
end
#
# API
#
def delete!(client: nil, filter: {}, includes: nil, limit: nil, sort: nil)
client ||= Spaceship::ConnectAPI
client.delete_app_store_version_submission(app_store_version_submission_id: id)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/app_preview_set.rb | spaceship/lib/spaceship/connect_api/models/app_preview_set.rb | require_relative '../model'
require_relative './app_preview'
module Spaceship
class ConnectAPI
class AppPreviewSet
include Spaceship::ConnectAPI::Model
attr_accessor :preview_type
attr_accessor :app_previews
module PreviewType
IPHONE_35 = "IPHONE_35"
IPHONE_40 = "IPHONE_40"
IPHONE_47 = "IPHONE_47"
IPHONE_55 = "IPHONE_55"
IPHONE_58 = "IPHONE_58"
IPHONE_65 = "IPHONE_65"
IPHONE_67 = "IPHONE_67"
IPAD_97 = "IPAD_97"
IPAD_105 = "IPAD_105"
IPAD_PRO_3GEN_11 = "IPAD_PRO_3GEN_11"
IPAD_PRO_129 = "IPAD_PRO_129"
IPAD_PRO_3GEN_129 = "IPAD_PRO_3GEN_129"
DESKTOP = "DESKTOP"
ALL = [
IPHONE_35,
IPHONE_40,
IPHONE_47,
IPHONE_55,
IPHONE_58,
IPHONE_65,
IPHONE_67,
IPAD_97,
IPAD_105,
IPAD_PRO_3GEN_11,
IPAD_PRO_129,
IPAD_PRO_3GEN_129,
DESKTOP
]
end
attr_mapping({
"previewType" => "preview_type",
"appPreviews" => "app_previews"
})
def self.type
return "appPreviewSets"
end
#
# API
#
def self.all(client: nil, filter: {}, includes: nil, limit: nil, sort: nil)
client ||= Spaceship::ConnectAPI
resp = client.get_app_preview_sets(filter: filter, includes: includes, limit: limit, sort: sort)
return resp.to_models
end
def self.get(client: nil, app_preview_set_id: nil, includes: "appPreviews")
client ||= Spaceship::ConnectAPI
return client.get_app_preview_set(app_preview_set_id: app_preview_set_id, filter: nil, includes: includes, limit: nil, sort: nil).first
end
def delete!(client: nil, filter: {}, includes: nil, limit: nil, sort: nil)
client ||= Spaceship::ConnectAPI
return client.delete_app_preview_set(app_preview_set_id: id)
end
def upload_preview(client: nil, path: nil, wait_for_processing: true, position: nil, frame_time_code: nil)
client ||= Spaceship::ConnectAPI
# Upload preview
preview = Spaceship::ConnectAPI::AppPreview.create(client: client, app_preview_set_id: id, path: path, wait_for_processing: wait_for_processing, frame_time_code: frame_time_code)
# Reposition (if specified)
unless position.nil?
# Get all app preview ids
set = AppPreviewSet.get(app_preview_set_id: id)
app_preview_ids = set.app_previews.map(&:id)
# Remove new uploaded preview
app_preview_ids.delete(preview.id)
# Insert preview at specified position
app_preview_ids = app_preview_ids.insert(position, preview.id).compact
# Reorder previews
reorder_previews(app_preview_ids: app_preview_ids)
end
return preview
end
def reorder_previews(client: nil, app_preview_ids: nil)
client ||= Spaceship::ConnectAPI
client.patch_app_preview_set_previews(app_preview_set_id: id, app_preview_ids: app_preview_ids)
return client.get_app_preview_set(app_preview_set_id: id, includes: "appPreviews").first
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/bundle_id.rb | spaceship/lib/spaceship/connect_api/models/bundle_id.rb | require_relative '../../connect_api'
require_relative './bundle_id_capability'
module Spaceship
class ConnectAPI
class BundleId
include Spaceship::ConnectAPI::Model
attr_accessor :identifier
attr_accessor :name
attr_accessor :seed_id
attr_accessor :platform
attr_accessor :bundle_id_capabilities
attr_mapping({
"identifier" => "identifier",
"name" => "name",
"seedId" => "seed_id",
"platform" => "platform",
"bundleIdCapabilities" => 'bundle_id_capabilities'
})
def self.type
return "bundleIds"
end
#
# Helpers
#
def supports_catalyst?
return bundle_id_capabilities.any? do |capability|
capability.is_type?(Spaceship::ConnectAPI::BundleIdCapability::Type::MARZIPAN)
end
end
#
# API
#
def self.all(client: nil, filter: {}, includes: nil, fields: nil, limit: Spaceship::ConnectAPI::MAX_OBJECTS_PER_PAGE_LIMIT, sort: nil)
client ||= Spaceship::ConnectAPI
resps = client.get_bundle_ids(filter: filter, includes: includes, fields: fields, limit: nil, sort: nil).all_pages
return resps.flat_map(&:to_models)
end
def self.find(identifier, includes: nil, fields: nil, client: nil)
client ||= Spaceship::ConnectAPI
return all(client: client, filter: { identifier: identifier }, includes: includes, fields: fields).find do |app|
app.identifier == identifier
end
end
def self.get(client: nil, bundle_id_id: nil, includes: nil)
client ||= Spaceship::ConnectAPI
return client.get_bundle_id(bundle_id_id: bundle_id_id, includes: includes).first
end
def self.create(client: nil, name: nil, platform: nil, identifier: nil, seed_id: nil)
client ||= Spaceship::ConnectAPI
resp = client.post_bundle_id(name: name, platform: platform, identifier: identifier, seed_id: seed_id)
return resp.to_models.first
end
#
# BundleIdsCapabilities
#
def get_capabilities(client: nil, includes: nil)
client ||= Spaceship::ConnectAPI
resp = client.get_bundle_id_capabilities(bundle_id_id: id, includes: includes)
return resp.to_models
end
def create_capability(capability_type, settings: [], client: nil)
raise "capability_type is required " if capability_type.nil?
client ||= Spaceship::ConnectAPI
resp = client.post_bundle_id_capability(bundle_id_id: id, capability_type: capability_type, settings: settings)
return resp.to_models.first
end
def update_capability(capability_type, enabled: false, settings: [], client: nil)
raise "capability_type is required " if capability_type.nil?
client ||= Spaceship::ConnectAPI
resp = client.patch_bundle_id_capability(bundle_id_id: id, seed_id: seed_id, enabled: enabled, capability_type: capability_type, settings: settings)
return resp.to_models.first
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/app_category.rb | spaceship/lib/spaceship/connect_api/models/app_category.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class AppCategory
include Spaceship::ConnectAPI::Model
attr_accessor :platforms
attr_mapping({
"platforms" => "platforms"
})
def self.type
return "appCategories"
end
LEGACY_CATEGORY_ITC_MAP = {
"Apps.Food_Drink" => "FOOD_AND_DRINK",
"Business" => "BUSINESS",
"Education" => "EDUCATION",
"SocialNetworking" => "SOCIAL_NETWORKING",
"Book" => "BOOKS",
"Sports" => "SPORTS",
"Finance" => "FINANCE",
"Reference" => "REFERENCE",
"Apps.GraphicsDesign" => "GRAPHICS_AND_DESIGN",
"Apps.DeveloperTools" => "DEVELOPER_TOOLS",
"Healthcare_Fitness" => "HEALTH_AND_FITNESS",
"Music" => "MUSIC",
"Weather" => "WEATHER",
"Travel" => "TRAVEL",
"Entertainment" => "ENTERTAINMENT",
"Stickers" => "STICKERS",
"Games" => "GAMES",
"Lifestyle" => "LIFESTYLE",
"Medical" => "MEDICAL",
"Apps.Newsstand" => "MAGAZINES_AND_NEWSPAPERS",
"Utilities" => "UTILITIES",
"Apps.Shopping" => "SHOPPING",
"Productivity" => "PRODUCTIVITY",
"News" => "NEWS",
"Photography" => "PHOTO_AND_VIDEO",
"Navigation" => "NAVIGATION"
}
LEGACY_SUBCATEGORY_ITC_MAP = {
"Apps.Stickers.Places" => "STICKERS_PLACES_AND_OBJECTS",
"Apps.Stickers.Emotions" => "STICKERS_EMOJI_AND_EXPRESSIONS",
"Apps.Stickers.BirthdaysAndCelebrations" => "STICKERS_CELEBRATIONS",
"Apps.Stickers.Celebrities" => "STICKERS_CELEBRITIES",
"Apps.Stickers.MoviesAndTV" => "STICKERS_MOVIES_AND_TV",
"Apps.Stickers.Sports" => "STICKERS_SPORTS_AND_ACTIVITIES",
"Apps.Stickers.FoodAndDrink" => "STICKERS_EATING_AND_DRINKING",
"Apps.Stickers.Characters" => "STICKERS_CHARACTERS",
"Apps.Stickers.Animals" => "STICKERS_ANIMALS",
"Apps.Stickers.Fashion" => "STICKERS_FASHION",
"Apps.Stickers.Art" => "STICKERS_ART",
"Apps.Stickers.Games" => "STICKERS_GAMING",
"Apps.Stickers.KidsAndFamily" => "STICKERS_KIDS_AND_FAMILY",
"Apps.Stickers.People" => "STICKERS_PEOPLE",
"Apps.Stickers.Music" => "STICKERS_MUSIC",
"Sports" => "GAMES_SPORTS",
"Word" => "GAMES_WORD",
"Music" => "GAMES_MUSIC",
"Adventure" => "GAMES_ADVENTURE",
"Action" => "GAMES_ACTION",
"RolePlaying" => "GAMES_ROLE_PLAYING",
"Arcade" => "GAMES_CASUAL",
"Board" => "GAMES_BOARD",
"Trivia" => "GAMES_TRIVIA",
"Card" => "GAMES_CARD",
"Puzzle" => "GAMES_PUZZLE",
"Casino" => "GAMES_CASINO",
"Strategy" => "GAMES_STRATEGY",
"Simulation" => "GAMES_SIMULATION",
"Racing" => "GAMES_RACING",
"Family" => "GAMES_FAMILY"
}
def self.map_category_from_itc(category)
category = category.gsub("MZGenre.", "")
return nil if category.empty?
LEGACY_CATEGORY_ITC_MAP[category] || category
end
def self.map_subcategory_from_itc(category)
category = category.gsub("MZGenre.", "")
return nil if category.empty?
LEGACY_SUBCATEGORY_ITC_MAP[category] || category
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/app_store_version_localization.rb | spaceship/lib/spaceship/connect_api/models/app_store_version_localization.rb | require_relative '../model'
require_relative './app_preview_set'
require_relative './app_screenshot_set'
require_relative '../../errors'
module Spaceship
class ConnectAPI
class AppStoreVersionLocalization
include Spaceship::ConnectAPI::Model
attr_accessor :description
attr_accessor :locale
attr_accessor :keywords
attr_accessor :marketing_url
attr_accessor :promotional_text
attr_accessor :support_url
attr_accessor :whats_new
attr_accessor :app_screenshot_sets
attr_accessor :app_preview_sets
attr_mapping({
"description" => "description",
"locale" => "locale",
"keywords" => "keywords",
"marketingUrl" => "marketing_url",
"promotionalText" => "promotional_text",
"supportUrl" => "support_url",
"whatsNew" => "whats_new",
"appScreenshotSets" => "app_screenshot_sets",
"appPreviewSets" => "app_preview_sets"
})
def self.type
return "appStoreVersionLocalizations"
end
#
# API
#
def self.get(client: nil, app_store_version_localization_id: nil, filter: {}, includes: nil, limit: nil, sort: nil)
client ||= Spaceship::ConnectAPI
resp = client.get_app_store_version_localization(app_store_version_localization_id: app_store_version_localization_id, filter: filter, includes: includes, limit: limit, sort: sort)
return resp.to_models
rescue => error
raise Spaceship::AppStoreLocalizationError.new(@locale, error)
end
def self.all(client: nil, app_store_version_id: nil, filter: {}, includes: nil, limit: nil, sort: nil)
client ||= Spaceship::ConnectAPI
resp = client.get_app_store_version_localizations(app_store_version_id: app_store_version_id, filter: filter, includes: includes, limit: limit, sort: sort)
return resp.to_models
rescue => error
raise Spaceship::AppStoreLocalizationError.new(@locale, error)
end
def update(client: nil, attributes: nil)
client ||= Spaceship::ConnectAPI
attributes = reverse_attr_mapping(attributes)
client.patch_app_store_version_localization(app_store_version_localization_id: id, attributes: attributes)
rescue => error
raise Spaceship::AppStoreLocalizationError.new(@locale, error)
end
def delete!(client: nil, filter: {}, includes: nil, limit: nil, sort: nil)
client ||= Spaceship::ConnectAPI
client.delete_app_store_version_localization(app_store_version_localization_id: id)
rescue => error
raise Spaceship::AppStoreLocalizationError.new(@locale, error)
end
#
# App Preview Sets
#
def get_app_preview_sets(client: nil, filter: {}, includes: "appPreviews", limit: nil, sort: nil)
client ||= Spaceship::ConnectAPI
filter ||= {}
filter["appStoreVersionLocalization"] = id
return Spaceship::ConnectAPI::AppPreviewSet.all(client: client, filter: filter, includes: includes, limit: limit, sort: sort)
rescue => error
raise Spaceship::AppStoreAppPreviewError.new(@locale, error)
end
def create_app_preview_set(client: nil, attributes: nil)
client ||= Spaceship::ConnectAPI
resp = client.post_app_preview_set(app_store_version_localization_id: id, attributes: attributes)
return resp.to_models.first
rescue => error
raise Spaceship::AppStoreAppPreviewError.new(@locale, error)
end
#
# App Screenshot Sets
#
def get_app_screenshot_sets(client: nil, filter: {}, includes: "appScreenshots", limit: nil, sort: nil)
client ||= Spaceship::ConnectAPI
return Spaceship::ConnectAPI::AppScreenshotSet.all(client: client, app_store_version_localization_id: id, filter: filter, includes: includes, limit: limit, sort: sort)
rescue => error
raise Spaceship::AppStoreScreenshotError.new(@locale, error)
end
def create_app_screenshot_set(client: nil, attributes: nil)
client ||= Spaceship::ConnectAPI
resp = client.post_app_screenshot_set(app_store_version_localization_id: id, attributes: attributes)
return resp.to_models.first
rescue => error
raise Spaceship::AppStoreScreenshotError.new(@locale, error)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/app_data_usage_category.rb | spaceship/lib/spaceship/connect_api/models/app_data_usage_category.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class AppDataUsageCategory
include Spaceship::ConnectAPI::Model
attr_accessor :deleted
attr_accessor :grouping
attr_mapping({
"deleted" => "deleted",
"grouping" => "grouping"
})
# Found at https://appstoreconnect.apple.com/iris/v1/appDataUsageCategories
module ID
PAYMENT_INFORMATION = "PAYMENT_INFORMATION"
CREDIT_AND_FRAUD = "CREDIT_AND_FRAUD"
OTHER_FINANCIAL_INFO = "OTHER_FINANCIAL_INFO"
PRECISE_LOCATION = "PRECISE_LOCATION"
SENSITIVE_INFO = "SENSITIVE_INFO"
PHYSICAL_ADDRESS = "PHYSICAL_ADDRESS"
EMAIL_ADDRESS = "EMAIL_ADDRESS"
NAME = "NAME"
PHONE_NUMBER = "PHONE_NUMBER"
OTHER_CONTACT_INFO = "OTHER_CONTACT_INFO"
CONTACTS = "CONTACTS"
EMAILS_OR_TEXT_MESSAGES = "EMAILS_OR_TEXT_MESSAGES"
PHOTOS_OR_VIDEOS = "PHOTOS_OR_VIDEOS"
AUDIO = "AUDIO"
GAMEPLAY_CONTENT = "GAMEPLAY_CONTENT"
CUSTOMER_SUPPORT = "CUSTOMER_SUPPORT"
OTHER_USER_CONTENT = "OTHER_USER_CONTENT"
BROWSING_HISTORY = "BROWSING_HISTORY"
SEARCH_HISTORY = "SEARCH_HISTORY"
USER_ID = "USER_ID"
DEVICE_ID = "DEVICE_ID"
PURCHASE_HISTORY = "PURCHASE_HISTORY"
PRODUCT_INTERACTION = "PRODUCT_INTERACTION"
ADVERTISING_DATA = "ADVERTISING_DATA"
OTHER_USAGE_DATA = "OTHER_USAGE_DATA"
CRASH_DATA = "CRASH_DATA"
PERFORMANCE_DATA = "PERFORMANCE_DATA"
OTHER_DIAGNOSTIC_DATA = "OTHER_DIAGNOSTIC_DATA"
OTHER_DATA = "OTHER_DATA"
HEALTH = "HEALTH"
FITNESS = "FITNESS"
COARSE_LOCATION = "COARSE_LOCATION"
end
def self.type
return "appDataUsageCategories"
end
#
# API
#
def self.all(filter: {}, includes: nil, limit: nil, sort: nil)
resps = Spaceship::ConnectAPI.get_app_data_usage_categories(filter: filter, includes: includes, limit: limit, sort: sort).all_pages
return resps.flat_map(&:to_models)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/app_data_usage_purposes.rb | spaceship/lib/spaceship/connect_api/models/app_data_usage_purposes.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class AppDataUsagePurpose
include Spaceship::ConnectAPI::Model
attr_accessor :deleted
attr_mapping({
"deleted" => "deleted"
})
# Found at https://appstoreconnect.apple.com/iris/v1/appDataUsagePurposes
module ID
THIRD_PARTY_ADVERTISING = "THIRD_PARTY_ADVERTISING"
DEVELOPERS_ADVERTISING = "DEVELOPERS_ADVERTISING"
ANALYTICS = "ANALYTICS"
PRODUCT_PERSONALIZATION = "PRODUCT_PERSONALIZATION"
APP_FUNCTIONALITY = "APP_FUNCTIONALITY"
OTHER_PURPOSES = "OTHER_PURPOSES"
end
def self.type
return "appDataUsagePurposes"
end
#
# API
#
def self.all(filter: {}, includes: nil, limit: nil, sort: nil)
resps = Spaceship::ConnectAPI.get_app_data_usage_purposes(filter: filter, includes: includes, limit: limit, sort: sort).all_pages
return resps.flat_map(&:to_models)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/beta_build_localization.rb | spaceship/lib/spaceship/connect_api/models/beta_build_localization.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class BetaBuildLocalization
include Spaceship::ConnectAPI::Model
attr_accessor :whats_new
attr_accessor :locale
attr_mapping({
"whatsNew" => "whats_new",
"locale" => "locale"
})
def self.type
return "betaBuildLocalizations"
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/beta_app_review_detail.rb | spaceship/lib/spaceship/connect_api/models/beta_app_review_detail.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class BetaAppReviewDetail
include Spaceship::ConnectAPI::Model
attr_accessor :contact_first_name
attr_accessor :contact_last_name
attr_accessor :contact_phone
attr_accessor :contact_email
attr_accessor :demo_account_name
attr_accessor :demo_account_password
attr_accessor :demo_account_required
attr_accessor :notes
attr_mapping({
"contactFirstName" => "contact_first_name",
"contactLastName" => "contact_last_name",
"contactPhone" => "contact_phone",
"contactEmail" => "contact_email",
"demoAccountName" => "demo_account_name",
"demoAccountPassword" => "demo_account_password",
"demoAccountRequired" => "demo_account_required",
"notes" => "notes"
})
def self.type
return "betaAppReviewDetails"
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/pre_release_version.rb | spaceship/lib/spaceship/connect_api/models/pre_release_version.rb | require_relative '../model'
module Spaceship
class ConnectAPI
class PreReleaseVersion
include Spaceship::ConnectAPI::Model
attr_accessor :version
attr_accessor :platform
attr_mapping({
"version" => "version",
"platform" => "platform"
})
def self.type
return "preReleaseVersions"
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/connect_api/models/profile.rb | spaceship/lib/spaceship/connect_api/models/profile.rb | require_relative '../../connect_api'
module Spaceship
class ConnectAPI
class Profile
include Spaceship::ConnectAPI::Model
attr_accessor :name
attr_accessor :platform
attr_accessor :profile_content
attr_accessor :uuid
attr_accessor :created_date
attr_accessor :profile_state
attr_accessor :profile_type
attr_accessor :expiration_date
attr_accessor :bundle_id
attr_accessor :certificates
attr_accessor :devices
attr_mapping({
"name" => "name",
"platform" => "platform",
"profileContent" => "profile_content",
"uuid" => "uuid",
"createdDate" => "created_date",
"profileState" => "profile_state",
"profileType" => "profile_type",
"expirationDate" => "expiration_date",
"bundleId" => "bundle_id",
"certificates" => "certificates",
"devices" => "devices"
})
module ProfileState
ACTIVE = "ACTIVE"
INVALID = "INVALID"
end
module ProfileType
IOS_APP_DEVELOPMENT = "IOS_APP_DEVELOPMENT"
IOS_APP_STORE = "IOS_APP_STORE"
IOS_APP_ADHOC = "IOS_APP_ADHOC"
IOS_APP_INHOUSE = "IOS_APP_INHOUSE"
MAC_APP_DEVELOPMENT = "MAC_APP_DEVELOPMENT"
MAC_APP_STORE = "MAC_APP_STORE"
MAC_APP_DIRECT = "MAC_APP_DIRECT"
TVOS_APP_DEVELOPMENT = "TVOS_APP_DEVELOPMENT"
TVOS_APP_STORE = "TVOS_APP_STORE"
TVOS_APP_ADHOC = "TVOS_APP_ADHOC"
TVOS_APP_INHOUSE = "TVOS_APP_INHOUSE"
MAC_CATALYST_APP_DEVELOPMENT = "MAC_CATALYST_APP_DEVELOPMENT"
MAC_CATALYST_APP_STORE = "MAC_CATALYST_APP_STORE"
MAC_CATALYST_APP_DIRECT = "MAC_CATALYST_APP_DIRECT"
# As of 2022-06-25, only available with Apple ID auth
MAC_APP_INHOUSE = "MAC_APP_INHOUSE"
MAC_CATALYST_APP_INHOUSE = "MAC_CATALYST_APP_INHOUSE"
end
def self.type
return "profiles"
end
def valid?
# Provisioning profiles are not invalidated automatically on the dev portal when the certificate expires.
# They become Invalid only when opened directly in the portal 🤷.
# We need to do an extra check on the expiration date to ensure the profile is valid.
expired = Time.now.utc > Time.parse(self.expiration_date)
is_valid = profile_state == ProfileState::ACTIVE && !expired
return is_valid
end
#
# API
#
def self.all(client: nil, filter: {}, includes: nil, fields: nil, limit: Spaceship::ConnectAPI::MAX_OBJECTS_PER_PAGE_LIMIT, sort: nil)
client ||= Spaceship::ConnectAPI
resps = client.get_profiles(filter: filter, includes: includes, fields: fields, limit: limit, sort: sort).all_pages
return resps.flat_map(&:to_models)
end
def self.create(client: nil, name: nil, profile_type: nil, bundle_id_id: nil, certificate_ids: nil, device_ids: nil)
client ||= Spaceship::ConnectAPI
resp = client.post_profiles(
bundle_id_id: bundle_id_id,
certificates: certificate_ids,
devices: device_ids,
attributes: {
name: name,
profileType: profile_type
}
)
return resp.to_models.first
end
def fetch_all_devices(client: nil, filter: {}, includes: nil, sort: nil)
client ||= Spaceship::ConnectAPI
resps = client.get_devices(profile_id: id, filter: filter, includes: includes).all_pages
return resps.flat_map(&:to_models)
end
def fetch_all_certificates(client: nil, filter: {}, includes: nil, sort: nil)
client ||= Spaceship::ConnectAPI
resps = client.get_certificates(profile_id: id, filter: filter, includes: includes).all_pages
return resps.flat_map(&:to_models)
end
def delete!(client: nil)
client ||= Spaceship::ConnectAPI
return client.delete_profile(profile_id: id)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.